index.js 18 KB

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