lyrics.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import { triesInterval, triesLimit } from "../constants";
  2. import { clamp, error, getAssetUrl, info, insertAfter, log } from "../utils";
  3. /** Base URL of geniURL */
  4. export const geniUrlBase = "https://api.sv443.net/geniurl";
  5. /** GeniURL endpoint that gives song metadata when provided with a `?q` or `?artist` and `?song` parameter - [more info](https://api.sv443.net/geniurl) */
  6. const geniURLSearchTopUrl = `${geniUrlBase}/search/top`;
  7. /**
  8. * The threshold to pass to geniURL's fuzzy filtering.
  9. * The lower the number, the more strictly the top results will adhere to the query.
  10. * Set to undefined to use the default.
  11. */
  12. const threshold = 0.55;
  13. const thresholdParam = threshold ? `&threshold=${clamp(threshold, 0, 1)}` : "";
  14. //#MARKER cache
  15. /** Cache with key format `ARTIST - SONG` (sanitized) and lyrics URLs as values. Used to prevent extraneous requests to geniURL. */
  16. const lyricsUrlCache = new Map<string, string>();
  17. /** How many cache entries can exist at a time - this is used to cap memory usage */
  18. const maxLyricsCacheSize = 100;
  19. // TODO: implement this
  20. /**
  21. * Returns the lyrics URL from the passed un-/sanitized artist and song name, or undefined if the entry doesn't exist yet.
  22. * **The passed parameters need to be sanitized first!**
  23. */
  24. export function getLyricsCacheEntry(artists: string, song: string) {
  25. return lyricsUrlCache.get(`${artists} - ${song}`);
  26. }
  27. /** Adds the provided entry into the lyrics URL cache */
  28. export function addLyricsCacheEntry(artists: string, song: string, lyricsUrl: string) {
  29. lyricsUrlCache.set(`${sanitizeArtists(artists)} - ${sanitizeSong(song)}`, lyricsUrl);
  30. // delete oldest entry if cache gets too big
  31. if(lyricsUrlCache.size > maxLyricsCacheSize)
  32. lyricsUrlCache.delete([...lyricsUrlCache.keys()].at(-1)!);
  33. }
  34. //#MARKER media control bar
  35. let mcCurrentSongTitle = "";
  36. let mcLyricsButtonAddTries = 0;
  37. /** Adds a lyrics button to the media controls bar */
  38. export function addMediaCtrlLyricsBtn(): void {
  39. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer") as HTMLElement;
  40. if(!likeContainer) {
  41. mcLyricsButtonAddTries++;
  42. if(mcLyricsButtonAddTries < triesLimit) {
  43. setTimeout(addMediaCtrlLyricsBtn, triesInterval); // TODO: improve this
  44. return;
  45. }
  46. return error(`Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  47. }
  48. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string") as HTMLDivElement;
  49. // run parallel without awaiting so the MutationObserver below can observe the title element in time
  50. (async () => {
  51. const gUrl = await getCurrentLyricsUrl();
  52. const linkElem = createLyricsBtn(gUrl ?? undefined);
  53. linkElem.id = "betterytm-lyrics-button";
  54. log(`Inserted lyrics button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  55. insertAfter(likeContainer, linkElem);
  56. })();
  57. mcCurrentSongTitle = songTitleElem.title;
  58. const onMutation = async (mutations: MutationRecord[]) => {
  59. for await(const mut of mutations) {
  60. const newTitle = (mut.target as HTMLElement).title;
  61. if(newTitle !== mcCurrentSongTitle && newTitle.length > 0) {
  62. const lyricsBtn = document.querySelector("#betterytm-lyrics-button") as HTMLAnchorElement;
  63. if(!lyricsBtn)
  64. return;
  65. log(`Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  66. lyricsBtn.style.cursor = "wait";
  67. lyricsBtn.style.pointerEvents = "none";
  68. mcCurrentSongTitle = newTitle;
  69. const url = await getCurrentLyricsUrl(); // can take a second or two
  70. if(!url)
  71. continue;
  72. lyricsBtn.href = url;
  73. lyricsBtn.title = "Open the current song's lyrics in a new tab";
  74. lyricsBtn.style.cursor = "pointer";
  75. lyricsBtn.style.visibility = "initial";
  76. lyricsBtn.style.display = "inline-flex";
  77. lyricsBtn.style.pointerEvents = "initial";
  78. }
  79. }
  80. };
  81. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used to watch for changes in the video title
  82. const obs = new MutationObserver(onMutation);
  83. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  84. }
  85. //#MARKER utils
  86. /** Removes everything in parentheses from the passed song name */
  87. export function sanitizeSong(songName: string) {
  88. const parensRegex = /\(.+\)/gmi;
  89. const squareParensRegex = /\[.+\]/gmi;
  90. // trim right after the song name:
  91. const sanitized = songName
  92. .replace(parensRegex, "")
  93. .replace(squareParensRegex, "");
  94. return sanitized.trim();
  95. }
  96. /** Removes the secondary artist (if it exists) from the passed artists string */
  97. export function sanitizeArtists(artists: string) {
  98. artists = artists.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; [•] character
  99. if(artists.match(/&/))
  100. artists = artists.split(/\s*&\s*/gm)[0];
  101. if(artists.match(/,/))
  102. artists = artists.split(/,\s*/gm)[0];
  103. return artists.trim();
  104. }
  105. /** Returns the lyrics URL from genius for the currently selected song */
  106. export async function getCurrentLyricsUrl() {
  107. try {
  108. // In videos the video title contains both artist and song title, in "regular" YTM songs, the video title only contains the song title
  109. const isVideo = typeof document.querySelector("ytmusic-player")?.getAttribute("video-mode_") === "string";
  110. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string") as HTMLElement;
  111. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child") as HTMLElement;
  112. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  113. return null;
  114. const songNameRaw = songTitleElem.title;
  115. const songName = sanitizeSong(songNameRaw);
  116. const artistName = sanitizeArtists(songMetaElem.title);
  117. /** Use when the current song is not a "real YTM song" with a static background, but rather a music video */
  118. const getGeniusUrlVideo = async () => {
  119. if(!songName.includes("-")) // for some fucking reason some music videos have YTM-like song title and artist separation, some don't
  120. return await getGeniusUrl(artistName, songName);
  121. const [artist, ...rest] = songName.split("-").map(v => v.trim());
  122. return await getGeniusUrl(artist, rest.join(" "));
  123. };
  124. // TODO: artist might need further splitting before comma or ampersand
  125. const url = isVideo ? await getGeniusUrlVideo() : (await getGeniusUrl(artistName, songName) ?? await getGeniusUrlVideo());
  126. return url;
  127. }
  128. catch(err) {
  129. error("Couldn't resolve lyrics URL:", err);
  130. return null;
  131. }
  132. }
  133. /** Fetches the actual lyrics URL from geniURL - **the passed parameters need to be sanitized first!** */
  134. export async function getGeniusUrl(artist: string, song: string): Promise<string | undefined> {
  135. try {
  136. const cacheEntry = getLyricsCacheEntry(artist, song);
  137. if(cacheEntry) {
  138. info(`Found lyrics URL in cache: ${cacheEntry}`);
  139. return cacheEntry;
  140. }
  141. const startTs = Date.now();
  142. const fetchUrl = `${geniURLSearchTopUrl}?artist=${encodeURIComponent(artist)}&song=${encodeURIComponent(song)}${thresholdParam}`;
  143. log(`Requesting URL from geniURL at '${fetchUrl}'`);
  144. const result = await (await fetch(fetchUrl)).json();
  145. if(typeof result === "object" && result.error) {
  146. error("Couldn't fetch lyrics URL:", result.message);
  147. return undefined;
  148. }
  149. const url = result.url;
  150. info(`Found lyrics URL (after ${Date.now() - startTs}ms): ${url}`);
  151. addLyricsCacheEntry(artist, song, url);
  152. return url;
  153. }
  154. catch(err) {
  155. error("Couldn't get lyrics URL due to error:", err);
  156. return undefined;
  157. }
  158. }
  159. /** Creates the base lyrics button element */
  160. export function createLyricsBtn(geniusUrl?: string, hideIfLoading = true): HTMLAnchorElement {
  161. const linkElem = document.createElement("a");
  162. linkElem.className = "ytmusic-player-bar bytm-generic-btn";
  163. linkElem.title = geniusUrl ? "Click to open this song's lyrics in a new tab" : "Loading lyrics URL...";
  164. if(geniusUrl)
  165. linkElem.href = geniusUrl;
  166. linkElem.role = "button";
  167. linkElem.target = "_blank";
  168. linkElem.rel = "noopener noreferrer";
  169. linkElem.style.visibility = hideIfLoading && geniusUrl ? "initial" : "hidden";
  170. linkElem.style.display = hideIfLoading && geniusUrl ? "inline-flex" : "none";
  171. const imgElem = document.createElement("img");
  172. imgElem.className = "bytm-generic-btn-img";
  173. imgElem.src = getAssetUrl("external/genius.png");
  174. linkElem.appendChild(imgElem);
  175. return linkElem;
  176. }