index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import { compress, decompress, pauseFor, type Stringifiable } from "@sv443-network/userutils";
  2. import { addStyleFromResource, domLoaded, warn } from "./utils";
  3. import { clearConfig, fixMissingCfgKeys, getFeatures, initConfig, setFeatures } from "./config";
  4. import { buildNumber, compressionFormat, defaultLogLevel, mode, scriptInfo } from "./constants";
  5. import { error, getDomain, info, getSessionId, log, setLogLevel, initTranslations, setLocale } from "./utils";
  6. import { initSiteEvents } from "./siteEvents";
  7. import { emitInterface, initInterface, initPlugins } from "./interface";
  8. import { initObservers, addSelectorListener, globservers } from "./observers";
  9. import { getWelcomeDialog } from "./dialogs";
  10. import type { FeatureConfig } from "./types";
  11. import {
  12. // layout
  13. addWatermark, removeUpgradeTab, initRemShareTrackParam, fixSpacing, initThumbnailOverlay, initHideCursorOnIdle, fixHdrIssues,
  14. // volume
  15. initVolumeFeatures,
  16. // song lists
  17. initQueueButtons, initAboveQueueBtns,
  18. // behavior
  19. initBeforeUnloadHook, disableBeforeUnload, initAutoCloseToasts, initRememberSongTime, disableDarkReader,
  20. // input
  21. initArrowKeySkip, initSiteSwitch, addAnchorImprovements, initNumKeysSkip,
  22. // lyrics
  23. addMediaCtrlLyricsBtn, initLyricsCache,
  24. // menu
  25. addConfigMenuOptionYT, addConfigMenuOptionYTM,
  26. // general
  27. initVersionCheck,
  28. } from "./features";
  29. //#region console watermark
  30. {
  31. // console watermark with sexy gradient
  32. const styleGradient = "background: rgba(165, 38, 38, 1); background: linear-gradient(90deg, rgb(154, 31, 103) 0%, rgb(135, 31, 31) 40%, rgb(184, 64, 41) 100%);";
  33. const styleCommon = "color: #fff; font-size: 1.3rem;";
  34. console.log();
  35. console.log(
  36. `%c${scriptInfo.name}%c${scriptInfo.version}%c • ${scriptInfo.namespace}%c\n\nBuild #${buildNumber}`,
  37. `${styleCommon} ${styleGradient} font-weight: bold; padding-left: 6px; padding-right: 6px;`,
  38. `${styleCommon} background-color: #333; padding-left: 8px; padding-right: 8px;`,
  39. "color: #fff; font-size: 1.2rem;",
  40. "padding: initial;",
  41. );
  42. console.log([
  43. "Powered by:",
  44. "─ Lots of ambition and dedication",
  45. "─ My song metadata API: https://api.sv443.net/geniurl",
  46. "─ My userscript utility library: https://github.com/Sv443-Network/UserUtils",
  47. "─ This library for semver comparison: https://github.com/omichelsen/compare-versions",
  48. "─ This tiny event listener library: https://github.com/ai/nanoevents",
  49. "─ This markdown parser library: https://github.com/markedjs/marked",
  50. "─ This fuzzy search library: https://github.com/krisk/Fuse",
  51. ].join("\n"));
  52. console.log();
  53. }
  54. //#region preInit
  55. /** Stuff that needs to be called ASAP, before anything async happens */
  56. function preInit() {
  57. try {
  58. const domain = getDomain();
  59. log("Session ID:", getSessionId());
  60. initInterface();
  61. setLogLevel(defaultLogLevel);
  62. if(domain === "ytm")
  63. initBeforeUnloadHook();
  64. init();
  65. }
  66. catch(err) {
  67. return error("Fatal pre-init error:", err);
  68. }
  69. }
  70. //#region init
  71. async function init() {
  72. try {
  73. const domain = getDomain();
  74. const features = await initConfig();
  75. setLogLevel(features.logLevel);
  76. await initLyricsCache();
  77. await initTranslations(features.locale ?? "en_US");
  78. setLocale(features.locale ?? "en_US");
  79. emitInterface("bytm:initPlugins");
  80. if(features.disableBeforeUnloadPopup && domain === "ytm")
  81. disableBeforeUnload();
  82. if(!domLoaded)
  83. document.addEventListener("DOMContentLoaded", onDomLoad, { once: true });
  84. else
  85. onDomLoad();
  86. if(features.rememberSongTime)
  87. initRememberSongTime();
  88. }
  89. catch(err) {
  90. error("Fatal error:", err);
  91. }
  92. }
  93. //#region onDomLoad
  94. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  95. async function onDomLoad() {
  96. const domain = getDomain();
  97. const features = getFeatures();
  98. const ftInit = [] as [string, Promise<void>][];
  99. try {
  100. initObservers();
  101. await Promise.allSettled([
  102. insertGlobalStyle(),
  103. initVersionCheck(),
  104. ]);
  105. }
  106. catch(err) {
  107. error("Fatal error in feature pre-init:", err);
  108. return;
  109. }
  110. log(`DOM loaded and feature pre-init finished, now initializing all features for domain "${domain}"...`);
  111. try {
  112. if(domain === "ytm") {
  113. //#region (ytm) misc
  114. ftInit.push(["initSiteEvents", initSiteEvents()]);
  115. //#region (ytm) welcome dlg
  116. if(typeof await GM.getValue("bytm-installed") !== "string") {
  117. // open welcome menu with language selector
  118. const dlg = await getWelcomeDialog();
  119. dlg.on("close", () => GM.setValue("bytm-installed", JSON.stringify({ timestamp: Date.now(), version: scriptInfo.version })));
  120. await dlg.mount();
  121. info("Showing welcome menu");
  122. await dlg.open();
  123. }
  124. //#region (ytm) layout
  125. if(features.watermarkEnabled)
  126. ftInit.push(["addWatermark", addWatermark()]);
  127. if(features.fixSpacing)
  128. ftInit.push(["fixSpacing", fixSpacing()]);
  129. if(features.removeUpgradeTab)
  130. ftInit.push(["removeUpgradeTab", removeUpgradeTab()]);
  131. ftInit.push(["initThumbnailOverlay", initThumbnailOverlay()]);
  132. if(features.hideCursorOnIdle)
  133. ftInit.push(["initHideCursorOnIdle", initHideCursorOnIdle()]);
  134. if(features.fixHdrIssues)
  135. ftInit.push(["fixHdrIssues", fixHdrIssues()]);
  136. //#region (ytm) volume
  137. ftInit.push(["initVolumeFeatures", initVolumeFeatures()]);
  138. //#region (ytm) song lists
  139. if(features.lyricsQueueButton || features.deleteFromQueueButton)
  140. ftInit.push(["initQueueButtons", initQueueButtons()]);
  141. ftInit.push(["initAboveQueueBtns", initAboveQueueBtns()]);
  142. //#region (ytm) behavior
  143. if(features.closeToastsTimeout > 0)
  144. ftInit.push(["initAutoCloseToasts", initAutoCloseToasts()]);
  145. //#region (ytm) input
  146. ftInit.push(["initArrowKeySkip", initArrowKeySkip()]);
  147. if(features.anchorImprovements)
  148. ftInit.push(["addAnchorImprovements", addAnchorImprovements()]);
  149. ftInit.push(["initNumKeysSkip", initNumKeysSkip()]);
  150. //#region (ytm) lyrics
  151. if(features.geniusLyrics)
  152. ftInit.push(["addMediaCtrlLyricsBtn", addMediaCtrlLyricsBtn()]);
  153. }
  154. //#region (ytm+yt) cfg menu option
  155. try {
  156. if(domain === "ytm") {
  157. addSelectorListener("body", "tp-yt-iron-dropdown #contentWrapper ytd-multi-page-menu-renderer #container.menu-container", {
  158. listener: addConfigMenuOptionYTM,
  159. });
  160. }
  161. else if(domain === "yt") {
  162. addSelectorListener<0, "yt">("ytGuide", "#sections ytd-guide-section-renderer:nth-child(5) #items ytd-guide-entry-renderer:nth-child(1)", {
  163. listener: (el) => el.parentElement && addConfigMenuOptionYT(el.parentElement),
  164. });
  165. }
  166. }
  167. catch(err) {
  168. error("Couldn't add config menu option:", err);
  169. }
  170. if(["ytm", "yt"].includes(domain)) {
  171. //#region (ytm+yt) layout
  172. if(features.disableDarkReaderSites !== "none")
  173. disableDarkReader();
  174. if(features.removeShareTrackingParamSites && (features.removeShareTrackingParamSites === domain || features.removeShareTrackingParamSites === "all"))
  175. ftInit.push(["initRemShareTrackParam", initRemShareTrackParam()]);
  176. //#region (ytm+yt) input
  177. ftInit.push(["initSiteSwitch", initSiteSwitch(domain)]);
  178. }
  179. const initStartTs = Date.now();
  180. // wait for feature init or timeout (in case an init function is hung up on a promise)
  181. await Promise.race([
  182. pauseFor(10_000),
  183. Promise.allSettled(ftInit.map(([, p]) => p)),
  184. ]);
  185. emitInterface("bytm:ready");
  186. info(`Done initializing all ${ftInit.length} features after ${Math.floor(Date.now() - initStartTs)}ms`);
  187. try {
  188. initPlugins();
  189. }
  190. catch(err) {
  191. error("Plugin loading error:", err);
  192. emitInterface("bytm:fatalError", "Error while loading plugins");
  193. }
  194. try {
  195. registerDevMenuCommands();
  196. }
  197. catch(e) {
  198. warn("Couldn't register dev menu commands:", e);
  199. }
  200. }
  201. catch(err) {
  202. error("Feature error:", err);
  203. emitInterface("bytm:fatalError", "Error while initializing features");
  204. }
  205. }
  206. //#region insert css bundle
  207. /** Inserts the bundled CSS files imported throughout the script into a <style> element in the <head> */
  208. async function insertGlobalStyle() {
  209. if(!await addStyleFromResource("css-bundle"))
  210. error("Couldn't add global CSS bundle due to an error");
  211. }
  212. //#region dev menu cmds
  213. /** Registers dev commands using `GM.registerMenuCommand` */
  214. function registerDevMenuCommands() {
  215. if(mode !== "development")
  216. return;
  217. GM.registerMenuCommand("Reset config", async () => {
  218. if(confirm("Reset the configuration to its default values?\nThis will automatically reload the page.")) {
  219. await clearConfig();
  220. disableBeforeUnload();
  221. location.reload();
  222. }
  223. }, "r");
  224. GM.registerMenuCommand("Fix missing config values", async () => {
  225. const oldFeats = JSON.parse(JSON.stringify(getFeatures())) as FeatureConfig;
  226. await setFeatures(fixMissingCfgKeys(oldFeats));
  227. console.log("Fixed missing config values.\nFrom:", oldFeats, "\n\nTo:", getFeatures());
  228. if(confirm("All missing or invalid config values were set to their default values.\nReload the page now?"))
  229. location.reload();
  230. });
  231. GM.registerMenuCommand("List GM values in console with decompression", async () => {
  232. const keys = await GM.listValues();
  233. console.log(`GM values (${keys.length}):`);
  234. if(keys.length === 0)
  235. console.log(" No values found.");
  236. const values = {} as Record<string, Stringifiable | undefined>;
  237. let longestKey = 0;
  238. for(const key of keys) {
  239. const isEncoded = key.startsWith("_uucfg-") ? await GM.getValue(`_uucfgenc-${key.substring(7)}`, false) : false;
  240. const val = await GM.getValue(key, undefined);
  241. values[key] = typeof val !== "undefined" && isEncoded ? await decompress(val, compressionFormat, "string") : val;
  242. longestKey = Math.max(longestKey, key.length);
  243. }
  244. for(const [key, finalVal] of Object.entries(values)) {
  245. const isEncoded = key.startsWith("_uucfg-") ? await GM.getValue(`_uucfgenc-${key.substring(7)}`, false) : false;
  246. const lengthStr = String(finalVal).length > 50 ? `(${String(finalVal).length} chars) ` : "";
  247. console.log(` "${key}"${" ".repeat(longestKey - key.length)} -${isEncoded ? "-[decoded]-" : ""}> ${lengthStr}${finalVal}`);
  248. }
  249. }, "l");
  250. GM.registerMenuCommand("List GM values in console, without decompression", async () => {
  251. const keys = await GM.listValues();
  252. console.log(`GM values (${keys.length}):`);
  253. if(keys.length === 0)
  254. console.log(" No values found.");
  255. const values = {} as Record<string, Stringifiable | undefined>;
  256. let longestKey = 0;
  257. for(const key of keys) {
  258. const val = await GM.getValue(key, undefined);
  259. values[key] = val;
  260. longestKey = Math.max(longestKey, key.length);
  261. }
  262. for(const [key, val] of Object.entries(values)) {
  263. const lengthStr = String(val).length >= 16 ? `(${String(val).length} chars) ` : "";
  264. console.log(` "${key}"${" ".repeat(longestKey - key.length)} -> ${lengthStr}${val}`);
  265. }
  266. });
  267. GM.registerMenuCommand("Delete all GM values", async () => {
  268. const keys = await GM.listValues();
  269. if(confirm(`Clear all ${keys.length} GM values?\nSee console for details.`)) {
  270. console.log(`Clearing ${keys.length} GM values:`);
  271. if(keys.length === 0)
  272. console.log(" No values found.");
  273. for(const key of keys) {
  274. await GM.deleteValue(key);
  275. console.log(` Deleted ${key}`);
  276. }
  277. }
  278. }, "d");
  279. GM.registerMenuCommand("Delete GM values by name (comma separated)", async () => {
  280. const keys = prompt("Enter the name(s) of the GM value to delete (comma separated).\nEmpty input cancels the operation.");
  281. if(!keys)
  282. return;
  283. for(const key of keys?.split(",") ?? []) {
  284. if(key && key.length > 0) {
  285. const truncLength = 400;
  286. const oldVal = await GM.getValue(key);
  287. await GM.deleteValue(key);
  288. console.log(`Deleted GM value '${key}' with previous value '${oldVal && String(oldVal).length > truncLength ? String(oldVal).substring(0, truncLength) + `… (${String(oldVal).length} / ${truncLength} chars.)` : oldVal}'`);
  289. }
  290. }
  291. }, "n");
  292. GM.registerMenuCommand("Reset install timestamp", async () => {
  293. await GM.deleteValue("bytm-installed");
  294. console.log("Reset install time.");
  295. }, "t");
  296. GM.registerMenuCommand("Reset version check timestamp", async () => {
  297. await GM.deleteValue("bytm-version-check");
  298. console.log("Reset version check time.");
  299. }, "v");
  300. GM.registerMenuCommand("List active selector listeners in console", async () => {
  301. const lines = [] as string[];
  302. let listenersAmt = 0;
  303. for(const [obsName, obs] of Object.entries(globservers)) {
  304. const listeners = obs.getAllListeners();
  305. lines.push(`- "${obsName}" (${listeners.size} listeners):`);
  306. [...listeners].forEach(([k, v]) => {
  307. listenersAmt += v.length;
  308. lines.push(` [${v.length}] ${k}`);
  309. v.forEach(({ all, continuous }, i) => {
  310. lines.push(` ${v.length > 1 && i !== v.length - 1 ? "├" : "└"}> ${continuous ? "continuous" : "single-shot"}, ${all ? "select multiple" : "select single"}`);
  311. });
  312. });
  313. }
  314. console.log(`Showing currently active listeners for ${Object.keys(globservers).length} observers with ${listenersAmt} total listeners:\n${lines.join("\n")}`);
  315. }, "s");
  316. GM.registerMenuCommand("Compress value", async () => {
  317. const input = prompt("Enter the value to compress.\nSee console for output.");
  318. if(input && input.length > 0) {
  319. const compressed = await compress(input, compressionFormat);
  320. console.log(`Compression result (${input.length} chars -> ${compressed.length} chars)\nValue: ${compressed}`);
  321. }
  322. });
  323. GM.registerMenuCommand("Decompress value", async () => {
  324. const input = prompt("Enter the value to decompress.\nSee console for output.");
  325. if(input && input.length > 0) {
  326. const decompressed = await decompress(input, compressionFormat);
  327. console.log(`Decompresion result (${input.length} chars -> ${decompressed.length} chars)\nValue: ${decompressed}`);
  328. }
  329. });
  330. log("Registered dev menu commands");
  331. }
  332. preInit();