interface.ts 17 KB

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