interface.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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.js";
  4. import { getResourceUrl, getSessionId, getVideoTime, log, setLocale, getLocale, hasKey, hasKeyFor, NanoEmitter, t, tp, type TrLocale, info, error, onInteraction, getThumbnailUrl, getBestThumbnailUrl, fetchVideoVotes } from "./utils/index.js";
  5. import { addSelectorListener } from "./observers.js";
  6. import { getFeatures, setFeatures } from "./config.js";
  7. import { autoLikeStore, featInfo, fetchLyricsUrlTop, getLyricsCacheEntry, sanitizeArtists, sanitizeSong } from "./features/index.js";
  8. import { allSiteEvents, type SiteEventsMap } from "./siteEvents.js";
  9. import { LogLevel, type FeatureConfig, type FeatureInfo, type LyricsCacheEntry, type PluginDef, type PluginInfo, type PluginRegisterResult, type PluginDefResolvable, type PluginEventMap, type PluginItem, type BytmObject, type AutoLikeData, type InterfaceFunctions } from "./types.js";
  10. import { BytmDialog, ExImDialog, createCircularBtn, createHotkeyInput, createRipple, createToggleInput, showIconToast, showToast } from "./components/index.js";
  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 - if a plugin changed the locale, the plugin ID is provided as well */
  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 when a dialog was closed - returns the dialog's instance */
  65. "bytm:dialogClosed": BytmDialog;
  66. /** Emitted when the dialog with the specified ID was closed - returns the dialog's instance - in TS, use `"bytm:dialogClosed:myIdWhatever" as "bytm:dialogClosed:id"` to make the error go away */
  67. "bytm:dialogClosed:id": BytmDialog;
  68. /** Emitted whenever the lyrics URL for a song is loaded */
  69. "bytm:lyricsLoaded": { type: "current" | "queue", artists: string, title: string, url: string };
  70. /** Emitted when the lyrics cache has been cleared */
  71. "bytm:lyricsCacheCleared": undefined;
  72. /** 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 */
  73. "bytm:lyricsCacheEntryAdded": { type: "best" | "penalized", entry: LyricsCacheEntry };
  74. // NOTE:
  75. // Additionally, all events from `SiteEventsMap` in `src/siteEvents.ts`
  76. // are emitted in this format: "bytm:siteEvent:nameOfSiteEvent"
  77. };
  78. /** Array of all events emittable on the interface (excluding plugin-specific, private events) */
  79. export const allInterfaceEvents = [
  80. "bytm:registerPlugins",
  81. "bytm:pluginsRegistered",
  82. "bytm:ready",
  83. "bytm:featureInitfeatureInitStarted",
  84. "bytm:fatalError",
  85. "bytm:observersReady",
  86. "bytm:configReady",
  87. "bytm:setLocale",
  88. "bytm:dialogOpened",
  89. "bytm:dialogOpened:id",
  90. "bytm:lyricsLoaded",
  91. "bytm:lyricsCacheReady",
  92. "bytm:lyricsCacheCleared",
  93. "bytm:lyricsCacheEntryAdded",
  94. ...allSiteEvents.map(e => `bytm:siteEvent:${e}`),
  95. ] as const;
  96. /**
  97. * All functions that can be called on the BYTM interface using `unsafeWindow.BYTM.functionName();` (or `const { functionName } = unsafeWindow.BYTM;`)
  98. * If prefixed with /**\/, the function is authenticated and requires a token to be passed as the first argument.
  99. */
  100. const globalFuncs: InterfaceFunctions = {
  101. // meta:
  102. registerPlugin,
  103. /**/ getPluginInfo,
  104. // bytm-specific:
  105. getResourceUrl,
  106. getSessionId,
  107. // dom:
  108. addSelectorListener,
  109. onInteraction,
  110. getVideoTime,
  111. getThumbnailUrl,
  112. getBestThumbnailUrl,
  113. // translations:
  114. /**/ setLocale: setLocaleInterface,
  115. getLocale,
  116. hasKey,
  117. hasKeyFor,
  118. t,
  119. tp,
  120. // feature config:
  121. /**/ getFeatures: getFeaturesInterface,
  122. /**/ saveFeatures: saveFeaturesInterface,
  123. // lyrics:
  124. fetchLyricsUrlTop,
  125. getLyricsCacheEntry,
  126. sanitizeArtists,
  127. sanitizeSong,
  128. // auto-like:
  129. /**/ getAutoLikeData: getAutoLikeDataInterface,
  130. /**/ saveAutoLikeData: saveAutoLikeDataInterface,
  131. fetchVideoVotes,
  132. // components:
  133. createHotkeyInput,
  134. createToggleInput,
  135. createCircularBtn,
  136. createRipple,
  137. showToast,
  138. showIconToast,
  139. };
  140. /** Initializes the BYTM interface */
  141. export function initInterface() {
  142. const props = {
  143. // meta / constants
  144. mode,
  145. branch,
  146. host,
  147. buildNumber,
  148. compressionFormat,
  149. ...scriptInfo,
  150. // functions
  151. ...globalFuncs,
  152. // classes
  153. NanoEmitter,
  154. BytmDialog,
  155. ExImDialog,
  156. // libraries
  157. UserUtils,
  158. compareVersions,
  159. };
  160. for(const [key, value] of Object.entries(props))
  161. setGlobalProp(key, value);
  162. log("Initialized BYTM interface");
  163. }
  164. /** Sets a global property on the unsafeWindow.BYTM object */
  165. export function setGlobalProp<
  166. TKey extends keyof Window["BYTM"],
  167. TValue = Window["BYTM"][TKey],
  168. >(
  169. key: TKey | (string & {}),
  170. value: TValue,
  171. ) {
  172. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  173. const win = getUnsafeWindow();
  174. if(typeof win.BYTM !== "object")
  175. win.BYTM = {} as BytmObject;
  176. win.BYTM[key] = value;
  177. }
  178. /** Emits an event on the BYTM interface */
  179. export function emitInterface<
  180. TEvt extends keyof InterfaceEvents,
  181. TDetail extends InterfaceEvents[TEvt],
  182. >(
  183. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  184. ...detail: (TDetail extends undefined ? [undefined?] : [TDetail])
  185. ) {
  186. try {
  187. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: detail?.[0] ?? undefined }));
  188. //@ts-ignore
  189. emitOnPlugins(type, undefined, ...detail);
  190. log(`Emitted interface event '${type}'${detail.length > 0 && detail?.[0] ? " with data:" : ""}`, ...detail);
  191. }
  192. catch(err) {
  193. error(`Couldn't emit interface event '${type}' due to an error:\n`, err);
  194. }
  195. }
  196. //#region register plugins
  197. /** Map of plugin ID and plugins that are queued up for registration */
  198. const queuedPlugins = new Map<string, PluginItem>();
  199. /** Map of plugin ID and all registered plugins */
  200. const registeredPlugins = new Map<string, PluginItem>();
  201. /** Map of plugin ID to auth token for plugins that have been registered */
  202. const registeredPluginTokens = new Map<string, string>();
  203. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  204. export function initPlugins() {
  205. // TODO(v1.3): check perms and ask user for initial activation
  206. for(const [key, { def, events }] of queuedPlugins) {
  207. try {
  208. registeredPlugins.set(key, { def, events });
  209. queuedPlugins.delete(key);
  210. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!);
  211. info(`Initialized plugin '${getPluginKey(def)}'`, LogLevel.Info);
  212. }
  213. catch(err) {
  214. error(`Failed to initialize plugin '${getPluginKey(def)}':`, err);
  215. }
  216. }
  217. emitInterface("bytm:pluginsRegistered");
  218. }
  219. /** Returns the key for a given plugin definition */
  220. function getPluginKey(plugin: PluginDefResolvable) {
  221. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  222. }
  223. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  224. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  225. return plugin
  226. ? {
  227. name: plugin.plugin.name,
  228. namespace: plugin.plugin.namespace,
  229. version: plugin.plugin.version,
  230. }
  231. : undefined;
  232. }
  233. /** Checks whether two plugins are the same, given their resolvable definition objects */
  234. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  235. return getPluginKey(def1) === getPluginKey(def2);
  236. }
  237. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  238. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  239. event: TEvtKey,
  240. predicate: ((def: PluginDef) => boolean) | boolean = true,
  241. ...data: Parameters<PluginEventMap[TEvtKey]>
  242. ) {
  243. for(const { def, events } of registeredPlugins.values())
  244. if(typeof predicate === "boolean" ? predicate : predicate(def))
  245. events.emit(event, ...data);
  246. }
  247. /**
  248. * @private FOR INTERNAL USE ONLY!
  249. * Returns the internal plugin def and events objects via its name and namespace, or undefined if it doesn't exist.
  250. */
  251. export function getPlugin(pluginName: string, namespace: string): PluginItem | undefined
  252. /**
  253. * @private FOR INTERNAL USE ONLY!
  254. * Returns the internal plugin def and events objects via resolvable definition, or undefined if it doesn't exist.
  255. */
  256. export function getPlugin(pluginDef: PluginDefResolvable): PluginItem | undefined
  257. /**
  258. * @private FOR INTERNAL USE ONLY!
  259. * Returns the internal plugin def and events objects via plugin ID (consisting of namespace and name), or undefined if it doesn't exist.
  260. */
  261. export function getPlugin(pluginId: string): PluginItem | undefined
  262. /**
  263. * @private FOR INTERNAL USE ONLY!
  264. * Returns the internal plugin def and events objects, or undefined if it doesn't exist.
  265. */
  266. export function getPlugin(...args: [pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  267. return typeof args[0] === "string" && typeof args[1] === "undefined"
  268. ? registeredPlugins.get(args[0])
  269. : args.length === 2
  270. ? registeredPlugins.get(`${args[1]}/${args[0]}`)
  271. : registeredPlugins.get(getPluginKey(args[0] as PluginDefResolvable));
  272. }
  273. /**
  274. * Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered.
  275. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  276. * @public Intended for general use in plugins.
  277. */
  278. export function getPluginInfo(token: string | undefined, name: string, namespace: string): PluginInfo | undefined
  279. /**
  280. * Returns info about a registered plugin on the BYTM interface by a resolvable definition object, or undefined if the plugin isn't registered.
  281. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  282. * @public Intended for general use in plugins.
  283. */
  284. export function getPluginInfo(token: string | undefined, plugin: PluginDefResolvable): PluginInfo | undefined
  285. /**
  286. * 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.
  287. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  288. * @public Intended for general use in plugins.
  289. */
  290. export function getPluginInfo(token: string | undefined, pluginId: string): PluginInfo | undefined
  291. /**
  292. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  293. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  294. * @public Intended for general use in plugins.
  295. */
  296. export function getPluginInfo(...args: [token: string | undefined, pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  297. if(resolveToken(args[0]) === undefined)
  298. return undefined;
  299. return pluginDefToInfo(
  300. registeredPlugins.get(
  301. typeof args[1] === "string" && typeof args[2] === "undefined"
  302. ? args[1]
  303. : args.length === 2
  304. ? `${args[2]}/${args[1]}`
  305. : getPluginKey(args[1] as PluginDefResolvable)
  306. )?.def
  307. );
  308. }
  309. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  310. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  311. const errors = [] as string[];
  312. const addNoPropErr = (jsonPath: string, type: string) =>
  313. errors.push(t("plugin_validation_error_no_property", jsonPath, type));
  314. const addInvalidPropErr = (jsonPath: string, value: string, examples: string[]) =>
  315. errors.push(tp("plugin_validation_error_invalid_property", examples, jsonPath, value, `'${examples.join("', '")}'`));
  316. // def.plugin and its properties:
  317. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  318. const { plugin } = pluginDef;
  319. !plugin?.name && addNoPropErr("plugin.name", "string");
  320. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  321. if(typeof plugin?.version !== "string")
  322. addNoPropErr("plugin.version", "MAJOR.MINOR.PATCH");
  323. else if(!compareVersions.validateStrict(plugin.version))
  324. addInvalidPropErr("plugin.version", plugin.version, ["0.0.1", "2.5.21-rc.1"]);
  325. return errors.length > 0 ? errors : undefined;
  326. }
  327. /** Registers a plugin on the BYTM interface */
  328. export function registerPlugin(def: PluginDef): PluginRegisterResult {
  329. const validationErrors = validatePluginDef(def);
  330. if(validationErrors)
  331. throw new Error(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`);
  332. const events = new NanoEmitter<PluginEventMap>({ publicEmit: true });
  333. const token = randomId(32, 36);
  334. const { plugin: { name } } = def;
  335. queuedPlugins.set(getPluginKey(def), {
  336. def: def,
  337. events,
  338. });
  339. registeredPluginTokens.set(getPluginKey(def), token);
  340. info(`Registered plugin: ${name}`, LogLevel.Info);
  341. return {
  342. info: getPluginInfo(token, def)!,
  343. events,
  344. token,
  345. };
  346. }
  347. /** Checks whether the passed token is a valid auth token for any registered plugin and returns the plugin ID, else returns undefined */
  348. export function resolveToken(token: string | undefined): string | undefined {
  349. return typeof token === "string" && token.length > 0
  350. ? [...registeredPluginTokens.entries()]
  351. .find(([k, t]) => registeredPlugins.has(k) && token === t)?.[0] ?? undefined
  352. : undefined;
  353. }
  354. //#region proxy funcs
  355. /**
  356. * Sets the new locale on the BYTM interface
  357. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  358. */
  359. export function setLocaleInterface(token: string | undefined, locale: TrLocale) {
  360. const pluginId = resolveToken(token);
  361. if(pluginId === undefined)
  362. return;
  363. setLocale(locale);
  364. emitInterface("bytm:setLocale", { pluginId, locale });
  365. }
  366. /**
  367. * Returns the current feature config, with sensitive values replaced by `undefined`
  368. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  369. */
  370. export function getFeaturesInterface(token: string | undefined) {
  371. if(resolveToken(token) === undefined)
  372. return undefined;
  373. const features = getFeatures();
  374. for(const ftKey of Object.keys(features)) {
  375. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  376. if(info && info.valueHidden) // @ts-ignore
  377. features[ftKey as keyof typeof features] = undefined;
  378. }
  379. return features as FeatureConfig;
  380. }
  381. /**
  382. * Saves the passed feature config synchronously to the in-memory cache and asynchronously to the persistent storage.
  383. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  384. */
  385. export function saveFeaturesInterface(token: string | undefined, features: FeatureConfig) {
  386. if(resolveToken(token) === undefined)
  387. return;
  388. setFeatures(features);
  389. }
  390. /**
  391. * Returns the auto-like data.
  392. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  393. */
  394. export function getAutoLikeDataInterface(token: string | undefined) {
  395. if(resolveToken(token) === undefined)
  396. return;
  397. return autoLikeStore.getData();
  398. }
  399. /**
  400. * Saves new auto-like data, synchronously to the in-memory cache and asynchronously to the persistent storage.
  401. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  402. */
  403. export function saveAutoLikeDataInterface(token: string | undefined, data: AutoLikeData) {
  404. if(resolveToken(token) === undefined)
  405. return;
  406. return autoLikeStore.setData(data);
  407. }