index.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 config = require('config');
  21. let currentComponent;
  22. let initializedComponents = [];
  23. let lockdownB = false;
  24. process.on('uncaughtException', err => {
  25. if (lockdownB || err.code === 'ECONNREFUSED' || err.code === 'UNCERTAIN_STATE') return;
  26. console.log(`UNCAUGHT EXCEPTION: ${err.stack}`);
  27. });
  28. const getError = (err) => {
  29. let error = 'An error occurred.';
  30. if (typeof err === "string") error = err;
  31. else if (err.message) {
  32. if (err.message !== 'Validation failed') error = err.message;
  33. else error = err.errors[Object.keys(err.errors)].message;
  34. }
  35. return error;
  36. };
  37. client.on('ready', () => {
  38. discordClientCBS.forEach((cb) => {
  39. cb();
  40. });
  41. discordClientCBS = [];
  42. console.log(`Logged in to Discord as ${client.user.username}#${client.user.discriminator}`);
  43. });
  44. client.on('disconnect', (err) => {
  45. console.log(`Discord disconnected. Code: ${err.code}.`);
  46. });
  47. client.login(config.get('apis.discord.token'));
  48. let discordClientCBS = [];
  49. const getDiscordClient = (cb) => {
  50. if (client.status === 0) return cb();
  51. else discordClientCBS.push(cb);
  52. };
  53. const logToDiscord = (message, color, type, critical, extraFields, cb = ()=>{}) => {
  54. getDiscordClient(() => {
  55. let richEmbed = new Discord.RichEmbed();
  56. richEmbed.setAuthor("Musare Logger", config.get("domain")+"/favicon-194x194.png", config.get("domain"));
  57. richEmbed.setColor(color);
  58. richEmbed.setDescription(message);
  59. //richEmbed.setFooter("Footer", "https://musare.com/favicon-194x194.png");
  60. //richEmbed.setImage("https://musare.com/favicon-194x194.png");
  61. //richEmbed.setThumbnail("https://musare.com/favicon-194x194.png");
  62. richEmbed.setTimestamp(new Date());
  63. richEmbed.setTitle("MUSARE ALERT");
  64. richEmbed.setURL(config.get("domain"));
  65. richEmbed.addField("Type:", type, true);
  66. richEmbed.addField("Critical:", (critical) ? 'True' : 'False', true);
  67. extraFields.forEach((extraField) => {
  68. richEmbed.addField(extraField.name, extraField.value, extraField.inline);
  69. });
  70. client.channels.get(config.get('apis.discord.loggingChannel')).sendEmbed(richEmbed).then(() => {
  71. cb();
  72. }).then((reason) => {
  73. cb(reason);
  74. });
  75. });
  76. };
  77. function lockdown() {
  78. if (lockdownB) return;
  79. lockdownB = true;
  80. initializedComponents.forEach((component) => {
  81. component._lockdown();
  82. });
  83. console.log("Backend locked down.");
  84. }
  85. function errorCb(message, err, component) {
  86. err = getError(err);
  87. lockdown();
  88. logToDiscord(message, "#FF0000", message, true, [{name: "Error:", value: err, inline: false}, {name: "Component:", value: component, inline: true}]);
  89. }
  90. async.waterfall([
  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/build/";
  179. app.get("/*", (req, res) => {
  180. const path = req.path;
  181. fs.access(rootDir + path, function(err) {
  182. if (!err) {
  183. res.sendFile(rootDir + path);
  184. } else {
  185. res.sendFile(rootDir + "index.html");
  186. }
  187. });
  188. });
  189. }
  190. if (lockdownB) return;
  191. next();
  192. }
  193. ], (err) => {
  194. if (err && err !== true) {
  195. lockdown();
  196. 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}]);
  197. console.error('An error occurred while initializing the backend server');
  198. } else {
  199. logToDiscord("The backend server started successfully.", "#00AA00", "Startup", false, []);
  200. console.info('Backend server has been successfully started');
  201. }
  202. });