index.js 20 KB

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