index.js 17 KB

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