index.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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: 3,
  9. playlist: 6,
  10. punishment: 1,
  11. queueSong: 1,
  12. report: 5,
  13. song: 9,
  14. station: 8,
  15. user: 3,
  16. youtubeApiRequest: 1,
  17. youtubeVideo: 1,
  18. ratings: 1
  19. };
  20. const regex = {
  21. azAZ09_: /^[A-Za-z0-9_]+$/,
  22. az09_: /^[a-z0-9_]+$/,
  23. emailSimple: /^[\x00-\x7F]+@[a-z0-9]+\.[a-z0-9]+(\.[a-z0-9]+)?$/,
  24. ascii: /^[\x00-\x7F]+$/,
  25. name: /^[\p{L}0-9 .'_-]+$/u,
  26. custom: regex => new RegExp(`^[${regex}]+$`)
  27. };
  28. const isLength = (string, min, max) => !(typeof string !== "string" || string.length < min || string.length > max);
  29. mongoose.Promise = bluebird;
  30. let DBModule;
  31. class _DBModule extends CoreClass {
  32. // eslint-disable-next-line require-jsdoc
  33. constructor() {
  34. super("db");
  35. DBModule = this;
  36. }
  37. /**
  38. * Initialises the database module
  39. *
  40. * @returns {Promise} - returns promise (reject, resolve)
  41. */
  42. initialize() {
  43. return new Promise((resolve, reject) => {
  44. this.schemas = {};
  45. this.models = {};
  46. const mongoUrl = config.get("mongo").url;
  47. mongoose
  48. .connect(mongoUrl, {
  49. useNewUrlParser: true,
  50. useUnifiedTopology: true
  51. })
  52. .then(async () => {
  53. this.schemas = {
  54. song: {},
  55. queueSong: {},
  56. station: {},
  57. user: {},
  58. dataRequest: {},
  59. activity: {},
  60. playlist: {},
  61. news: {},
  62. report: {},
  63. punishment: {},
  64. youtubeApiRequest: {},
  65. youtubeVideo: {},
  66. ratings: {}
  67. };
  68. const importSchema = schemaName =>
  69. new Promise(resolve => {
  70. import(`./schemas/${schemaName}`).then(schema => {
  71. this.schemas[schemaName] = new mongoose.Schema(schema.default);
  72. return resolve();
  73. });
  74. });
  75. await importSchema("song");
  76. await importSchema("queueSong");
  77. await importSchema("station");
  78. await importSchema("user");
  79. await importSchema("dataRequest");
  80. await importSchema("activity");
  81. await importSchema("playlist");
  82. await importSchema("news");
  83. await importSchema("report");
  84. await importSchema("punishment");
  85. await importSchema("youtubeApiRequest");
  86. await importSchema("youtubeVideo");
  87. await importSchema("ratings");
  88. this.models = {
  89. song: mongoose.model("song", this.schemas.song),
  90. queueSong: mongoose.model("queueSong", this.schemas.queueSong),
  91. station: mongoose.model("station", this.schemas.station),
  92. user: mongoose.model("user", this.schemas.user),
  93. dataRequest: mongoose.model("dataRequest", this.schemas.dataRequest),
  94. activity: mongoose.model("activity", this.schemas.activity),
  95. playlist: mongoose.model("playlist", this.schemas.playlist),
  96. news: mongoose.model("news", this.schemas.news),
  97. report: mongoose.model("report", this.schemas.report),
  98. punishment: mongoose.model("punishment", this.schemas.punishment),
  99. youtubeApiRequest: mongoose.model("youtubeApiRequest", this.schemas.youtubeApiRequest),
  100. youtubeVideo: mongoose.model("youtubeVideo", this.schemas.youtubeVideo),
  101. ratings: mongoose.model("ratings", this.schemas.ratings)
  102. };
  103. mongoose.connection.on("error", err => {
  104. this.log("ERROR", err);
  105. });
  106. mongoose.connection.on("disconnected", () => {
  107. this.log("ERROR", "Disconnected, going to try to reconnect...");
  108. this.setStatus("RECONNECTING");
  109. });
  110. mongoose.connection.on("reconnected", () => {
  111. this.log("INFO", "Reconnected.");
  112. this.setStatus("READY");
  113. });
  114. mongoose.connection.on("reconnectFailed", () => {
  115. this.log("INFO", "Reconnect failed, stopping reconnecting.");
  116. this.setStatus("FAILED");
  117. });
  118. // User
  119. this.schemas.user
  120. .path("username")
  121. .validate(
  122. username =>
  123. isLength(username, 2, 32) &&
  124. regex.custom("a-zA-Z0-9_-").test(username) &&
  125. username.replaceAll(/[_]/g, "").length > 0,
  126. "Invalid username."
  127. );
  128. this.schemas.user.path("email.address").validate(email => {
  129. if (!isLength(email, 3, 254)) return false;
  130. if (email.indexOf("@") !== email.lastIndexOf("@")) return false;
  131. return regex.emailSimple.test(email) && regex.ascii.test(email);
  132. }, "Invalid email.");
  133. this.schemas.user
  134. .path("name")
  135. .validate(
  136. name =>
  137. isLength(name, 1, 64) &&
  138. regex.name.test(name) &&
  139. name.replaceAll(/[ .'_-]/g, "").length > 0,
  140. "Invalid name."
  141. );
  142. // Station
  143. this.schemas.station
  144. .path("name")
  145. .validate(id => isLength(id, 2, 16) && regex.az09_.test(id), "Invalid station name.");
  146. this.schemas.station
  147. .path("displayName")
  148. .validate(
  149. displayName => isLength(displayName, 2, 32) && regex.ascii.test(displayName),
  150. "Invalid display name."
  151. );
  152. this.schemas.station.path("description").validate(description => {
  153. if (!isLength(description, 2, 200)) return false;
  154. const characters = description.split("");
  155. return characters.filter(character => character.charCodeAt(0) === 21328).length === 0;
  156. }, "Invalid display name.");
  157. this.schemas.station.path("owner").validate({
  158. validator: owner =>
  159. new Promise((resolve, reject) => {
  160. this.models.station.countDocuments({ owner }, (err, c) => {
  161. if (err) reject(new Error("A mongo error happened."));
  162. else if (c >= 25) reject(new Error("User already has 25 stations."));
  163. else resolve();
  164. });
  165. }),
  166. message: "User already has 25 stations."
  167. });
  168. // Song
  169. const songTitle = title => isLength(title, 1, 100);
  170. this.schemas.song.path("title").validate(songTitle, "Invalid title.");
  171. this.schemas.song.path("artists").validate(artists => artists.length <= 10, "Invalid artists.");
  172. const songArtists = artists =>
  173. artists.filter(artist => isLength(artist, 1, 64) && artist !== "NONE").length ===
  174. artists.length;
  175. this.schemas.song.path("artists").validate(songArtists, "Invalid artists.");
  176. const songGenres = genres => {
  177. if (genres.length > 16) return false;
  178. return (
  179. genres.filter(genre => isLength(genre, 1, 32) && regex.ascii.test(genre)).length ===
  180. genres.length
  181. );
  182. };
  183. this.schemas.song.path("genres").validate(songGenres, "Invalid genres.");
  184. const songTags = tags =>
  185. tags.filter(tag => /^[a-zA-Z0-9_]{1,64}$|^[a-zA-Z0-9_]{1,64}\[[a-zA-Z0-9_]{1,64}\]$/.test(tag))
  186. .length === tags.length;
  187. this.schemas.song.path("tags").validate(songTags, "Invalid tags.");
  188. const songThumbnail = thumbnail => {
  189. if (!isLength(thumbnail, 1, 256)) return false;
  190. if (config.get("cookie.secure") === true) return thumbnail.startsWith("https://");
  191. return thumbnail.startsWith("http://") || thumbnail.startsWith("https://");
  192. };
  193. this.schemas.song.path("thumbnail").validate(songThumbnail, "Invalid thumbnail.");
  194. // Playlist
  195. this.schemas.playlist
  196. .path("displayName")
  197. .validate(
  198. displayName => isLength(displayName, 1, 32) && regex.ascii.test(displayName),
  199. "Invalid display name."
  200. );
  201. this.schemas.playlist.path("createdBy").validate(createdBy => {
  202. this.models.playlist.countDocuments({ createdBy }, (err, c) => !(err || c >= 100));
  203. }, "Max 100 playlists per user.");
  204. this.schemas.playlist
  205. .path("songs")
  206. .validate(songs => songs.length <= 10000, "Max 10000 songs per playlist.");
  207. // this.schemas.playlist.path("songs").validate(songs => {
  208. // if (songs.length === 0) return true;
  209. // return songs[0].duration <= 10800;
  210. // }, "Max 3 hours per song.");
  211. this.models.activity.syncIndexes();
  212. this.models.dataRequest.syncIndexes();
  213. this.models.news.syncIndexes();
  214. this.models.playlist.syncIndexes();
  215. this.models.punishment.syncIndexes();
  216. this.models.queueSong.syncIndexes();
  217. this.models.report.syncIndexes();
  218. this.models.song.syncIndexes();
  219. this.models.station.syncIndexes();
  220. this.models.user.syncIndexes();
  221. this.models.youtubeApiRequest.syncIndexes();
  222. this.models.youtubeVideo.syncIndexes();
  223. this.models.ratings.syncIndexes();
  224. if (config.get("skipDbDocumentsVersionCheck")) resolve();
  225. else {
  226. this.runJob("CHECK_DOCUMENT_VERSIONS", {}, null, -1)
  227. .then(() => {
  228. resolve();
  229. })
  230. .catch(err => {
  231. reject(err);
  232. });
  233. }
  234. })
  235. .catch(err => {
  236. this.log("ERROR", err);
  237. reject(err);
  238. });
  239. });
  240. }
  241. /**
  242. * Checks if all documents have the correct document version
  243. *
  244. * @returns {Promise} - returns promise (reject, resolve)
  245. */
  246. CHECK_DOCUMENT_VERSIONS() {
  247. return new Promise((resolve, reject) => {
  248. async.each(
  249. Object.keys(REQUIRED_DOCUMENT_VERSIONS),
  250. (modelName, next) => {
  251. const model = DBModule.models[modelName];
  252. const requiredDocumentVersion = REQUIRED_DOCUMENT_VERSIONS[modelName];
  253. model.countDocuments({ documentVersion: { $ne: requiredDocumentVersion } }, (err, count) => {
  254. if (err) next(err);
  255. else if (count > 0)
  256. next(
  257. `Collection "${modelName}" has ${count} documents with a wrong document version. Run migration.`
  258. );
  259. else next();
  260. });
  261. },
  262. err => {
  263. if (err) reject(new Error(err));
  264. else resolve();
  265. }
  266. );
  267. });
  268. }
  269. /**
  270. * Returns a database model
  271. *
  272. * @param {object} payload - object containing the payload
  273. * @param {object} payload.modelName - name of the model to get
  274. * @returns {Promise} - returns promise (reject, resolve)
  275. */
  276. GET_MODEL(payload) {
  277. return new Promise(resolve => {
  278. resolve(DBModule.models[payload.modelName]);
  279. });
  280. }
  281. /**
  282. * Returns a database schema
  283. *
  284. * @param {object} payload - object containing the payload
  285. * @param {object} payload.schemaName - name of the schema to get
  286. * @returns {Promise} - returns promise (reject, resolve)
  287. */
  288. GET_SCHEMA(payload) {
  289. return new Promise(resolve => {
  290. resolve(DBModule.schemas[payload.schemaName]);
  291. });
  292. }
  293. /**
  294. * Gets data
  295. *
  296. * @param {object} payload - object containing the payload
  297. * @param {string} payload.page - the page
  298. * @param {string} payload.pageSize - the page size
  299. * @param {string} payload.properties - the properties to return for each song
  300. * @param {string} payload.sort - the sort object
  301. * @param {string} payload.queries - the queries array
  302. * @param {string} payload.operator - the operator for queries
  303. * @param {string} payload.modelName - the db collection modal name
  304. * @param {string} payload.blacklistedProperties - the properties that are not allowed to be returned, filtered by or sorted by
  305. * @param {string} payload.specialProperties - the special properties
  306. * @param {string} payload.specialQueries - the special queries
  307. * @returns {Promise} - returns a promise (resolve, reject)
  308. */
  309. GET_DATA(payload) {
  310. return new Promise((resolve, reject) => {
  311. async.waterfall(
  312. [
  313. // Creates pipeline array
  314. next => next(null, []),
  315. // If a query filter property or sort property is blacklisted, throw error
  316. (pipeline, next) => {
  317. const { sort, queries, blacklistedProperties } = payload;
  318. if (
  319. queries.some(query =>
  320. blacklistedProperties.some(blacklistedProperty =>
  321. blacklistedProperty.startsWith(query.filter.property)
  322. )
  323. )
  324. )
  325. return next("Unable to filter by blacklisted property.");
  326. if (
  327. Object.keys(sort).some(property =>
  328. blacklistedProperties.some(blacklistedProperty =>
  329. blacklistedProperty.startsWith(property)
  330. )
  331. )
  332. )
  333. return next("Unable to sort by blacklisted property.");
  334. return next(null, pipeline);
  335. },
  336. // If a filter or property exists for a special property, add some custom pipeline steps
  337. (pipeline, next) => {
  338. const { properties, queries, specialProperties } = payload;
  339. async.eachLimit(
  340. Object.entries(specialProperties),
  341. 1,
  342. ([specialProperty, pipelineSteps], next) => {
  343. // Check if a filter with the special property exists
  344. const filterExists =
  345. queries.map(query => query.filter.property).indexOf(specialProperty) !== -1;
  346. // Check if a property with the special property exists
  347. const propertyExists = properties.indexOf(specialProperty) !== -1;
  348. // If no such filter or property exists, skip this function
  349. if (!filterExists && !propertyExists) return next();
  350. // Add the specified pipeline steps into the pipeline
  351. pipeline.push(...pipelineSteps);
  352. return next();
  353. },
  354. err => {
  355. next(err, pipeline);
  356. }
  357. );
  358. },
  359. // Adds the match stage to aggregation pipeline, which is responsible for filtering
  360. (pipeline, next) => {
  361. const { queries, operator, specialQueries } = payload;
  362. let queryError;
  363. const newQueries = queries.flatMap(query => {
  364. const { data, filter, filterType } = query;
  365. const newQuery = {};
  366. if (filterType === "regex") {
  367. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  368. } else if (filterType === "contains") {
  369. newQuery[filter.property] = new RegExp(
  370. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  371. "i"
  372. );
  373. } else if (filterType === "exact") {
  374. newQuery[filter.property] = data.toString();
  375. } else if (filterType === "datetimeBefore") {
  376. newQuery[filter.property] = { $lte: new Date(data) };
  377. } else if (filterType === "datetimeAfter") {
  378. newQuery[filter.property] = { $gte: new Date(data) };
  379. } else if (filterType === "numberLesserEqual") {
  380. newQuery[filter.property] = { $lte: Number(data) };
  381. } else if (filterType === "numberLesser") {
  382. newQuery[filter.property] = { $lt: Number(data) };
  383. } else if (filterType === "numberGreater") {
  384. newQuery[filter.property] = { $gt: Number(data) };
  385. } else if (filterType === "numberGreaterEqual") {
  386. newQuery[filter.property] = { $gte: Number(data) };
  387. } else if (filterType === "numberEquals") {
  388. newQuery[filter.property] = { $eq: Number(data) };
  389. } else if (filterType === "boolean") {
  390. newQuery[filter.property] = { $eq: !!data };
  391. }
  392. if (specialQueries[filter.property]) {
  393. return specialQueries[filter.property](newQuery);
  394. }
  395. return newQuery;
  396. });
  397. if (queryError) next(queryError);
  398. const queryObject = {};
  399. if (newQueries.length > 0) {
  400. if (operator === "and") queryObject.$and = newQueries;
  401. else if (operator === "or") queryObject.$or = newQueries;
  402. else if (operator === "nor") queryObject.$nor = newQueries;
  403. }
  404. pipeline.push({ $match: queryObject });
  405. next(null, pipeline);
  406. },
  407. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  408. (pipeline, next) => {
  409. const { sort } = payload;
  410. const newSort = Object.fromEntries(
  411. Object.entries(sort).map(([property, direction]) => [
  412. property,
  413. direction === "ascending" ? 1 : -1
  414. ])
  415. );
  416. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  417. next(null, pipeline);
  418. },
  419. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  420. (pipeline, next) => {
  421. const { properties } = payload;
  422. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  423. next(null, pipeline);
  424. },
  425. // Adds second project stage to aggregation pipeline, responsible for excluding some specific properties
  426. (pipeline, next) => {
  427. const { blacklistedProperties } = payload;
  428. if (blacklistedProperties.length > 0)
  429. pipeline.push({
  430. $project: Object.fromEntries(blacklistedProperties.map(property => [property, 0]))
  431. });
  432. next(null, pipeline);
  433. },
  434. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  435. (pipeline, next) => {
  436. const { page, pageSize } = payload;
  437. pipeline.push({
  438. $facet: {
  439. count: [{ $count: "count" }],
  440. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  441. }
  442. });
  443. // console.dir(pipeline, { depth: 6 });
  444. next(null, pipeline);
  445. },
  446. (pipeline, next) => {
  447. const { modelName } = payload;
  448. DBModule.runJob("GET_MODEL", { modelName }, this)
  449. .then(model => {
  450. if (!model) return next("Invalid model.");
  451. return next(null, pipeline, model);
  452. })
  453. .catch(err => {
  454. next(err);
  455. });
  456. },
  457. // Executes the aggregation pipeline
  458. (pipeline, model, next) => {
  459. model.aggregate(pipeline).exec((err, result) => {
  460. // console.dir(err);
  461. // console.dir(result, { depth: 6 });
  462. if (err) return next(err);
  463. if (result[0].count.length === 0) return next(null, 0, []);
  464. const { count } = result[0].count[0];
  465. const { documents } = result[0];
  466. // console.log(111, err, result, count, documents[0]);
  467. return next(null, count, documents);
  468. });
  469. }
  470. ],
  471. (err, count, documents) => {
  472. if (err && err !== true) return reject(new Error(err));
  473. return resolve({ data: documents, count });
  474. }
  475. );
  476. });
  477. }
  478. /**
  479. * Checks if a password to be stored in the database has a valid length
  480. *
  481. * @param {object} password - the password itself
  482. * @returns {Promise} - returns promise (reject, resolve)
  483. */
  484. passwordValid(password) {
  485. return isLength(password, 6, 200);
  486. }
  487. }
  488. export default new _DBModule();