interface.ts 19 KB

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