BetterYTM.user.js 34 KB

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