BetterYTM.user.js 24 KB

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