BetterYTM.user.js 34 KB

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