index.js 19 KB

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