BetterYTM.user.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @namespace https://github.com/Sv443/BetterYTM#readme
  4. // @version 1.0.0
  5. // @license MIT
  6. // @author Sv443
  7. // @copyright Sv443 <[email protected]> (https://github.com/Sv443)
  8. // @description Improvements for YouTube Music
  9. // @description:de Verbesserungen für YouTube Music
  10. // @match https://music.youtube.com/*
  11. // @match https://www.youtube.com/*
  12. // @icon https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/icon/v2.1_200.png
  13. // @run-at document-start
  14. // @grant GM.getValue
  15. // @grant GM.setValue
  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. "use-strict";
  26. (async () => {
  27. /** Set to true to enable debug mode for more output in the JS console */
  28. const dbg = true;
  29. // const branch = "main";
  30. const branch = "develop"; // #DEBUG#
  31. const featInfo = {
  32. arrowKeySupport: {
  33. desc: "Arrow keys should skip forwards and backwards by 10 seconds?",
  34. type: "toggle",
  35. default: true,
  36. },
  37. removeUpgradeTab: {
  38. desc: "Remove the \"Upgrade\" / YT Music Premium tab?",
  39. type: "toggle",
  40. default: true,
  41. },
  42. switchBetweenSites: {
  43. desc: "Add F9 as a hotkey to switch between the YT and YTM sites on a video / song?",
  44. type: "toggle",
  45. default: true,
  46. },
  47. geniusLyrics: {
  48. desc: "Add a button to the media controls bar to search for the current song's lyrics on genius.com in a new tab?",
  49. type: "toggle",
  50. default: true,
  51. },
  52. lyricsButtonsOnSongQueue: {
  53. desc: "TODO: Add a lyrics button to each song in the queue (\"up next\" tab)?",
  54. type: "toggle",
  55. default: true,
  56. },
  57. volumeSliderSize: {
  58. desc: "The width of the volume slider in px",
  59. type: "number",
  60. min: 10,
  61. max: 1000,
  62. default: 175,
  63. },
  64. volumeSliderStep: {
  65. desc: "Volume slider sensitivity - the smaller this number, the finer the volume control",
  66. type: "slider",
  67. min: 1,
  68. max: 20,
  69. default: 2,
  70. },
  71. removeWatermark: {
  72. desc: "Remove the watermark under the YTM logo?",
  73. type: "toggle",
  74. default: false,
  75. },
  76. };
  77. /** @type {FeatureConfig} */
  78. const defaultFeatures = Object.keys(featInfo).reduce((acc, key) => {
  79. acc[key] = featInfo[key].default;
  80. return acc;
  81. }, {});
  82. const featureConf = await loadFeatureConf();
  83. console.log("bytm load", featureConf);
  84. const features = { ...defaultFeatures, ...featureConf };
  85. // const features = { ...defaultFeatures };
  86. console.log("bytm save", features);
  87. await saveFeatureConf(features);
  88. //#MARKER types
  89. /** @typedef {"yt"|"ytm"} Domain Constant string representation of which domain this script is currently running on */
  90. /** @typedef {typeof defaultFeatures} FeatureConfig */
  91. //#MARKER init
  92. /** Specifies the hard limit for repetitive tasks */
  93. const triesLimit = 40;
  94. /** Base URL of geniURL */
  95. const geniUrlBase = "https://api.sv443.net/geniurl";
  96. /** GeniURL endpoint that gives song metadata when provided with a `?q` parameter - [more info](https://api.sv443.net/geniurl) */
  97. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  98. const info = Object.freeze({
  99. name: GM.info.script.name, // eslint-disable-line no-undef
  100. version: GM.info.script.version, // eslint-disable-line no-undef
  101. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  102. });
  103. function init()
  104. {
  105. try
  106. {
  107. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  108. console.log(`Powered by lots of ambition and my song metadata API called geniURL: ${geniUrlBase}`);
  109. document.addEventListener("DOMContentLoaded", onDomLoad);
  110. }
  111. catch(err)
  112. {
  113. console.error("BetterYTM - General Error:", err);
  114. }
  115. }
  116. //#MARKER events
  117. /**
  118. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  119. */
  120. async function onDomLoad()
  121. {
  122. const domain = getDomain();
  123. dbg && console.log(`BetterYTM: Initializing features for domain '${domain}'`);
  124. try
  125. {
  126. if(domain === "ytm")
  127. {
  128. if(features.arrowKeySupport)
  129. {
  130. document.addEventListener("keydown", onKeyDown);
  131. dbg && console.log(`BetterYTM: Added key press listener`);
  132. }
  133. if(features.removeUpgradeTab)
  134. removeUpgradeTab();
  135. if(!features.removeWatermark)
  136. addWatermark();
  137. if(features.geniusLyrics)
  138. await addMediaCtrlGeniusBtn();
  139. if(features.lyricsButtonsOnSongQueue)
  140. await addQueueGeniusBtns();
  141. if(typeof features.volumeSliderSize === "number")
  142. setVolSliderSize(features.volumeSliderSize);
  143. setVolSliderStep();
  144. }
  145. if(["ytm", "yt"].includes(domain))
  146. {
  147. if(features.switchBetweenSites)
  148. initSiteSwitch(domain);
  149. try
  150. {
  151. addMenu();
  152. }
  153. catch(err)
  154. {
  155. console.error("BetterYTM: Couldn't add menu:", err);
  156. }
  157. }
  158. }
  159. catch(err)
  160. {
  161. console.error(`BetterYTM: General error while executing feature:`, err);
  162. }
  163. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  164. // applyTheme();
  165. }
  166. //#MARKER menu
  167. /**
  168. * Adds an element to open the BetterYTM menu
  169. */
  170. function addMenu()
  171. {
  172. // const domain = getDomain();
  173. // bg & menu
  174. const backgroundElem = document.createElement("div");
  175. backgroundElem.id = "betterytm-menu-bg";
  176. backgroundElem.title = "Click here to close the menu";
  177. backgroundElem.style.visibility = "hidden";
  178. backgroundElem.style.display = "none";
  179. backgroundElem.addEventListener("click", (e) => {
  180. if(e.target.id === "betterytm-menu-bg")
  181. closeMenu();
  182. });
  183. const menuContainer = document.createElement("div");
  184. menuContainer.title = "";
  185. menuContainer.id = "betterytm-menu";
  186. menuContainer.style.borderRadius = "15px";
  187. // title
  188. const titleCont = document.createElement("div");
  189. titleCont.style.padding = "8px 20px 20px 8px";
  190. titleCont.style.display = "flex";
  191. titleCont.style.justifyContent = "space-between";
  192. titleCont.id = "betterytm-menu-titlecont";
  193. const titleElem = document.createElement("h2");
  194. titleElem.id = "betterytm-menu-title";
  195. titleElem.innerText = "BetterYTM - Configuration";
  196. const linksCont = document.createElement("div");
  197. linksCont.id = "betterytm-menu-linkscont";
  198. const addLink = (imgSrc, href, title) => {
  199. const anchorElem = document.createElement("a");
  200. anchorElem.className = "betterytm-menu-link";
  201. anchorElem.rel = "noopener noreferrer";
  202. anchorElem.target = "_blank";
  203. anchorElem.href = href;
  204. anchorElem.title = title;
  205. anchorElem.style.marginLeft = "10px";
  206. const imgElem = document.createElement("img");
  207. imgElem.className = "betterytm-menu-img";
  208. imgElem.src = imgSrc;
  209. imgElem.style.width = "32px";
  210. imgElem.style.height = "32px";
  211. anchorElem.appendChild(imgElem);
  212. linksCont.appendChild(anchorElem);
  213. };
  214. addLink(`https://raw.githubusercontent.com/Sv443/BetterYTM/${branch}/resources/external/github.png`, info.namespace, `${info.name} on GitHub`);
  215. addLink(`https://raw.githubusercontent.com/Sv443/BetterYTM/${branch}/resources/external/greasyfork.png`, "https://greasyfork.org/xyz", `${info.name} on GreasyFork`);
  216. const closeElem = document.createElement("img");
  217. closeElem.id = "betterytm-menu-close";
  218. closeElem.src = `https://raw.githubusercontent.com/Sv443/BetterYTM/${branch}/resources/icon/close.png`;
  219. closeElem.title = "Click to close the menu";
  220. closeElem.style.marginLeft = "50px";
  221. closeElem.style.width = "32px";
  222. closeElem.style.height = "32px";
  223. closeElem.addEventListener("click", closeMenu);
  224. linksCont.appendChild(closeElem);
  225. titleCont.appendChild(titleElem);
  226. titleCont.appendChild(linksCont);
  227. // TODO: features
  228. const featuresCont = document.createElement("div");
  229. featuresCont.id = "betterytm-menu-opts";
  230. featuresCont.style.display = "flex";
  231. featuresCont.style.flexDirection = "column";
  232. /**
  233. * Gets called whenever the feature config is changed
  234. * @param {keyof typeof defaultFeatures} key
  235. * @param {number|boolean} initialVal
  236. * @param {number|boolean} newVal
  237. */
  238. const confChanged = async (key, initialVal, newVal) => {
  239. dbg && console.info(`BetterYTM: Feature config changed, key '${key}' from value '${initialVal}' to '${newVal}'`);
  240. /** @type {FeatureConfig} */
  241. const featConf = {...(await loadFeatureConf())};
  242. featConf[key] = newVal;
  243. await saveFeatureConf(featConf);
  244. dbg && console.log("BetterYTM: Saved feature config changes");
  245. console.log("#DEBUG", await GM.getValue("bytm-config")); // eslint-disable-line no-undef
  246. };
  247. const featKeys = Object.keys(features);
  248. for(const key of featKeys)
  249. {
  250. const ftInfo = featInfo[key];
  251. if(!ftInfo)
  252. continue;
  253. const { desc, type, default: ftDef } = ftInfo;
  254. const val = features[key];
  255. const initialVal = val || ftDef;
  256. const ftConfElem = document.createElement("div");
  257. ftConfElem.id = `bytm-ftconf-${key}`;
  258. ftConfElem.style.display = "flex";
  259. ftConfElem.style.flexDirection = "row";
  260. ftConfElem.style.justifyContent = "space-between";
  261. ftConfElem.style.padding = "8px 20px";
  262. {
  263. const textElem = document.createElement("span");
  264. textElem.style.display = "inline-block";
  265. textElem.style.fontSize = "15px";
  266. textElem.innerText = desc;
  267. ftConfElem.appendChild(textElem);
  268. }
  269. {
  270. let inputType;
  271. switch(type)
  272. {
  273. case "toggle":
  274. inputType = "checkbox";
  275. break;
  276. case "slider":
  277. inputType = "range";
  278. break;
  279. case "number":
  280. inputType = "number";
  281. break;
  282. }
  283. const inputElemId = `bytm-ftconf-${key}-input`;
  284. const ctrlElem = document.createElement("span");
  285. ctrlElem.style.display = "inline-block";
  286. ctrlElem.style.whiteSpace = "nowrap";
  287. const inputElem = document.createElement("input");
  288. inputElem.id = inputElemId;
  289. inputElem.style.marginRight = "20px";
  290. inputElem.type = inputType;
  291. inputElem.value = initialVal;
  292. if(ftInfo.min && ftInfo.max)
  293. {
  294. inputElem.min = ftInfo.min;
  295. inputElem.max = ftInfo.max;
  296. }
  297. if(type === "toggle")
  298. inputElem.checked = initialVal;
  299. const fmtVal = v => String(v);
  300. let labelElem;
  301. if(type === "slider")
  302. {
  303. labelElem = document.createElement("label");
  304. labelElem.style.marginRight = "20px";
  305. labelElem.style.fontSize = "16px";
  306. labelElem["for"] = inputElemId;
  307. labelElem.innerText = fmtVal(initialVal);
  308. inputElem.addEventListener("change", () => labelElem.innerText = fmtVal(parseInt(inputElem.value)));
  309. }
  310. inputElem.addEventListener("change", ({ currentTarget }) => {
  311. let v = parseInt(currentTarget.value);
  312. if(isNaN(v))
  313. v = currentTarget.value;
  314. confChanged(key, initialVal, (type !== "toggle" ? v : currentTarget.checked));
  315. });
  316. const resetElem = document.createElement("button");
  317. resetElem.innerText = "Reset";
  318. resetElem.addEventListener("click", () => {
  319. inputElem[type !== "toggle" ? "value" : "checked"] = ftDef;
  320. if(labelElem)
  321. labelElem.innerText = fmtVal(parseInt(inputElem.value));
  322. confChanged(key, initialVal, ftDef);
  323. });
  324. labelElem && ctrlElem.appendChild(labelElem);
  325. ctrlElem.appendChild(inputElem);
  326. ctrlElem.appendChild(resetElem);
  327. ftConfElem.appendChild(ctrlElem);
  328. }
  329. featuresCont.appendChild(ftConfElem);
  330. }
  331. const footerElem = document.createElement("div");
  332. footerElem.style.marginTop = "40px";
  333. footerElem.style.fontSize = "17px";
  334. footerElem.style.textDecoration = "underline";
  335. footerElem.style.padding = "8px 20px";
  336. footerElem.innerText = "You need to reload the page to apply changes.";
  337. const reloadElem = document.createElement("button");
  338. reloadElem.style.marginLeft = "20px";
  339. reloadElem.innerText = "Reload now";
  340. reloadElem.title = "Click to reload the page";
  341. reloadElem.addEventListener("click", () => location.reload());
  342. footerElem.appendChild(reloadElem);
  343. featuresCont.appendChild(footerElem);
  344. // finalize
  345. menuContainer.appendChild(titleCont);
  346. menuContainer.appendChild(featuresCont);
  347. backgroundElem.appendChild(menuContainer);
  348. document.body.appendChild(backgroundElem);
  349. // add style
  350. const menuStyle = `\
  351. #betterytm-menu-bg {
  352. display: block;
  353. position: fixed;
  354. width: 100vw;
  355. height: 100vh;
  356. top: 0;
  357. left: 0;
  358. z-index: 15;
  359. background-color: rgba(0, 0, 0, 0.6);
  360. }
  361. #betterytm-menu {
  362. display: inline-block;
  363. position: fixed;
  364. width: 50vw;
  365. height: auto;
  366. min-height: 500px;
  367. left: 25vw;
  368. top: 25vh;
  369. z-index: 16;
  370. overflow: auto;
  371. padding: 8px;
  372. color: #fff;
  373. background-color: #212121;
  374. }
  375. #betterytm-menu-titlecont {
  376. display: flex;
  377. }
  378. #betterytm-menu-title {
  379. font-size: 20px;
  380. margin-top: 5px;
  381. margin-bottom: 8px;
  382. }
  383. #betterytm-menu-linkscont {
  384. display: flex;
  385. }
  386. .betterytm-menu-link {
  387. display: inline-block;
  388. }
  389. .betterytm-menu-img {
  390. }
  391. #betterytm-menu-close {
  392. cursor: pointer;
  393. }
  394. `;
  395. dbg && console.log("BetterYTM: Added menu elem:", backgroundElem);
  396. /* #DEBUG */ openMenu();
  397. addGlobalStyle(menuStyle, "menu");
  398. }
  399. function closeMenu()
  400. {
  401. const menuBg = document.querySelector("#betterytm-menu-bg");
  402. menuBg.style.visibility = "hidden";
  403. menuBg.style.display = "none";
  404. }
  405. function openMenu()
  406. {
  407. const menuBg = document.querySelector("#betterytm-menu-bg");
  408. menuBg.style.visibility = "visible";
  409. menuBg.style.display = "block";
  410. }
  411. //#MARKER features
  412. //#SECTION arrow key skip
  413. /**
  414. * Called when the user presses keys
  415. * @param {KeyboardEvent} evt
  416. */
  417. function onKeyDown(evt)
  418. {
  419. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  420. {
  421. // discard the event when a (text) input is currently active, like when editing a playlist
  422. if(["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName))
  423. return dbg && console.info(`BetterYTM: Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  424. dbg && console.log(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  425. // 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
  426. const defaultProps = {
  427. altKey: false,
  428. bubbles: true,
  429. cancelBubble: false,
  430. cancelable: true,
  431. charCode: 0,
  432. composed: true,
  433. ctrlKey: false,
  434. currentTarget: null,
  435. defaultPrevented: evt.defaultPrevented,
  436. explicitOriginalTarget: document.body,
  437. isTrusted: true,
  438. metaKey: false,
  439. originalTarget: document.body,
  440. repeat: false,
  441. shiftKey: false,
  442. srcElement: document.body,
  443. target: document.body,
  444. type: "keydown",
  445. view: window,
  446. };
  447. let invalidKey = false;
  448. let keyProps = {};
  449. switch(evt.code)
  450. {
  451. case "ArrowLeft":
  452. keyProps = {
  453. code: "KeyH",
  454. key: "h",
  455. keyCode: 72,
  456. which: 72,
  457. };
  458. break;
  459. case "ArrowRight":
  460. keyProps = {
  461. code: "KeyL",
  462. key: "l",
  463. keyCode: 76,
  464. which: 76,
  465. };
  466. break;
  467. default:
  468. // console.warn("BetterYTM - Unknown key", evt.code);
  469. invalidKey = true;
  470. break;
  471. }
  472. if(!invalidKey)
  473. {
  474. const proxyProps = { ...defaultProps, ...keyProps };
  475. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  476. dbg && console.log(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  477. }
  478. else if(dbg)
  479. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  480. }
  481. }
  482. //#SECTION site switch
  483. /**
  484. * Initializes the site switch feature
  485. * @param {Domain} domain
  486. */
  487. function initSiteSwitch(domain)
  488. {
  489. // TODO:
  490. // extra features:
  491. // - keep video time
  492. document.addEventListener("keydown", (e) => {
  493. if(e.key == "F9")
  494. switchSite(domain === "yt" ? "ytm" : "yt");
  495. });
  496. dbg && console.log(`BetterYTM: Initialized site switch listener`);
  497. }
  498. /**
  499. * Switches to the other site (between YT and YTM)
  500. * @param {Domain} newDomain
  501. */
  502. function switchSite(newDomain)
  503. {
  504. try
  505. {
  506. let subdomain;
  507. if(newDomain === "ytm")
  508. subdomain = "music";
  509. else if(newDomain === "yt")
  510. subdomain = "www";
  511. if(!subdomain)
  512. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  513. const { pathname, search, hash } = new URL(location.href);
  514. const vt = getVideoTime() ?? 0;
  515. dbg && console.log(`BetterYTM: Found video time of ${vt} seconds`);
  516. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  517. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  518. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  519. location.href = url;
  520. }
  521. catch(err)
  522. {
  523. console.error(`BetterYTM: Error while switching site:`, err);
  524. }
  525. }
  526. //#SECTION remove upgrade tab
  527. let removeUpgradeTries = 0;
  528. /**
  529. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  530. */
  531. function removeUpgradeTab()
  532. {
  533. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  534. if(tabElem)
  535. {
  536. tabElem.remove();
  537. dbg && console.log(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  538. }
  539. else if(removeUpgradeTries < triesLimit)
  540. {
  541. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  542. removeUpgradeTries++;
  543. }
  544. else
  545. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  546. }
  547. //#SECTION add watermark
  548. /**
  549. * Adds a watermark beneath the logo
  550. */
  551. function addWatermark()
  552. {
  553. const watermark = document.createElement("a");
  554. watermark.id = "betterytm-watermark";
  555. watermark.className = "style-scope ytmusic-nav-bar";
  556. watermark.innerText = info.name;
  557. watermark.title = "Open menu";
  558. watermark.href = "#";
  559. watermark.addEventListener("click", () => openMenu());
  560. const style = `\
  561. #betterytm-watermark {
  562. font-size: 10px;
  563. display: inline-block;
  564. position: absolute;
  565. left: 45px;
  566. top: 46px;
  567. z-index: 10;
  568. color: white;
  569. text-decoration: none;
  570. cursor: pointer;
  571. }
  572. @media(max-width: 615px) {
  573. #betterytm-watermark {
  574. display: none;
  575. }
  576. }
  577. #betterytm-watermark:hover {
  578. text-decoration: underline;
  579. }`;
  580. addGlobalStyle(style, "watermark");
  581. const logoElem = document.querySelector("#left-content");
  582. insertAfter(logoElem, watermark);
  583. dbg && console.log(`BetterYTM: Added watermark element:`, watermark);
  584. }
  585. //#SECTION genius.com lyrics button
  586. let mcCurrentSongTitle = "";
  587. let mcLyricsButtonAddTries = 0;
  588. /**
  589. * Adds a genius.com lyrics button to the media controls bar
  590. */
  591. async function addMediaCtrlGeniusBtn()
  592. {
  593. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  594. if(!likeContainer)
  595. {
  596. mcLyricsButtonAddTries++;
  597. if(mcLyricsButtonAddTries < triesLimit)
  598. return setTimeout(addMediaCtrlGeniusBtn, 250); // TODO: improve this
  599. return console.error(`BetterYTM: Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  600. }
  601. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  602. const gUrl = await getCurrentGeniusUrl();
  603. const linkElem = document.createElement("a");
  604. linkElem.id = "betterytm-lyrics-button";
  605. linkElem.className = "ytmusic-player-bar";
  606. linkElem.title = "Search for lyrics on genius.com";
  607. linkElem.href = gUrl;
  608. linkElem.target = "_blank";
  609. linkElem.rel = "noopener noreferrer";
  610. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  611. linkElem.style.display = gUrl ? "initial" : "none";
  612. const style = `\
  613. #betterytm-lyrics-button {
  614. display: inline-flex;
  615. align-items: center;
  616. justify-content: center;
  617. position: relative;
  618. vertical-align: middle;
  619. margin-left: 8px;
  620. width: 40px;
  621. height: 40px;
  622. border-radius: 100%;
  623. background-color: transparent;
  624. }
  625. #betterytm-lyrics-button:hover {
  626. background-color: #383838;
  627. }
  628. #betterytm-lyrics-img {
  629. display: inline-block;
  630. z-index: 10;
  631. width: 24px;
  632. height: 24px;
  633. padding: 5px;
  634. }`;
  635. addGlobalStyle(style, "lyrics");
  636. const imgElem = document.createElement("img");
  637. imgElem.id = "betterytm-lyrics-img";
  638. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  639. linkElem.appendChild(imgElem);
  640. dbg && console.log(`BetterYTM: Inserted genius button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  641. insertAfter(likeContainer, linkElem);
  642. mcCurrentSongTitle = songTitleElem.title;
  643. const onMutation = async (/**@type {MutationRecord[]}*/ mutations) => {
  644. for await(const mut of mutations)
  645. {
  646. const newTitle = mut.target.title;
  647. if(newTitle != mcCurrentSongTitle)
  648. {
  649. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  650. dbg && console.log(`BetterYTM: Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  651. lyricsBtn.style.cursor = "wait";
  652. lyricsBtn.style.pointerEvents = "none";
  653. mcCurrentSongTitle = newTitle;
  654. lyricsBtn.href = await getCurrentGeniusUrl(); // can take a second or two
  655. lyricsBtn.style.cursor = "pointer";
  656. lyricsBtn.style.visibility = "initial";
  657. lyricsBtn.style.display = "initial";
  658. lyricsBtn.style.pointerEvents = "initial";
  659. }
  660. }
  661. };
  662. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  663. const obs = new MutationObserver(onMutation);
  664. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  665. }
  666. /**
  667. * Adds genius lyrics buttons to the song queue
  668. */
  669. async function addQueueGeniusBtns()
  670. {
  671. }
  672. /**
  673. * Returns the genius.com lyrics site URL for the current song
  674. * @returns {Promise<string|null>}
  675. */
  676. async function getCurrentGeniusUrl()
  677. {
  678. try
  679. {
  680. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  681. const isVideo = typeof document.querySelector("ytmusic-player").getAttribute("video-mode_") === "string";
  682. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  683. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  684. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  685. return null;
  686. /** @param {string} songName */
  687. const sanitizeSongName = (songName) => {
  688. const songNameRegex = /\(.+\)/gmi;
  689. let sanitized;
  690. if(songName.match(songNameRegex))
  691. sanitized = songName.replace(songNameRegex, ""); // should hopefully trim right after the song name
  692. return (sanitized ?? songName).trim();
  693. };
  694. /** @param {string} songMeta */
  695. const splitArtist = (songMeta) => {
  696. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at bullet (&bull; / •) character
  697. if(songMeta.match(/&/))
  698. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  699. if(songMeta.match(/,/))
  700. songMeta = songMeta.split(/,\s*/gm)[0];
  701. return songMeta.trim();
  702. }
  703. const songNameRaw = songTitleElem.title;
  704. const songName = sanitizeSongName(songNameRaw);
  705. const artistName = splitArtist(songMetaElem.title);
  706. const defQuery = encodeURIComponent(`${artistName} ${songName}`);
  707. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  708. const getGeniusUrlVideo = async () => {
  709. if(!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  710. return await getGeniusUrl(defQuery);
  711. const query = encodeURIComponent(songName.split("-").map(v => v.trim()).join(" "));
  712. return await getGeniusUrl(query);
  713. };
  714. // TODO: artist might need further splitting before comma or ampersand
  715. const url = isVideo ? await getGeniusUrlVideo() : (await getGeniusUrl(defQuery) ?? await getGeniusUrlVideo());
  716. return url;
  717. }
  718. catch(err)
  719. {
  720. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  721. return null;
  722. }
  723. }
  724. /**
  725. * @param {string} query
  726. * @returns {Promise<string|undefined>}
  727. */
  728. async function getGeniusUrl(query)
  729. {
  730. try
  731. {
  732. dbg && console.log(`BetterYTM: Fetching genius URL from geniURL API for query '${query}'`);
  733. const result = await (await fetch(`${geniURLSearchTopUrl}?q=${query}`)).json();
  734. if(result.error)
  735. {
  736. console.error("BetterYTM: Couldn't fetch genius.com URL:", result.message);
  737. return undefined;
  738. }
  739. return result?.url;
  740. }
  741. catch(err)
  742. {
  743. console.error("Couldn't get genius URL due to error:", err);
  744. return undefined;
  745. }
  746. }
  747. // #SECTION volume slider
  748. /**
  749. * Sets the volume slider to a set size
  750. */
  751. function setVolSliderSize()
  752. {
  753. const { volumeSliderSize: size } = features;
  754. if(typeof size !== "number" || isNaN(parseInt(size)))
  755. return;
  756. const style = `\
  757. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  758. width: ${size}px !important;
  759. }`;
  760. addGlobalStyle(style, "vol_slider_size");
  761. }
  762. /**
  763. * Sets the `step` attribute of the volume slider
  764. */
  765. function setVolSliderStep()
  766. {
  767. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  768. sliderElem.setAttribute("step", features.volumeSliderStep);
  769. }
  770. //#MARKER other
  771. /**
  772. * Returns the current domain as a constant string representation
  773. * @throws {Error} If script runs on an unexpected website
  774. * @returns {Domain}
  775. */
  776. function getDomain()
  777. {
  778. const { hostname } = new URL(location.href);
  779. if(hostname.includes("music.youtube"))
  780. return "ytm";
  781. else if(hostname.includes("youtube"))
  782. return "yt";
  783. else
  784. throw new Error("BetterYTM is running on an unexpected website");
  785. }
  786. /**
  787. * TODO: this is entirely broken now
  788. * Returns the current video time in seconds
  789. * @returns {number|null} Returns null if the video time is unavailable
  790. */
  791. function getVideoTime()
  792. {
  793. const domain = getDomain();
  794. try
  795. {
  796. if(domain === "ytm")
  797. {
  798. const pbEl = document.querySelector("#progress-bar");
  799. return pbEl.value ?? null;
  800. }
  801. 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
  802. return 0;
  803. return null;
  804. }
  805. catch(err)
  806. {
  807. console.error("BetterYTM: Couldn't get video time due to error:", err);
  808. return null;
  809. }
  810. }
  811. /**
  812. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  813. * @param {HTMLElement} beforeNode
  814. * @param {HTMLElement} afterNode
  815. * @returns {HTMLElement} Returns the `afterNode`
  816. */
  817. function insertAfter(beforeNode, afterNode)
  818. {
  819. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  820. return afterNode;
  821. }
  822. /**
  823. * Adds global CSS style through a `<style>` element in the document's `<head>`
  824. * @param {string} style CSS string
  825. * @param {string} [ref] Reference name that is included in the `<style>`'s ID - defaults to a random number if left undefined
  826. */
  827. function addGlobalStyle(style, ref)
  828. {
  829. if(typeof ref !== "string" || ref.length === 0)
  830. ref = String(Math.floor(Math.random() * 1000));
  831. const styleElem = document.createElement("style");
  832. styleElem.id = `bytm-style-${ref}`;
  833. if(styleElem.styleSheet)
  834. styleElem.styleSheet.cssText = style;
  835. else
  836. styleElem.appendChild(document.createTextNode(style));
  837. document.querySelector("head").appendChild(styleElem);
  838. dbg && console.log(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  839. }
  840. //#SECTION feature config
  841. /**
  842. * Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved
  843. * @returns {Promise<Readonly<FeatureConfig | {}>>}
  844. */
  845. async function loadFeatureConf()
  846. {
  847. const defConf = Object.freeze({...defaultFeatures});
  848. try
  849. {
  850. /** @type {string} */
  851. const featureConf = await GM.getValue("bytm-config"); // eslint-disable-line no-undef
  852. if(!featureConf)
  853. {
  854. await setDefaultFeatConf();
  855. return defConf;
  856. }
  857. return Object.freeze(featureConf ? JSON.parse(featureConf) : {});
  858. }
  859. catch(err)
  860. {
  861. await setDefaultFeatConf();
  862. return defConf;
  863. }
  864. }
  865. /**
  866. * Saves a feature configuration saved persistently
  867. * @param {FeatureConfig} featureConf
  868. * @returns {Promise<void>}
  869. */
  870. function saveFeatureConf(featureConf)
  871. {
  872. if(!featureConf || typeof featureConf != "object")
  873. throw new TypeError("Feature config not provided or invalid");
  874. return GM.setValue("bytm-config", JSON.stringify(featureConf)); // eslint-disable-line no-undef
  875. }
  876. /**
  877. * @returns {Promise<void>}
  878. */
  879. function setDefaultFeatConf()
  880. {
  881. return GM.setValue("bytm-config", JSON.stringify(defaultFeatures)); // eslint-disable-line no-undef
  882. }
  883. init(); // call init() when script is loaded
  884. })();