index.js 13 KB

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