BetterYTM.user.js 26 KB

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