interface.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import * as UserUtils from "@sv443-network/userutils";
  2. import { createNanoEvents } from "nanoevents";
  3. import { mode, branch, host, buildNumber, compressionFormat, scriptInfo } from "./constants";
  4. import { getResourceUrl, getSessionId, getVideoTime, log, setLocale, getLocale, hasKey, hasKeyFor, NanoEmitter, t, tp, type TrLocale, info, error, onInteraction, getThumbnailUrl, getBestThumbnailUrl } from "./utils";
  5. import { addSelectorListener } from "./observers";
  6. import { getFeatures, setFeatures } from "./config";
  7. import { compareVersionArrays, compareVersions, featInfo, fetchLyricsUrlTop, getLyricsCacheEntry, sanitizeArtists, sanitizeSong, type LyricsCache } from "./features";
  8. import { allSiteEvents, type SiteEventsMap } from "./siteEvents";
  9. import { LogLevel, type FeatureConfig, type FeatureInfo, type LyricsCacheEntry, type PluginDef, type PluginInfo, type PluginRegisterResult, type PluginDefResolvable, type PluginEventMap, type PluginItem, type BytmObject } from "./types";
  10. import { BytmDialog, createCircularBtn, createHotkeyInput, createToggleInput } from "./components";
  11. const { getUnsafeWindow, randomId } = UserUtils;
  12. //#region interface globals
  13. /** All events that can be emitted on the BYTM interface and the data they provide */
  14. export type InterfaceEventsMap = {
  15. [K in keyof InterfaceEvents]: (data: InterfaceEvents[K]) => void;
  16. };
  17. /** All events that can be emitted on the BYTM interface and the data they provide */
  18. export type InterfaceEvents = {
  19. /** Emitted whenever the plugins should be registered using `unsafeWindow.BYTM.registerPlugin()` */
  20. "bytm:initPlugins": undefined;
  21. /** Emitted whenever all plugins have been loaded */
  22. "bytm:pluginsRegistered": undefined;
  23. /** Emitted when BYTM has finished initializing all features */
  24. "bytm:ready": undefined;
  25. /** Emitted when a fatal error occurs and the script can't continue to run. Returns a short error description (not really meant to be displayed to the user). */
  26. "bytm:fatalError": string;
  27. /**
  28. * Emitted whenever the SelectorObserver instances have been initialized
  29. * Use `unsafeWindow.BYTM.addObserverListener()` to add custom listener functions to the observers
  30. */
  31. "bytm:observersReady": undefined;
  32. /** Emitted as soon as the feature config has finished loading and can be accessed via `unsafeWindow.BYTM.getFeatures(token)` */
  33. "bytm:configReady": undefined;
  34. /** Emitted whenever the locale is changed */
  35. "bytm:setLocale": { locale: TrLocale };
  36. /** Emitted when a dialog was opened - returns the dialog's instance */
  37. "bytm:dialogOpened": BytmDialog;
  38. /** Emitted when the dialog with the specified ID was opened - returns the dialog's instance - in TS, use `"bytm:dialogOpened:myIdWhatever" as "bytm:dialogOpened:id"` to make the error go away */
  39. "bytm:dialogOpened:id": BytmDialog;
  40. /** Emitted whenever the lyrics URL for a song is loaded */
  41. "bytm:lyricsLoaded": { type: "current" | "queue", artists: string, title: string, url: string };
  42. /** Emitted when the lyrics cache has been loaded */
  43. "bytm:lyricsCacheReady": LyricsCache;
  44. /** Emitted when the lyrics cache has been cleared */
  45. "bytm:lyricsCacheCleared": undefined;
  46. /** Emitted when an entry is added to the lyrics cache - "penalized" entries get removed from cache faster because they were less related in lyrics lookups, opposite to the "best" entries */
  47. "bytm:lyricsCacheEntryAdded": { type: "best" | "penalized", entry: LyricsCacheEntry };
  48. // additionally all events from SiteEventsMap in `src/siteEvents.ts`
  49. // are emitted in this format: "bytm:siteEvent:nameOfSiteEvent"
  50. };
  51. export const allInterfaceEvents = [
  52. "bytm:initPlugins",
  53. "bytm:pluginsRegistered",
  54. "bytm:ready",
  55. "bytm:fatalError",
  56. "bytm:observersReady",
  57. "bytm:configReady",
  58. "bytm:setLocale",
  59. "bytm:dialogOpened",
  60. "bytm:dialogOpened:id",
  61. "bytm:lyricsLoaded",
  62. "bytm:lyricsCacheReady",
  63. "bytm:lyricsCacheCleared",
  64. "bytm:lyricsCacheEntryAdded",
  65. ...allSiteEvents.map(e => `bytm:siteEvent:${e}`),
  66. ] as const;
  67. /** All functions that can be called on the BYTM interface using `unsafeWindow.BYTM.functionName();` (or `const { functionName } = unsafeWindow.BYTM;`) */
  68. const globalFuncs = {
  69. // meta
  70. registerPlugin,
  71. getPluginInfo,
  72. // utils
  73. addSelectorListener,
  74. getResourceUrl,
  75. getSessionId,
  76. getVideoTime,
  77. setLocale: setLocaleInterface,
  78. getLocale,
  79. hasKey,
  80. hasKeyFor,
  81. t,
  82. tp,
  83. getFeatures: getFeaturesInterface,
  84. saveFeatures: saveFeaturesInterface,
  85. fetchLyricsUrlTop,
  86. getLyricsCacheEntry,
  87. sanitizeArtists,
  88. sanitizeSong,
  89. compareVersions,
  90. compareVersionArrays,
  91. onInteraction,
  92. getThumbnailUrl,
  93. getBestThumbnailUrl,
  94. };
  95. /** Initializes the BYTM interface */
  96. export function initInterface() {
  97. const props = {
  98. mode,
  99. branch,
  100. host,
  101. buildNumber,
  102. compressionFormat,
  103. ...scriptInfo,
  104. ...globalFuncs,
  105. UserUtils,
  106. NanoEmitter,
  107. BytmDialog,
  108. createHotkeyInput,
  109. createToggleInput,
  110. createCircularBtn,
  111. };
  112. for(const [key, value] of Object.entries(props))
  113. setGlobalProp(key, value);
  114. log("Initialized BYTM interface");
  115. }
  116. /** Sets a global property on the unsafeWindow.BYTM object */
  117. export function setGlobalProp<
  118. TKey extends keyof Window["BYTM"],
  119. TValue = Window["BYTM"][TKey],
  120. >(
  121. key: TKey | (string & {}),
  122. value: TValue,
  123. ) {
  124. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  125. const win = getUnsafeWindow();
  126. if(typeof win.BYTM !== "object")
  127. win.BYTM = {} as BytmObject;
  128. win.BYTM[key] = value;
  129. }
  130. /** Emits an event on the BYTM interface */
  131. export function emitInterface<
  132. TEvt extends keyof InterfaceEvents,
  133. TDetail extends InterfaceEvents[TEvt],
  134. >(
  135. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  136. ...data: (TDetail extends undefined ? [undefined?] : [TDetail])
  137. ) {
  138. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: data?.[0] ?? undefined }));
  139. }
  140. //#region register plugins
  141. /** Plugins that are queued up for registration */
  142. const pluginsQueued = new Map<string, PluginItem>();
  143. /** Registered plugins including their event listener instance */
  144. const pluginsRegistered = new Map<string, PluginItem>();
  145. /** Auth tokens for plugins that have been registered */
  146. const pluginTokens = new Map<string, string>();
  147. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  148. export function initPlugins() {
  149. // TODO(v1.3): check perms and ask user for initial activation
  150. for(const [key, { def, events }] of pluginsQueued) {
  151. try {
  152. pluginsRegistered.set(key, { def, events });
  153. pluginsQueued.delete(key);
  154. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!);
  155. }
  156. catch(err) {
  157. error(`Failed to initialize plugin '${getPluginKey(def)}':`, err);
  158. }
  159. }
  160. for(const evt of allInterfaceEvents) // @ts-ignore
  161. getUnsafeWindow().addEventListener(evt, (...args) => emitOnPlugins(evt, undefined, ...args));
  162. emitInterface("bytm:pluginsRegistered");
  163. }
  164. /** Returns the key for a given plugin definition */
  165. function getPluginKey(plugin: PluginDefResolvable) {
  166. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  167. }
  168. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  169. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  170. return plugin && {
  171. name: plugin.plugin.name,
  172. namespace: plugin.plugin.namespace,
  173. version: plugin.plugin.version,
  174. };
  175. }
  176. /** Checks whether two plugins are the same, given their resolvable definition objects */
  177. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  178. return getPluginKey(def1) === getPluginKey(def2);
  179. }
  180. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  181. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  182. event: TEvtKey,
  183. predicate: ((def: PluginDef) => boolean) | boolean = true,
  184. ...data: Parameters<PluginEventMap[TEvtKey]>
  185. ) {
  186. for(const { def, events } of pluginsRegistered.values())
  187. if(typeof predicate === "boolean" ? predicate : predicate(def))
  188. events.emit(event, ...data);
  189. }
  190. /**
  191. * @private FOR INTERNAL USE ONLY!
  192. * Returns the internal plugin object by its name and namespace, or undefined if it doesn't exist
  193. */
  194. export function getPlugin(name: string, namespace: string): PluginItem | undefined
  195. /**
  196. * @private FOR INTERNAL USE ONLY!
  197. * Returns the internal plugin object by a resolvable definition object, or undefined if it doesn't exist
  198. */
  199. export function getPlugin(plugin: PluginDefResolvable): PluginItem | undefined
  200. /**
  201. * @private FOR INTERNAL USE ONLY!
  202. * Returns the internal plugin object, or undefined if it doesn't exist
  203. */
  204. export function getPlugin(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  205. return args.length === 2
  206. ? pluginsRegistered.get(`${args[1]}/${args[0]}`)
  207. : pluginsRegistered.get(getPluginKey(args[0] as PluginDefResolvable));
  208. }
  209. /**
  210. * Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered.
  211. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  212. * @public Intended for general use in plugins.
  213. */
  214. export function getPluginInfo(token: string | undefined, name: string, namespace: string): PluginInfo | undefined
  215. /**
  216. * Returns info about a registered plugin on the BYTM interface by a resolvable definition object, or undefined if the plugin isn't registered.
  217. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  218. * @public Intended for general use in plugins.
  219. */
  220. export function getPluginInfo(token: string | undefined, plugin: PluginDefResolvable): PluginInfo | undefined
  221. /**
  222. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  223. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  224. * @public Intended for general use in plugins.
  225. */
  226. export function getPluginInfo(...args: [token: string | undefined, pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  227. if(resolveToken(args[0]) === undefined)
  228. return undefined;
  229. return pluginDefToInfo(
  230. pluginsRegistered.get(
  231. args.length === 2
  232. ? `${args[2]}/${args[1]}`
  233. : getPluginKey(args[1] as PluginDefResolvable)
  234. )?.def
  235. );
  236. }
  237. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  238. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  239. const errors = [] as string[];
  240. const addNoPropErr = (prop: string, type: string) =>
  241. errors.push(t("plugin_validation_error_no_property", prop, type));
  242. // def.plugin and its properties:
  243. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  244. const { plugin } = pluginDef;
  245. !plugin?.name && addNoPropErr("plugin.name", "string");
  246. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  247. !plugin?.version && addNoPropErr("plugin.version", "[major: number, minor: number, patch: number]");
  248. return errors.length > 0 ? errors : undefined;
  249. }
  250. /** Registers a plugin on the BYTM interface */
  251. export function registerPlugin(def: PluginDef): PluginRegisterResult {
  252. const validationErrors = validatePluginDef(def);
  253. if(validationErrors) {
  254. error(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`, LogLevel.Info);
  255. throw new Error(`Invalid plugin definition:\n- ${validationErrors.join("\n- ")}`);
  256. }
  257. const events = createNanoEvents<PluginEventMap>();
  258. const token = randomId(32, 36);
  259. const { plugin: { name } } = def;
  260. pluginsQueued.set(getPluginKey(def), {
  261. def: def,
  262. events,
  263. });
  264. pluginTokens.set(getPluginKey(def), token);
  265. info(`Registered plugin: ${name}`, LogLevel.Info);
  266. return {
  267. info: getPluginInfo(token, def)!,
  268. events,
  269. token,
  270. };
  271. }
  272. /** Checks whether the passed token is a valid auth token for any registered plugin and returns the resolvable plugin ID, else returns undefined */
  273. export function resolveToken(token: string | undefined): string | undefined {
  274. return token ? [...pluginTokens.entries()].find(([, v]) => v === token)?.[0] ?? undefined : undefined;
  275. }
  276. //#region proxy funcs
  277. /**
  278. * Sets the new locale on the BYTM interface
  279. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  280. */
  281. function setLocaleInterface(token: string | undefined, locale: TrLocale) {
  282. if(resolveToken(token) === undefined)
  283. return;
  284. setLocale(locale);
  285. emitInterface("bytm:setLocale", { locale });
  286. }
  287. /**
  288. * Returns the current feature config, with sensitive values replaced by `undefined`
  289. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  290. */
  291. function getFeaturesInterface(token: string | undefined) {
  292. if(resolveToken(token) === undefined)
  293. return undefined;
  294. const features = getFeatures();
  295. for(const ftKey of Object.keys(features)) {
  296. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  297. if(info && info.valueHidden) // @ts-ignore
  298. features[ftKey as keyof typeof features] = undefined;
  299. }
  300. return features as FeatureConfig;
  301. }
  302. /**
  303. * Saves the passed feature config synchronously to the in-memory cache and asynchronously to the persistent storage.
  304. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  305. */
  306. function saveFeaturesInterface(token: string | undefined, features: FeatureConfig) {
  307. if(resolveToken(token) === undefined)
  308. return;
  309. setFeatures(features);
  310. }