index.js 18 KB

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