index.js 19 KB

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