interface.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import * as UserUtils from "@sv443-network/userutils";
  2. import * as compareVersions from "compare-versions";
  3. import { mode, branch, host, buildNumber, compressionFormat, scriptInfo, initialParams, sessionStorageAvailable } 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, reloadTab, getVideoElement, getVideoSelector, pureObj } from "./utils/index.js";
  5. import { addSelectorListener } from "./observers.js";
  6. import { defaultData, 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 { showPrompt } from "./dialogs/prompt.js";
  11. import { BytmDialog } from "./components/BytmDialog.js";
  12. import { createHotkeyInput } from "./components/hotkeyInput.js";
  13. import { createToggleInput } from "./components/toggleInput.js";
  14. import { createCircularBtn } from "./components/circularButton.js";
  15. import { createRipple } from "./components/ripple.js";
  16. import { showIconToast, showToast } from "./components/toast.js";
  17. import { ExImDialog } from "./components/ExImDialog.js";
  18. import { MarkdownDialog } from "./components/MarkdownDialog.js";
  19. const { autoPlural, getUnsafeWindow, randomId, NanoEmitter } = UserUtils;
  20. //#region interface globals
  21. /** All events that can be emitted on the BYTM interface and the data they provide */
  22. export type InterfaceEventsMap = {
  23. [K in keyof InterfaceEvents]: (data: InterfaceEvents[K]) => void;
  24. };
  25. /** All events that can be emitted on the BYTM interface and the data they provide */
  26. export type InterfaceEvents = {
  27. //#region startup events
  28. // (sorted in order of execution)
  29. /** Emitted as soon as the feature config has finished loading and can be accessed via `unsafeWindow.BYTM.getFeatures(token)` */
  30. "bytm:configReady": undefined;
  31. /** Emitted when the lyrics cache has been loaded */
  32. "bytm:lyricsCacheReady": undefined;
  33. /** Emitted whenever the locale is changed - if a plugin changed the locale, the plugin ID is provided as well */
  34. "bytm:setLocale": { locale: TrLocale, pluginId?: string };
  35. /** When this is emitted, this is your call to register your plugin using the function passed as the sole argument */
  36. "bytm:registerPlugin": (pluginDef: PluginDef) => PluginRegisterResult;
  37. /**
  38. * Emitted whenever the SelectorObserver instances have been initialized and can be used to listen for DOM changes and wait for elements to be available.
  39. * Use `unsafeWindow.BYTM.addObserverListener(name, selector, opts)` to add custom listener functions to the observers (see contributing guide).
  40. */
  41. "bytm:observersReady": undefined;
  42. /**
  43. * Emitted when the feature initialization has started.
  44. * This is the last event that is emitted before the `bytm:ready` event.
  45. * As soon as this is emitted, you cannot register any more plugins.
  46. */
  47. "bytm:featureInitStarted": 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 (or undefined in the case of the config menu) */
  61. "bytm:dialogOpened": BytmDialog | undefined;
  62. /** 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 */
  63. "bytm:dialogOpened:id": BytmDialog | undefined;
  64. /** Emitted when a dialog was closed - returns the dialog's instance (or undefined in the case of the config menu) */
  65. "bytm:dialogClosed": BytmDialog | undefined;
  66. /** 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 */
  67. "bytm:dialogClosed:id": BytmDialog | undefined;
  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:registerPlugin",
  81. "bytm:ready",
  82. "bytm:featureInitfeatureInitStarted",
  83. "bytm:fatalError",
  84. "bytm:observersReady",
  85. "bytm:configReady",
  86. "bytm:setLocale",
  87. "bytm:dialogOpened",
  88. "bytm:dialogOpened:id",
  89. "bytm:lyricsLoaded",
  90. "bytm:lyricsCacheReady",
  91. "bytm:lyricsCacheCleared",
  92. "bytm:lyricsCacheEntryAdded",
  93. ...allSiteEvents.map(e => `bytm:siteEvent:${e}`),
  94. ] as const;
  95. /**
  96. * All functions that can be called on the BYTM interface using `unsafeWindow.BYTM.functionName();` (or `const { functionName } = unsafeWindow.BYTM;`)
  97. * If prefixed with /\*🔒\*\/, the function is authenticated and requires a token to be passed as the first argument.
  98. */
  99. const globalFuncs: InterfaceFunctions = pureObj({
  100. // meta:
  101. /*🔒*/ getPluginInfo,
  102. // bytm-specific:
  103. getDomain,
  104. getResourceUrl,
  105. getSessionId,
  106. reloadTab,
  107. // dom:
  108. setInnerHtml,
  109. addSelectorListener,
  110. onInteraction,
  111. getVideoTime,
  112. getThumbnailUrl,
  113. getBestThumbnailUrl,
  114. waitVideoElementReady,
  115. getVideoElement,
  116. getVideoSelector,
  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. getDefaultFeatures: () => JSON.parse(JSON.stringify(defaultData)),
  131. // lyrics:
  132. fetchLyricsUrlTop,
  133. getLyricsCacheEntry,
  134. sanitizeArtists,
  135. sanitizeSong,
  136. // auto-like:
  137. /*🔒*/ getAutoLikeData: getAutoLikeDataInterface,
  138. /*🔒*/ saveAutoLikeData: saveAutoLikeDataInterface,
  139. fetchVideoVotes,
  140. // components:
  141. createHotkeyInput,
  142. createToggleInput,
  143. createCircularBtn,
  144. createRipple,
  145. showToast,
  146. showIconToast,
  147. showPrompt,
  148. // other:
  149. formatNumber,
  150. });
  151. /** Initializes the BYTM interface */
  152. export function initInterface() {
  153. const props = {
  154. // meta / constants
  155. mode,
  156. branch,
  157. host,
  158. buildNumber,
  159. initialParams,
  160. compressionFormat,
  161. sessionStorageAvailable,
  162. ...scriptInfo,
  163. // functions
  164. ...globalFuncs,
  165. // classes
  166. NanoEmitter,
  167. BytmDialog,
  168. ExImDialog,
  169. MarkdownDialog,
  170. // libraries
  171. UserUtils,
  172. compareVersions,
  173. };
  174. for(const [key, value] of Object.entries(props))
  175. setGlobalProp(key, value);
  176. log("Initialized BYTM interface");
  177. }
  178. /** Sets a global property on the unsafeWindow.BYTM object - ⚠️ use with caution as these props can be accessed by any script on the page! */
  179. export function setGlobalProp<
  180. TKey extends keyof BytmObject,
  181. TValue = BytmObject[TKey],
  182. >(
  183. key: TKey | (string & {}),
  184. value: TValue,
  185. ) {
  186. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  187. const win = getUnsafeWindow();
  188. if(typeof win.BYTM !== "object")
  189. win.BYTM = pureObj({}) as BytmObject;
  190. win.BYTM[key] = value;
  191. }
  192. /** Emits an event on the BYTM interface */
  193. export function emitInterface<
  194. TEvt extends keyof InterfaceEvents,
  195. TDetail extends InterfaceEvents[TEvt],
  196. >(
  197. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  198. ...detail: (TDetail extends undefined ? [undefined?] : [TDetail])
  199. ) {
  200. try {
  201. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: detail?.[0] ?? undefined }));
  202. //@ts-ignore
  203. emitOnPlugins(type, undefined, ...detail);
  204. log(`Emitted interface event '${type}'${detail.length > 0 && detail?.[0] ? " with data:" : ""}`, ...detail);
  205. }
  206. catch(err) {
  207. error(`Couldn't emit interface event '${type}' due to an error:\n`, err);
  208. }
  209. }
  210. //#region register plugins
  211. /** Map of plugin ID and all registered plugins */
  212. const registeredPlugins = new Map<string, PluginItem>();
  213. /** Map of plugin ID to auth token for plugins that have been registered */
  214. const registeredPluginTokens = new Map<string, string>();
  215. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  216. export function initPlugins() {
  217. // TODO: check perms and ask user for initial activation
  218. const registerPlugin = (def: PluginDef): PluginRegisterResult => {
  219. try {
  220. const plKey = getPluginKey(def);
  221. if(registeredPlugins.has(plKey))
  222. throw new PluginError(`Failed to register plugin '${plKey}': Plugin with the same name and namespace is already registered`);
  223. const validationErrors = validatePluginDef(def);
  224. if(validationErrors)
  225. throw new PluginError(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`);
  226. const events = new NanoEmitter<PluginEventMap>({ publicEmit: true });
  227. const token = randomId(32, 36, true);
  228. registeredPlugins.set(plKey, {
  229. def: def,
  230. events,
  231. });
  232. registeredPluginTokens.set(plKey, token);
  233. info(`Successfully registered plugin '${plKey}'`);
  234. setTimeout(() => emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!), 1);
  235. return {
  236. info: getPluginInfo(token, def)!,
  237. events,
  238. token,
  239. };
  240. }
  241. catch(err) {
  242. error(`Failed to register plugin '${getPluginKey(def)}':`, err instanceof PluginError ? err : new PluginError(String(err)));
  243. throw err;
  244. }
  245. };
  246. emitInterface("bytm:registerPlugin", (def: PluginDef) => registerPlugin(def));
  247. if(registeredPlugins.size > 0)
  248. log(`Registered ${registeredPlugins.size} ${autoPlural("plugin", registeredPlugins.size)}`);
  249. }
  250. /** Returns the registered plugins as an array of tuples with the items `[id: string, item: PluginItem]` */
  251. export function getRegisteredPlugins() {
  252. return [...registeredPlugins.entries()];
  253. }
  254. /** Returns the key for a given plugin definition */
  255. function getPluginKey(plugin: PluginDefResolvable) {
  256. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  257. }
  258. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  259. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  260. return plugin
  261. ? {
  262. name: plugin.plugin.name,
  263. namespace: plugin.plugin.namespace,
  264. version: plugin.plugin.version,
  265. }
  266. : undefined;
  267. }
  268. /** Checks whether two plugins are the same, given their resolvable definition objects */
  269. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  270. return getPluginKey(def1) === getPluginKey(def2);
  271. }
  272. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  273. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  274. event: TEvtKey,
  275. predicate: ((def: PluginDef) => boolean) | boolean = true,
  276. ...data: Parameters<PluginEventMap[TEvtKey]>
  277. ) {
  278. for(const { def, events } of registeredPlugins.values())
  279. if(typeof predicate === "boolean" ? predicate : predicate(def))
  280. events.emit(event, ...data);
  281. }
  282. /**
  283. * @private FOR INTERNAL USE ONLY!
  284. * Returns the internal plugin def and events objects via its name and namespace, or undefined if it doesn't exist.
  285. */
  286. export function getPlugin(pluginName: string, namespace: string): PluginItem | undefined
  287. /**
  288. * @private FOR INTERNAL USE ONLY!
  289. * Returns the internal plugin def and events objects via resolvable definition, or undefined if it doesn't exist.
  290. */
  291. export function getPlugin(pluginDef: PluginDefResolvable): PluginItem | undefined
  292. /**
  293. * @private FOR INTERNAL USE ONLY!
  294. * Returns the internal plugin def and events objects via plugin ID (consisting of namespace and name), or undefined if it doesn't exist.
  295. */
  296. export function getPlugin(pluginId: string): PluginItem | undefined
  297. /**
  298. * @private FOR INTERNAL USE ONLY!
  299. * Returns the internal plugin def and events objects, or undefined if it doesn't exist.
  300. */
  301. export function getPlugin(...args: [pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  302. return typeof args[0] === "string" && typeof args[1] === "undefined"
  303. ? registeredPlugins.get(args[0])
  304. : args.length === 2
  305. ? registeredPlugins.get(`${args[1]}/${args[0]}`)
  306. : registeredPlugins.get(getPluginKey(args[0] as PluginDefResolvable));
  307. }
  308. /**
  309. * Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered.
  310. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  311. * @public Intended for general use in plugins.
  312. */
  313. export function getPluginInfo(token: string | undefined, name: string, namespace: string): PluginInfo | undefined
  314. /**
  315. * Returns info about a registered plugin on the BYTM interface by a resolvable definition object, or undefined if the plugin isn't registered.
  316. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  317. * @public Intended for general use in plugins.
  318. */
  319. export function getPluginInfo(token: string | undefined, plugin: PluginDefResolvable): PluginInfo | undefined
  320. /**
  321. * 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.
  322. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  323. * @public Intended for general use in plugins.
  324. */
  325. export function getPluginInfo(token: string | undefined, pluginId: string): PluginInfo | undefined
  326. /**
  327. * Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered.
  328. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  329. * @public Intended for general use in plugins.
  330. */
  331. export function getPluginInfo(...args: [token: string | undefined, pluginDefOrNameOrId: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  332. if(resolveToken(args[0]) === undefined)
  333. return undefined;
  334. return pluginDefToInfo(
  335. registeredPlugins.get(
  336. typeof args[1] === "string" && typeof args[2] === "undefined"
  337. ? args[1]
  338. : args.length === 2
  339. ? `${args[2]}/${args[1]}`
  340. : getPluginKey(args[1] as PluginDefResolvable)
  341. )?.def
  342. );
  343. }
  344. /** Validates the passed PluginDef object and returns an array of errors - returns undefined if there were no errors - never returns an empty array */
  345. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  346. const errors = [] as string[];
  347. const addNoPropErr = (jsonPath: string, type: string) =>
  348. errors.push(t("plugin_validation_error_no_property", jsonPath, type));
  349. const addInvalidPropErr = (jsonPath: string, value: string, examples: string[]) =>
  350. errors.push(tp("plugin_validation_error_invalid_property", examples, jsonPath, value, `'${examples.join("', '")}'`));
  351. // def.plugin and its properties:
  352. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  353. const { plugin } = pluginDef;
  354. !plugin?.name && addNoPropErr("plugin.name", "string");
  355. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  356. if(typeof plugin?.version !== "string")
  357. addNoPropErr("plugin.version", "MAJOR.MINOR.PATCH");
  358. else if(!compareVersions.validateStrict(plugin.version))
  359. addInvalidPropErr("plugin.version", plugin.version, ["0.0.1", "2.5.21-rc.1"]);
  360. return errors.length > 0 ? errors : undefined;
  361. }
  362. /** Checks whether the passed token is a valid auth token for any registered plugin and returns the plugin ID, else returns undefined */
  363. export function resolveToken(token: string | undefined): string | undefined {
  364. return typeof token === "string" && token.length > 0
  365. ? [...registeredPluginTokens.entries()]
  366. .find(([k, t]) => registeredPlugins.has(k) && token === t)?.[0] ?? undefined
  367. : undefined;
  368. }
  369. //#region proxy funcs
  370. /**
  371. * Sets the new locale on the BYTM interface
  372. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  373. */
  374. export function setLocaleInterface(token: string | undefined, locale: TrLocale) {
  375. const pluginId = resolveToken(token);
  376. if(pluginId === undefined)
  377. return;
  378. setLocale(locale);
  379. emitInterface("bytm:setLocale", { pluginId, locale });
  380. }
  381. /**
  382. * Returns the current feature config, with sensitive values replaced by `undefined`
  383. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  384. */
  385. export function getFeaturesInterface(token: string | undefined) {
  386. if(resolveToken(token) === undefined)
  387. return undefined;
  388. const features = getFeatures();
  389. for(const ftKey of Object.keys(features)) {
  390. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  391. if(info && info.valueHidden) // @ts-ignore
  392. features[ftKey as keyof typeof features] = undefined;
  393. }
  394. return features as FeatureConfig;
  395. }
  396. /**
  397. * Saves the passed feature config synchronously to the in-memory cache and asynchronously to the persistent storage.
  398. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  399. */
  400. export function saveFeaturesInterface(token: string | undefined, features: FeatureConfig) {
  401. if(resolveToken(token) === undefined)
  402. return;
  403. setFeatures(features);
  404. }
  405. /**
  406. * Returns the auto-like data.
  407. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  408. */
  409. export function getAutoLikeDataInterface(token: string | undefined) {
  410. if(resolveToken(token) === undefined)
  411. return;
  412. return autoLikeStore.getData();
  413. }
  414. /**
  415. * Saves new auto-like data, synchronously to the in-memory cache and asynchronously to the persistent storage.
  416. * This is an authenticated function so you must pass the session- and plugin-unique token, retreived at registration.
  417. */
  418. export function saveAutoLikeDataInterface(token: string | undefined, data: AutoLikeData) {
  419. if(resolveToken(token) === undefined)
  420. return;
  421. return autoLikeStore.setData(data);
  422. }