index.js 9.8 KB

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