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 = 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 parensRegex = /\(.+\)/gmi;
  732. const squareParensRegex = /\[.+\]/gmi;
  733. // trim right after the song name:
  734. let sanitized = songName
  735. .replace(parensRegex, "")
  736. .replace(squareParensRegex, "");
  737. return sanitized.trim();
  738. };
  739. /** @param {string} songMeta */
  740. const splitArtist = (songMeta) => {
  741. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at bullet (&bull; / •) character
  742. if(songMeta.match(/&/))
  743. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  744. if(songMeta.match(/,/))
  745. songMeta = songMeta.split(/,\s*/gm)[0];
  746. return songMeta.trim();
  747. }
  748. const songNameRaw = songTitleElem.title;
  749. const songName = sanitizeSongName(songNameRaw);
  750. const artistName = splitArtist(songMetaElem.title);
  751. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  752. const getGeniusUrlVideo = async () => {
  753. if(!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  754. return await getGeniusUrl(artistName, songName);
  755. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  756. return await getGeniusUrl(artist, rest.join(" "));
  757. };
  758. // TODO: artist might need further splitting before comma or ampersand
  759. const url = isVideo ? await getGeniusUrlVideo() : (await getGeniusUrl(artistName, songName) ?? await getGeniusUrlVideo());
  760. return url;
  761. }
  762. catch(err)
  763. {
  764. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  765. return null;
  766. }
  767. }
  768. /**
  769. * @param {string} artist
  770. * @param {string} song
  771. * @returns {Promise<string|undefined>}
  772. */
  773. async function getGeniusUrl(artist, song)
  774. {
  775. try
  776. {
  777. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}`;
  778. dbg && console.log(`BetterYTM: Requesting URL from geniURL at '${fetchUrl}'`);
  779. const result = await (await fetch(fetchUrl)).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. })();