interface.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 } 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, siteEvents, 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 } from "./types";
  10. import { BytmDialog, createHotkeyInput, createToggleInput } from "./components";
  11. const { getUnsafeWindow } = UserUtils;
  12. //#region interface globals
  13. /** All events that can be emitted on the BYTM interface and the data they provide */
  14. export type InterfaceEvents = {
  15. /** Emitted whenever the plugins should be registered using `unsafeWindow.BYTM.registerPlugin()` */
  16. "bytm:initPlugins": undefined;
  17. /** Emitted whenever all plugins have been loaded */
  18. "bytm:pluginsLoaded": undefined;
  19. /** Emitted when BYTM has finished initializing all features */
  20. "bytm:ready": undefined;
  21. /**
  22. * Emitted whenever the SelectorObserver instances have been initialized
  23. * Use `unsafeWindow.BYTM.addObserverListener()` to add custom listener functions to the observers
  24. */
  25. "bytm:observersReady": undefined;
  26. /** Emitted as soon as the feature config has been loaded */
  27. "bytm:configReady": FeatureConfig;
  28. /** Emitted whenever the locale is changed */
  29. "bytm:setLocale": { locale: TrLocale };
  30. /** Emitted when a dialog was opened - returns the dialog's instance */
  31. "bytm:dialogOpened": BytmDialog;
  32. /** Emitted when the dialog with the specified ID was opened - returns the dialog's instance - in TS, use `"..." as "bytm:dialogOpened:id"` to make the error go away */
  33. "bytm:dialogOpened:id": BytmDialog;
  34. /** Emitted whenever the lyrics URL for a song is loaded */
  35. "bytm:lyricsLoaded": { type: "current" | "queue", artists: string, title: string, url: string };
  36. /** Emitted when the lyrics cache has been loaded */
  37. "bytm:lyricsCacheReady": LyricsCache;
  38. /** Emitted when the lyrics cache has been cleared */
  39. "bytm:lyricsCacheCleared": undefined;
  40. /** 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 */
  41. "bytm:lyricsCacheEntryAdded": { type: "best" | "penalized", entry: LyricsCacheEntry };
  42. // additionally all events from SiteEventsMap in `src/siteEvents.ts`
  43. // are emitted in this format: "bytm:siteEvent:nameOfSiteEvent"
  44. };
  45. /** All functions that can be called on the BYTM interface using `unsafeWindow.BYTM.functionName();` (or `const { functionName } = unsafeWindow.BYTM;`) */
  46. const globalFuncs = {
  47. // meta
  48. registerPlugin,
  49. getPluginInfo,
  50. // utils
  51. addSelectorListener,
  52. getResourceUrl,
  53. getSessionId,
  54. getVideoTime,
  55. setLocale,
  56. getLocale,
  57. hasKey,
  58. hasKeyFor,
  59. t,
  60. tp,
  61. getFeatures: getFeaturesInterface,
  62. saveFeatures: setFeatures,
  63. fetchLyricsUrlTop,
  64. getLyricsCacheEntry,
  65. sanitizeArtists,
  66. sanitizeSong,
  67. compareVersions,
  68. compareVersionArrays,
  69. };
  70. /** Initializes the BYTM interface */
  71. export function initInterface() {
  72. const props = {
  73. mode,
  74. branch,
  75. host,
  76. buildNumber,
  77. compressionFormat,
  78. ...scriptInfo,
  79. ...globalFuncs,
  80. UserUtils,
  81. NanoEmitter,
  82. BytmDialog,
  83. createHotkeyInput,
  84. createToggleInput,
  85. };
  86. for(const [key, value] of Object.entries(props))
  87. setGlobalProp(key, value);
  88. log("Initialized BYTM interface");
  89. }
  90. /** Sets a global property on the unsafeWindow.BYTM object */
  91. export function setGlobalProp<
  92. TKey extends keyof Window["BYTM"],
  93. TValue = Window["BYTM"][TKey],
  94. > (
  95. key: TKey | (string & {}),
  96. value: TValue,
  97. ) {
  98. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  99. const win = getUnsafeWindow();
  100. if(typeof win.BYTM !== "object")
  101. win.BYTM = {} as typeof window.BYTM;
  102. win.BYTM[key] = value;
  103. }
  104. /** Emits an event on the BYTM interface */
  105. export function emitInterface<
  106. TEvt extends keyof InterfaceEvents,
  107. TDetail extends InterfaceEvents[TEvt],
  108. >(
  109. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  110. ...data: (TDetail extends undefined ? [undefined?] : [TDetail])
  111. ) {
  112. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: data[0] }));
  113. }
  114. //#region register plugins
  115. /** Plugins that are queued up for registration */
  116. const pluginQueue = new Map<string, PluginItem>();
  117. /** Registered plugins including their event listener instance */
  118. const pluginMap = new Map<string, PluginItem>();
  119. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  120. export function initPlugins() {
  121. // TODO(v1.3): check perms and ask user for initial activation
  122. for(const [key, { def, events }] of pluginQueue) {
  123. pluginMap.set(key, { def, events });
  124. pluginQueue.delete(key);
  125. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!);
  126. }
  127. for(const evt of allSiteEvents) // @ts-ignore
  128. siteEvents.on(evt, (...args) => emitOnPlugins(evt, () => true, ...args));
  129. emitInterface("bytm:pluginsLoaded");
  130. }
  131. /** Returns the key for a given plugin definition */
  132. function getPluginKey(plugin: PluginDefResolvable) {
  133. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  134. }
  135. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  136. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  137. return plugin && {
  138. name: plugin.plugin.name,
  139. namespace: plugin.plugin.namespace,
  140. version: plugin.plugin.version,
  141. };
  142. }
  143. /** Checks whether two plugin definitions are the same */
  144. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  145. return getPluginKey(def1) === getPluginKey(def2);
  146. }
  147. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  148. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  149. event: TEvtKey,
  150. predicate: ((def: PluginDef) => boolean) | boolean = true,
  151. ...data: Parameters<PluginEventMap[TEvtKey]>
  152. ) {
  153. for(const { def, events } of pluginMap.values())
  154. if(typeof predicate === "boolean" ? predicate : predicate(def))
  155. events.emit(event, ...data);
  156. }
  157. /**
  158. * @private FOR INTERNAL USE ONLY!
  159. * Returns the internal plugin object by its name and namespace, or undefined if it doesn't exist
  160. */
  161. export function getPlugin(name: string, namespace: string): PluginItem | undefined
  162. /**
  163. * @private FOR INTERNAL USE ONLY!
  164. * Returns the internal plugin object by a resolvable definition object, or undefined if it doesn't exist
  165. */
  166. export function getPlugin(plugin: PluginDefResolvable): PluginItem | undefined
  167. /**
  168. * @private FOR INTERNAL USE ONLY!
  169. * Returns the internal plugin object, or undefined if it doesn't exist
  170. */
  171. export function getPlugin(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  172. return args.length === 2
  173. ? pluginMap.get(`${args[1]}/${args[0]}`)
  174. : pluginMap.get(getPluginKey(args[0] as PluginDefResolvable));
  175. }
  176. /**
  177. * Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered.
  178. * @public Intended for general use in plugins.
  179. */
  180. export function getPluginInfo(name: string, namespace: string): PluginInfo | undefined
  181. /**
  182. * Returns info about a registered plugin on the BYTM interface by a resolvable definition object, or undefined if the plugin isn't registered.
  183. * @public Intended for general use in plugins.
  184. */
  185. export function getPluginInfo(plugin: PluginDefResolvable): PluginInfo | undefined
  186. /**
  187. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  188. * @public Intended for general use in plugins.
  189. */
  190. export function getPluginInfo(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  191. return pluginDefToInfo(
  192. args.length === 2
  193. ? pluginMap.get(`${args[1]}/${args[0]}`)?.def
  194. : pluginMap.get(getPluginKey(args[0] as PluginDefResolvable))?.def
  195. );
  196. }
  197. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  198. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  199. const errors = [] as string[];
  200. const addNoPropErr = (prop: string, type: string) =>
  201. errors.push(t("plugin_validation_error_no_property", prop, type));
  202. // def.plugin and its properties:
  203. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  204. const { plugin } = pluginDef;
  205. !plugin?.name && addNoPropErr("plugin.name", "string");
  206. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  207. !plugin?.version && addNoPropErr("plugin.version", "[major: number, minor: number, patch: number]");
  208. return errors.length > 0 ? errors : undefined;
  209. }
  210. /** Registers a plugin on the BYTM interface */
  211. export function registerPlugin(def: PluginDef): PluginRegisterResult {
  212. const validationErrors = validatePluginDef(def);
  213. if(validationErrors) {
  214. error(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`, LogLevel.Info);
  215. throw new Error(`Invalid plugin definition:\n- ${validationErrors.join("\n- ")}`);
  216. }
  217. const events = createNanoEvents<PluginEventMap>();
  218. const { plugin: { name } } = def;
  219. pluginQueue.set(getPluginKey(def), {
  220. def: def,
  221. events,
  222. });
  223. info(`Registered plugin: ${name}`, LogLevel.Info);
  224. return {
  225. info: getPluginInfo(def)!,
  226. events,
  227. };
  228. }
  229. //#region proxy funcs
  230. /** Returns the current feature config, with sensitive values replaced by `undefined` */
  231. export function getFeaturesInterface() {
  232. const features = getFeatures();
  233. for(const ftKey of Object.keys(features)) {
  234. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  235. if(info && info.valueHidden) // @ts-ignore
  236. features[ftKey as keyof typeof features] = undefined;
  237. }
  238. return features as FeatureConfig;
  239. }