index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import { compress, decompress, pauseFor, type Stringifiable } from "@sv443-network/userutils";
  2. import { addStyleFromResource, domLoaded, warn } from "./utils/index.js";
  3. import { clearConfig, fixMissingCfgKeys, getFeatures, initConfig, setFeatures } from "./config.js";
  4. import { buildNumber, compressionFormat, defaultLogLevel, mode, scriptInfo } from "./constants.js";
  5. import { error, getDomain, info, getSessionId, log, setLogLevel, initTranslations, setLocale } from "./utils/index.js";
  6. import { initSiteEvents } from "./siteEvents.js";
  7. import { emitInterface, initInterface, initPlugins } from "./interface.js";
  8. import { initObservers, addSelectorListener, globservers } from "./observers.js";
  9. import { getWelcomeDialog } from "./dialogs/index.js";
  10. import type { FeatureConfig } from "./types.js";
  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, initAutoLike,
  22. // lyrics
  23. addPlayerBarLyricsBtn, initLyricsCache,
  24. // menu
  25. addConfigMenuOptionYT, addConfigMenuOptionYTM,
  26. // general
  27. initVersionCheck,
  28. } from "./features/index.js";
  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. log("Session ID:", getSessionId());
  59. initInterface();
  60. setLogLevel(defaultLogLevel);
  61. if(getDomain() === "ytm")
  62. initBeforeUnloadHook();
  63. init();
  64. }
  65. catch(err) {
  66. return error("Fatal pre-init error:", err);
  67. }
  68. }
  69. //#region init
  70. async function init() {
  71. try {
  72. const domain = getDomain();
  73. const features = await initConfig();
  74. setLogLevel(features.logLevel);
  75. await initLyricsCache();
  76. await initTranslations(features.locale ?? "en_US");
  77. setLocale(features.locale ?? "en_US");
  78. emitInterface("bytm:registerPlugins");
  79. if(features.disableBeforeUnloadPopup && domain === "ytm")
  80. disableBeforeUnload();
  81. if(!domLoaded)
  82. document.addEventListener("DOMContentLoaded", onDomLoad, { once: true });
  83. else
  84. onDomLoad();
  85. if(features.rememberSongTime)
  86. initRememberSongTime();
  87. }
  88. catch(err) {
  89. error("Fatal error:", err);
  90. }
  91. }
  92. //#region onDomLoad
  93. /** Called when the DOM has finished loading and can be queried and altered by the userscript */
  94. async function onDomLoad() {
  95. const domain = getDomain();
  96. const features = getFeatures();
  97. const ftInit = [] as [string, Promise<void>][];
  98. // for being able to apply domain-specific styles (prefix any CSS selector with "body.bytm-dom-yt" or "body.bytm-dom-ytm")
  99. document.body.classList.add(`bytm-dom-${domain}`);
  100. try {
  101. initObservers();
  102. await Promise.allSettled([
  103. insertGlobalStyle(),
  104. initVersionCheck(),
  105. ]);
  106. }
  107. catch(err) {
  108. error("Fatal error in feature pre-init:", err);
  109. return;
  110. }
  111. log(`DOM loaded and feature pre-init finished, now initializing all features for domain "${domain}"...`);
  112. try {
  113. //#region welcome dlg
  114. if(typeof await GM.getValue("bytm-installed") !== "string") {
  115. // open welcome menu with language selector
  116. const dlg = await getWelcomeDialog();
  117. dlg.on("close", () => GM.setValue("bytm-installed", JSON.stringify({ timestamp: Date.now(), version: scriptInfo.version })));
  118. info("Showing welcome menu");
  119. await dlg.open();
  120. }
  121. if(domain === "ytm") {
  122. //#region (ytm) layout
  123. if(features.watermarkEnabled)
  124. ftInit.push(["addWatermark", addWatermark()]);
  125. if(features.fixSpacing)
  126. ftInit.push(["fixSpacing", fixSpacing()]);
  127. if(features.removeUpgradeTab)
  128. ftInit.push(["removeUpgradeTab", removeUpgradeTab()]);
  129. ftInit.push(["thumbnailOverlay", initThumbnailOverlay()]);
  130. if(features.hideCursorOnIdle)
  131. ftInit.push(["hideCursorOnIdle", initHideCursorOnIdle()]);
  132. if(features.fixHdrIssues)
  133. ftInit.push(["fixHdrIssues", fixHdrIssues()]);
  134. //#region (ytm) volume
  135. ftInit.push(["volumeFeatures", initVolumeFeatures()]);
  136. //#region (ytm) song lists
  137. if(features.lyricsQueueButton || features.deleteFromQueueButton)
  138. ftInit.push(["queueButtons", initQueueButtons()]);
  139. ftInit.push(["aboveQueueBtns", initAboveQueueBtns()]);
  140. //#region (ytm) behavior
  141. if(features.closeToastsTimeout > 0)
  142. ftInit.push(["autoCloseToasts", initAutoCloseToasts()]);
  143. //#region (ytm) input
  144. ftInit.push(["arrowKeySkip", initArrowKeySkip()]);
  145. if(features.anchorImprovements)
  146. ftInit.push(["anchorImprovements", addAnchorImprovements()]);
  147. ftInit.push(["numKeysSkip", initNumKeysSkip()]);
  148. //#region (ytm) lyrics
  149. if(features.geniusLyrics)
  150. ftInit.push(["playerBarLyricsBtn", addPlayerBarLyricsBtn()]);
  151. }
  152. //#region (ytm+yt) cfg menu option
  153. try {
  154. if(domain === "ytm") {
  155. addSelectorListener("body", "tp-yt-iron-dropdown #contentWrapper ytd-multi-page-menu-renderer #container.menu-container", {
  156. listener: addConfigMenuOptionYTM,
  157. });
  158. }
  159. else if(domain === "yt") {
  160. addSelectorListener<0, "yt">("ytGuide", "#sections ytd-guide-section-renderer:nth-child(5) #items ytd-guide-entry-renderer:nth-child(1)", {
  161. listener: (el) => el.parentElement && addConfigMenuOptionYT(el.parentElement),
  162. });
  163. }
  164. }
  165. catch(err) {
  166. error("Couldn't add config menu option:", err);
  167. }
  168. if(["ytm", "yt"].includes(domain)) {
  169. //#region general
  170. ftInit.push(["initSiteEvents", initSiteEvents()]);
  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(["siteSwitch", initSiteSwitch(domain)]);
  178. if(getFeatures().autoLikeChannels)
  179. ftInit.push(["autoLikeChannels", initAutoLike()]);
  180. }
  181. emitInterface("bytm:featureInitStarted");
  182. try {
  183. initPlugins();
  184. }
  185. catch(err) {
  186. error("Plugin loading error:", err);
  187. emitInterface("bytm:fatalError", "Error while loading plugins");
  188. }
  189. const initStartTs = Date.now();
  190. // wait for feature init or timeout (in case an init function is hung up on a promise)
  191. await Promise.race([
  192. pauseFor(getFeatures().initTimeout > 0 ? getFeatures().initTimeout * 1000 : 8_000),
  193. Promise.allSettled(
  194. ftInit.map(([name, prom]) =>
  195. new Promise(async (res) => {
  196. const v = await prom;
  197. emitInterface("bytm:featureInitialized", name);
  198. res(v);
  199. })
  200. )
  201. ),
  202. ]);
  203. emitInterface("bytm:ready");
  204. info(`Done initializing all ${ftInit.length} features after ${Math.floor(Date.now() - initStartTs)}ms`);
  205. try {
  206. registerDevMenuCommands();
  207. }
  208. catch(e) {
  209. warn("Couldn't register dev menu commands:", e);
  210. }
  211. }
  212. catch(err) {
  213. error("Feature error:", err);
  214. emitInterface("bytm:fatalError", "Error while initializing features");
  215. }
  216. }
  217. //#region insert css bundle
  218. /** Inserts the bundled CSS files imported throughout the script into a <style> element in the <head> */
  219. async function insertGlobalStyle() {
  220. if(!await addStyleFromResource("css-bundle"))
  221. error("Couldn't add global CSS bundle due to an error");
  222. }
  223. //#region dev menu cmds
  224. /** Registers dev commands using `GM.registerMenuCommand` */
  225. function registerDevMenuCommands() {
  226. if(mode !== "development")
  227. return;
  228. GM.registerMenuCommand("Reset config", async () => {
  229. if(confirm("Reset the configuration to its default values?\nThis will automatically reload the page.")) {
  230. await clearConfig();
  231. disableBeforeUnload();
  232. location.reload();
  233. }
  234. }, "r");
  235. GM.registerMenuCommand("Fix missing config values", async () => {
  236. const oldFeats = JSON.parse(JSON.stringify(getFeatures())) as FeatureConfig;
  237. await setFeatures(fixMissingCfgKeys(oldFeats));
  238. console.log("Fixed missing config values.\nFrom:", oldFeats, "\n\nTo:", getFeatures());
  239. if(confirm("All missing or invalid config values were set to their default values.\nReload the page now?"))
  240. location.reload();
  241. });
  242. GM.registerMenuCommand("List GM values in console with decompression", async () => {
  243. const keys = await GM.listValues();
  244. console.log(`GM values (${keys.length}):`);
  245. if(keys.length === 0)
  246. console.log(" No values found.");
  247. const values = {} as Record<string, Stringifiable | undefined>;
  248. let longestKey = 0;
  249. for(const key of keys) {
  250. const isEncoded = key.startsWith("_uucfg-") ? await GM.getValue(`_uucfgenc-${key.substring(7)}`, false) : false;
  251. const val = await GM.getValue(key, undefined);
  252. values[key] = typeof val !== "undefined" && isEncoded ? await decompress(val, compressionFormat, "string") : val;
  253. longestKey = Math.max(longestKey, key.length);
  254. }
  255. for(const [key, finalVal] of Object.entries(values)) {
  256. const isEncoded = key.startsWith("_uucfg-") ? await GM.getValue(`_uucfgenc-${key.substring(7)}`, false) : false;
  257. const lengthStr = String(finalVal).length > 50 ? `(${String(finalVal).length} chars) ` : "";
  258. console.log(` "${key}"${" ".repeat(longestKey - key.length)} -${isEncoded ? "-[decoded]-" : ""}> ${lengthStr}${finalVal}`);
  259. }
  260. }, "l");
  261. GM.registerMenuCommand("List GM values in console, without decompression", async () => {
  262. const keys = await GM.listValues();
  263. console.log(`GM values (${keys.length}):`);
  264. if(keys.length === 0)
  265. console.log(" No values found.");
  266. const values = {} as Record<string, Stringifiable | undefined>;
  267. let longestKey = 0;
  268. for(const key of keys) {
  269. const val = await GM.getValue(key, undefined);
  270. values[key] = val;
  271. longestKey = Math.max(longestKey, key.length);
  272. }
  273. for(const [key, val] of Object.entries(values)) {
  274. const lengthStr = String(val).length >= 16 ? `(${String(val).length} chars) ` : "";
  275. console.log(` "${key}"${" ".repeat(longestKey - key.length)} -> ${lengthStr}${val}`);
  276. }
  277. });
  278. GM.registerMenuCommand("Delete all GM values", async () => {
  279. const keys = await GM.listValues();
  280. if(confirm(`Clear all ${keys.length} GM values?\nSee console for details.`)) {
  281. console.log(`Clearing ${keys.length} GM values:`);
  282. if(keys.length === 0)
  283. console.log(" No values found.");
  284. for(const key of keys) {
  285. await GM.deleteValue(key);
  286. console.log(` Deleted ${key}`);
  287. }
  288. }
  289. }, "d");
  290. GM.registerMenuCommand("Delete GM values by name (comma separated)", async () => {
  291. const keys = prompt("Enter the name(s) of the GM value to delete (comma separated).\nEmpty input cancels the operation.");
  292. if(!keys)
  293. return;
  294. for(const key of keys?.split(",") ?? []) {
  295. if(key && key.length > 0) {
  296. const truncLength = 400;
  297. const oldVal = await GM.getValue(key);
  298. await GM.deleteValue(key);
  299. 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}'`);
  300. }
  301. }
  302. }, "n");
  303. GM.registerMenuCommand("Reset install timestamp", async () => {
  304. await GM.deleteValue("bytm-installed");
  305. console.log("Reset install time.");
  306. }, "t");
  307. GM.registerMenuCommand("Reset version check timestamp", async () => {
  308. await GM.deleteValue("bytm-version-check");
  309. console.log("Reset version check time.");
  310. }, "v");
  311. GM.registerMenuCommand("List active selector listeners in console", async () => {
  312. const lines = [] as string[];
  313. let listenersAmt = 0;
  314. for(const [obsName, obs] of Object.entries(globservers)) {
  315. const listeners = obs.getAllListeners();
  316. lines.push(`- "${obsName}" (${listeners.size} listeners):`);
  317. [...listeners].forEach(([k, v]) => {
  318. listenersAmt += v.length;
  319. lines.push(` [${v.length}] ${k}`);
  320. v.forEach(({ all, continuous }, i) => {
  321. lines.push(` ${v.length > 1 && i !== v.length - 1 ? "├" : "└"}> ${continuous ? "continuous" : "single-shot"}${all ? ", multiple" : ""}`);
  322. });
  323. });
  324. }
  325. console.log(`Showing currently active listeners for ${Object.keys(globservers).length} observers with ${listenersAmt} total listeners:\n${lines.join("\n")}`);
  326. }, "s");
  327. GM.registerMenuCommand("Compress value", async () => {
  328. const input = prompt("Enter the value to compress.\nSee console for output.");
  329. if(input && input.length > 0) {
  330. const compressed = await compress(input, compressionFormat);
  331. console.log(`Compression result (${input.length} chars -> ${compressed.length} chars)\nValue: ${compressed}`);
  332. }
  333. });
  334. GM.registerMenuCommand("Decompress value", async () => {
  335. const input = prompt("Enter the value to decompress.\nSee console for output.");
  336. if(input && input.length > 0) {
  337. const decompressed = await decompress(input, compressionFormat);
  338. console.log(`Decompresion result (${input.length} chars -> ${decompressed.length} chars)\nValue: ${decompressed}`);
  339. }
  340. });
  341. log("Registered dev menu commands");
  342. }
  343. preInit();