interface.ts 16 KB

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