index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import config from "config";
  2. import mongoose from "mongoose";
  3. import bluebird from "bluebird";
  4. import async from "async";
  5. import CoreClass from "../../core";
  6. const REQUIRED_DOCUMENT_VERSIONS = {
  7. activity: 1,
  8. news: 1,
  9. playlist: 1,
  10. punishment: 1,
  11. queueSong: 1,
  12. report: 1,
  13. song: 1,
  14. station: 3,
  15. user: 1
  16. };
  17. const regex = {
  18. azAZ09_: /^[A-Za-z0-9_]+$/,
  19. az09_: /^[a-z0-9_]+$/,
  20. emailSimple: /^[\x00-\x7F]+@[a-z0-9]+\.[a-z0-9]+(\.[a-z0-9]+)?$/,
  21. ascii: /^[\x00-\x7F]+$/,
  22. custom: regex => new RegExp(`^[${regex}]+$`)
  23. };
  24. const isLength = (string, min, max) => !(typeof string !== "string" || string.length < min || string.length > max);
  25. mongoose.Promise = bluebird;
  26. let DBModule;
  27. class _DBModule extends CoreClass {
  28. // eslint-disable-next-line require-jsdoc
  29. constructor() {
  30. super("db");
  31. DBModule = this;
  32. }
  33. /**
  34. * Initialises the database module
  35. *
  36. * @returns {Promise} - returns promise (reject, resolve)
  37. */
  38. initialize() {
  39. return new Promise((resolve, reject) => {
  40. this.schemas = {};
  41. this.models = {};
  42. const mongoUrl = config.get("mongo").url;
  43. mongoose.set("useFindAndModify", false);
  44. mongoose
  45. .connect(mongoUrl, {
  46. useNewUrlParser: true,
  47. useUnifiedTopology: true,
  48. useCreateIndex: true
  49. })
  50. .then(async () => {
  51. this.schemas = {
  52. song: {},
  53. queueSong: {},
  54. station: {},
  55. user: {},
  56. activity: {},
  57. playlist: {},
  58. news: {},
  59. report: {},
  60. punishment: {}
  61. };
  62. const importSchema = schemaName =>
  63. new Promise(resolve => {
  64. import(`./schemas/${schemaName}`).then(schema => {
  65. this.schemas[schemaName] = new mongoose.Schema(schema.default);
  66. return resolve();
  67. });
  68. });
  69. await importSchema("song");
  70. await importSchema("queueSong");
  71. await importSchema("station");
  72. await importSchema("user");
  73. await importSchema("activity");
  74. await importSchema("playlist");
  75. await importSchema("news");
  76. await importSchema("report");
  77. await importSchema("punishment");
  78. this.models = {
  79. song: mongoose.model("song", this.schemas.song),
  80. queueSong: mongoose.model("queueSong", this.schemas.queueSong),
  81. station: mongoose.model("station", this.schemas.station),
  82. user: mongoose.model("user", this.schemas.user),
  83. activity: mongoose.model("activity", this.schemas.activity),
  84. playlist: mongoose.model("playlist", this.schemas.playlist),
  85. news: mongoose.model("news", this.schemas.news),
  86. report: mongoose.model("report", this.schemas.report),
  87. punishment: mongoose.model("punishment", this.schemas.punishment)
  88. };
  89. mongoose.connection.on("error", err => {
  90. this.log("ERROR", err);
  91. });
  92. mongoose.connection.on("disconnected", () => {
  93. this.log("ERROR", "Disconnected, going to try to reconnect...");
  94. this.setStatus("RECONNECTING");
  95. });
  96. mongoose.connection.on("reconnected", () => {
  97. this.log("INFO", "Reconnected.");
  98. this.setStatus("READY");
  99. });
  100. mongoose.connection.on("reconnectFailed", () => {
  101. this.log("INFO", "Reconnect failed, stopping reconnecting.");
  102. // this.failed = true;
  103. // this._lockdown();
  104. this.setStatus("FAILED");
  105. });
  106. // User
  107. this.schemas.user
  108. .path("username")
  109. .validate(
  110. username => isLength(username, 2, 32) && regex.custom("a-zA-Z0-9_-").test(username),
  111. "Invalid username."
  112. );
  113. this.schemas.user.path("email.address").validate(email => {
  114. if (!isLength(email, 3, 254)) return false;
  115. if (email.indexOf("@") !== email.lastIndexOf("@")) return false;
  116. return regex.emailSimple.test(email) && regex.ascii.test(email);
  117. }, "Invalid email.");
  118. // Station
  119. this.schemas.station
  120. .path("name")
  121. .validate(id => isLength(id, 2, 16) && regex.az09_.test(id), "Invalid station name.");
  122. this.schemas.station
  123. .path("displayName")
  124. .validate(
  125. displayName => isLength(displayName, 2, 32) && regex.ascii.test(displayName),
  126. "Invalid display name."
  127. );
  128. this.schemas.station.path("description").validate(description => {
  129. if (!isLength(description, 2, 200)) return false;
  130. const characters = description.split("");
  131. return characters.filter(character => character.charCodeAt(0) === 21328).length === 0;
  132. }, "Invalid display name.");
  133. this.schemas.station.path("owner").validate({
  134. validator: owner =>
  135. new Promise((resolve, reject) => {
  136. this.models.station.countDocuments({ owner }, (err, c) => {
  137. if (err) reject(new Error("A mongo error happened."));
  138. else if (c >= 3) reject(new Error("User already has 3 stations."));
  139. else resolve();
  140. });
  141. }),
  142. message: "User already has 3 stations."
  143. });
  144. /*
  145. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  146. let totalDuration = 0;
  147. queue.forEach((song) => {
  148. totalDuration += song.duration;
  149. });
  150. return callback(totalDuration <= 3600 * 3);
  151. }, 'The max length of the queue is 3 hours.');
  152. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  153. if (queue.length === 0) return callback(true);
  154. let totalDuration = 0;
  155. const userId = queue[queue.length - 1].requestedBy;
  156. queue.forEach((song) => {
  157. if (userId === song.requestedBy) {
  158. totalDuration += song.duration;
  159. }
  160. });
  161. return callback(totalDuration <= 900);
  162. }, 'The max length of songs per user is 15 minutes.');
  163. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  164. if (queue.length === 0) return callback(true);
  165. let totalSongs = 0;
  166. const userId = queue[queue.length - 1].requestedBy;
  167. queue.forEach((song) => {
  168. if (userId === song.requestedBy) {
  169. totalSongs++;
  170. }
  171. });
  172. if (totalSongs <= 2) return callback(true);
  173. if (totalSongs > 3) return callback(false);
  174. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return callback(true);
  175. return callback(false);
  176. }, 'The max amount of songs per user is 3, and only 2 in a row is allowed.');
  177. */
  178. // Song
  179. const songTitle = title => isLength(title, 1, 100);
  180. this.schemas.song.path("title").validate(songTitle, "Invalid title.");
  181. this.schemas.queueSong.path("title").validate(songTitle, "Invalid title.");
  182. this.schemas.song
  183. .path("artists")
  184. .validate(artists => !(artists.length < 1 || artists.length > 10), "Invalid artists.");
  185. this.schemas.queueSong
  186. .path("artists")
  187. .validate(artists => !(artists.length < 0 || artists.length > 10), "Invalid artists.");
  188. const songArtists = artists =>
  189. artists.filter(artist => isLength(artist, 1, 64) && artist !== "NONE").length ===
  190. artists.length;
  191. this.schemas.song.path("artists").validate(songArtists, "Invalid artists.");
  192. this.schemas.queueSong.path("artists").validate(songArtists, "Invalid artists.");
  193. const songGenres = genres => {
  194. if (genres.length < 1 || genres.length > 16) return false;
  195. return (
  196. genres.filter(genre => isLength(genre, 1, 32) && regex.ascii.test(genre)).length ===
  197. genres.length
  198. );
  199. };
  200. this.schemas.song.path("genres").validate(songGenres, "Invalid genres.");
  201. this.schemas.queueSong.path("genres").validate(songGenres, "Invalid genres.");
  202. const songThumbnail = thumbnail => {
  203. if (!isLength(thumbnail, 1, 256)) return false;
  204. if (config.get("cookie.secure") === true) return thumbnail.startsWith("https://");
  205. return thumbnail.startsWith("http://") || thumbnail.startsWith("https://");
  206. };
  207. this.schemas.song.path("thumbnail").validate(songThumbnail, "Invalid thumbnail.");
  208. this.schemas.queueSong.path("thumbnail").validate(songThumbnail, "Invalid thumbnail.");
  209. // Playlist
  210. this.schemas.playlist
  211. .path("displayName")
  212. .validate(
  213. displayName => isLength(displayName, 1, 32) && regex.ascii.test(displayName),
  214. "Invalid display name."
  215. );
  216. this.schemas.playlist.path("createdBy").validate(createdBy => {
  217. this.models.playlist.countDocuments({ createdBy }, (err, c) => !(err || c >= 10));
  218. }, "Max 10 playlists per user.");
  219. this.schemas.playlist
  220. .path("songs")
  221. .validate(songs => songs.length <= 5000, "Max 5000 songs per playlist.");
  222. this.schemas.playlist.path("songs").validate(songs => {
  223. if (songs.length === 0) return true;
  224. return songs[0].duration <= 10800;
  225. }, "Max 3 hours per song.");
  226. this.schemas.playlist.index({ createdFor: 1, type: 1 }, { unique: true });
  227. // Report
  228. this.schemas.report
  229. .path("description")
  230. .validate(
  231. description =>
  232. !description || (isLength(description, 0, 400) && regex.ascii.test(description)),
  233. "Invalid description."
  234. );
  235. if (config.get("skipDbDocumentsVersionCheck")) resolve();
  236. else {
  237. this.runJob("CHECK_DOCUMENT_VERSIONS", {}, null, -1)
  238. .then(() => {
  239. resolve();
  240. })
  241. .catch(err => {
  242. reject(err);
  243. });
  244. }
  245. })
  246. .catch(err => {
  247. this.log("ERROR", err);
  248. reject(err);
  249. });
  250. });
  251. }
  252. /**
  253. * Checks if all documents have the correct document version
  254. *
  255. * @returns {Promise} - returns promise (reject, resolve)
  256. */
  257. CHECK_DOCUMENT_VERSIONS() {
  258. return new Promise((resolve, reject) => {
  259. async.each(
  260. Object.keys(REQUIRED_DOCUMENT_VERSIONS),
  261. (modelName, next) => {
  262. const model = DBModule.models[modelName];
  263. const requiredDocumentVersion = REQUIRED_DOCUMENT_VERSIONS[modelName];
  264. model.countDocuments({ documentVersion: { $ne: requiredDocumentVersion } }, (err, count) => {
  265. if (err) next(err);
  266. else if (count > 0)
  267. next(
  268. `Collection "${modelName}" has ${count} documents with a wrong document version. Run migration.`
  269. );
  270. else next();
  271. });
  272. },
  273. err => {
  274. if (err) reject(new Error(err));
  275. else resolve();
  276. }
  277. );
  278. });
  279. }
  280. /**
  281. * Returns a database model
  282. *
  283. * @param {object} payload - object containing the payload
  284. * @param {object} payload.modelName - name of the model to get
  285. * @returns {Promise} - returns promise (reject, resolve)
  286. */
  287. GET_MODEL(payload) {
  288. return new Promise(resolve => {
  289. resolve(DBModule.models[payload.modelName]);
  290. });
  291. }
  292. /**
  293. * Returns a database schema
  294. *
  295. * @param {object} payload - object containing the payload
  296. * @param {object} payload.schemaName - name of the schema to get
  297. * @returns {Promise} - returns promise (reject, resolve)
  298. */
  299. GET_SCHEMA(payload) {
  300. return new Promise(resolve => {
  301. resolve(DBModule.schemas[payload.schemaName]);
  302. });
  303. }
  304. /**
  305. * Checks if a password to be stored in the database has a valid length
  306. *
  307. * @param {object} password - the password itself
  308. * @returns {Promise} - returns promise (reject, resolve)
  309. */
  310. passwordValid(password) {
  311. return isLength(password, 6, 200);
  312. }
  313. }
  314. export default new _DBModule();