index.js 19 KB

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