BetterYTM.user.js 34 KB

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