index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. import "./loadEnvVariables.js";
  2. import util from "util";
  3. import config from "config";
  4. // eslint-disable-next-line no-extend-native
  5. Array.prototype.remove = function (item) {
  6. this.splice(this.indexOf(item), 1);
  7. };
  8. process.on("uncaughtException", err => {
  9. if (err.code === "ECONNREFUSED" || err.code === "UNCERTAIN_STATE") return;
  10. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  11. });
  12. const blacklistedConsoleLogs = [
  13. ];
  14. const oldConsole = {};
  15. oldConsole.log = console.log;
  16. console.log = (...args) => {
  17. const string = util.format.apply(null, args);
  18. let blacklisted = false;
  19. blacklistedConsoleLogs.forEach(blacklistedConsoleLog => {
  20. if (string.indexOf(blacklistedConsoleLog) !== -1) blacklisted = true;
  21. });
  22. if (!blacklisted) oldConsole.log.apply(null, args);
  23. };
  24. const fancyConsole = config.get("fancyConsole");
  25. if (config.debug && config.debug.traceUnhandledPromises === true) {
  26. console.log("Enabled trace-unhandled/register");
  27. import("trace-unhandled/register");
  28. }
  29. // class ModuleManager {
  30. // constructor() {
  31. // this.modules = {};
  32. // this.modulesInitialized = 0;
  33. // this.totalModules = 0;
  34. // this.modulesLeft = [];
  35. // this.i = 0;
  36. // this.lockdown = false;
  37. // this.fancyConsole = fancyConsole;
  38. // }
  39. // addModule(moduleName) {
  40. // console.log("add module", moduleName);
  41. // const moduleClass = new require(`./logic/${moduleName}`);
  42. // this.modules[moduleName] = new moduleClass(moduleName, this);
  43. // this.totalModules++;
  44. // this.modulesLeft.push(moduleName);
  45. // }
  46. // initialize() {
  47. // if (!this.modules["logger"]) return console.error("There is no logger module");
  48. // this.logger = this.modules["logger"];
  49. // if (this.fancyConsole) {
  50. // this.replaceConsoleWithLogger();
  51. // this.logger.reservedLines = Object.keys(this.modules).length + 5;
  52. // }
  53. // for (let moduleName in this.modules) {
  54. // let module = this.modules[moduleName];
  55. // if (this.lockdown) break;
  56. // module._onInitialize().then(() => {
  57. // this.moduleInitialized(moduleName);
  58. // });
  59. // let dependenciesInitializedPromises = [];
  60. // module.dependsOn.forEach(dependencyName => {
  61. // let dependency = this.modules[dependencyName];
  62. // dependenciesInitializedPromises.push(dependency._onInitialize());
  63. // });
  64. // module.lastTime = Date.now();
  65. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  66. // if (this.lockdown) return;
  67. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  68. // module._initialize();
  69. // });
  70. // }
  71. // }
  72. // async printStatus() {
  73. // try { await Promise.race([this.logger._onInitialize(), this.logger._isInitialized()]); } catch { return; }
  74. // if (!this.fancyConsole) return;
  75. // let colors = this.logger.colors;
  76. // const rows = process.stdout.rows;
  77. // process.stdout.cursorTo(0, rows - this.logger.reservedLines);
  78. // process.stdout.clearScreenDown();
  79. // process.stdout.cursorTo(0, (rows - this.logger.reservedLines) + 2);
  80. // process.stdout.write(`${colors.FgYellow}Modules${colors.FgWhite}:\n`);
  81. // for (let moduleName in this.modules) {
  82. // let module = this.modules[moduleName];
  83. // let tabsAmount = Math.max(0, Math.ceil(2 - (moduleName.length / 8)));
  84. // let tabs = Array(tabsAmount).fill(`\t`).join("");
  85. // let timing = module.timeDifferences.map((timeDifference) => {
  86. // return `${colors.FgMagenta}${timeDifference}${colors.FgCyan}ms${colors.FgWhite}`;
  87. // }).join(", ");
  88. // let stateColor;
  89. // if (module.state === "NOT_INITIALIZED") stateColor = colors.FgWhite;
  90. // else if (module.state === "INITIALIZED") stateColor = colors.FgGreen;
  91. // else if (module.state === "LOCKDOWN" && !module.failed) stateColor = colors.FgRed;
  92. // else if (module.state === "LOCKDOWN" && module.failed) stateColor = colors.FgMagenta;
  93. // else stateColor = colors.FgYellow;
  94. // process.stdout.write(`${moduleName}${tabs}${stateColor}${module.state}\t${colors.FgYellow}Stage: ${colors.FgRed}${module.stage}${colors.FgWhite}. ${colors.FgYellow}Timing${colors.FgWhite}: [${timing}]${colors.FgWhite}${colors.FgWhite}. ${colors.FgYellow}Total time${colors.FgWhite}: ${colors.FgRed}${module.totalTimeInitialize}${colors.FgCyan}ms${colors.Reset}\n`);
  95. // }
  96. // }
  97. // moduleInitialized(moduleName) {
  98. // this.modulesInitialized++;
  99. // this.modulesLeft.splice(this.modulesLeft.indexOf(moduleName), 1);
  100. // this.logger.info("MODULE_MANAGER", `Initialized: ${this.modulesInitialized}/${this.totalModules}.`);
  101. // if (this.modulesLeft.length === 0) this.allModulesInitialized();
  102. // }
  103. // allModulesInitialized() {
  104. // this.logger.success("MODULE_MANAGER", "All modules have started!");
  105. // }
  106. // aModuleFailed(failedModule) {
  107. // this.logger.error("MODULE_MANAGER", `A module has failed, locking down. Module: ${failedModule.name}`);
  108. // this._lockdown();
  109. // }
  110. // replaceConsoleWithLogger() {
  111. // this.oldConsole = {
  112. // log: console.log,
  113. // debug: console.debug,
  114. // info: console.info,
  115. // warn: console.warn,
  116. // error: console.error
  117. // };
  118. // console.log = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  119. // console.debug = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  120. // console.info = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  121. // console.warn = (...args) => this.logger.debug(args.map(arg => util.format(arg)));
  122. // console.error = (...args) => this.logger.error("CONSOLE", args.map(arg => util.format(arg)));
  123. // }
  124. // replaceLoggerWithConsole() {
  125. // console.log = this.oldConsole.log;
  126. // console.debug = this.oldConsole.debug;
  127. // console.info = this.oldConsole.info;
  128. // console.warn = this.oldConsole.warn;
  129. // console.error = this.oldConsole.error;
  130. // }
  131. // _lockdown() {
  132. // this.lockdown = true;
  133. // for (let moduleName in this.modules) {
  134. // let module = this.modules[moduleName];
  135. // if (module.lockdownImmune) continue;
  136. // module._lockdown();
  137. // }
  138. // }
  139. // }
  140. // const moduleManager = new ModuleManager();
  141. // module.exports = moduleManager;
  142. // moduleManager.addModule("cache");
  143. // moduleManager.addModule("db");
  144. // moduleManager.addModule("mail");
  145. // moduleManager.addModule("api");
  146. // moduleManager.addModule("app");
  147. // moduleManager.addModule("io");
  148. // moduleManager.addModule("logger");
  149. // moduleManager.addModule("notifications");
  150. // moduleManager.addModule("activities");
  151. // moduleManager.addModule("playlists");
  152. // moduleManager.addModule("punishments");
  153. // moduleManager.addModule("songs");
  154. // moduleManager.addModule("stations");
  155. // moduleManager.addModule("tasks");
  156. // moduleManager.addModule("utils");
  157. // moduleManager.initialize();
  158. // process.stdin.on("data", function (data) {
  159. // if(data.toString() === "lockdown\r\n"){
  160. // console.log("Locking down.");
  161. // moduleManager._lockdown();
  162. // }
  163. // });
  164. // if (fancyConsole) {
  165. // const rows = process.stdout.rows;
  166. // for(let i = 0; i < rows; i++) {
  167. // process.stdout.write("\n");
  168. // }
  169. // }
  170. class ModuleManager {
  171. // eslint-disable-next-line require-jsdoc
  172. constructor() {
  173. this.modules = {};
  174. this.modulesNotInitialized = [];
  175. this.i = 0;
  176. this.lockdown = false;
  177. this.fancyConsole = fancyConsole;
  178. this.debugLogs = {
  179. stationIssue: []
  180. };
  181. this.debugJobs = {
  182. all: [],
  183. completed: []
  184. };
  185. this.name = "MODULE_MANAGER";
  186. }
  187. /**
  188. * Adds a new module to the backend server/module manager
  189. *
  190. * @param {string} moduleName - the name of the module (also needs to be the same as the filename of a module located in the logic folder or "logic/moduleName/index.js")
  191. */
  192. async addModule(moduleName) {
  193. this.log("INFO", "Adding module", moduleName);
  194. // import(`./logic/${moduleName}`).then(Module => {
  195. // // eslint-disable-next-line new-cap
  196. // const instantiatedModule = new Module.default();
  197. // this.modules[moduleName] = instantiatedModule;
  198. // this.modulesNotInitialized.push(instantiatedModule);
  199. // if (moduleName === "cache") console.log(56, this.modules);
  200. // });
  201. this.modules[moduleName] = import(`./logic/${moduleName}`);
  202. }
  203. /**
  204. * Initialises a new module to the backend server/module manager
  205. *
  206. */
  207. async initialize() {
  208. // if (!this.modules["logger"]) return console.error("There is no logger module");
  209. // this.logger = this.modules["logger"];
  210. // if (this.fancyConsole) {
  211. // this.replaceConsoleWithLogger();
  212. this.reservedLines = Object.keys(this.modules).length + 5;
  213. // }
  214. await Promise.all(Object.values(this.modules)).then(modules => {
  215. for (let module = 0; module < modules.length; module += 1) {
  216. this.modules[modules[module].default.name] = modules[module].default;
  217. this.modulesNotInitialized.push(modules[module].default);
  218. }
  219. }); // ensures all modules are imported, then converts promise to the default export of the import
  220. Object.keys(this.modules).every(moduleKey => {
  221. const module = this.modules[moduleKey];
  222. module.setModuleManager(this);
  223. if (this.lockdown) return false;
  224. module._initialize();
  225. // let dependenciesInitializedPromises = [];
  226. // module.dependsOn.forEach(dependencyName => {
  227. // let dependency = this.modules[dependencyName];
  228. // dependenciesInitializedPromises.push(dependency._onInitialize());
  229. // });
  230. // module.lastTime = Date.now();
  231. // Promise.all(dependenciesInitializedPromises).then((res, res2) => {
  232. // if (this.lockdown) return;
  233. // this.logger.info("MODULE_MANAGER", `${moduleName} dependencies have been completed`);
  234. // module._initialize();
  235. // });
  236. return true;
  237. });
  238. }
  239. /**
  240. * Called when a module is initialised
  241. *
  242. * @param {object} module - the module object/class
  243. */
  244. onInitialize(module) {
  245. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  246. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  247. this.log(
  248. "INFO",
  249. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  250. Object.keys(this.modules).length
  251. }.`
  252. );
  253. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  254. }
  255. }
  256. /**
  257. * Called when a module fails to initialise
  258. *
  259. * @param {object} module - the module object/class
  260. */
  261. onFail(module) {
  262. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  263. this.log("ERROR", "A module failed to initialize!");
  264. }
  265. }
  266. /**
  267. * Called when every module has initialised
  268. *
  269. */
  270. onAllModulesInitialized() {
  271. this.log("INFO", "All modules initialized!");
  272. }
  273. /**
  274. * Creates a new log message
  275. *
  276. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  277. */
  278. log(...args) {
  279. const _arguments = Array.from(args);
  280. const type = _arguments[0];
  281. _arguments.splice(0, 1);
  282. const start = `|${this.name.toUpperCase()}|`;
  283. const numberOfSpacesNeeded = 20 - start.length;
  284. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  285. if (type === "INFO") {
  286. _arguments[0] += "\x1b[36m";
  287. _arguments.push("\x1b[0m");
  288. console.log.apply(null, _arguments);
  289. } else if (type === "ERROR") {
  290. _arguments[0] += "\x1b[31m";
  291. _arguments.push("\x1b[0m");
  292. console.error.apply(null, _arguments);
  293. }
  294. }
  295. }
  296. const moduleManager = new ModuleManager();
  297. moduleManager.addModule("cache");
  298. moduleManager.addModule("db");
  299. moduleManager.addModule("mail");
  300. moduleManager.addModule("activities");
  301. moduleManager.addModule("api");
  302. moduleManager.addModule("app");
  303. moduleManager.addModule("io");
  304. moduleManager.addModule("notifications");
  305. moduleManager.addModule("playlists");
  306. moduleManager.addModule("punishments");
  307. moduleManager.addModule("songs");
  308. moduleManager.addModule("stations");
  309. moduleManager.addModule("tasks");
  310. moduleManager.addModule("utils");
  311. moduleManager.addModule("youtube");
  312. moduleManager.initialize();
  313. process.stdin.on("data", data => {
  314. const command = data.toString().replace(/\r?\n|\r/g, "");
  315. if (command === "lockdown") {
  316. console.log("Locking down.");
  317. moduleManager._lockdown();
  318. }
  319. if (command === "status") {
  320. console.log("Status:");
  321. Object.keys(moduleManager.modules).forEach(moduleName => {
  322. const module = moduleManager.modules[moduleName];
  323. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  324. console.log(
  325. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  326. "\t"
  327. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  328. module.jobQueue.concurrency
  329. }. Stage: ${module.getStage()}`
  330. );
  331. });
  332. // moduleManager._lockdown();
  333. }
  334. if (command.startsWith("running")) {
  335. const parts = command.split(" ");
  336. console.log(moduleManager.modules[parts[1]].jobQueue.runningTasks);
  337. }
  338. if (command.startsWith("queued")) {
  339. const parts = command.split(" ");
  340. console.log(moduleManager.modules[parts[1]].jobQueue.queue);
  341. }
  342. if (command.startsWith("paused")) {
  343. const parts = command.split(" ");
  344. console.log(moduleManager.modules[parts[1]].jobQueue.pausedTasks);
  345. }
  346. if (command.startsWith("stats")) {
  347. const parts = command.split(" ");
  348. console.log(moduleManager.modules[parts[1]].jobStatistics);
  349. }
  350. if (command.startsWith("debug")) {
  351. moduleManager.modules.youtube
  352. .runJob("GET_PLAYLIST", { url: "https://www.youtube.com/playlist?list=PLN-cFDG8y28Pz4dkAFwDNH0as0-prFfvR" })
  353. .then(response => {
  354. console.log(1111, response);
  355. })
  356. .catch(err => {
  357. console.log(1112, err);
  358. });
  359. }
  360. if (command.startsWith("eval")) {
  361. const evalCommand = command.replace("eval ", "");
  362. console.log(`Running eval command: ${evalCommand}`);
  363. const response = eval(evalCommand);
  364. console.log(`Eval response: `, response);
  365. }
  366. });
  367. export default moduleManager;