BetterYTM.user.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @name:de BetterYTM
  4. // @namespace https://github.com/Sv443/BetterYTM#readme
  5. // @version 1.0.0
  6. // @license MIT
  7. // @author Sv443
  8. // @copyright Sv443 <[email protected]> (https://github.com/Sv443)
  9. // @description Improvements for YouTube Music
  10. // @description:de Verbesserungen für YouTube Music
  11. // @match https://music.youtube.com/*
  12. // @match https://www.youtube.com/*
  13. // @icon https://www.google.com/s2/favicons?domain=music.youtube.com
  14. // @run-at document-start
  15. // @grant GM.getValue
  16. // @grant GM.setValue
  17. // @connect self
  18. // @connect youtube.com
  19. // @connect github.com
  20. // @connect githubusercontent.com
  21. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  22. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  23. // ==/UserScript==
  24. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  25. /* C&D this, Susan 🖕 */
  26. (async () => {
  27. "use-strict";
  28. /** Set to true to enable debug mode for more output in the JS console */
  29. const dbg = true;
  30. const defaultFeatures = {
  31. /** Whether arrow keys should skip forwards and backwards by 10 seconds */
  32. arrowKeySupport: true,
  33. /** Whether to remove the "Upgrade" / YT Music Premium tab */
  34. removeUpgradeTab: true,
  35. /** Whether to add a key combination to switch between the YT and YTM sites on a video */
  36. switchBetweenSites: true,
  37. /** Adds a button to the media controls bar to search for the current song's lyrics on genius.com in a new tab */
  38. geniusLyrics: true,
  39. /** Adds a lyrics button to each song in the queue ("up next" tab) */
  40. lyricsButtonsOnSongQueue: true,
  41. /** Makes the volume slider bigger */
  42. bigVolumeSlider: true,
  43. /** The smaller this number, the finer the volume control - YTM's default is 5 */
  44. volumeSliderStep: 2,
  45. /** Set to true to remove the watermark under the YTM logo */
  46. removeWatermark: false,
  47. };
  48. const featureConf = await loadFeatureConf();
  49. console.log("bytm load", featureConf);
  50. // const features = { ...defaultFeatures, ...featureConf };
  51. const features = { ...defaultFeatures };
  52. console.log("bytm save", features);
  53. await saveFeatureConf(features);
  54. //#MARKER types
  55. /** @typedef {"yt"|"ytm"} Domain Constant string representation of which domain this script is currently running on */
  56. //#MARKER init
  57. /** Specifies the hard limit for repetitive tasks */
  58. const triesLimit = 40;
  59. /** Base URL of geniURL */
  60. const geniURLBaseUrl = "https://api.sv443.net/geniurl";
  61. /** GeniURL endpoint that gives song metadata when provided with a `?q` parameter - [more info](https://api.sv443.net/geniurl) */
  62. const geniURLSearchTopUrl = `${geniURLBaseUrl}/search/top`;
  63. const info = Object.freeze({
  64. name: GM.info.script.name, // eslint-disable-line no-undef
  65. version: GM.info.script.version, // eslint-disable-line no-undef
  66. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  67. });
  68. function init()
  69. {
  70. try
  71. {
  72. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  73. console.log(`Powered by lots of ambition and my song metadata API called geniURL: ${geniURLBaseUrl}`);
  74. document.addEventListener("DOMContentLoaded", onDomLoad);
  75. }
  76. catch(err)
  77. {
  78. console.error("BetterYTM - General Error:", err);
  79. }
  80. }
  81. //#MARKER events
  82. /**
  83. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  84. */
  85. async function onDomLoad()
  86. {
  87. const domain = getDomain();
  88. dbg && console.log(`BetterYTM: Initializing features for domain '${domain}'`);
  89. try
  90. {
  91. if(domain === "ytm")
  92. {
  93. if(features.arrowKeySupport)
  94. {
  95. document.addEventListener("keydown", onKeyDown);
  96. dbg && console.log(`BetterYTM: Added key press listener`);
  97. }
  98. if(features.removeUpgradeTab)
  99. removeUpgradeTab();
  100. if(!features.removeWatermark)
  101. addWatermark();
  102. if(features.geniusLyrics)
  103. await addMediaCtrlGeniusBtn();
  104. if(features.lyricsButtonsOnSongQueue)
  105. await addQueueGeniusBtns();
  106. if(features.bigVolumeSlider)
  107. makeVolSliderBig();
  108. setVolumeSliderStep();
  109. }
  110. if(["ytm", "yt"].includes(domain))
  111. {
  112. if(features.switchBetweenSites)
  113. initSiteSwitch(domain);
  114. try
  115. {
  116. addMenu();
  117. }
  118. catch(err)
  119. {
  120. console.error("BetterYTM: Couldn't add menu:", err);
  121. }
  122. }
  123. }
  124. catch(err)
  125. {
  126. console.error(`BetterYTM: General error while executing feature:`, err);
  127. }
  128. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  129. // applyTheme();
  130. }
  131. //#MARKER menu
  132. /**
  133. * Adds an element to open the BetterYTM menu
  134. */
  135. function addMenu()
  136. {
  137. // const domain = getDomain();
  138. // bg & menu
  139. const backgroundElem = document.createElement("div");
  140. backgroundElem.id = "betterytm-menu-bg";
  141. backgroundElem.title = "Click here to close the menu";
  142. backgroundElem.style.visibility = "hidden";
  143. backgroundElem.style.display = "none";
  144. backgroundElem.addEventListener("click", (e) => {
  145. if(e.target.id === "betterytm-menu-bg")
  146. closeMenu();
  147. });
  148. const menuContainer = document.createElement("div");
  149. menuContainer.title = "";
  150. menuContainer.id = "betterytm-menu";
  151. // title
  152. const titleCont = document.createElement("div");
  153. titleCont.id = "betterytm-menu-titlecont";
  154. const titleElem = document.createElement("h2");
  155. titleElem.id = "betterytm-menu-title";
  156. titleElem.innerText = "BetterYTM - Menu";
  157. const linksCont = document.createElement("div");
  158. linksCont.id = "betterytm-menu-linkscont";
  159. const addLink = (imgSrc, href, title) => {
  160. const anchorElem = document.createElement("a");
  161. anchorElem.className = "betterytm-menu-link";
  162. anchorElem.rel = "noopener noreferrer";
  163. anchorElem.target = "_blank";
  164. anchorElem.href = href;
  165. anchorElem.title = title;
  166. const linkElem = document.createElement("img");
  167. linkElem.className = "betterytm-menu-img";
  168. linkElem.src = imgSrc;
  169. anchorElem.appendChild(linkElem);
  170. linksCont.appendChild(anchorElem);
  171. };
  172. addLink("TODO:github.png", info.namespace, `${info.name} on GitHub`);
  173. addLink("TODO:greasyfork.png", "https://greasyfork.org/", `${info.name} on GreasyFork`);
  174. const closeElem = document.createElement("img");
  175. closeElem.id = "betterytm-menu-close";
  176. closeElem.src = "TODO:close.png";
  177. closeElem.title = "Click to close the menu";
  178. closeElem.addEventListener("click", closeMenu);
  179. titleCont.appendChild(titleElem);
  180. titleCont.appendChild(linksCont);
  181. titleCont.appendChild(closeElem);
  182. // TODO: features
  183. const featuresCont = document.createElement("div");
  184. featuresCont.id = "betterytm-menu-opts";
  185. // finalize
  186. menuContainer.appendChild(titleCont);
  187. menuContainer.appendChild(featuresCont);
  188. backgroundElem.appendChild(menuContainer);
  189. document.body.appendChild(backgroundElem);
  190. // add style
  191. const menuStyle = `\
  192. #betterytm-menu-bg {
  193. display: block;
  194. position: fixed;
  195. width: 100vw;
  196. height: 100vh;
  197. top: 0;
  198. left: 0;
  199. z-index: 15;
  200. background-color: rgba(0, 0, 0, 0.6);
  201. }
  202. #betterytm-menu {
  203. display: inline-block;
  204. position: fixed;
  205. width: 50vw;
  206. height: 50vh;
  207. min-height: 500px;
  208. left: 25vw;
  209. top: 25vh;
  210. z-index: 16;
  211. overflow: auto;
  212. padding: 8px;
  213. color: #fff;
  214. background-color: #212121;
  215. }
  216. #betterytm-menu-titlecont {
  217. display: flex;
  218. }
  219. #betterytm-menu-title {
  220. font-size: 20px;
  221. margin-top: 5px;
  222. margin-bottom: 8px;
  223. }
  224. #betterytm-menu-linkscont {
  225. display: flex;
  226. }
  227. .betterytm-menu-link {
  228. display: inline-block;
  229. }
  230. .betterytm-menu-img {
  231. }
  232. #betterytm-menu-close {
  233. cursor: pointer;
  234. }
  235. `;
  236. dbg && console.log("BetterYTM: Added menu elem:", backgroundElem);
  237. /* #DEBUG */ //openMenu();
  238. addGlobalStyle(menuStyle, "menu");
  239. }
  240. function closeMenu()
  241. {
  242. const menuBg = document.querySelector("#betterytm-menu-bg");
  243. menuBg.style.visibility = "hidden";
  244. menuBg.style.display = "none";
  245. }
  246. // function openMenu()
  247. // {
  248. // const menuBg = document.querySelector("#betterytm-menu-bg");
  249. // menuBg.style.visibility = "visible";
  250. // menuBg.style.display = "block";
  251. // }
  252. //#MARKER features
  253. //#SECTION arrow key skip
  254. /**
  255. * Called when the user presses keys
  256. * @param {KeyboardEvent} evt
  257. */
  258. function onKeyDown(evt)
  259. {
  260. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  261. {
  262. // discard the event when a (text) input is currently active, like when editing a playlist
  263. if(["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName))
  264. return dbg && console.info(`BetterYTM: Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  265. dbg && console.log(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  266. // 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
  267. const defaultProps = {
  268. altKey: false,
  269. bubbles: true,
  270. cancelBubble: false,
  271. cancelable: true,
  272. charCode: 0,
  273. composed: true,
  274. ctrlKey: false,
  275. currentTarget: null,
  276. defaultPrevented: evt.defaultPrevented,
  277. explicitOriginalTarget: document.body,
  278. isTrusted: true,
  279. metaKey: false,
  280. originalTarget: document.body,
  281. repeat: false,
  282. shiftKey: false,
  283. srcElement: document.body,
  284. target: document.body,
  285. type: "keydown",
  286. view: window,
  287. };
  288. let invalidKey = false;
  289. let keyProps = {};
  290. switch(evt.code)
  291. {
  292. case "ArrowLeft":
  293. keyProps = {
  294. code: "KeyH",
  295. key: "h",
  296. keyCode: 72,
  297. which: 72,
  298. };
  299. break;
  300. case "ArrowRight":
  301. keyProps = {
  302. code: "KeyL",
  303. key: "l",
  304. keyCode: 76,
  305. which: 76,
  306. };
  307. break;
  308. default:
  309. // console.warn("BetterYTM - Unknown key", evt.code);
  310. invalidKey = true;
  311. break;
  312. }
  313. if(!invalidKey)
  314. {
  315. const proxyProps = { ...defaultProps, ...keyProps };
  316. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  317. dbg && console.log(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  318. }
  319. else if(dbg)
  320. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  321. }
  322. }
  323. //#SECTION site switch
  324. /**
  325. * Initializes the site switch feature
  326. * @param {Domain} domain
  327. */
  328. function initSiteSwitch(domain)
  329. {
  330. // TODO:
  331. // extra features:
  332. // - keep video time
  333. document.addEventListener("keydown", (e) => {
  334. if(e.key == "F9")
  335. switchSite(domain === "yt" ? "ytm" : "yt");
  336. });
  337. dbg && console.log(`BetterYTM: Initialized site switch listener`);
  338. }
  339. /**
  340. * Switches to the other site (between YT and YTM)
  341. * @param {Domain} newDomain
  342. */
  343. function switchSite(newDomain)
  344. {
  345. try
  346. {
  347. let subdomain;
  348. if(newDomain === "ytm")
  349. subdomain = "music";
  350. else if(newDomain === "yt")
  351. subdomain = "www";
  352. if(!subdomain)
  353. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  354. const { pathname, search, hash } = new URL(location.href);
  355. const vt = getVideoTime() ?? 0;
  356. dbg && console.log(`BetterYTM: Found video time of ${vt} seconds`);
  357. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  358. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  359. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  360. location.href = url;
  361. }
  362. catch(err)
  363. {
  364. console.error(`BetterYTM: Error while switching site:`, err);
  365. }
  366. }
  367. //#SECTION remove upgrade tab
  368. let removeUpgradeTries = 0;
  369. /**
  370. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  371. */
  372. function removeUpgradeTab()
  373. {
  374. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  375. if(tabElem)
  376. {
  377. tabElem.remove();
  378. dbg && console.log(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  379. }
  380. else if(removeUpgradeTries < triesLimit)
  381. {
  382. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  383. removeUpgradeTries++;
  384. }
  385. else
  386. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  387. }
  388. //#SECTION add watermark
  389. /**
  390. * Adds a watermark beneath the logo
  391. */
  392. function addWatermark()
  393. {
  394. const watermark = document.createElement("a");
  395. watermark.id = "betterytm-watermark";
  396. watermark.className = "style-scope ytmusic-nav-bar";
  397. watermark.innerText = info.name;
  398. watermark.title = `${info.name} v${info.version}`;
  399. watermark.href = info.namespace;
  400. watermark.target = "_blank";
  401. watermark.rel = "noopener noreferrer";
  402. const style = `\
  403. #betterytm-watermark {
  404. display: inline-block;
  405. position: absolute;
  406. left: 45px;
  407. top: 43px;
  408. z-index: 10;
  409. color: white;
  410. text-decoration: none;
  411. cursor: pointer;
  412. }
  413. @media(max-width: 615px) {
  414. #betterytm-watermark {
  415. display: none;
  416. }
  417. }
  418. #betterytm-watermark:hover {
  419. text-decoration: underline;
  420. }`;
  421. addGlobalStyle(style, "watermark");
  422. const logoElem = document.querySelector("#left-content");
  423. insertAfter(logoElem, watermark);
  424. dbg && console.log(`BetterYTM: Added watermark element:`, watermark);
  425. }
  426. //#SECTION genius.com lyrics button
  427. let mcCurrentSongTitle = "";
  428. let mcLyricsButtonAddTries = 0;
  429. /**
  430. * Adds a genius.com lyrics button to the media controls bar
  431. */
  432. async function addMediaCtrlGeniusBtn()
  433. {
  434. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  435. if(!likeContainer)
  436. {
  437. mcLyricsButtonAddTries++;
  438. if(mcLyricsButtonAddTries < triesLimit)
  439. return setTimeout(addMediaCtrlGeniusBtn, 250); // TODO: improve this
  440. return console.error(`BetterYTM: Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  441. }
  442. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  443. const gUrl = await getCurrentGeniusUrl();
  444. const linkElem = document.createElement("a");
  445. linkElem.id = "betterytm-lyrics-button";
  446. linkElem.className = "ytmusic-player-bar";
  447. linkElem.title = "Search for lyrics on genius.com";
  448. linkElem.href = gUrl;
  449. linkElem.target = "_blank";
  450. linkElem.rel = "noopener noreferrer";
  451. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  452. linkElem.style.display = gUrl ? "initial" : "none";
  453. const style = `\
  454. #betterytm-lyrics-button {
  455. display: inline-flex;
  456. align-items: center;
  457. justify-content: center;
  458. position: relative;
  459. vertical-align: middle;
  460. margin-left: 8px;
  461. width: 40px;
  462. height: 40px;
  463. border-radius: 100%;
  464. background-color: transparent;
  465. }
  466. #betterytm-lyrics-button:hover {
  467. background-color: #383838;
  468. }
  469. #betterytm-lyrics-img {
  470. display: inline-block;
  471. z-index: 10;
  472. width: 24px;
  473. height: 24px;
  474. padding: 5px;
  475. }`;
  476. addGlobalStyle(style, "lyrics");
  477. const imgElem = document.createElement("img");
  478. imgElem.id = "betterytm-lyrics-img";
  479. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  480. linkElem.appendChild(imgElem);
  481. dbg && console.log(`BetterYTM: Inserted genius button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  482. insertAfter(likeContainer, linkElem);
  483. mcCurrentSongTitle = songTitleElem.title;
  484. const onMutation = async (/**@type {MutationRecord[]}*/ mutations) => {
  485. for await(const mut of mutations)
  486. {
  487. const newTitle = mut.target.title;
  488. if(newTitle != mcCurrentSongTitle)
  489. {
  490. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  491. dbg && console.log(`BetterYTM: Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  492. lyricsBtn.style.cursor = "wait";
  493. lyricsBtn.style.pointerEvents = "none";
  494. mcCurrentSongTitle = newTitle;
  495. lyricsBtn.href = await getCurrentGeniusUrl(); // can take a second or two
  496. lyricsBtn.style.cursor = "pointer";
  497. lyricsBtn.style.visibility = "initial";
  498. lyricsBtn.style.display = "initial";
  499. lyricsBtn.style.pointerEvents = "initial";
  500. }
  501. }
  502. };
  503. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  504. const obs = new MutationObserver(onMutation);
  505. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  506. }
  507. /**
  508. * Adds genius lyrics buttons to the song queue
  509. */
  510. async function addQueueGeniusBtns()
  511. {
  512. }
  513. /**
  514. * Returns the genius.com lyrics site URL for the current song
  515. * @returns {Promise<string|null>}
  516. */
  517. async function getCurrentGeniusUrl()
  518. {
  519. try
  520. {
  521. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  522. const isVideo = typeof document.querySelector("ytmusic-player").getAttribute("video-mode_") === "string";
  523. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  524. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  525. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  526. return null;
  527. /** @param {string} songName */
  528. const sanitizeSongName = (songName) => {
  529. const songNameRegex = /\((\w|\d|\s|[.,\-_&/])+\)/gmi;
  530. let sanitized;
  531. if(songName.match(songNameRegex))
  532. sanitized = songName.replace(songNameRegex, ""); // should hopefully trim right after the song name
  533. return (sanitized ?? songName).trim();
  534. };
  535. /** @param {string} songMeta */
  536. const splitArtist = (songMeta) => {
  537. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at bullet (&bull; / •) character
  538. if(songMeta.match(/&/))
  539. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  540. if(songMeta.match(/,/))
  541. songMeta = songMeta.split(/,\s*/gm)[0];
  542. return songMeta.trim();
  543. }
  544. const songNameRaw = songTitleElem.title;
  545. const songName = sanitizeSongName(songNameRaw);
  546. const artistName = splitArtist(songMetaElem.title);
  547. const defQuery = encodeURIComponent(`${artistName} ${songName}`);
  548. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  549. const getGeniusUrlVideo = async () => {
  550. if(!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  551. return await getGeniusUrl(defQuery);
  552. const query = encodeURIComponent(songName.split("-").map(v => v.trim()).join(" "));
  553. return await getGeniusUrl(query);
  554. };
  555. // TODO: artist might need further splitting before comma or ampersand
  556. const url = isVideo ? await getGeniusUrlVideo() : (await getGeniusUrl(defQuery) ?? await getGeniusUrlVideo());
  557. return url;
  558. }
  559. catch(err)
  560. {
  561. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  562. return null;
  563. }
  564. }
  565. /**
  566. * @param {string} query
  567. * @returns {Promise<string|undefined>}
  568. */
  569. async function getGeniusUrl(query)
  570. {
  571. try
  572. {
  573. dbg && console.log(`BetterYTM: Fetching genius URL from geniURL API for query '${query}'`);
  574. const result = await (await fetch(`${geniURLSearchTopUrl}?q=${query}`)).json();
  575. if(result.error)
  576. {
  577. console.error("BetterYTM: Couldn't fetch genius.com URL:", result.message);
  578. return undefined;
  579. }
  580. return result?.url;
  581. }
  582. catch(err)
  583. {
  584. console.error("Couldn't get genius URL due to error:", err);
  585. return undefined;
  586. }
  587. }
  588. // #SECTION volume slider
  589. /**
  590. * Makes the volume slider big
  591. */
  592. function makeVolSliderBig()
  593. {
  594. const style = `\
  595. .volume-slider.ytmusic-player-bar, .expand-volume-slider.ytmusic-player-bar {
  596. width: 200px !important;
  597. }`;
  598. addGlobalStyle(style, "big_vol_slider");
  599. }
  600. /**
  601. * Sets the `step` attribute of the volume slider
  602. */
  603. function setVolumeSliderStep()
  604. {
  605. const sliderElem = document.querySelector("tp-yt-paper-slider#volume-slider");
  606. sliderElem.setAttribute("step", features.volumeSliderStep);
  607. }
  608. //#MARKER other
  609. /**
  610. * Returns the current domain as a constant string representation
  611. * @throws {Error} If script runs on an unexpected website
  612. * @returns {Domain}
  613. */
  614. function getDomain()
  615. {
  616. const { hostname } = new URL(location.href);
  617. if(hostname.includes("music.youtube"))
  618. return "ytm";
  619. else if(hostname.includes("youtube"))
  620. return "yt";
  621. else
  622. throw new Error("BetterYTM is running on an unexpected website");
  623. }
  624. /**
  625. * TODO: this is entirely broken now
  626. * Returns the current video time in seconds
  627. * @returns {number|null} Returns null if the video time is unavailable
  628. */
  629. function getVideoTime()
  630. {
  631. const domain = getDomain();
  632. try
  633. {
  634. if(domain === "ytm")
  635. {
  636. const pbEl = document.querySelector("#progress-bar");
  637. return pbEl.value ?? null;
  638. }
  639. 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
  640. return 0;
  641. return null;
  642. }
  643. catch(err)
  644. {
  645. console.error("BetterYTM: Couldn't get video time due to error:", err);
  646. return null;
  647. }
  648. }
  649. /**
  650. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  651. * @param {HTMLElement} beforeNode
  652. * @param {HTMLElement} afterNode
  653. * @returns {HTMLElement} Returns the `afterNode`
  654. */
  655. function insertAfter(beforeNode, afterNode)
  656. {
  657. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  658. return afterNode;
  659. }
  660. /**
  661. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  662. * @param {string} style CSS string
  663. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  664. */
  665. function addGlobalStyle(style, ref)
  666. {
  667. const styleElem = document.createElement("style");
  668. styleElem.id = `betterytm-${ref}-style`;
  669. if(styleElem.styleSheet)
  670. styleElem.styleSheet.cssText = style;
  671. else
  672. styleElem.appendChild(document.createTextNode(style));
  673. document.querySelector("head").appendChild(styleElem);
  674. dbg && console.log(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  675. }
  676. /**
  677. * Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved
  678. * @returns {Promise<Readonly<typeof defaultFeatures | {}>>}
  679. */
  680. async function loadFeatureConf()
  681. {
  682. /** @type {string} */
  683. const featureConf = await GM.getValue("bytm-featureconf"); // eslint-disable-line no-undef
  684. return Object.freeze(featureConf ? JSON.parse(featureConf) : {});
  685. }
  686. /**
  687. * Saves a feature configuration saved persistently
  688. * @param {typeof defaultFeatures} featureConf
  689. * @returns {Promise<void>}
  690. */
  691. function saveFeatureConf(featureConf)
  692. {
  693. if(!featureConf || typeof featureConf != "object")
  694. throw new TypeError("Feature config not provided or invalid");
  695. return GM.setValue("bytm-featureconf", JSON.stringify(featureConf)); // eslint-disable-line no-undef
  696. }
  697. init(); // call init() when script is loaded
  698. })();