BetterYTM.user.js 33 KB

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