index.js 11 KB

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