interface.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. const globalFuncs = {
  46. // meta
  47. registerPlugin,
  48. getPluginInfo,
  49. // utils
  50. addSelectorListener,
  51. getResourceUrl,
  52. getSessionId,
  53. getVideoTime,
  54. setLocale,
  55. getLocale,
  56. hasKey,
  57. hasKeyFor,
  58. t,
  59. tp,
  60. getFeatures: getFeaturesInterface,
  61. saveFeatures: setFeatures,
  62. fetchLyricsUrlTop,
  63. getLyricsCacheEntry,
  64. sanitizeArtists,
  65. sanitizeSong,
  66. compareVersions,
  67. compareVersionArrays,
  68. };
  69. /** Initializes the BYTM interface */
  70. export function initInterface() {
  71. const props = {
  72. mode,
  73. branch,
  74. host,
  75. buildNumber,
  76. compressionFormat,
  77. ...scriptInfo,
  78. ...globalFuncs,
  79. UserUtils,
  80. NanoEmitter,
  81. BytmDialog,
  82. createHotkeyInput,
  83. createToggleInput,
  84. };
  85. for(const [key, value] of Object.entries(props))
  86. setGlobalProp(key, value);
  87. log("Initialized BYTM interface");
  88. }
  89. /** Sets a global property on the unsafeWindow.BYTM object */
  90. export function setGlobalProp<
  91. TKey extends keyof Window["BYTM"],
  92. TValue = Window["BYTM"][TKey],
  93. > (
  94. key: TKey | (string & {}),
  95. value: TValue,
  96. ) {
  97. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  98. const win = getUnsafeWindow();
  99. if(typeof win.BYTM !== "object")
  100. win.BYTM = {} as typeof window.BYTM;
  101. win.BYTM[key] = value;
  102. }
  103. /** Emits an event on the BYTM interface */
  104. export function emitInterface<
  105. TEvt extends keyof InterfaceEvents,
  106. TDetail extends InterfaceEvents[TEvt],
  107. >(
  108. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  109. ...data: (TDetail extends undefined ? [undefined?] : [TDetail])
  110. ) {
  111. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: data[0] }));
  112. }
  113. //#region register plugins
  114. /** Plugins that are queued up for registration */
  115. const pluginQueue = new Map<string, PluginItem>();
  116. /** Registered plugins including their event listener instance */
  117. const pluginMap = new Map<string, PluginItem>();
  118. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  119. export function initPlugins() {
  120. // TODO(v1.3): check perms and ask user for initial activation
  121. for(const [key, { def, events }] of pluginQueue) {
  122. pluginMap.set(key, { def, events });
  123. pluginQueue.delete(key);
  124. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!);
  125. }
  126. for(const evt of allSiteEvents) // @ts-ignore
  127. siteEvents.on(evt, (...args) => emitOnPlugins(evt, () => true, ...args));
  128. emitInterface("bytm:pluginsLoaded");
  129. }
  130. /** Returns the key for a given plugin definition */
  131. function getPluginKey(plugin: PluginDefResolvable) {
  132. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  133. }
  134. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  135. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  136. return plugin && {
  137. name: plugin.plugin.name,
  138. namespace: plugin.plugin.namespace,
  139. version: plugin.plugin.version,
  140. };
  141. }
  142. /** Checks whether two plugin definitions are the same */
  143. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  144. return getPluginKey(def1) === getPluginKey(def2);
  145. }
  146. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  147. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  148. event: TEvtKey,
  149. predicate: (def: PluginDef) => boolean = () => true,
  150. ...data: Parameters<PluginEventMap[TEvtKey]>
  151. ) {
  152. for(const { def, events } of pluginMap.values())
  153. predicate(def) && events.emit(event, ...data);
  154. }
  155. /** Returns the internal plugin object by its name and namespace, or undefined if it doesn't exist */
  156. export function getPlugin(name: string, namespace: string): PluginItem | undefined
  157. /** Returns the internal plugin object by its definition, or undefined if it doesn't exist */
  158. export function getPlugin(plugin: PluginDefResolvable): PluginItem | undefined
  159. /** Returns the internal plugin object, or undefined if it doesn't exist */
  160. export function getPlugin(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  161. return args.length === 2
  162. ? pluginMap.get(`${args[1]}/${args[0]}`)
  163. : pluginMap.get(getPluginKey(args[0] as PluginDefResolvable));
  164. }
  165. /** Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered */
  166. export function getPluginInfo(name: string, namespace: string): PluginInfo | undefined
  167. /** Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered */
  168. export function getPluginInfo(plugin: PluginDefResolvable): PluginInfo | undefined
  169. /** Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered */
  170. export function getPluginInfo(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  171. return pluginDefToInfo(
  172. args.length === 2
  173. ? pluginMap.get(`${args[1]}/${args[0]}`)?.def
  174. : pluginMap.get(getPluginKey(args[0] as PluginDefResolvable))?.def
  175. );
  176. }
  177. /** Validates the passed PluginDef object and returns an array of errors */
  178. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  179. const errors = [] as string[];
  180. const addNoPropErr = (prop: string, type: string) =>
  181. errors.push(t("plugin_validation_error_no_property", prop, type));
  182. // def.plugin and its properties:
  183. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  184. const { plugin } = pluginDef;
  185. !plugin?.name && addNoPropErr("plugin.name", "string");
  186. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  187. !plugin?.version && addNoPropErr("plugin.version", "[major: number, minor: number, patch: number]");
  188. return errors.length > 0 ? errors : undefined;
  189. }
  190. /** Registers a plugin on the BYTM interface */
  191. export function registerPlugin(def: PluginDef): PluginRegisterResult {
  192. const validationErrors = validatePluginDef(def);
  193. if(validationErrors) {
  194. error(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`, LogLevel.Info);
  195. throw new Error(`Invalid plugin definition:\n- ${validationErrors.join("\n- ")}`);
  196. }
  197. const events = createNanoEvents<PluginEventMap>();
  198. const { plugin: { name } } = def;
  199. pluginQueue.set(getPluginKey(def), {
  200. def: def,
  201. events,
  202. });
  203. info(`Registered plugin: ${name}`, LogLevel.Info);
  204. return {
  205. info: getPluginInfo(def)!,
  206. events,
  207. };
  208. }
  209. //#region proxy funcs
  210. /** Returns the current feature config, with sensitive values replaced by `undefined` */
  211. export function getFeaturesInterface() {
  212. const features = getFeatures();
  213. for(const ftKey of Object.keys(features)) {
  214. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  215. if(info && info.valueHidden) // @ts-ignore
  216. features[ftKey as keyof typeof features] = undefined;
  217. }
  218. return features as FeatureConfig;
  219. }