index.js 20 KB

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