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