interface.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 { getDomain, waitVideoElementReady, getResourceUrl, getSessionId, getVideoTime, log, setLocale, getLocale, hasKey, hasKeyFor, t, tp, type TrLocale, info, error, onInteraction, getThumbnailUrl, getBestThumbnailUrl, fetchVideoVotes, setInnerHtml, getCurrentMediaType, tl, tlp, PluginError, formatNumber } 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 { 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, MarkdownDialog, createCircularBtn, createHotkeyInput, createRipple, createToggleInput, showIconToast, showToast } from "./components/index.js";
  11. import { showPrompt } from "./dialogs/prompt.js";
  12. const { autoPlural, getUnsafeWindow, randomId, NanoEmitter } = 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 - if a plugin changed the locale, the plugin ID is provided as well */
  27. "bytm:setLocale": { locale: TrLocale, pluginId?: string };
  28. /** When this is emitted, this is your call to register your plugin using the function passed as the sole argument */
  29. "bytm:registerPlugin": (pluginDef: PluginDef) => PluginRegisterResult;
  30. /**
  31. * Emitted whenever the SelectorObserver instances have been initialized and can be used to listen for DOM changes and wait for elements to be available.
  32. * Use `unsafeWindow.BYTM.addObserverListener(name, selector, opts)` to add custom listener functions to the observers (see contributing guide).
  33. */
  34. "bytm:observersReady": undefined;
  35. /**
  36. * Emitted when the feature initialization has started.
  37. * This is the last event that is emitted before the `bytm:ready` event.
  38. * As soon as this is emitted, you cannot register any more plugins.
  39. */
  40. "bytm:featureInitStarted": undefined;
  41. /** Emitted when a feature has been initialized. The data is the feature's key as seen in `onDomLoad()` of `src/index.ts` */
  42. "bytm:featureInitialized": string;
  43. /** Emitted when BYTM has finished initializing all features or has reached the init timeout and has entered an idle state. */
  44. "bytm:ready": undefined;
  45. //#region additional events
  46. // (not sorted)
  47. /**
  48. * Emitted when a fatal error occurs and the script can't continue to run.
  49. * Returns a short error description that's not really meant to be displayed to the user (console is fine).
  50. * But may be helpful in plugin development if the plugin causes an internal error.
  51. */
  52. "bytm:fatalError": string;
  53. /** Emitted when a dialog was opened - returns the dialog's instance (or undefined in the case of the config menu) */
  54. "bytm:dialogOpened": BytmDialog | undefined;
  55. /** Emitted when the dialog with the specified ID was opened - returns the dialog's instance (or undefined in the case of the config menu) - in TS, use `"bytm:dialogOpened:myIdWhatever" as "bytm:dialogOpened:id"` to make the error go away */
  56. "bytm:dialogOpened:id": BytmDialog | undefined;
  57. /** Emitted when a dialog was closed - returns the dialog's instance (or undefined in the case of the config menu) */
  58. "bytm:dialogClosed": BytmDialog | undefined;
  59. /** Emitted when the dialog with the specified ID was closed - returns the dialog's instance (or undefined in the case of the config menu) - in TS, use `"bytm:dialogClosed:myIdWhatever" as "bytm:dialogClosed:id"` to make the error go away */
  60. "bytm:dialogClosed:id": BytmDialog | undefined;
  61. /** Emitted whenever the lyrics URL for a song is loaded */
  62. "bytm:lyricsLoaded": { type: "current" | "queue", artists: string, title: string, url: string };
  63. /** Emitted when the lyrics cache has been cleared */
  64. "bytm:lyricsCacheCleared": undefined;
  65. /** 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 */
  66. "bytm:lyricsCacheEntryAdded": { type: "best" | "penalized", entry: LyricsCacheEntry };
  67. // NOTE:
  68. // Additionally, all events from `SiteEventsMap` in `src/siteEvents.ts`
  69. // are emitted in this format: "bytm:siteEvent:nameOfSiteEvent"
  70. };
  71. /** Array of all events emittable on the interface (excluding plugin-specific, private events) */
  72. export const allInterfaceEvents = [
  73. "bytm:registerPlugin",
  74. "bytm:ready",
  75. "bytm:featureInitfeatureInitStarted",
  76. "bytm:fatalError",
  77. "bytm:observersReady",
  78. "bytm:configReady",
  79. "bytm:setLocale",
  80. "bytm:dialogOpened",
  81. "bytm:dialogOpened:id",
  82. "bytm:lyricsLoaded",
  83. "bytm:lyricsCacheReady",
  84. "bytm:lyricsCacheCleared",
  85. "bytm:lyricsCacheEntryAdded",
  86. ...allSiteEvents.map(e => `bytm:siteEvent:${e}`),
  87. ] as const;
  88. /**
  89. * All functions that can be called on the BYTM interface using `unsafeWindow.BYTM.functionName();` (or `const { functionName } = unsafeWindow.BYTM;`)
  90. * If prefixed with /\*🔒\*\/, the function is authenticated and requires a token to be passed as the first argument.
  91. */
  92. const globalFuncs: InterfaceFunctions = {
  93. // meta:
  94. /*🔒*/ getPluginInfo,
  95. // bytm-specific:
  96. getDomain,
  97. getResourceUrl,
  98. getSessionId,
  99. // dom:
  100. setInnerHtml,
  101. addSelectorListener,
  102. onInteraction,
  103. getVideoTime,
  104. getThumbnailUrl,
  105. getBestThumbnailUrl,
  106. waitVideoElementReady,
  107. getCurrentMediaType,
  108. // translations:
  109. /*🔒*/ setLocale: setLocaleInterface,
  110. getLocale,
  111. hasKey,
  112. hasKeyFor,
  113. t,
  114. tp,
  115. tl,
  116. tlp,
  117. // feature config:
  118. /*🔒*/ getFeatures: getFeaturesInterface,
  119. /*🔒*/ saveFeatures: saveFeaturesInterface,
  120. // lyrics:
  121. fetchLyricsUrlTop,
  122. getLyricsCacheEntry,
  123. sanitizeArtists,
  124. sanitizeSong,
  125. // auto-like:
  126. /*🔒*/ getAutoLikeData: getAutoLikeDataInterface,
  127. /*🔒*/ saveAutoLikeData: saveAutoLikeDataInterface,
  128. fetchVideoVotes,
  129. // components:
  130. createHotkeyInput,
  131. createToggleInput,
  132. createCircularBtn,
  133. createRipple,
  134. showToast,
  135. showIconToast,
  136. showPrompt,
  137. // other:
  138. formatNumber,
  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. MarkdownDialog,
  157. // libraries
  158. UserUtils,
  159. compareVersions,
  160. };
  161. for(const [key, value] of Object.entries(props))
  162. setGlobalProp(key, value);
  163. log("Initialized BYTM interface");
  164. }
  165. /** Sets a global property on the unsafeWindow.BYTM object - ⚠️ use with caution as these props can be accessed by any script on the page! */
  166. export function setGlobalProp<
  167. TKey extends keyof BytmObject,
  168. TValue = BytmObject[TKey],
  169. >(
  170. key: TKey | (string & {}),
  171. value: TValue,
  172. ) {
  173. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  174. const win = getUnsafeWindow();
  175. if(typeof win.BYTM !== "object")
  176. win.BYTM = {} as BytmObject;
  177. win.BYTM[key] = value;
  178. }
  179. /** Emits an event on the BYTM interface */
  180. export function emitInterface<
  181. TEvt extends keyof InterfaceEvents,
  182. TDetail extends InterfaceEvents[TEvt],
  183. >(
  184. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  185. ...detail: (TDetail extends undefined ? [undefined?] : [TDetail])
  186. ) {
  187. try {
  188. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: detail?.[0] ?? undefined }));
  189. //@ts-ignore
  190. emitOnPlugins(type, undefined, ...detail);
  191. log(`Emitted interface event '${type}'${detail.length > 0 && detail?.[0] ? " with data:" : ""}`, ...detail);
  192. }
  193. catch(err) {
  194. error(`Couldn't emit interface event '${type}' due to an error:\n`, err);
  195. }
  196. }
  197. //#region register plugins
  198. /** Map of plugin ID and all registered plugins */
  199. const registeredPlugins = new Map<string, PluginItem>();
  200. /** Map of plugin ID to auth token for plugins that have been registered */
  201. const registeredPluginTokens = new Map<string, string>();
  202. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  203. export function initPlugins() {
  204. // TODO: check perms and ask user for initial activation
  205. const registerPlugin = (def: PluginDef): PluginRegisterResult => {
  206. try {
  207. const plKey = getPluginKey(def);
  208. if(registeredPlugins.has(plKey))
  209. throw new PluginError(`Failed to register plugin '${plKey}': Plugin with the same name and namespace is already registered`);
  210. const validationErrors = validatePluginDef(def);
  211. if(validationErrors)
  212. throw new PluginError(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`);
  213. const events = new NanoEmitter<PluginEventMap>({ publicEmit: true });
  214. const token = randomId(32, 36, true);
  215. registeredPlugins.set(plKey, {
  216. def: def,
  217. events,
  218. });
  219. registeredPluginTokens.set(plKey, token);
  220. info(`Successfully registered plugin '${plKey}'`);
  221. setTimeout(() => emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!), 1);
  222. return {
  223. info: getPluginInfo(token, def)!,
  224. events,
  225. token,
  226. };
  227. }
  228. catch(err) {
  229. error(`Failed to register plugin '${getPluginKey(def)}':`, err instanceof PluginError ? err : new PluginError(String(err)));
  230. throw err;
  231. }
  232. };
  233. emitInterface("bytm:registerPlugin", (def: PluginDef) => registerPlugin(def));
  234. if(registeredPlugins.size > 0)
  235. log(`Registered ${registeredPlugins.size} ${autoPlural("plugin", registeredPlugins.size)}`);
  236. }
  237. /** Returns the registered plugins as an array of tuples with the items `[id: string, item: PluginItem]` */
  238. export function getRegisteredPlugins() {
  239. return [...registeredPlugins.entries()];
  240. }
  241. /** Returns the key for a given plugin definition */
  242. function getPluginKey(plugin: PluginDefResolvable) {
  243. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  244. }
  245. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  246. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  247. return plugin
  248. ? {
  249. name: plugin.plugin.name,
  250. namespace: plugin.plugin.namespace,
  251. version: plugin.plugin.version,
  252. }
  253. : undefined;
  254. }
  255. /** Checks whether two plugins are the same, given their resolvable definition objects */
  256. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  257. return getPluginKey(def1) === getPluginKey(def2);
  258. }
  259. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  260. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  261. event: TEvtKey,
  262. predicate: ((def: PluginDef) => boolean) | boolean = true,
  263. ...data: Parameters<PluginEventMap[TEvtKey]>
  264. ) {
  265. for(const { def, events } of registeredPlugins.values())
  266. if(typeof predicate === "boolean" ? predicate : predicate(def))
  267. events.emit(event, ...data);
  268. }
  269. /**
  270. * @private FOR INTERNAL USE ONLY!
  271. * Returns the internal plugin def and events objects via its name and namespace, or undefined if it doesn't exist.
  272. */
  273. export function getPlugin(pluginName: string, namespace: string): PluginItem | undefined
  274. /**
  275. * @private FOR INTERNAL USE ONLY!
  276. * Returns the internal plugin def and events objects via resolvable definition, or undefined if it doesn't exist.
  277. */
  278. export function getPlugin(pluginDef: PluginDefResolvable): PluginItem | undefined
  279. /**
  280. * @private FOR INTERNAL USE ONLY!
  281. * Returns the internal plugin def and events objects via plugin ID (consisting of namespace and name), or undefined if it doesn't exist.
  282. */
  283. export function getPlugin(pluginId: string): PluginItem | undefined
  284. /**
  285. * @private FOR INTERNAL USE ONLY!
  286. * Returns the internal plugin def and events objects, or undefined if it doesn't exist.
  287. */
  288. export function getPlugin(...args: [pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  289. return typeof args[0] === "string" && typeof args[1] === "undefined"
  290. ? registeredPlugins.get(args[0])
  291. : args.length === 2
  292. ? registeredPlugins.get(`${args[1]}/${args[0]}`)
  293. : registeredPlugins.get(getPluginKey(args[0] as PluginDefResolvable));
  294. }
  295. /**
  296. * Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered.
  297. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  298. * @public Intended for general use in plugins.
  299. */
  300. export function getPluginInfo(token: string | undefined, name: string, namespace: string): PluginInfo | undefined
  301. /**
  302. * Returns info about a registered plugin on the BYTM interface by a resolvable definition object, or undefined if the plugin isn't registered.
  303. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  304. * @public Intended for general use in plugins.
  305. */
  306. export function getPluginInfo(token: string | undefined, plugin: PluginDefResolvable): PluginInfo | undefined
  307. /**
  308. * 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.
  309. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  310. * @public Intended for general use in plugins.
  311. */
  312. export function getPluginInfo(token: string | undefined, pluginId: string): PluginInfo | undefined
  313. /**
  314. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  315. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  316. * @public Intended for general use in plugins.
  317. */
  318. export function getPluginInfo(...args: [token: string | undefined, pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  319. if(resolveToken(args[0]) === undefined)
  320. return undefined;
  321. return pluginDefToInfo(
  322. registeredPlugins.get(
  323. typeof args[1] === "string" && typeof args[2] === "undefined"
  324. ? args[1]
  325. : args.length === 2
  326. ? `${args[2]}/${args[1]}`
  327. : getPluginKey(args[1] as PluginDefResolvable)
  328. )?.def
  329. );
  330. }
  331. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  332. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  333. const errors = [] as string[];
  334. const addNoPropErr = (jsonPath: string, type: string) =>
  335. errors.push(t("plugin_validation_error_no_property", jsonPath, type));
  336. const addInvalidPropErr = (jsonPath: string, value: string, examples: string[]) =>
  337. errors.push(tp("plugin_validation_error_invalid_property", examples, jsonPath, value, `'${examples.join("', '")}'`));
  338. // def.plugin and its properties:
  339. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  340. const { plugin } = pluginDef;
  341. !plugin?.name && addNoPropErr("plugin.name", "string");
  342. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  343. if(typeof plugin?.version !== "string")
  344. addNoPropErr("plugin.version", "MAJOR.MINOR.PATCH");
  345. else if(!compareVersions.validateStrict(plugin.version))
  346. addInvalidPropErr("plugin.version", plugin.version, ["0.0.1", "2.5.21-rc.1"]);
  347. return errors.length > 0 ? errors : undefined;
  348. }
  349. /** Checks whether the passed token is a valid auth token for any registered plugin and returns the plugin ID, else returns undefined */
  350. export function resolveToken(token: string | undefined): string | undefined {
  351. return typeof token === "string" && token.length > 0
  352. ? [...registeredPluginTokens.entries()]
  353. .find(([k, t]) => registeredPlugins.has(k) && token === t)?.[0] ?? undefined
  354. : undefined;
  355. }
  356. //#region proxy funcs
  357. /**
  358. * Sets the new locale on the BYTM interface
  359. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  360. */
  361. export function setLocaleInterface(token: string | undefined, locale: TrLocale) {
  362. const pluginId = resolveToken(token);
  363. if(pluginId === undefined)
  364. return;
  365. setLocale(locale);
  366. emitInterface("bytm:setLocale", { pluginId, locale });
  367. }
  368. /**
  369. * Returns the current feature config, with sensitive values replaced by `undefined`
  370. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  371. */
  372. export function getFeaturesInterface(token: string | undefined) {
  373. if(resolveToken(token) === undefined)
  374. return undefined;
  375. const features = getFeatures();
  376. for(const ftKey of Object.keys(features)) {
  377. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  378. if(info && info.valueHidden) // @ts-ignore
  379. features[ftKey as keyof typeof features] = undefined;
  380. }
  381. return features as FeatureConfig;
  382. }
  383. /**
  384. * Saves the passed feature config synchronously to the in-memory cache and asynchronously to the persistent storage.
  385. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  386. */
  387. export function saveFeaturesInterface(token: string | undefined, features: FeatureConfig) {
  388. if(resolveToken(token) === undefined)
  389. return;
  390. setFeatures(features);
  391. }
  392. /**
  393. * Returns the auto-like data.
  394. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  395. */
  396. export function getAutoLikeDataInterface(token: string | undefined) {
  397. if(resolveToken(token) === undefined)
  398. return;
  399. return autoLikeStore.getData();
  400. }
  401. /**
  402. * Saves new auto-like data, synchronously to the in-memory cache and asynchronously to the persistent storage.
  403. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  404. */
  405. export function saveAutoLikeDataInterface(token: string | undefined, data: AutoLikeData) {
  406. if(resolveToken(token) === undefined)
  407. return;
  408. return autoLikeStore.setData(data);
  409. }