index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. import "./loadEnvVariables.js";
  2. import util from "util";
  3. import config from "config";
  4. import fs from "fs";
  5. import package_json from "./package.json" assert { type: "json" };
  6. const REQUIRED_CONFIG_VERSION = 10;
  7. // eslint-disable-next-line
  8. Array.prototype.remove = function (item) {
  9. this.splice(this.indexOf(item), 1);
  10. };
  11. process.on("uncaughtException", err => {
  12. if (err.code === "ECONNREFUSED" || err.code === "UNCERTAIN_STATE") return;
  13. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  14. });
  15. const blacklistedConsoleLogs = [];
  16. const oldConsole = {};
  17. oldConsole.log = console.log;
  18. console.log = (...args) => {
  19. const string = util.format.apply(null, args);
  20. let blacklisted = false;
  21. blacklistedConsoleLogs.forEach(blacklistedConsoleLog => {
  22. if (string.indexOf(blacklistedConsoleLog) !== -1) blacklisted = true;
  23. });
  24. if (!blacklisted) oldConsole.log.apply(null, args);
  25. };
  26. const MUSARE_VERSION = package_json.version;
  27. const printVersion = () => {
  28. console.log(`Musare version: ${MUSARE_VERSION}.`);
  29. try {
  30. const head_contents = fs.readFileSync(".parent_git/HEAD").toString().replaceAll("\n", "");
  31. const branch = new RegExp("ref: refs/heads/([A-Za-z0-9_.-]+)").exec(head_contents)[1];
  32. const config_contents = fs.readFileSync(".parent_git/config").toString().replaceAll("\t", "").split("\n");
  33. const remote = new RegExp("remote = (.+)").exec(config_contents[config_contents.indexOf(`[branch "${branch}"]`) + 1])[1];
  34. const remote_url = new RegExp("url = (.+)").exec(config_contents[config_contents.indexOf(`[remote "${remote}"]`) + 1])[1];
  35. const latest_commit = fs.readFileSync(`.parent_git/refs/heads/${branch}`).toString().replaceAll("\n", "");
  36. const latest_commit_short = latest_commit.substr(0, 7);
  37. console.log(`Git branch: ${remote}/${branch}. Remote url: ${remote_url}. Latest commit: ${latest_commit} (${latest_commit_short}).`);
  38. } catch(e) {
  39. console.log(`Could not get Git info: ${e.message}.`);
  40. }
  41. }
  42. printVersion();
  43. if (
  44. (!config.has("configVersion") || config.get("configVersion") !== REQUIRED_CONFIG_VERSION) &&
  45. !(config.has("skipConfigVersionCheck") && config.get("skipConfigVersionCheck"))
  46. ) {
  47. console.log(
  48. "CONFIG VERSION IS WRONG. PLEASE UPDATE YOUR CONFIG WITH THE HELP OF THE TEMPLATE FILE AND THE README FILE."
  49. );
  50. process.exit();
  51. }
  52. if (config.debug && config.debug.traceUnhandledPromises === true) {
  53. console.log("Enabled trace-unhandled/register");
  54. import("trace-unhandled/register");
  55. }
  56. class JobManager {
  57. // eslint-disable-next-line require-jsdoc
  58. constructor() {
  59. this.jobs = {};
  60. }
  61. /**
  62. * Adds a job to the list of jobs
  63. *
  64. * @param {object} job - the job object
  65. */
  66. addJob(job) {
  67. if (!this.jobs[job.module.name]) this.jobs[job.module.name] = {};
  68. this.jobs[job.module.name][job.toString()] = job;
  69. }
  70. /**
  71. * Removes a job from the list of running jobs (after it's completed)
  72. *
  73. * @param {object} job - the job object
  74. */
  75. removeJob(job) {
  76. if (!this.jobs[job.module.name]) this.jobs[job.module.name] = {};
  77. delete this.jobs[job.module.name][job.toString()];
  78. }
  79. /**
  80. * Returns detail about a job via a identifier
  81. *
  82. * @param {string} uuid - the job identifier
  83. * @returns {object} - the job object
  84. */
  85. getJob(uuid) {
  86. let job = null;
  87. Object.keys(this.jobs).forEach(moduleName => {
  88. if (this.jobs[moduleName][uuid]) job = this.jobs[moduleName][uuid];
  89. });
  90. return job;
  91. }
  92. }
  93. class ModuleManager {
  94. // eslint-disable-next-line require-jsdoc
  95. constructor() {
  96. this.modules = {};
  97. this.modulesNotInitialized = [];
  98. this.jobManager = new JobManager();
  99. this.i = 0;
  100. this.lockdown = false;
  101. this.debugLogs = {
  102. stationIssue: []
  103. };
  104. this.debugJobs = {
  105. all: [],
  106. completed: []
  107. };
  108. this.name = "MODULE_MANAGER";
  109. }
  110. /**
  111. * Adds a new module to the backend server/module manager
  112. *
  113. * @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")
  114. */
  115. async addModule(moduleName) {
  116. this.log("INFO", "Adding module", moduleName);
  117. this.modules[moduleName] = import(`./logic/${moduleName}`);
  118. }
  119. /**
  120. * Initialises a new module to the backend server/module manager
  121. *
  122. */
  123. async initialize() {
  124. this.reservedLines = Object.keys(this.modules).length + 5;
  125. await Promise.all(Object.values(this.modules)).then(modules => {
  126. for (let module = 0; module < modules.length; module += 1) {
  127. this.modules[modules[module].default.name] = modules[module].default;
  128. this.modulesNotInitialized.push(modules[module].default);
  129. }
  130. }); // ensures all modules are imported, then converts promise to the default export of the import
  131. Object.keys(this.modules).every(moduleKey => {
  132. const module = this.modules[moduleKey];
  133. module.setModuleManager(this);
  134. if (this.lockdown) return false;
  135. module._initialize();
  136. return true;
  137. });
  138. }
  139. /**
  140. * Called when a module is initialised
  141. *
  142. * @param {object} module - the module object/class
  143. */
  144. onInitialize(module) {
  145. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  146. this.modulesNotInitialized.splice(this.modulesNotInitialized.indexOf(module), 1);
  147. this.log(
  148. "INFO",
  149. `Initialized: ${Object.keys(this.modules).length - this.modulesNotInitialized.length}/${
  150. Object.keys(this.modules).length
  151. }.`
  152. );
  153. if (this.modulesNotInitialized.length === 0) this.onAllModulesInitialized();
  154. }
  155. }
  156. /**
  157. * Called when a module fails to initialise
  158. *
  159. * @param {object} module - the module object/class
  160. */
  161. onFail(module) {
  162. if (this.modulesNotInitialized.indexOf(module) !== -1) {
  163. this.log("ERROR", "A module failed to initialize!");
  164. }
  165. }
  166. /**
  167. * Called when every module has initialised
  168. *
  169. */
  170. onAllModulesInitialized() {
  171. this.log("INFO", "All modules initialized!");
  172. }
  173. /**
  174. * Creates a new log message
  175. *
  176. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  177. */
  178. log(...args) {
  179. const _arguments = Array.from(args);
  180. const type = _arguments[0];
  181. _arguments.splice(0, 1);
  182. const start = `|${this.name.toUpperCase()}|`;
  183. const numberOfSpacesNeeded = 20 - start.length;
  184. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  185. if (type === "INFO") {
  186. _arguments[0] += "\x1b[36m";
  187. _arguments.push("\x1b[0m");
  188. console.log.apply(null, _arguments);
  189. } else if (type === "ERROR") {
  190. _arguments[0] += "\x1b[31m";
  191. _arguments.push("\x1b[0m");
  192. console.error.apply(null, _arguments);
  193. }
  194. }
  195. /**
  196. * Locks down all modules
  197. */
  198. _lockdown() {
  199. this.lockdown = true;
  200. Object.keys(this.modules).every(moduleKey => {
  201. const module = this.modules[moduleKey];
  202. module.setStatus("LOCKDOWN");
  203. return true;
  204. });
  205. }
  206. }
  207. const moduleManager = new ModuleManager();
  208. if (!config.get("migration")) {
  209. moduleManager.addModule("cache");
  210. moduleManager.addModule("db");
  211. moduleManager.addModule("mail");
  212. moduleManager.addModule("activities");
  213. moduleManager.addModule("api");
  214. moduleManager.addModule("app");
  215. moduleManager.addModule("ws");
  216. moduleManager.addModule("notifications");
  217. moduleManager.addModule("playlists");
  218. moduleManager.addModule("punishments");
  219. moduleManager.addModule("songs");
  220. moduleManager.addModule("stations");
  221. moduleManager.addModule("media");
  222. moduleManager.addModule("tasks");
  223. moduleManager.addModule("utils");
  224. moduleManager.addModule("youtube");
  225. } else {
  226. moduleManager.addModule("migration");
  227. }
  228. moduleManager.initialize();
  229. /**
  230. * Prints a job
  231. *
  232. * @param {object} job - the job
  233. * @param {number} layer - the layer
  234. */
  235. function printJob(job, layer) {
  236. const tabs = Array(layer).join("\t");
  237. if (job) {
  238. console.log(`${tabs}${job.name} (${job.toString()}) ${job.status}`);
  239. job.childJobs.forEach(childJob => {
  240. printJob(childJob, layer + 1);
  241. });
  242. } else console.log(`${tabs}JOB WAS REMOVED`);
  243. }
  244. /**
  245. * Prints a task
  246. *
  247. * @param {object} task - the task
  248. * @param {number} layer - the layer
  249. */
  250. function printTask(task, layer) {
  251. const tabs = Array(layer).join("\t");
  252. console.log(`${tabs}${task.job.name} (${task.job.toString()}) ${task.job.status} (priority: ${task.priority})`);
  253. task.job.childJobs.forEach(childJob => {
  254. printJob(childJob, layer + 1);
  255. });
  256. }
  257. import * as readline from 'node:readline';
  258. var rl = readline.createInterface({
  259. input: process.stdin,
  260. output: process.stdout,
  261. completer: function(command) {
  262. const parts = command.split(" ");
  263. const commands = ["version", "lockdown", "status", "running ", "queued ", "paused ", "stats ", "jobinfo ", "runjob ", "eval "];
  264. if (parts.length === 1) {
  265. const hits = commands.filter(c => c.startsWith(parts[0]));
  266. return [hits.length ? hits : commands, command];
  267. } else if (parts.length === 2) {
  268. if (["queued", "running", "paused", "runjob", "stats"].indexOf(parts[0]) !== -1) {
  269. const modules = Object.keys(moduleManager.modules);
  270. const hits = modules.filter(module => module.startsWith(parts[1])).map(module => `${parts[0]} ${module}${parts[0] === "runjob" ? " " : ""}`);
  271. return [hits.length ? hits : modules, command];
  272. } else {
  273. return [];
  274. }
  275. } else if (parts.length === 3) {
  276. if (parts[0] === "runjob") {
  277. const modules = Object.keys(moduleManager.modules);
  278. if (modules.indexOf(parts[1]) !== -1) {
  279. const jobs = moduleManager.modules[parts[1]].jobNames;
  280. const hits = jobs.filter(job => job.startsWith(parts[2])).map(job => `${parts[0]} ${parts[1]} ${job} `);
  281. return [hits.length ? hits : jobs, command];
  282. }
  283. } else {
  284. return [];
  285. }
  286. } else {
  287. return [];
  288. }
  289. }
  290. });
  291. rl.on("line",function(command) {
  292. if (command === "version") {
  293. printVersion();
  294. }
  295. if (command === "lockdown") {
  296. console.log("Locking down.");
  297. moduleManager._lockdown();
  298. }
  299. if (command === "status") {
  300. console.log("Status:");
  301. Object.keys(moduleManager.modules).forEach(moduleName => {
  302. const module = moduleManager.modules[moduleName];
  303. const tabsNeeded = 4 - Math.ceil((moduleName.length + 1) / 8);
  304. console.log(
  305. `${moduleName.toUpperCase()}${Array(tabsNeeded).join(
  306. "\t"
  307. )}${module.getStatus()}. Jobs in queue: ${module.jobQueue.lengthQueue()}. Jobs in progress: ${module.jobQueue.lengthRunning()}. Jobs paused: ${module.jobQueue.lengthPaused()} Concurrency: ${
  308. module.jobQueue.concurrency
  309. }. Stage: ${module.getStage()}`
  310. );
  311. });
  312. }
  313. if (command.startsWith("running")) {
  314. const parts = command.split(" ");
  315. moduleManager.modules[parts[1]].jobQueue.runningTasks.forEach(task => {
  316. printTask(task, 1);
  317. });
  318. }
  319. if (command.startsWith("queued")) {
  320. const parts = command.split(" ");
  321. moduleManager.modules[parts[1]].jobQueue.queue.forEach(task => {
  322. printTask(task, 1);
  323. });
  324. }
  325. if (command.startsWith("paused")) {
  326. const parts = command.split(" ");
  327. moduleManager.modules[parts[1]].jobQueue.pausedTasks.forEach(task => {
  328. printTask(task, 1);
  329. });
  330. }
  331. if (command.startsWith("stats")) {
  332. const parts = command.split(" ");
  333. console.log(moduleManager.modules[parts[1]].jobStatistics);
  334. }
  335. if (command.startsWith("jobinfo")) {
  336. const parts = command.split(" ");
  337. const uuid = parts[1];
  338. const jobFound = moduleManager.jobManager.getJob(uuid);
  339. if (jobFound) {
  340. let topParent = jobFound;
  341. let levelsDeep = 0;
  342. while (topParent.parentJob && topParent !== topParent.parentJob) {
  343. topParent = jobFound.parentJob;
  344. levelsDeep += 1;
  345. }
  346. console.log(
  347. `Found job, displaying that job and the full tree from the top parent job. The job is ${levelsDeep} levels deep from the top parent.`
  348. );
  349. console.log(jobFound);
  350. printJob(topParent, 1);
  351. } else console.log("Could not find job in job manager.");
  352. }
  353. if (command.startsWith("runjob")) {
  354. const parts = command.split(" ");
  355. const module = parts[1];
  356. const jobName = parts[2];
  357. const payload = parts.length < 4 ? {} : JSON.parse(parts[3]);
  358. moduleManager.modules[module]
  359. .runJob(jobName, payload)
  360. .then(response => {
  361. console.log("runjob success", response);
  362. })
  363. .catch(err => {
  364. console.log("runjob error", err);
  365. });
  366. }
  367. if (command.startsWith("eval")) {
  368. const evalCommand = command.replace("eval ", "");
  369. console.log(`Running eval command: ${evalCommand}`);
  370. // eslint-disable-next-line no-eval
  371. const response = eval(evalCommand);
  372. console.log(`Eval response: `, response);
  373. }
  374. if (command.startsWith("debug")) {
  375. moduleManager.modules["youtube"].apiCalls.forEach(apiCall => {
  376. // console.log(`${apiCall.date.toISOString()} - ${apiCall.url} - ${apiCall.quotaCost} - ${JSON.stringify(apiCall.params)}`);
  377. console.log(apiCall);
  378. });
  379. }
  380. });
  381. export default moduleManager;