interface.ts 9.8 KB

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