index.js 13 KB

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