BetterYTM.user.js 33 KB

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