index.js 9.1 KB

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