index.js 19 KB

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