index.js 21 KB

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