BetterYTM.user.js 26 KB

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