index.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. return false;
  183. });
  184. const songTitle = title => isLength(title, 1, 100);
  185. this.schemas.song.path("title").validate(songTitle, "Invalid title.");
  186. this.schemas.song.path("artists").validate(artists => artists.length <= 10, "Invalid artists.");
  187. const songArtists = artists =>
  188. artists.filter(artist => isLength(artist, 1, 64) && artist !== "NONE").length ===
  189. artists.length;
  190. this.schemas.song.path("artists").validate(songArtists, "Invalid artists.");
  191. const songGenres = genres => {
  192. if (genres.length > 16) return false;
  193. return (
  194. genres.filter(genre => isLength(genre, 1, 32) && regex.ascii.test(genre)).length ===
  195. genres.length
  196. );
  197. };
  198. this.schemas.song.path("genres").validate(songGenres, "Invalid genres.");
  199. const songTags = tags =>
  200. tags.filter(tag => /^[a-zA-Z0-9_]{1,64}$|^[a-zA-Z0-9_]{1,64}\[[a-zA-Z0-9_]{1,64}\]$/.test(tag))
  201. .length === tags.length;
  202. this.schemas.song.path("tags").validate(songTags, "Invalid tags.");
  203. const songThumbnail = thumbnail => {
  204. if (!isLength(thumbnail, 1, 256)) return false;
  205. if (config.get("cookie.secure") === true) return thumbnail.startsWith("https://");
  206. return thumbnail.startsWith("http://") || thumbnail.startsWith("https://");
  207. };
  208. this.schemas.song.path("thumbnail").validate(songThumbnail, "Invalid thumbnail.");
  209. // Playlist
  210. this.schemas.playlist
  211. .path("displayName")
  212. .validate(
  213. displayName => isLength(displayName, 1, 32) && regex.ascii.test(displayName),
  214. "Invalid display name."
  215. );
  216. this.schemas.playlist.path("createdBy").validate(createdBy => {
  217. this.models.playlist.countDocuments({ createdBy }, (err, c) => !(err || c >= 100));
  218. }, "Max 100 playlists per user.");
  219. this.schemas.playlist
  220. .path("songs")
  221. .validate(songs => songs.length <= 10000, "Max 10000 songs per playlist.");
  222. // this.schemas.playlist.path("songs").validate(songs => {
  223. // if (songs.length === 0) return true;
  224. // return songs[0].duration <= 10800;
  225. // }, "Max 3 hours per song.");
  226. this.models.activity.syncIndexes();
  227. this.models.dataRequest.syncIndexes();
  228. this.models.news.syncIndexes();
  229. this.models.playlist.syncIndexes();
  230. this.models.punishment.syncIndexes();
  231. this.models.queueSong.syncIndexes();
  232. this.models.report.syncIndexes();
  233. this.models.song.syncIndexes();
  234. this.models.station.syncIndexes();
  235. this.models.user.syncIndexes();
  236. this.models.youtubeApiRequest.syncIndexes();
  237. this.models.youtubeVideo.syncIndexes();
  238. this.models.ratings.syncIndexes();
  239. this.models.importJob.syncIndexes();
  240. this.models.stationHistory.syncIndexes();
  241. this.models.soundcloudTrack.syncIndexes();
  242. if (config.get("skipDbDocumentsVersionCheck")) resolve();
  243. else {
  244. this.runJob("CHECK_DOCUMENT_VERSIONS", {}, null, -1)
  245. .then(() => {
  246. resolve();
  247. })
  248. .catch(err => {
  249. reject(err);
  250. });
  251. }
  252. })
  253. .catch(err => {
  254. this.log("ERROR", err);
  255. reject(err);
  256. });
  257. });
  258. }
  259. /**
  260. * Checks if all documents have the correct document version
  261. *
  262. * @returns {Promise} - returns promise (reject, resolve)
  263. */
  264. CHECK_DOCUMENT_VERSIONS() {
  265. return new Promise((resolve, reject) => {
  266. async.each(
  267. Object.keys(REQUIRED_DOCUMENT_VERSIONS),
  268. (modelName, next) => {
  269. const model = DBModule.models[modelName];
  270. const requiredDocumentVersion = REQUIRED_DOCUMENT_VERSIONS[modelName];
  271. model.countDocuments({ documentVersion: { $ne: requiredDocumentVersion } }, (err, count) => {
  272. if (err) next(err);
  273. else if (count > 0)
  274. next(
  275. `Collection "${modelName}" has ${count} documents with a wrong document version. Run migration.`
  276. );
  277. else next();
  278. });
  279. },
  280. err => {
  281. if (err) reject(new Error(err));
  282. else resolve();
  283. }
  284. );
  285. });
  286. }
  287. /**
  288. * Returns a database model
  289. *
  290. * @param {object} payload - object containing the payload
  291. * @param {object} payload.modelName - name of the model to get
  292. * @returns {Promise} - returns promise (reject, resolve)
  293. */
  294. GET_MODEL(payload) {
  295. return new Promise(resolve => {
  296. resolve(DBModule.models[payload.modelName]);
  297. });
  298. }
  299. /**
  300. * Returns a database schema
  301. *
  302. * @param {object} payload - object containing the payload
  303. * @param {object} payload.schemaName - name of the schema to get
  304. * @returns {Promise} - returns promise (reject, resolve)
  305. */
  306. GET_SCHEMA(payload) {
  307. return new Promise(resolve => {
  308. resolve(DBModule.schemas[payload.schemaName]);
  309. });
  310. }
  311. /**
  312. * Gets data
  313. *
  314. * @param {object} payload - object containing the payload
  315. * @param {string} payload.page - the page
  316. * @param {string} payload.pageSize - the page size
  317. * @param {string} payload.properties - the properties to return for each song
  318. * @param {string} payload.sort - the sort object
  319. * @param {string} payload.queries - the queries array
  320. * @param {string} payload.operator - the operator for queries
  321. * @param {string} payload.modelName - the db collection modal name
  322. * @param {string} payload.blacklistedProperties - the properties that are not allowed to be returned, filtered by or sorted by
  323. * @param {string} payload.specialProperties - the special properties
  324. * @param {string} payload.specialQueries - the special queries
  325. * @returns {Promise} - returns a promise (resolve, reject)
  326. */
  327. GET_DATA(payload) {
  328. return new Promise((resolve, reject) => {
  329. async.waterfall(
  330. [
  331. // Creates pipeline array
  332. next => next(null, []),
  333. // If a query filter property or sort property is blacklisted, throw error
  334. (pipeline, next) => {
  335. const { sort, queries, blacklistedProperties } = payload;
  336. if (
  337. queries.some(query =>
  338. blacklistedProperties.some(blacklistedProperty =>
  339. blacklistedProperty.startsWith(query.filter.property)
  340. )
  341. )
  342. )
  343. return next("Unable to filter by blacklisted property.");
  344. if (
  345. Object.keys(sort).some(property =>
  346. blacklistedProperties.some(blacklistedProperty =>
  347. blacklistedProperty.startsWith(property)
  348. )
  349. )
  350. )
  351. return next("Unable to sort by blacklisted property.");
  352. return next(null, pipeline);
  353. },
  354. // If a filter or property exists for a special property, add some custom pipeline steps
  355. (pipeline, next) => {
  356. const { properties, queries, specialProperties } = payload;
  357. async.eachLimit(
  358. Object.entries(specialProperties),
  359. 1,
  360. ([specialProperty, pipelineSteps], next) => {
  361. // Check if a filter with the special property exists
  362. const filterExists =
  363. queries.map(query => query.filter.property).indexOf(specialProperty) !== -1;
  364. // Check if a property with the special property exists
  365. const propertyExists = properties.indexOf(specialProperty) !== -1;
  366. // If no such filter or property exists, skip this function
  367. if (!filterExists && !propertyExists) return next();
  368. // Add the specified pipeline steps into the pipeline
  369. pipeline.push(...pipelineSteps);
  370. return next();
  371. },
  372. err => {
  373. next(err, pipeline);
  374. }
  375. );
  376. },
  377. // Adds the match stage to aggregation pipeline, which is responsible for filtering
  378. (pipeline, next) => {
  379. const { queries, operator, specialQueries, specialFilters } = payload;
  380. let queryError;
  381. const newQueries = queries.flatMap(query => {
  382. const { data, filter, filterType } = query;
  383. const newQuery = {};
  384. if (filterType === "regex") {
  385. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  386. } else if (filterType === "contains") {
  387. newQuery[filter.property] = new RegExp(
  388. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  389. "i"
  390. );
  391. } else if (filterType === "exact") {
  392. newQuery[filter.property] = data.toString();
  393. } else if (filterType === "datetimeBefore") {
  394. newQuery[filter.property] = { $lte: new Date(data) };
  395. } else if (filterType === "datetimeAfter") {
  396. newQuery[filter.property] = { $gte: new Date(data) };
  397. } else if (filterType === "numberLesserEqual") {
  398. newQuery[filter.property] = { $lte: Number(data) };
  399. } else if (filterType === "numberLesser") {
  400. newQuery[filter.property] = { $lt: Number(data) };
  401. } else if (filterType === "numberGreater") {
  402. newQuery[filter.property] = { $gt: Number(data) };
  403. } else if (filterType === "numberGreaterEqual") {
  404. newQuery[filter.property] = { $gte: Number(data) };
  405. } else if (filterType === "numberEquals") {
  406. newQuery[filter.property] = { $eq: Number(data) };
  407. } else if (filterType === "boolean") {
  408. newQuery[filter.property] = { $eq: !!data };
  409. } else if (filterType === "special") {
  410. pipeline.push(...specialFilters[filter.property](data));
  411. newQuery[filter.property] = { $eq: true };
  412. }
  413. if (specialQueries[filter.property]) {
  414. return specialQueries[filter.property](newQuery);
  415. }
  416. return newQuery;
  417. });
  418. if (queryError) next(queryError);
  419. const queryObject = {};
  420. if (newQueries.length > 0) {
  421. if (operator === "and") queryObject.$and = newQueries;
  422. else if (operator === "or") queryObject.$or = newQueries;
  423. else if (operator === "nor") queryObject.$nor = newQueries;
  424. }
  425. pipeline.push({ $match: queryObject });
  426. next(null, pipeline);
  427. },
  428. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  429. (pipeline, next) => {
  430. const { sort } = payload;
  431. const newSort = Object.fromEntries(
  432. Object.entries(sort).map(([property, direction]) => [
  433. property,
  434. direction === "ascending" ? 1 : -1
  435. ])
  436. );
  437. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  438. next(null, pipeline);
  439. },
  440. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  441. (pipeline, next) => {
  442. const { properties } = payload;
  443. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  444. next(null, pipeline);
  445. },
  446. // Adds second project stage to aggregation pipeline, responsible for excluding some specific properties
  447. (pipeline, next) => {
  448. const { blacklistedProperties } = payload;
  449. if (blacklistedProperties.length > 0)
  450. pipeline.push({
  451. $project: Object.fromEntries(blacklistedProperties.map(property => [property, 0]))
  452. });
  453. next(null, pipeline);
  454. },
  455. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  456. (pipeline, next) => {
  457. const { page, pageSize } = payload;
  458. pipeline.push({
  459. $facet: {
  460. count: [{ $count: "count" }],
  461. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  462. }
  463. });
  464. // console.dir(pipeline, { depth: 6 });
  465. next(null, pipeline);
  466. },
  467. (pipeline, next) => {
  468. const { modelName } = payload;
  469. DBModule.runJob("GET_MODEL", { modelName }, this)
  470. .then(model => {
  471. if (!model) return next("Invalid model.");
  472. return next(null, pipeline, model);
  473. })
  474. .catch(err => {
  475. next(err);
  476. });
  477. },
  478. // Executes the aggregation pipeline
  479. (pipeline, model, next) => {
  480. model.aggregate(pipeline).exec((err, result) => {
  481. // console.dir(err);
  482. // console.dir(result, { depth: 6 });
  483. if (err) return next(err);
  484. if (result[0].count.length === 0) return next(null, 0, []);
  485. const { count } = result[0].count[0];
  486. const { documents } = result[0];
  487. // console.log(111, err, result, count, documents[0]);
  488. return next(null, count, documents);
  489. });
  490. }
  491. ],
  492. (err, count, documents) => {
  493. if (err && err !== true) return reject(new Error(err));
  494. return resolve({ data: documents, count });
  495. }
  496. );
  497. });
  498. }
  499. /**
  500. * Checks if a password to be stored in the database has a valid length
  501. *
  502. * @param {object} password - the password itself
  503. * @returns {Promise} - returns promise (reject, resolve)
  504. */
  505. passwordValid(password) {
  506. return isLength(password, 6, 200);
  507. }
  508. }
  509. export default new _DBModule();