index.js 7.2 KB

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