index.js 11 KB

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