index.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. 'use strict';
  2. process.env.NODE_CONFIG_DIR = `${__dirname}/config`;
  3. const async = require('async');
  4. const fs = require('fs');
  5. const Discord = require("discord.js");
  6. const client = new Discord.Client();
  7. const db = require('./logic/db');
  8. const app = require('./logic/app');
  9. const mail = require('./logic/mail');
  10. const api = require('./logic/api');
  11. const io = require('./logic/io');
  12. const stations = require('./logic/stations');
  13. const songs = require('./logic/songs');
  14. const playlists = require('./logic/playlists');
  15. const cache = require('./logic/cache');
  16. const notifications = require('./logic/notifications');
  17. const punishments = require('./logic/punishments');
  18. const logger = require('./logic/logger');
  19. const tasks = require('./logic/tasks');
  20. const i18n = require('./logic/i18n');
  21. const config = require('config');
  22. let currentComponent;
  23. let initializedComponents = [];
  24. let lockdownB = false;
  25. process.on('uncaughtException', err => {
  26. if (lockdownB || err.code === 'ECONNREFUSED' || err.code === 'UNCERTAIN_STATE') return;
  27. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  28. });
  29. const getError = (err) => {
  30. let error = 'An error occurred.';
  31. if (typeof err === "string") error = err;
  32. else if (err.message) {
  33. if (err.message !== 'Validation failed') error = err.message;
  34. else error = err.errors[Object.keys(err.errors)].message;
  35. }
  36. return error;
  37. };
  38. client.on('ready', () => {
  39. console.log(`Logged in to Discord as ${client.user.username}#${client.user.discriminator}`);
  40. initialize();
  41. });
  42. client.on('disconnect', (err) => {
  43. console.log(`Discord disconnected. Code: ${err.code}.`);
  44. });
  45. client.login(config.get('apis.discord.token'));
  46. const logToDiscord = (message, color, type, critical, extraFields, cb = ()=>{}) => {
  47. let richEmbed = new Discord.RichEmbed();
  48. richEmbed.setAuthor("Musare Logger", config.get("domain")+"/favicon-194x194.png", config.get("domain"));
  49. richEmbed.setColor(color);
  50. richEmbed.setDescription(message);
  51. //richEmbed.setFooter("Footer", "https://musare.com/favicon-194x194.png");
  52. //richEmbed.setImage("https://musare.com/favicon-194x194.png");
  53. //richEmbed.setThumbnail("https://musare.com/favicon-194x194.png");
  54. richEmbed.setTimestamp(new Date());
  55. richEmbed.setTitle("MUSARE ALERT");
  56. richEmbed.setURL(config.get("domain"));
  57. richEmbed.addField("Type:", type, true);
  58. richEmbed.addField("Critical:", (critical) ? 'True' : 'False', true);
  59. extraFields.forEach((extraField) => {
  60. richEmbed.addField(extraField.name, extraField.value, extraField.inline);
  61. });
  62. client.channels.get(config.get('apis.discord.loggingChannel')).send("", { embed: richEmbed }).then(() => {
  63. cb();
  64. }).then((reason) => {
  65. cb(reason);
  66. });
  67. };
  68. function lockdown() {
  69. if (lockdownB) return;
  70. lockdownB = true;
  71. initializedComponents.forEach((component) => {
  72. component._lockdown();
  73. });
  74. console.log("Backend locked down.");
  75. }
  76. function errorCb(message, err, component) {
  77. err = getError(err);
  78. lockdown();
  79. logToDiscord(message, "#FF0000", message, true, [{name: "Error:", value: err, inline: false}, {name: "Component:", value: component, inline: true}]);
  80. }
  81. let initialized = false;
  82. function initialize() {
  83. if (!initialized) initialized = true;
  84. else return;
  85. async.waterfall([
  86. // setup our translation
  87. (next) => {
  88. currentComponent = 'Translation';
  89. i18n.init(next);
  90. },
  91. // setup our Redis cache
  92. (next) => {
  93. currentComponent = 'Cache';
  94. cache.init(config.get('redis').url, config.get('redis').password, errorCb, () => {
  95. next();
  96. });
  97. },
  98. // setup our MongoDB database
  99. (next) => {
  100. initializedComponents.push(cache);
  101. currentComponent = 'DB';
  102. db.init(config.get("mongo").url, errorCb, next);
  103. },
  104. // setup the express server
  105. (next) => {
  106. initializedComponents.push(db);
  107. currentComponent = 'App';
  108. app.init(next);
  109. },
  110. // setup the mail
  111. (next) => {
  112. initializedComponents.push(app);
  113. currentComponent = 'Mail';
  114. mail.init(next);
  115. },
  116. // setup the socket.io server (all client / server communication is done over this)
  117. (next) => {
  118. initializedComponents.push(mail);
  119. currentComponent = 'IO';
  120. io.init(next);
  121. },
  122. // setup the punishment system
  123. (next) => {
  124. initializedComponents.push(io);
  125. currentComponent = 'Punishments';
  126. punishments.init(next);
  127. },
  128. // setup the notifications
  129. (next) => {
  130. initializedComponents.push(punishments);
  131. currentComponent = 'Notifications';
  132. notifications.init(config.get('redis').url, config.get('redis').password, errorCb, next);
  133. },
  134. // setup the stations
  135. (next) => {
  136. initializedComponents.push(notifications);
  137. currentComponent = 'Stations';
  138. stations.init(next)
  139. },
  140. // setup the songs
  141. (next) => {
  142. initializedComponents.push(stations);
  143. currentComponent = 'Songs';
  144. songs.init(next)
  145. },
  146. // setup the playlists
  147. (next) => {
  148. initializedComponents.push(songs);
  149. currentComponent = 'Playlists';
  150. playlists.init(next)
  151. },
  152. // setup the API
  153. (next) => {
  154. initializedComponents.push(playlists);
  155. currentComponent = 'API';
  156. api.init(next)
  157. },
  158. // setup the logger
  159. (next) => {
  160. initializedComponents.push(api);
  161. currentComponent = 'Logger';
  162. logger.init(next)
  163. },
  164. // setup the tasks system
  165. (next) => {
  166. initializedComponents.push(logger);
  167. currentComponent = 'Tasks';
  168. tasks.init(next)
  169. },
  170. // setup the frontend for local setups
  171. (next) => {
  172. initializedComponents.push(tasks);
  173. currentComponent = 'Windows';
  174. if (!config.get("isDocker")) {
  175. const express = require('express');
  176. const app = express();
  177. app.listen(config.get("frontendPort"));
  178. const rootDir = __dirname.substr(0, __dirname.lastIndexOf("backend")) + "frontend/dist/";
  179. const rootDirAssets = __dirname.substr(0, __dirname.lastIndexOf("backend")) + "frontend/app/";
  180. const rootDirLocales = __dirname.substr(0, __dirname.lastIndexOf("backend"));
  181. app.get("/locales/*", (req, res) => {
  182. let path = req.path;
  183. res.set('Cache-Control', 'max-age=8640000000');
  184. fs.access(rootDirLocales + path, function (err) {
  185. console.log("Error: ", !!err);
  186. if (!err) {
  187. res.sendFile(rootDirLocales + path);
  188. } else {
  189. res.redirect("/");
  190. }
  191. });
  192. });
  193. app.get("/assets/*", (req, res) => {
  194. const path = req.path;
  195. res.set('Cache-Control', 'max-age=8640000000');
  196. fs.access(rootDirAssets + path, function (err) {
  197. console.log("Error: ", !!err);
  198. if (!err) {
  199. res.sendFile(rootDirAssets + path);
  200. } else {
  201. res.redirect("/");
  202. }
  203. });
  204. });
  205. app.get("/*", (req, res) => {
  206. const path = req.path;
  207. fs.access(rootDir + path, function (err) {
  208. if (!err) {
  209. res.set('Cache-Control', 'max-age=8640000000');
  210. res.sendFile(rootDir + path);
  211. } else {
  212. res.sendFile(rootDir + "index.html");
  213. }
  214. });
  215. });
  216. }
  217. if (lockdownB) return;
  218. next();
  219. }
  220. ], (err) => {
  221. if (err && err !== true) {
  222. lockdown();
  223. logToDiscord("An error occurred while initializing the backend server.", "#FF0000", "Startup error", true, [{
  224. name: "Error:",
  225. value: err,
  226. inline: false
  227. }, {name: "Component:", value: currentComponent, inline: true}]);
  228. console.error('An error occurred while initializing the backend server');
  229. } else {
  230. logToDiscord("The backend server started successfully.", "#00AA00", "Startup", false, []);
  231. console.info('Backend server has been successfully started');
  232. }
  233. });
  234. }