BetterYTM.user.js 19 KB

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