BetterYTM.user.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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 = false;
  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. display: inline-block;
  272. position: absolute;
  273. left: 45px;
  274. top: 43px;
  275. z-index: 10;
  276. color: white;
  277. text-decoration: none;
  278. cursor: pointer;
  279. }
  280. @media(max-width: 615px) {
  281. #betterytm-watermark {
  282. display: none;
  283. }
  284. }
  285. #betterytm-watermark:hover {
  286. text-decoration: underline;
  287. }`;
  288. addGlobalStyle(style, "watermark");
  289. const logoElem = document.querySelector("#left-content");
  290. insertAfter(logoElem, watermark);
  291. dbg && console.info(`BetterYTM: Added watermark element:`, watermark);
  292. }
  293. //#SECTION genius.com lyrics button
  294. let currentSongTitle = "";
  295. let lyricsButtonAddTries = 0;
  296. /**
  297. * Adds a genius.com lyrics button to the media controls bar
  298. */
  299. function addGeniusButton()
  300. {
  301. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  302. if(!likeContainer)
  303. {
  304. lyricsButtonAddTries++;
  305. if(lyricsButtonAddTries < triesLimit)
  306. return setTimeout(addGeniusButton, 250); // TODO: improve this
  307. return console.error(`BetterYTM: Couldn't find like buttons to append lyrics button to after ${lyricsButtonAddTries} tries`);
  308. }
  309. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  310. const gUrl = getGeniusUrl();
  311. const linkElem = document.createElement("a");
  312. linkElem.id = "betterytm-lyrics-button";
  313. linkElem.className = "ytmusic-player-bar";
  314. linkElem.title = "Search for lyrics on genius.com";
  315. linkElem.href = gUrl;
  316. linkElem.target = "_blank";
  317. linkElem.rel = "noopener noreferrer";
  318. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  319. const style = `\
  320. #betterytm-lyrics-button {
  321. display: inline-flex;
  322. align-items: center;
  323. justify-content: center;
  324. position: relative;
  325. vertical-align: middle;
  326. margin-left: 8px;
  327. width: 40px;
  328. height: 40px;
  329. border-radius: 100%;
  330. background-color: transparent;
  331. }
  332. #betterytm-lyrics-button:hover {
  333. background-color: #383838;
  334. }
  335. #betterytm-lyrics-img {
  336. display: inline-block;
  337. z-index: 10;
  338. width: 24px;
  339. height: 24px;
  340. padding: 5px;
  341. }`;
  342. addGlobalStyle(style, "lyrics");
  343. const imgElem = document.createElement("img");
  344. imgElem.id = "betterytm-lyrics-img";
  345. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  346. linkElem.appendChild(imgElem);
  347. dbg && console.info(`BetterYTM: Inserted genius button after ${lyricsButtonAddTries} tries:`, linkElem);
  348. insertAfter(likeContainer, linkElem);
  349. currentSongTitle = songTitleElem.title;
  350. /** @param {MutationRecord[]} mutations */
  351. const onMutation = (mutations) => {
  352. mutations.forEach(mut => {
  353. const newTitle = mut.target.title;
  354. if(newTitle != currentSongTitle)
  355. {
  356. dbg && console.info(`BetterYTM: Song title changed from '${currentSongTitle}' to '${newTitle}'`);
  357. currentSongTitle = newTitle;
  358. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  359. lyricsBtn.href = getGeniusUrl();
  360. lyricsBtn.style.visibility = "initial";
  361. }
  362. });
  363. };
  364. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  365. const obs = new MutationObserver(onMutation);
  366. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  367. }
  368. /**
  369. * Returns the genius.com search URL for the current song
  370. * @returns {string|null}
  371. */
  372. function getGeniusUrl()
  373. {
  374. try
  375. {
  376. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  377. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  378. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  379. return null;
  380. const sanitizeSongName = (songName) => {
  381. let sanitized;
  382. if(songName.match(/\(|feat|ft/gmi))
  383. {
  384. // should hopefully trim right after the song name
  385. sanitized = songName.substring(0, songName.indexOf("("));
  386. }
  387. return (sanitized || songName).trim();
  388. };
  389. const songNameRaw = songTitleElem.title;
  390. const songName = sanitizeSongName(songNameRaw);
  391. const songMeta = songMetaElem.title;
  392. const artistName = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; (•) character
  393. // TODO: artist might need further splitting before comma or ampersand
  394. const sn = encodeURIComponent(songName);
  395. const an = encodeURIComponent(artistName);
  396. const acParams = features.geniusAutoclickBestResult ? `&bytm-ac-sn=${sn}&bytm-ac-an=${an}` : "";
  397. const url = `https://genius.com/search?q=${sn}%20${an}${acParams}`;
  398. dbg && console.info(`BetterYTM: Resolved genius.com URL for song '${songName}' by '${artistName}': ${url}`);
  399. return url;
  400. }
  401. catch(err)
  402. {
  403. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  404. }
  405. }
  406. //#SECTION autoclick best genius.com result
  407. /**
  408. * Automatically clicks the best matching result in a genius.com search
  409. */
  410. function autoclickGeniusResult()
  411. {
  412. if(!location.pathname.includes("/search"))
  413. return;
  414. const miniCards = document.querySelectorAll(".mini_card-title_and_subtitle");
  415. if(!miniCards || miniCards.length == 0)
  416. {
  417. if(geniusAutoclickTries < Math.round(triesLimit * 2.5)) // tries limit higher due to lower timeout
  418. {
  419. geniusAutoclickTries++;
  420. return setTimeout(autoclickGeniusResult, 100); // TODO: improve this
  421. }
  422. else
  423. return console.error(`BetterYTM: Couldn't find result minicards after ${geniusAutoclickTries} tries`);
  424. }
  425. const params = getGeniusAcParams();
  426. if(!params)
  427. return console.info("BetterYTM: No query params present, not autoclicking");
  428. const { songName, artistName } = params;
  429. const resultNode = findMatchingGeniusResult(songName, artistName);
  430. if(!resultNode)
  431. return console.error("BetterYTM: Couldn't find matching result node");
  432. dbg && console.info(`BetterYTM: Found matching result node after ${geniusAutoclickTries} tries:`, resultNode);
  433. resultNode.click();
  434. }
  435. let geniusAutoclickTries = 0;
  436. /**
  437. * Finds a result minicard node that matches the provided song and artist names (case insensitive)
  438. * @param {string} song
  439. * @param {string} artist
  440. * @returns {Node|null}
  441. */
  442. function findMatchingGeniusResult(song, artist)
  443. {
  444. const miniCards = document.querySelectorAll(".mini_card-title_and_subtitle");
  445. dbg && console.info(`BetterYTM: Found ${miniCards.length} minicards in results, searching for match...`);
  446. for(const card of miniCards)
  447. {
  448. if(card.childNodes && card.childNodes.length > 0)
  449. {
  450. const title = Array.from(card.childNodes).find(cn => cn.classList && cn.classList.contains("mini_card-title"));
  451. const subTitle = Array.from(card.childNodes).find(cn => cn.classList && cn.classList.contains("mini_card-subtitle"));
  452. if(!title || !subTitle || !title.innerText || !subTitle.innerText)
  453. continue;
  454. const songName = title.innerText.toLowerCase();
  455. const artistName = subTitle.innerText.toLowerCase();
  456. // 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
  457. if(songName.includes(song.toLowerCase()) && artistName.includes(artist.toLowerCase()))
  458. return card;
  459. }
  460. }
  461. return null;
  462. }
  463. /**
  464. * Returns autoclick query params if they exist, else returns null
  465. * @returns {({ songName: string, artistName: string })|null}
  466. */
  467. function getGeniusAcParams()
  468. {
  469. const params = location.search.substring(1).split(/&/g);
  470. if(params.find(p => p.includes("bytm-ac-sn=")) && params.find(p => p.includes("bytm-ac-an=")))
  471. {
  472. const songName = decodeURIComponent(params.find(p => p.includes("bytm-ac-sn=")).split(/=/)[1]);
  473. const artistName = decodeURIComponent(params.find(p => p.includes("bytm-ac-an=")).split(/=/)[1]);
  474. return { songName, artistName };
  475. }
  476. return null;
  477. }
  478. //#MARKER other
  479. /**
  480. * Returns the current domain as a constant string representation
  481. * @throws {Error} If script runs on an unexpected website
  482. * @returns {Domain}
  483. */
  484. function getDomain()
  485. {
  486. const { hostname } = new URL(location.href);
  487. if(hostname.includes("music.youtube"))
  488. return "ytm";
  489. else if(hostname.includes("youtube"))
  490. return "yt";
  491. else if(hostname.includes("genius"))
  492. return "genius";
  493. else
  494. throw new Error("BetterYTM is running on an unexpected website");
  495. }
  496. /**
  497. * Returns the current video time in seconds
  498. * @returns {number|null} Returns null if the video time is unavailable
  499. */
  500. function getVideoTime()
  501. {
  502. const domain = getDomain();
  503. try
  504. {
  505. if(domain === "ytm")
  506. {
  507. const pbEl = document.querySelector("#progress-bar");
  508. return pbEl.value ?? null;
  509. }
  510. 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
  511. return 0;
  512. return null;
  513. }
  514. catch(err)
  515. {
  516. console.error("BetterYTM: Couldn't get video time due to error:", err);
  517. return null;
  518. }
  519. }
  520. /**
  521. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  522. * @param {HTMLElement} beforeNode
  523. * @param {HTMLElement} afterNode
  524. * @returns {HTMLElement} Returns the `afterNode`
  525. */
  526. function insertAfter(beforeNode, afterNode)
  527. {
  528. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  529. return afterNode;
  530. }
  531. /**
  532. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  533. * @param {string} style CSS string
  534. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  535. */
  536. function addGlobalStyle(style, ref)
  537. {
  538. const styleElem = document.createElement("style");
  539. styleElem.id = `betterytm-${ref}-style`;
  540. if(styleElem.styleSheet)
  541. styleElem.styleSheet.cssText = style;
  542. else
  543. styleElem.appendChild(document.createTextNode(style));
  544. document.querySelector("head").appendChild(styleElem);
  545. dbg && console.info(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  546. }
  547. init(); // call init() when script is loaded
  548. })();