index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. 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(
  125. name => isLength(name, 1, 64) && regex.name.test(name),
  126. "Invalid name."
  127. );
  128. // Station
  129. this.schemas.station
  130. .path("name")
  131. .validate(id => isLength(id, 2, 16) && regex.az09_.test(id), "Invalid station name.");
  132. this.schemas.station
  133. .path("displayName")
  134. .validate(
  135. displayName => isLength(displayName, 2, 32) && regex.ascii.test(displayName),
  136. "Invalid display name."
  137. );
  138. this.schemas.station.path("description").validate(description => {
  139. if (!isLength(description, 2, 200)) return false;
  140. const characters = description.split("");
  141. return characters.filter(character => character.charCodeAt(0) === 21328).length === 0;
  142. }, "Invalid display name.");
  143. this.schemas.station.path("owner").validate({
  144. validator: owner =>
  145. new Promise((resolve, reject) => {
  146. this.models.station.countDocuments({ owner }, (err, c) => {
  147. if (err) reject(new Error("A mongo error happened."));
  148. else if (c >= 3) reject(new Error("User already has 3 stations."));
  149. else resolve();
  150. });
  151. }),
  152. message: "User already has 3 stations."
  153. });
  154. /*
  155. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  156. let totalDuration = 0;
  157. queue.forEach((song) => {
  158. totalDuration += song.duration;
  159. });
  160. return callback(totalDuration <= 3600 * 3);
  161. }, 'The max length of the queue is 3 hours.');
  162. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  163. if (queue.length === 0) return callback(true);
  164. let totalDuration = 0;
  165. const userId = queue[queue.length - 1].requestedBy;
  166. queue.forEach((song) => {
  167. if (userId === song.requestedBy) {
  168. totalDuration += song.duration;
  169. }
  170. });
  171. return callback(totalDuration <= 900);
  172. }, 'The max length of songs per user is 15 minutes.');
  173. this.schemas.station.path('queue').validate((queue, callback) => { //Callback no longer works, see station max count
  174. if (queue.length === 0) return callback(true);
  175. let totalSongs = 0;
  176. const userId = queue[queue.length - 1].requestedBy;
  177. queue.forEach((song) => {
  178. if (userId === song.requestedBy) {
  179. totalSongs++;
  180. }
  181. });
  182. if (totalSongs <= 2) return callback(true);
  183. if (totalSongs > 3) return callback(false);
  184. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId) return callback(true);
  185. return callback(false);
  186. }, 'The max amount of songs per user is 3, and only 2 in a row is allowed.');
  187. */
  188. // Song
  189. const songTitle = title => isLength(title, 1, 100);
  190. this.schemas.song.path("title").validate(songTitle, "Invalid title.");
  191. this.schemas.song.path("artists").validate(artists => artists.length <= 10, "Invalid artists.");
  192. const songArtists = artists =>
  193. artists.filter(artist => isLength(artist, 1, 64) && artist !== "NONE").length ===
  194. artists.length;
  195. this.schemas.song.path("artists").validate(songArtists, "Invalid artists.");
  196. const songGenres = genres => {
  197. if (genres.length > 16) return false;
  198. return (
  199. genres.filter(genre => isLength(genre, 1, 32) && regex.ascii.test(genre)).length ===
  200. genres.length
  201. );
  202. };
  203. this.schemas.song.path("genres").validate(songGenres, "Invalid genres.");
  204. const songThumbnail = thumbnail => {
  205. if (!isLength(thumbnail, 1, 256)) return false;
  206. if (config.get("cookie.secure") === true) return thumbnail.startsWith("https://");
  207. return thumbnail.startsWith("http://") || thumbnail.startsWith("https://");
  208. };
  209. this.schemas.song.path("thumbnail").validate(songThumbnail, "Invalid thumbnail.");
  210. // Playlist
  211. this.schemas.playlist
  212. .path("displayName")
  213. .validate(
  214. displayName => isLength(displayName, 1, 32) && regex.ascii.test(displayName),
  215. "Invalid display name."
  216. );
  217. this.schemas.playlist.path("createdBy").validate(createdBy => {
  218. this.models.playlist.countDocuments({ createdBy }, (err, c) => !(err || c >= 10));
  219. }, "Max 10 playlists per user.");
  220. this.schemas.playlist
  221. .path("songs")
  222. .validate(songs => songs.length <= 5000, "Max 5000 songs per playlist.");
  223. this.schemas.playlist.path("songs").validate(songs => {
  224. if (songs.length === 0) return true;
  225. return songs[0].duration <= 10800;
  226. }, "Max 3 hours per song.");
  227. this.schemas.playlist.index({ createdFor: 1, type: 1 }, { unique: true });
  228. // Report
  229. this.schemas.report
  230. .path("description")
  231. .validate(
  232. description =>
  233. !description || (isLength(description, 0, 400) && regex.ascii.test(description)),
  234. "Invalid description."
  235. );
  236. if (config.get("skipDbDocumentsVersionCheck")) resolve();
  237. else {
  238. this.runJob("CHECK_DOCUMENT_VERSIONS", {}, null, -1)
  239. .then(() => {
  240. resolve();
  241. })
  242. .catch(err => {
  243. reject(err);
  244. });
  245. }
  246. })
  247. .catch(err => {
  248. this.log("ERROR", err);
  249. reject(err);
  250. });
  251. });
  252. }
  253. /**
  254. * Checks if all documents have the correct document version
  255. *
  256. * @returns {Promise} - returns promise (reject, resolve)
  257. */
  258. CHECK_DOCUMENT_VERSIONS() {
  259. return new Promise((resolve, reject) => {
  260. async.each(
  261. Object.keys(REQUIRED_DOCUMENT_VERSIONS),
  262. (modelName, next) => {
  263. const model = DBModule.models[modelName];
  264. const requiredDocumentVersion = REQUIRED_DOCUMENT_VERSIONS[modelName];
  265. model.countDocuments({ documentVersion: { $ne: requiredDocumentVersion } }, (err, count) => {
  266. if (err) next(err);
  267. else if (count > 0)
  268. next(
  269. `Collection "${modelName}" has ${count} documents with a wrong document version. Run migration.`
  270. );
  271. else next();
  272. });
  273. },
  274. err => {
  275. if (err) reject(new Error(err));
  276. else resolve();
  277. }
  278. );
  279. });
  280. }
  281. /**
  282. * Returns a database model
  283. *
  284. * @param {object} payload - object containing the payload
  285. * @param {object} payload.modelName - name of the model to get
  286. * @returns {Promise} - returns promise (reject, resolve)
  287. */
  288. GET_MODEL(payload) {
  289. return new Promise(resolve => {
  290. resolve(DBModule.models[payload.modelName]);
  291. });
  292. }
  293. /**
  294. * Returns a database schema
  295. *
  296. * @param {object} payload - object containing the payload
  297. * @param {object} payload.schemaName - name of the schema to get
  298. * @returns {Promise} - returns promise (reject, resolve)
  299. */
  300. GET_SCHEMA(payload) {
  301. return new Promise(resolve => {
  302. resolve(DBModule.schemas[payload.schemaName]);
  303. });
  304. }
  305. /**
  306. * Checks if a password to be stored in the database has a valid length
  307. *
  308. * @param {object} password - the password itself
  309. * @returns {Promise} - returns promise (reject, resolve)
  310. */
  311. passwordValid(password) {
  312. return isLength(password, 6, 200);
  313. }
  314. }
  315. export default new _DBModule();