interface.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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, createRipple, createToggleInput, showIconToast, showToast } 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. // TODO: document
  122. showToast,
  123. showIconToast,
  124. createRipple,
  125. };
  126. /** Initializes the BYTM interface */
  127. export function initInterface() {
  128. const props = {
  129. // meta / constants
  130. mode,
  131. branch,
  132. host,
  133. buildNumber,
  134. compressionFormat,
  135. ...scriptInfo,
  136. // functions
  137. ...globalFuncs,
  138. // classes
  139. NanoEmitter,
  140. BytmDialog,
  141. // libraries
  142. UserUtils,
  143. compareVersions,
  144. };
  145. for(const [key, value] of Object.entries(props))
  146. setGlobalProp(key, value);
  147. log("Initialized BYTM interface");
  148. }
  149. /** Sets a global property on the unsafeWindow.BYTM object */
  150. export function setGlobalProp<
  151. TKey extends keyof Window["BYTM"],
  152. TValue = Window["BYTM"][TKey],
  153. >(
  154. key: TKey | (string & {}),
  155. value: TValue,
  156. ) {
  157. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  158. const win = getUnsafeWindow();
  159. if(typeof win.BYTM !== "object")
  160. win.BYTM = {} as BytmObject;
  161. win.BYTM[key] = value;
  162. }
  163. /** Emits an event on the BYTM interface */
  164. export function emitInterface<
  165. TEvt extends keyof InterfaceEvents,
  166. TDetail extends InterfaceEvents[TEvt],
  167. >(
  168. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  169. ...detail: (TDetail extends undefined ? [undefined?] : [TDetail])
  170. ) {
  171. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: detail?.[0] ?? undefined }));
  172. //@ts-ignore
  173. emitOnPlugins(type, undefined, ...detail);
  174. log(`Emitted interface event '${type}'${detail.length > 0 && detail?.[0] ? " with data:" : ""}`, ...detail);
  175. }
  176. //#region register plugins
  177. /** Map of plugin ID and plugins that are queued up for registration */
  178. const pluginsQueued = new Map<string, PluginItem>();
  179. /** Map of plugin ID and all registered plugins */
  180. const pluginsRegistered = new Map<string, PluginItem>();
  181. /** Map of plugin ID to auth token for plugins that have been registered */
  182. const pluginTokens = new Map<string, string>();
  183. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  184. export function initPlugins() {
  185. // TODO(v1.3): check perms and ask user for initial activation
  186. for(const [key, { def, events }] of pluginsQueued) {
  187. try {
  188. pluginsRegistered.set(key, { def, events });
  189. pluginsQueued.delete(key);
  190. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!);
  191. }
  192. catch(err) {
  193. error(`Failed to initialize plugin '${getPluginKey(def)}':`, err);
  194. }
  195. }
  196. emitInterface("bytm:pluginsRegistered");
  197. }
  198. /** Returns the key for a given plugin definition */
  199. function getPluginKey(plugin: PluginDefResolvable) {
  200. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  201. }
  202. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  203. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  204. return plugin
  205. ? {
  206. name: plugin.plugin.name,
  207. namespace: plugin.plugin.namespace,
  208. version: plugin.plugin.version,
  209. }
  210. : undefined;
  211. }
  212. /** Checks whether two plugins are the same, given their resolvable definition objects */
  213. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  214. return getPluginKey(def1) === getPluginKey(def2);
  215. }
  216. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  217. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  218. event: TEvtKey,
  219. predicate: ((def: PluginDef) => boolean) | boolean = true,
  220. ...data: Parameters<PluginEventMap[TEvtKey]>
  221. ) {
  222. for(const { def, events } of pluginsRegistered.values())
  223. if(typeof predicate === "boolean" ? predicate : predicate(def))
  224. events.emit(event, ...data);
  225. }
  226. /**
  227. * @private FOR INTERNAL USE ONLY!
  228. * Returns the internal plugin def and events objects via its name and namespace, or undefined if it doesn't exist.
  229. */
  230. export function getPlugin(pluginName: string, namespace: string): PluginItem | undefined
  231. /**
  232. * @private FOR INTERNAL USE ONLY!
  233. * Returns the internal plugin def and events objects via resolvable definition, or undefined if it doesn't exist.
  234. */
  235. export function getPlugin(pluginDef: PluginDefResolvable): PluginItem | undefined
  236. /**
  237. * @private FOR INTERNAL USE ONLY!
  238. * Returns the internal plugin def and events objects via plugin ID (consisting of namespace and name), or undefined if it doesn't exist.
  239. */
  240. export function getPlugin(pluginId: string): PluginItem | undefined
  241. /**
  242. * @private FOR INTERNAL USE ONLY!
  243. * Returns the internal plugin def and events objects, or undefined if it doesn't exist.
  244. */
  245. export function getPlugin(...args: [pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  246. return typeof args[0] === "string" && typeof args[1] === "undefined"
  247. ? pluginsRegistered.get(args[0])
  248. : args.length === 2
  249. ? pluginsRegistered.get(`${args[1]}/${args[0]}`)
  250. : pluginsRegistered.get(getPluginKey(args[0] as PluginDefResolvable));
  251. }
  252. /**
  253. * Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered.
  254. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  255. * @public Intended for general use in plugins.
  256. */
  257. export function getPluginInfo(token: string | undefined, name: string, namespace: string): PluginInfo | undefined
  258. /**
  259. * Returns info about a registered plugin on the BYTM interface by a resolvable definition object, or undefined if the plugin isn't registered.
  260. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  261. * @public Intended for general use in plugins.
  262. */
  263. export function getPluginInfo(token: string | undefined, plugin: PluginDefResolvable): PluginInfo | undefined
  264. /**
  265. * 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.
  266. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  267. * @public Intended for general use in plugins.
  268. */
  269. export function getPluginInfo(token: string | undefined, pluginId: string): PluginInfo | undefined
  270. /**
  271. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  272. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  273. * @public Intended for general use in plugins.
  274. */
  275. export function getPluginInfo(...args: [token: string | undefined, pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  276. if(resolveToken(args[0]) === undefined)
  277. return undefined;
  278. return pluginDefToInfo(
  279. pluginsRegistered.get(
  280. typeof args[1] === "string" && typeof args[2] === "undefined"
  281. ? args[1]
  282. : args.length === 2
  283. ? `${args[2]}/${args[1]}`
  284. : getPluginKey(args[1] as PluginDefResolvable)
  285. )?.def
  286. );
  287. }
  288. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  289. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  290. const errors = [] as string[];
  291. const addNoPropErr = (jsonPath: string, type: string) =>
  292. errors.push(t("plugin_validation_error_no_property", jsonPath, type));
  293. const addInvalidPropErr = (jsonPath: string, value: string, examples: string[]) =>
  294. errors.push(tp("plugin_validation_error_invalid_property", examples, jsonPath, value, `'${examples.join("', '")}'`));
  295. // def.plugin and its properties:
  296. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  297. const { plugin } = pluginDef;
  298. !plugin?.name && addNoPropErr("plugin.name", "string");
  299. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  300. if(typeof plugin?.version !== "string")
  301. addNoPropErr("plugin.version", "MAJOR.MINOR.PATCH");
  302. else if(!compareVersions.validateStrict(plugin.version))
  303. addInvalidPropErr("plugin.version", plugin.version, ["0.0.1", "2.5.21-rc.1"]);
  304. return errors.length > 0 ? errors : undefined;
  305. }
  306. /** Registers a plugin on the BYTM interface */
  307. export function registerPlugin(def: PluginDef): PluginRegisterResult {
  308. const validationErrors = validatePluginDef(def);
  309. if(validationErrors) {
  310. error(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`, LogLevel.Info);
  311. throw new Error(`Invalid plugin definition:\n- ${validationErrors.join("\n- ")}`);
  312. }
  313. const events = createNanoEvents<PluginEventMap>();
  314. const token = randomId(32, 36);
  315. const { plugin: { name } } = def;
  316. pluginsQueued.set(getPluginKey(def), {
  317. def: def,
  318. events,
  319. });
  320. pluginTokens.set(getPluginKey(def), token);
  321. info(`Registered plugin: ${name}`, LogLevel.Info);
  322. return {
  323. info: getPluginInfo(token, def)!,
  324. events,
  325. token,
  326. };
  327. }
  328. /** Checks whether the passed token is a valid auth token for any registered plugin and returns the plugin ID, else returns undefined */
  329. export function resolveToken(token: string | undefined): string | undefined {
  330. return token ? [...pluginTokens.entries()].find(([, v]) => v === token)?.[0] ?? undefined : undefined;
  331. }
  332. //#region proxy funcs
  333. /**
  334. * Sets the new locale on the BYTM interface
  335. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  336. */
  337. function setLocaleInterface(token: string | undefined, locale: TrLocale) {
  338. const pluginId = resolveToken(token);
  339. if(pluginId === undefined)
  340. return;
  341. setLocale(locale);
  342. emitInterface("bytm:setLocale", { pluginId, locale });
  343. }
  344. /**
  345. * Returns the current feature config, with sensitive values replaced by `undefined`
  346. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  347. */
  348. function getFeaturesInterface(token: string | undefined) {
  349. if(resolveToken(token) === undefined)
  350. return undefined;
  351. const features = getFeatures();
  352. for(const ftKey of Object.keys(features)) {
  353. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  354. if(info && info.valueHidden) // @ts-ignore
  355. features[ftKey as keyof typeof features] = undefined;
  356. }
  357. return features as FeatureConfig;
  358. }
  359. /**
  360. * Saves the passed feature config synchronously to the in-memory cache and asynchronously to the persistent storage.
  361. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  362. */
  363. function saveFeaturesInterface(token: string | undefined, features: FeatureConfig) {
  364. if(resolveToken(token) === undefined)
  365. return;
  366. setFeatures(features);
  367. }