index.js 17 KB

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