index.js 9.7 KB

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