interface.ts 11 KB

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