misc.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. import { compress, fetchAdvanced, randomId } from "@sv443-network/userutils";
  2. import { marked } from "marked";
  3. import { branch, compressionFormat, repo } from "../constants";
  4. import { type Domain, type ResourceKey } from "../types";
  5. import { error, type TrLocale, warn } from ".";
  6. import langMapping from "../../assets/locales.json" assert { type: "json" };
  7. //#SECTION misc
  8. /**
  9. * Returns the current domain as a constant string representation
  10. * @throws Throws if script runs on an unexpected website
  11. */
  12. export function getDomain(): Domain {
  13. if(location.hostname.match(/^music\.youtube/))
  14. return "ytm";
  15. else if(location.hostname.match(/youtube\./))
  16. return "yt";
  17. else
  18. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  19. }
  20. /** Returns a pseudo-random ID unique to each session - returns null if sessionStorage is unavailable */
  21. export function getSessionId(): string | null {
  22. try {
  23. let sesId = window.sessionStorage.getItem("_bytm-session-id");
  24. if(!sesId)
  25. window.sessionStorage.setItem("_bytm-session-id", sesId = randomId(8, 36));
  26. return sesId;
  27. }
  28. catch(err) {
  29. warn("Couldn't get session ID, sessionStorage / cookies might be disabled:", err);
  30. return null;
  31. }
  32. }
  33. let isCompressionSupported: boolean | undefined;
  34. /** Tests whether compression via the predefined {@linkcode compressionFormat} is supported */
  35. export async function compressionSupported() {
  36. if(typeof isCompressionSupported === "boolean")
  37. return isCompressionSupported;
  38. try {
  39. await compress(".", compressionFormat, "string");
  40. return isCompressionSupported = true;
  41. }
  42. catch(e) {
  43. return isCompressionSupported = false;
  44. }
  45. }
  46. /** Returns a string with the given array's items separated by a default separator (`", "` by default), with an optional different separator for the last item */
  47. export function arrayWithSeparators<TArray>(array: TArray[], separator = ", ", lastSeparator?: string) {
  48. const arr = [...array];
  49. if(!lastSeparator)
  50. lastSeparator = separator;
  51. if(arr.length === 0)
  52. return "";
  53. else if(arr.length <= 2)
  54. return arr.join(lastSeparator);
  55. else
  56. return `${arr.slice(0, -1).join(separator)}${lastSeparator}${arr.at(-1)!}`;
  57. }
  58. /** Returns the watch ID of the current video or null if not on a video page */
  59. export function getWatchId() {
  60. const { searchParams, pathname } = new URL(location.href);
  61. return pathname.includes("/watch") ? searchParams.get("v") : null;
  62. }
  63. type ThumbQuality = `${"" | "hq" | "mq" | "sd" | "maxres"}default`;
  64. /** Returns the thumbnail URL for a video with the given watch ID and quality (defaults to "hqdefault") */
  65. export function getThumbnailUrl(watchId: string, quality?: ThumbQuality): string
  66. /** Returns the thumbnail URL for a video with the given watch ID and index */
  67. export function getThumbnailUrl(watchId: string, index: 0 | 1 | 2 | 3): string
  68. /** Returns the thumbnail URL for a video with either a given quality identifier or index */
  69. export function getThumbnailUrl(watchId: string, qualityOrIndex: ThumbQuality | 0 | 1 | 2 | 3 = "hqdefault") {
  70. return `https://i.ytimg.com/vi/${watchId}/${qualityOrIndex}.jpg`;
  71. }
  72. /** Returns the best available thumbnail URL for a video with the given watch ID */
  73. export async function getBestThumbnailUrl(watchId: string) {
  74. const priorityList = ["maxresdefault", "sddefault", 0];
  75. for(const quality of priorityList) {
  76. let response: Response | undefined;
  77. const url = getThumbnailUrl(watchId, quality as ThumbQuality);
  78. try {
  79. response = await fetchAdvanced(url, { method: "HEAD", timeout: 5000 });
  80. }
  81. catch(e) {
  82. void e;
  83. }
  84. if(response?.ok)
  85. return url;
  86. }
  87. }
  88. /** Copies a JSON-serializable object */
  89. export function reserialize<T>(data: T): T {
  90. return JSON.parse(JSON.stringify(data));
  91. }
  92. //#SECTION resources
  93. /**
  94. * Returns the URL of a resource by its name, as defined in `assets/resources.json`, from GM resource cache - [see GM.getResourceUrl docs](https://wiki.greasespot.net/GM.getResourceUrl)
  95. * Falls back to a `raw.githubusercontent.com` URL or base64-encoded data URI if the resource is not available in the GM resource cache
  96. */
  97. export async function getResourceUrl(name: ResourceKey | "_") {
  98. let url = await GM.getResourceUrl(name);
  99. if(!url || url.length === 0) {
  100. const resource = GM.info.script.resources?.[name].url;
  101. if(typeof resource === "string") {
  102. const resourceUrl = new URL(resource);
  103. const resourcePath = resourceUrl.pathname;
  104. if(resourcePath)
  105. return `https://raw.githubusercontent.com/${repo}/${branch}${resourcePath}`;
  106. }
  107. warn(`Couldn't get blob URL nor external URL for @resource '${name}', trying to use base64-encoded fallback`);
  108. // @ts-ignore
  109. url = await GM.getResourceUrl(name, false);
  110. }
  111. return url;
  112. }
  113. /**
  114. * Returns the preferred locale of the user, provided it is supported by the userscript.
  115. * Prioritizes `navigator.language`, then `navigator.languages`, then `"en_US"` as a fallback.
  116. */
  117. export function getPreferredLocale(): TrLocale {
  118. const navLang = navigator.language.replace(/-/g, "_");
  119. const navLangs = navigator.languages
  120. .filter(lang => lang.match(/^[a-z]{2}(-|_)[A-Z]$/) !== null)
  121. .map(lang => lang.replace(/-/g, "_"));
  122. if(Object.entries(langMapping).find(([key]) => key === navLang))
  123. return navLang as TrLocale;
  124. for(const loc of navLangs) {
  125. if(Object.entries(langMapping).find(([key]) => key === loc))
  126. return loc as TrLocale;
  127. }
  128. // if navigator.languages has entries that aren't locale codes in the format xx_XX
  129. if(navigator.languages.some(lang => lang.match(/^[a-z]{2}$/))) {
  130. for(const lang of navLangs) {
  131. const foundLoc = Object.entries(langMapping).find(([key]) => key.startsWith(lang))?.[0];
  132. if(foundLoc)
  133. return foundLoc as TrLocale;
  134. }
  135. }
  136. return "en_US";
  137. }
  138. /** Returns the content behind the passed resource identifier to be assigned to an element's innerHTML property */
  139. export async function resourceToHTMLString(resource: ResourceKey) {
  140. try {
  141. const resourceUrl = await getResourceUrl(resource);
  142. if(!resourceUrl)
  143. throw new Error(`Couldn't find URL for resource '${resource}'`);
  144. return await (await fetchAdvanced(resourceUrl)).text();
  145. }
  146. catch(err) {
  147. error("Couldn't get SVG element from resource:", err);
  148. return null;
  149. }
  150. }
  151. /** Parses a markdown string using marked and turns it into an HTML string with default settings - doesn't sanitize against XSS! */
  152. export function parseMarkdown(mdString: string) {
  153. return marked.parse(mdString, {
  154. async: true,
  155. gfm: true,
  156. });
  157. }
  158. /** Returns the content of the changelog markdown file */
  159. export async function getChangelogMd() {
  160. return await (await fetchAdvanced(await getResourceUrl("doc-changelog"))).text();
  161. }
  162. /** Returns the changelog as HTML with a details element for each version */
  163. export async function getChangelogHtmlWithDetails() {
  164. try {
  165. const changelogMd = await getChangelogMd();
  166. let changelogHtml = await parseMarkdown(changelogMd);
  167. const getVerId = (verStr: string) => verStr.trim().replace(/[._#\s-]/g, "");
  168. changelogHtml = changelogHtml.replace(/<div\s+class="split">\s*<\/div>\s*\n?\s*<br(\s\/)?>/gm, "</details>\n<br>\n<details class=\"bytm-changelog-version-details\">");
  169. const h2Matches = Array.from(changelogHtml.matchAll(/<h2(\s+id=".+")?>([\d\w\s.]+)<\/h2>/gm));
  170. for(const match of h2Matches) {
  171. const [fullMatch, , verStr] = match;
  172. const verId = getVerId(verStr);
  173. const h2Elem = `<h2 id="${verId}" role="subheading" aria-level="1">Version ${verStr}</h2>`;
  174. const summaryElem = `<summary tab-index="0">${h2Elem}</summary>`;
  175. changelogHtml = changelogHtml.replace(fullMatch, `${summaryElem}`);
  176. }
  177. changelogHtml = `<details class="bytm-changelog-version-details">${changelogHtml}</details>`;
  178. return changelogHtml;
  179. }
  180. catch(err) {
  181. return `Error while preparing changelog: ${err}`;
  182. }
  183. }