BetterYTM.user.js 31 KB

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