index.js 11 KB

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