index.js 13 KB

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