index.ts 14 KB

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