utils.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. import { branch, scriptInfo } from "./constants";
  2. import type { Domain, LogLevel } from "./types";
  3. //#SECTION logging
  4. let curLogLevel: LogLevel = 1;
  5. /** Sets the current log level. 0 = Debug, 1 = Info */
  6. export function setLogLevel(level: LogLevel) {
  7. curLogLevel = level;
  8. }
  9. /** Extracts the log level from the last item from spread arguments - returns 1 if the last item is not a number or too low or high */
  10. function getLogLevel(args: unknown[]): number {
  11. const minLogLvl = 0, maxLogLvl = 1;
  12. if(typeof args.at(-1) === "number")
  13. return clamp(
  14. args.splice(args.length - 1)[0] as number,
  15. minLogLvl,
  16. maxLogLvl,
  17. );
  18. return 0;
  19. }
  20. /** Common prefix to be able to tell logged messages apart and filter them in devtools */
  21. const consPrefix = `[${scriptInfo.name}]`;
  22. const consPrefixDbg = `[${scriptInfo.name}/#DEBUG]`;
  23. /**
  24. * Logs string-compatible values to the console, as long as the log level is sufficient.
  25. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if they shouldn't be.
  26. */
  27. export function log(...args: unknown[]): void {
  28. if(curLogLevel <= getLogLevel(args))
  29. console.log(consPrefix, ...args);
  30. }
  31. /**
  32. * Logs string-compatible values to the console as info, as long as the log level is sufficient.
  33. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if they shouldn't be.
  34. */
  35. export function info(...args: unknown[]): void {
  36. if(curLogLevel <= getLogLevel(args))
  37. console.info(consPrefix, ...args);
  38. }
  39. /**
  40. * Logs string-compatible values to the console as a warning, as long as the log level is sufficient.
  41. * @param args Last parameter is log level (0 = Debug, 1/undefined = Info) - any number as the last parameter will be stripped out! Convert to string if they shouldn't be.
  42. */
  43. export function warn(...args: unknown[]): void {
  44. if(curLogLevel <= getLogLevel(args))
  45. console.warn(consPrefix, ...args);
  46. }
  47. /** Logs string-compatible values to the console as an error, no matter the log level. */
  48. export function error(...args: unknown[]): void {
  49. console.error(consPrefix, ...args);
  50. }
  51. /** Logs string-compatible values to the console, intended for debugging only */
  52. export function dbg(...args: unknown[]): void {
  53. console.log(consPrefixDbg, ...args);
  54. }
  55. //#SECTION video time
  56. /**
  57. * Returns the current video time in seconds
  58. * Dispatches mouse movement events in case the video time can't be estimated
  59. * @returns Returns null if the video time is unavailable
  60. */
  61. export function getVideoTime() {
  62. return new Promise<number | null>((res) => {
  63. const domain = getDomain();
  64. try {
  65. if(domain === "ytm") {
  66. const pbEl = document.querySelector("#progress-bar") as HTMLProgressElement;
  67. return res(!isNaN(Number(pbEl.value)) ? Number(pbEl.value) : null);
  68. }
  69. else if(domain === "yt") {
  70. // YT doesn't update the progress bar when it's hidden (contrary to YTM which never hides it)
  71. ytForceShowVideoTime();
  72. const pbSelector = ".ytp-chrome-bottom div.ytp-progress-bar[role=\"slider\"]";
  73. const progElem = document.querySelector<HTMLProgressElement>(pbSelector);
  74. let videoTime = progElem ? Number(progElem.getAttribute("aria-valuenow")!) : -1;
  75. const mut = new MutationObserver(() => {
  76. // .observe() is only called when the element exists - no need to check for null
  77. videoTime = Number(document.querySelector<HTMLProgressElement>(pbSelector)!.getAttribute("aria-valuenow")!);
  78. });
  79. const observe = (progElem: HTMLElement) => {
  80. mut.observe(progElem, {
  81. attributes: true,
  82. attributeFilter: ["aria-valuenow"],
  83. });
  84. setTimeout(() => {
  85. res(videoTime >= 0 && !isNaN(videoTime) ? videoTime : null);
  86. }, 500);
  87. };
  88. if(!progElem)
  89. return onSelectorExists(pbSelector, observe);
  90. else
  91. return observe(progElem);
  92. // Possible solution:
  93. // - Use MutationObserver to detect when attributes of progress bar (selector `div.ytp-progress-bar[role="slider"]`) change
  94. // - Wait until the attribute increments, then save the value of `aria-valuenow` and the current system time to memory
  95. // - When site switch hotkey is pressed, take saved `aria-valuenow` value and add the difference between saved system time and current system time
  96. // - If no value is present, use the script from `dev/ytForceShowVideoTime.js` to simulate mouse movement to force the element to update
  97. // - Subtract one or two seconds to make up for rounding errors
  98. // - profit
  99. // if(!ytCurrentVideoTime) {
  100. // ytForceShowVideoTime();
  101. // const videoTime = document.querySelector("#TODO")?.getAttribute("aria-valuenow") ?? null;
  102. // }
  103. }
  104. }
  105. catch(err) {
  106. error("Couldn't get video time due to error:", err);
  107. res(null);
  108. }
  109. });
  110. }
  111. /**
  112. * Sends events that force the video controls to become visible for about 3 seconds.
  113. * This only works once, then the page needs to be reloaded!
  114. */
  115. function ytForceShowVideoTime() {
  116. const player = document.querySelector("#movie_player");
  117. if(!player)
  118. return false;
  119. const defaultProps = {
  120. // needed because otherwise YTM errors out - see https://github.com/Sv443/BetterYTM/issues/18#show_issue
  121. view: getUnsafeWindow(),
  122. bubbles: true,
  123. cancelable: false,
  124. };
  125. player.dispatchEvent(new MouseEvent("mouseenter", defaultProps));
  126. const { x, y, width, height } = player.getBoundingClientRect();
  127. const screenY = Math.round(y + height / 2);
  128. const screenX = x + Math.min(50, Math.round(width / 3));
  129. player.dispatchEvent(new MouseEvent("mousemove", {
  130. ...defaultProps,
  131. screenY,
  132. screenX,
  133. movementX: 5,
  134. movementY: 0,
  135. }));
  136. return true;
  137. }
  138. // /** Parses a video time string in the format `[hh:m]m:ss` to the equivalent number of seconds - returns 0 if input couldn't be parsed */
  139. // function parseVideoTime(videoTime: string) {
  140. // const matches = /^((\d{1,2}):)?(\d{1,2}):(\d{2})$/.exec(videoTime);
  141. // if(!matches)
  142. // return 0;
  143. // const [, , hrs, min, sec] = matches as unknown as [string, string | undefined, string | undefined, string, string];
  144. // let finalTime = 0;
  145. // if(hrs)
  146. // finalTime += Number(hrs) * 60 * 60;
  147. // finalTime += Number(min) * 60 + Number(sec);
  148. // return isNaN(finalTime) ? 0 : finalTime;
  149. // }
  150. //#SECTION DOM
  151. /**
  152. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  153. * @returns Returns the `afterNode`
  154. */
  155. export function insertAfter(beforeNode: HTMLElement, afterNode: HTMLElement) {
  156. beforeNode.parentNode?.insertBefore(afterNode, beforeNode.nextSibling);
  157. return afterNode;
  158. }
  159. /** Adds a parent container around the provided element - returns the new parent node */
  160. export function addParent(element: HTMLElement, newParent: HTMLElement) {
  161. const oldParent = element.parentNode;
  162. if(!oldParent)
  163. throw new Error("Element doesn't have a parent node");
  164. oldParent.replaceChild(newParent, element);
  165. newParent.appendChild(element);
  166. return newParent;
  167. }
  168. /**
  169. * Adds global CSS style through a `<style>` element in the document's `<head>`
  170. * @param style CSS string
  171. * @param ref Reference name that is included in the `<style>`'s ID - prefixed with `betterytm-style-` - defaults to a random number if left undefined
  172. */
  173. export function addGlobalStyle(style: string, ref?: string) {
  174. if(typeof ref !== "string" || ref.length === 0)
  175. ref = String(Math.floor(Math.random() * 10_000));
  176. const styleElem = document.createElement("style");
  177. styleElem.id = `betterytm-style-${ref}`;
  178. styleElem.innerHTML = style;
  179. document.head.appendChild(styleElem);
  180. log(`Inserted global style with ref '${ref}':`, styleElem);
  181. }
  182. const selectorExistsMap = new Map<string, Array<(element: HTMLElement) => void>>();
  183. /**
  184. * Calls the `listener` as soon as the `selector` exists in the DOM.
  185. * Listeners are deleted as soon as they are called once.
  186. * Multiple listeners with the same selector may be registered.
  187. */
  188. export function onSelectorExists(selector: string, listener: (element: HTMLElement) => void) {
  189. const el = document.querySelector<HTMLElement>(selector);
  190. if(el)
  191. listener(el);
  192. else {
  193. if(selectorExistsMap.get(selector))
  194. selectorExistsMap.set(selector, [...selectorExistsMap.get(selector)!, listener]);
  195. else
  196. selectorExistsMap.set(selector, [listener]);
  197. }
  198. }
  199. /** Initializes the MutationObserver responsible for checking selectors registered in `onSelectorExists()` */
  200. export function initSelectorExistsCheck() {
  201. const observer = new MutationObserver(() => {
  202. for(const [selector, listeners] of selectorExistsMap.entries()) {
  203. const el = document.querySelector<HTMLElement>(selector);
  204. if(el) {
  205. listeners.forEach(listener => listener(el));
  206. selectorExistsMap.delete(selector);
  207. }
  208. }
  209. });
  210. observer.observe(document.body, {
  211. subtree: true,
  212. childList: true,
  213. });
  214. log("Initialized \"selector exists\" MutationObserver");
  215. }
  216. /** Preloads an array of image URLs so they can be loaded instantly from cache later on */
  217. export function precacheImages(srcUrls: string[], rejects = false) {
  218. const promises = srcUrls.map(src => new Promise((res, rej) => {
  219. const image = new Image();
  220. image.src = src;
  221. image.addEventListener("load", () => res(image));
  222. image.addEventListener("error", () => rejects && rej(`Failed to preload image with URL '${src}'`));
  223. }));
  224. return Promise.allSettled(promises);
  225. }
  226. //#SECTION misc
  227. type FetchOpts = RequestInit & {
  228. timeout: number;
  229. };
  230. /** Calls the fetch API with special options */
  231. export async function fetchAdvanced(url: string, options: Partial<FetchOpts> = {}) {
  232. const { timeout = 10000 } = options;
  233. const controller = new AbortController();
  234. const id = setTimeout(() => controller.abort(), timeout);
  235. const res = await fetch(url, {
  236. ...options,
  237. signal: controller.signal,
  238. });
  239. clearTimeout(id);
  240. return res;
  241. }
  242. /**
  243. * Creates an invisible anchor with _blank target and clicks it.
  244. * This has to be run in relatively quick succession to a user interaction event, else the browser rejects it.
  245. */
  246. export function openInNewTab(href: string) {
  247. try {
  248. const openElem = document.createElement("a");
  249. Object.assign(openElem, {
  250. className: "betterytm-open-in-new-tab",
  251. target: "_blank",
  252. rel: "noopener noreferrer",
  253. href,
  254. });
  255. openElem.style.visibility = "hidden";
  256. document.body.appendChild(openElem);
  257. openElem.click();
  258. // timeout just to be safe
  259. setTimeout(() => openElem.remove(), 200);
  260. }
  261. catch(err) {
  262. error("Couldn't open URL in a new tab due to an error:", err);
  263. }
  264. }
  265. /**
  266. * Returns `unsafeWindow` if it is available, otherwise falls back to just `window`
  267. * unsafeWindow is sometimes needed because otherwise YTM errors out - see [this issue](https://github.com/Sv443/BetterYTM/issues/18#show_issue)
  268. */
  269. export function getUnsafeWindow() {
  270. try {
  271. // throws ReferenceError if the "@grant unsafeWindow" isn't present
  272. return unsafeWindow;
  273. }
  274. catch(e) {
  275. return window;
  276. }
  277. }
  278. /**
  279. * Returns the current domain as a constant string representation
  280. * @throws Throws if script runs on an unexpected website
  281. */
  282. export function getDomain(): Domain {
  283. const { hostname } = new URL(location.href);
  284. if(hostname.includes("music.youtube"))
  285. return "ytm";
  286. else if(hostname.includes("youtube"))
  287. return "yt";
  288. else
  289. throw new Error("BetterYTM is running on an unexpected website. Please don't tamper with the @match directives in the userscript header.");
  290. }
  291. /** Returns the URL of the asset hosted on GitHub at the specified relative `path` (starting at `ROOT/assets/`) */
  292. export function getAssetUrl(path: string) {
  293. return `https://raw.githubusercontent.com/Sv443/BetterYTM/${branch}/assets/${path}`;
  294. }
  295. /**
  296. * Automatically appends an `s` to the passed `word`, if `num` is not equal to 1
  297. * @param word A word in singular form, to auto-convert to plural
  298. * @param num If this is an array, the amount of items is used
  299. */
  300. export function autoPlural(word: string, num: number | unknown[]) {
  301. if(Array.isArray(num))
  302. num = num.length;
  303. return `${word}${num === 1 ? "" : "s"}`;
  304. }
  305. /** Ensures the passed `value` always stays between `min` and `max` */
  306. export function clamp(value: number, min: number, max: number) {
  307. return Math.max(Math.min(value, max), min);
  308. }
  309. /** Pauses async execution for the specified time in ms */
  310. export function pauseFor(time: number) {
  311. return new Promise((res) => {
  312. setTimeout(res, time);
  313. });
  314. }