BetterYTM.user.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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. addGlobalStyle(menuStyle, "menu");
  397. }
  398. function closeMenu()
  399. {
  400. const menuBg = document.querySelector("#betterytm-menu-bg");
  401. menuBg.style.visibility = "hidden";
  402. menuBg.style.display = "none";
  403. }
  404. function openMenu()
  405. {
  406. const menuBg = document.querySelector("#betterytm-menu-bg");
  407. menuBg.style.visibility = "visible";
  408. menuBg.style.display = "block";
  409. }
  410. //#MARKER features
  411. //#SECTION arrow key skip
  412. /**
  413. * Called when the user presses keys
  414. * @param {KeyboardEvent} evt
  415. */
  416. function onKeyDown(evt)
  417. {
  418. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  419. {
  420. // discard the event when a (text) input is currently active, like when editing a playlist
  421. if(["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName))
  422. return dbg && console.info(`BetterYTM: Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  423. dbg && console.log(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  424. // 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
  425. const defaultProps = {
  426. altKey: false,
  427. bubbles: true,
  428. cancelBubble: false,
  429. cancelable: true,
  430. charCode: 0,
  431. composed: true,
  432. ctrlKey: false,
  433. currentTarget: null,
  434. defaultPrevented: evt.defaultPrevented,
  435. explicitOriginalTarget: document.body,
  436. isTrusted: true,
  437. metaKey: false,
  438. originalTarget: document.body,
  439. repeat: false,
  440. shiftKey: false,
  441. srcElement: document.body,
  442. target: document.body,
  443. type: "keydown",
  444. view: window,
  445. };
  446. let invalidKey = false;
  447. let keyProps = {};
  448. switch(evt.code)
  449. {
  450. case "ArrowLeft":
  451. keyProps = {
  452. code: "KeyH",
  453. key: "h",
  454. keyCode: 72,
  455. which: 72,
  456. };
  457. break;
  458. case "ArrowRight":
  459. keyProps = {
  460. code: "KeyL",
  461. key: "l",
  462. keyCode: 76,
  463. which: 76,
  464. };
  465. break;
  466. default:
  467. // console.warn("BetterYTM - Unknown key", evt.code);
  468. invalidKey = true;
  469. break;
  470. }
  471. if(!invalidKey)
  472. {
  473. const proxyProps = { ...defaultProps, ...keyProps };
  474. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  475. dbg && console.log(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  476. }
  477. else if(dbg)
  478. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  479. }
  480. }
  481. //#SECTION site switch
  482. /**
  483. * Initializes the site switch feature
  484. * @param {Domain} domain
  485. */
  486. function initSiteSwitch(domain)
  487. {
  488. // TODO:
  489. // extra features:
  490. // - keep video time
  491. document.addEventListener("keydown", (e) => {
  492. if(e.key == "F9")
  493. switchSite(domain === "yt" ? "ytm" : "yt");
  494. });
  495. dbg && console.log(`BetterYTM: Initialized site switch listener`);
  496. }
  497. /**
  498. * Switches to the other site (between YT and YTM)
  499. * @param {Domain} newDomain
  500. */
  501. function switchSite(newDomain)
  502. {
  503. try
  504. {
  505. let subdomain;
  506. if(newDomain === "ytm")
  507. subdomain = "music";
  508. else if(newDomain === "yt")
  509. subdomain = "www";
  510. if(!subdomain)
  511. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  512. const { pathname, search, hash } = new URL(location.href);
  513. const vt = getVideoTime() ?? 0;
  514. dbg && console.log(`BetterYTM: Found video time of ${vt} seconds`);
  515. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  516. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  517. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  518. location.href = url;
  519. }
  520. catch(err)
  521. {
  522. console.error(`BetterYTM: Error while switching site:`, err);
  523. }
  524. }
  525. //#SECTION remove upgrade tab
  526. let removeUpgradeTries = 0;
  527. /**
  528. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  529. */
  530. function removeUpgradeTab()
  531. {
  532. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  533. if(tabElem)
  534. {
  535. tabElem.remove();
  536. dbg && console.log(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  537. }
  538. else if(removeUpgradeTries < triesLimit)
  539. {
  540. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  541. removeUpgradeTries++;
  542. }
  543. else
  544. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  545. }
  546. //#SECTION add watermark
  547. /**
  548. * Adds a watermark beneath the logo
  549. */
  550. function addWatermark()
  551. {
  552. const watermark = document.createElement("a");
  553. watermark.id = "betterytm-watermark";
  554. watermark.className = "style-scope ytmusic-nav-bar";
  555. watermark.innerText = info.name;
  556. watermark.title = "Open menu";
  557. watermark.href = "#";
  558. watermark.addEventListener("click", () => openMenu());
  559. const style = `\
  560. #betterytm-watermark {
  561. font-size: 10px;
  562. display: inline-block;
  563. position: absolute;
  564. left: 45px;
  565. top: 46px;
  566. z-index: 10;
  567. color: white;
  568. text-decoration: none;
  569. cursor: pointer;
  570. }
  571. @media(max-width: 615px) {
  572. #betterytm-watermark {
  573. display: none;
  574. }
  575. }
  576. #betterytm-watermark:hover {
  577. text-decoration: underline;
  578. }`;
  579. addGlobalStyle(style, "watermark");
  580. const logoElem = document.querySelector("#left-content");
  581. insertAfter(logoElem, watermark);
  582. dbg && console.log(`BetterYTM: Added watermark element:`, watermark);
  583. }
  584. //#SECTION genius.com lyrics button
  585. let mcCurrentSongTitle = "";
  586. let mcLyricsButtonAddTries = 0;
  587. /**
  588. * Adds a genius.com lyrics button to the media controls bar
  589. */
  590. async function addMediaCtrlGeniusBtn()
  591. {
  592. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  593. if(!likeContainer)
  594. {
  595. mcLyricsButtonAddTries++;
  596. if(mcLyricsButtonAddTries < triesLimit)
  597. return setTimeout(addMediaCtrlGeniusBtn, 250); // TODO: improve this
  598. return console.error(`BetterYTM: Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  599. }
  600. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  601. const gUrl = await getCurrentGeniusUrl();
  602. const linkElem = document.createElement("a");
  603. linkElem.id = "betterytm-lyrics-button";
  604. linkElem.className = "ytmusic-player-bar";
  605. linkElem.title = "Search for lyrics on genius.com";
  606. linkElem.href = gUrl;
  607. linkElem.target = "_blank";
  608. linkElem.rel = "noopener noreferrer";
  609. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  610. linkElem.style.display = gUrl ? "inline-flex" : "none";
  611. const style = `\
  612. #betterytm-lyrics-button {
  613. align-items: center;
  614. justify-content: center;
  615. position: relative;
  616. vertical-align: middle;
  617. margin-left: 8px;
  618. width: 40px;
  619. height: 40px;
  620. border-radius: 100%;
  621. background-color: transparent;
  622. }
  623. #betterytm-lyrics-button:hover {
  624. background-color: #383838;
  625. }
  626. #betterytm-lyrics-img {
  627. display: inline-block;
  628. z-index: 10;
  629. width: 24px;
  630. height: 24px;
  631. padding: 5px;
  632. }`;
  633. addGlobalStyle(style, "lyrics");
  634. const imgElem = document.createElement("img");
  635. imgElem.id = "betterytm-lyrics-img";
  636. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  637. linkElem.appendChild(imgElem);
  638. dbg && console.log(`BetterYTM: Inserted genius button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  639. insertAfter(likeContainer, linkElem);
  640. mcCurrentSongTitle = songTitleElem.title;
  641. const onMutation = async (/**@type {MutationRecord[]}*/ mutations) => {
  642. for await(const mut of mutations)
  643. {
  644. const newTitle = mut.target.title;
  645. if(newTitle != mcCurrentSongTitle)
  646. {
  647. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  648. dbg && console.log(`BetterYTM: Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  649. lyricsBtn.style.cursor = "wait";
  650. lyricsBtn.style.pointerEvents = "none";
  651. mcCurrentSongTitle = newTitle;
  652. lyricsBtn.href = await getCurrentGeniusUrl(); // can take a second or two
  653. lyricsBtn.style.cursor = "pointer";
  654. lyricsBtn.style.visibility = "initial";
  655. lyricsBtn.style.display = "inline-flex";
  656. lyricsBtn.style.pointerEvents = "initial";
  657. }
  658. }
  659. };
  660. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  661. const obs = new MutationObserver(onMutation);
  662. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  663. }
  664. /**
  665. * Adds genius lyrics buttons to the song queue
  666. */
  667. async function addQueueGeniusBtns()
  668. {
  669. }
  670. /**
  671. * Returns the genius.com lyrics site URL for the current song
  672. * @returns {Promise<string|null>}
  673. */
  674. async function getCurrentGeniusUrl()
  675. {
  676. try
  677. {
  678. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  679. const isVideo = typeof document.querySelector("ytmusic-player").getAttribute("video-mode_") === "string";
  680. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  681. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  682. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  683. return null;
  684. /** @param {string} songName */
  685. const sanitizeSongName = (songName) => {
  686. const songNameRegex = /\(.+\)/gmi;
  687. let sanitized;
  688. if(songName.match(songNameRegex))
  689. sanitized = songName.replace(songNameRegex, ""); // should hopefully trim right after the song name
  690. return (sanitized ?? songName).trim();
  691. };
  692. /** @param {string} songMeta */
  693. const splitArtist = (songMeta) => {
  694. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at bullet (&bull; / •) character
  695. if(songMeta.match(/&/))
  696. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  697. if(songMeta.match(/,/))
  698. songMeta = songMeta.split(/,\s*/gm)[0];
  699. return songMeta.trim();
  700. }
  701. const songNameRaw = songTitleElem.title;
  702. const songName = sanitizeSongName(songNameRaw);
  703. const artistName = splitArtist(songMetaElem.title);
  704. const defQuery = encodeURIComponent(`${artistName} ${songName}`);
  705. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  706. const getGeniusUrlVideo = async () => {
  707. if(!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  708. return await getGeniusUrl(defQuery);
  709. const query = encodeURIComponent(songName.split("-").map(v => v.trim()).join(" "));
  710. return await getGeniusUrl(query);
  711. };
  712. // TODO: artist might need further splitting before comma or ampersand
  713. const url = isVideo ? await getGeniusUrlVideo() : (await getGeniusUrl(defQuery) ?? await getGeniusUrlVideo());
  714. return url;
  715. }
  716. catch(err)
  717. {
  718. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  719. return null;
  720. }
  721. }
  722. /**
  723. * @param {string} query
  724. * @returns {Promise<string|undefined>}
  725. */
  726. async function getGeniusUrl(query)
  727. {
  728. try
  729. {
  730. dbg && console.log(`BetterYTM: Fetching genius URL from geniURL API for query '${query}'`);
  731. const result = await (await fetch(`${geniURLSearchTopUrl}?q=${query}`)).json();
  732. if(result.error)
  733. {
  734. console.error("BetterYTM: Couldn't fetch genius.com URL:", result.message);
  735. return undefined;
  736. }
  737. return result?.url;
  738. }
  739. catch(err)
  740. {
  741. console.error("Couldn't get genius URL due to error:", err);
  742. return undefined;
  743. }
  744. }
  745. // #SECTION volume slider
  746. /**
  747. * Sets the volume slider to a set size
  748. */
  749. function setVolSliderSize()
  750. {
  751. const { volumeSliderSize: size } = features;
  752. if(typeof size !== "number" || isNaN(parseInt(size)))
  753. return;
  754. const style = `\
  755. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  756. width: ${size}px !important;
  757. }`;
  758. addGlobalStyle(style, "vol_slider_size");
  759. }
  760. /**
  761. * Sets the `step` attribute of the volume slider
  762. */
  763. function setVolSliderStep()
  764. {
  765. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  766. sliderElem.setAttribute("step", features.volumeSliderStep);
  767. }
  768. //#MARKER other
  769. /**
  770. * Returns the current domain as a constant string representation
  771. * @throws {Error} If script runs on an unexpected website
  772. * @returns {Domain}
  773. */
  774. function getDomain()
  775. {
  776. const { hostname } = new URL(location.href);
  777. if(hostname.includes("music.youtube"))
  778. return "ytm";
  779. else if(hostname.includes("youtube"))
  780. return "yt";
  781. else
  782. throw new Error("BetterYTM is running on an unexpected website");
  783. }
  784. /**
  785. * TODO: this is entirely broken now
  786. * Returns the current video time in seconds
  787. * @returns {number|null} Returns null if the video time is unavailable
  788. */
  789. function getVideoTime()
  790. {
  791. const domain = getDomain();
  792. try
  793. {
  794. if(domain === "ytm")
  795. {
  796. const pbEl = document.querySelector("#progress-bar");
  797. return pbEl.value ?? null;
  798. }
  799. 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
  800. return 0;
  801. return null;
  802. }
  803. catch(err)
  804. {
  805. console.error("BetterYTM: Couldn't get video time due to error:", err);
  806. return null;
  807. }
  808. }
  809. /**
  810. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  811. * @param {HTMLElement} beforeNode
  812. * @param {HTMLElement} afterNode
  813. * @returns {HTMLElement} Returns the `afterNode`
  814. */
  815. function insertAfter(beforeNode, afterNode)
  816. {
  817. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  818. return afterNode;
  819. }
  820. /**
  821. * Adds global CSS style through a `<style>` element in the document's `<head>`
  822. * @param {string} style CSS string
  823. * @param {string} [ref] Reference name that is included in the `<style>`'s ID - defaults to a random number if left undefined
  824. */
  825. function addGlobalStyle(style, ref)
  826. {
  827. if(typeof ref !== "string" || ref.length === 0)
  828. ref = String(Math.floor(Math.random() * 1000));
  829. const styleElem = document.createElement("style");
  830. styleElem.id = `bytm-style-${ref}`;
  831. if(styleElem.styleSheet)
  832. styleElem.styleSheet.cssText = style;
  833. else
  834. styleElem.appendChild(document.createTextNode(style));
  835. document.querySelector("head").appendChild(styleElem);
  836. dbg && console.log(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  837. }
  838. //#SECTION feature config
  839. /**
  840. * Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved
  841. * @returns {Promise<Readonly<FeatureConfig | {}>>}
  842. */
  843. async function loadFeatureConf()
  844. {
  845. const defConf = Object.freeze({...defaultFeatures});
  846. try
  847. {
  848. /** @type {string} */
  849. const featureConf = await GM.getValue("bytm-config"); // eslint-disable-line no-undef
  850. if(!featureConf)
  851. {
  852. await setDefaultFeatConf();
  853. return defConf;
  854. }
  855. return Object.freeze(featureConf ? JSON.parse(featureConf) : {});
  856. }
  857. catch(err)
  858. {
  859. await setDefaultFeatConf();
  860. return defConf;
  861. }
  862. }
  863. /**
  864. * Saves a feature configuration saved persistently
  865. * @param {FeatureConfig} featureConf
  866. * @returns {Promise<void>}
  867. */
  868. function saveFeatureConf(featureConf)
  869. {
  870. if(!featureConf || typeof featureConf != "object")
  871. throw new TypeError("Feature config not provided or invalid");
  872. return GM.setValue("bytm-config", JSON.stringify(featureConf)); // eslint-disable-line no-undef
  873. }
  874. /**
  875. * @returns {Promise<void>}
  876. */
  877. function setDefaultFeatConf()
  878. {
  879. return GM.setValue("bytm-config", JSON.stringify(defaultFeatures)); // eslint-disable-line no-undef
  880. }
  881. init(); // call init() when script is loaded
  882. })();