interface.ts 19 KB

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