index.js 19 KB

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