reports.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. import async from "async";
  2. import { isAdminRequired, isLoginRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const WSModule = moduleManager.modules.ws;
  7. const SongsModule = moduleManager.modules.songs;
  8. const CacheModule = moduleManager.modules.cache;
  9. const ActivitiesModule = moduleManager.modules.activities;
  10. CacheModule.runJob("SUB", {
  11. channel: "report.issue.toggle",
  12. cb: data =>
  13. WSModule.runJob("EMIT_TO_ROOMS", {
  14. rooms: [`edit-song.${data.songId}`, `view-report.${data.reportId}`],
  15. args: [
  16. "event:admin.report.issue.toggled",
  17. { data: { issueId: data.issueId, reportId: data.reportId, resolved: data.resolved } }
  18. ]
  19. })
  20. });
  21. CacheModule.runJob("SUB", {
  22. channel: "report.resolve",
  23. cb: ({ reportId, songId }) =>
  24. WSModule.runJob("EMIT_TO_ROOMS", {
  25. rooms: ["admin.reports", `edit-song.${songId}`, `view-report.${reportId}`],
  26. args: ["event:admin.report.resolved", { data: { reportId } }]
  27. })
  28. });
  29. CacheModule.runJob("SUB", {
  30. channel: "report.create",
  31. cb: report => {
  32. console.log(report);
  33. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  34. userModel
  35. .findById(report.createdBy)
  36. .select({ avatar: -1, name: -1, username: -1 })
  37. .exec((err, { avatar, name, username }) => {
  38. report.createdBy = {
  39. avatar,
  40. name,
  41. username,
  42. _id: report.createdBy
  43. };
  44. WSModule.runJob("EMIT_TO_ROOMS", {
  45. rooms: ["admin.reports", `edit-song.${report.song._id}`],
  46. args: ["event:admin.report.created", { data: { report } }]
  47. });
  48. });
  49. });
  50. }
  51. });
  52. export default {
  53. /**
  54. * Gets reports, used in the admin reports page by the AdvancedTable component
  55. *
  56. * @param {object} session - the session object automatically added by the websocket
  57. * @param page - the page
  58. * @param pageSize - the size per page
  59. * @param properties - the properties to return for each user
  60. * @param sort - the sort object
  61. * @param queries - the queries array
  62. * @param operator - the operator for queries
  63. * @param cb
  64. */
  65. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  66. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  67. async.waterfall(
  68. [
  69. // Creates pipeline array
  70. next => next(null, []),
  71. // If a filter exists for createdBy, add createdByUsername property to all documents
  72. (pipeline, next) => {
  73. // Check if a filter with the createdBy property exists
  74. const createdByFilterExists =
  75. queries.map(query => query.filter.property).indexOf("createdBy") !== -1;
  76. // If no such filter exists, skip this function
  77. if (!createdByFilterExists) return next(null, pipeline);
  78. // Adds createdByOID field, which is an ObjectId version of createdBy
  79. pipeline.push({
  80. $addFields: {
  81. createdByOID: {
  82. $convert: {
  83. input: "$createdBy",
  84. to: "objectId",
  85. onError: "unknown",
  86. onNull: "unknown"
  87. }
  88. }
  89. }
  90. });
  91. // Looks up user(s) with the same _id as the createdByOID and puts the result in the createdByUser field
  92. pipeline.push({
  93. $lookup: {
  94. from: "users",
  95. localField: "createdByOID",
  96. foreignField: "_id",
  97. as: "createdByUser"
  98. }
  99. });
  100. // Unwinds the createdByUser array field into an object
  101. pipeline.push({
  102. $unwind: {
  103. path: "$createdByUser",
  104. preserveNullAndEmptyArrays: true
  105. }
  106. });
  107. // Adds createdByUsername field from the createdByUser username, or unknown if it doesn't exist
  108. pipeline.push({
  109. $addFields: {
  110. createdByUsername: {
  111. $ifNull: ["$createdByUser.username", "unknown"]
  112. }
  113. }
  114. });
  115. // Removes the createdByOID and createdByUser property, just in case it doesn't get removed at a later stage
  116. pipeline.push({
  117. $project: {
  118. createdByOID: 0,
  119. createdByUser: 0
  120. }
  121. });
  122. return next(null, pipeline);
  123. },
  124. // Adds the match stage to aggregation pipeline, which is responsible for filtering
  125. (pipeline, next) => {
  126. let queryError;
  127. const newQueries = queries.flatMap(query => {
  128. const { data, filter, filterType } = query;
  129. const newQuery = {};
  130. if (filterType === "regex") {
  131. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  132. } else if (filterType === "contains") {
  133. newQuery[filter.property] = new RegExp(
  134. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  135. "i"
  136. );
  137. } else if (filterType === "exact") {
  138. newQuery[filter.property] = data.toString();
  139. } else if (filterType === "datetimeBefore") {
  140. newQuery[filter.property] = { $lte: new Date(data) };
  141. } else if (filterType === "datetimeAfter") {
  142. newQuery[filter.property] = { $gte: new Date(data) };
  143. } else if (filterType === "numberLesserEqual") {
  144. newQuery[filter.property] = { $lte: data };
  145. } else if (filterType === "numberLesser") {
  146. newQuery[filter.property] = { $lt: data };
  147. } else if (filterType === "numberGreater") {
  148. newQuery[filter.property] = { $gt: data };
  149. } else if (filterType === "numberGreaterEqual") {
  150. newQuery[filter.property] = { $gte: data };
  151. } else if (filterType === "numberEquals" || filterType === "boolean") {
  152. newQuery[filter.property] = { $eq: data };
  153. }
  154. if (filter.property === "createdBy")
  155. return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
  156. return newQuery;
  157. });
  158. if (queryError) next(queryError);
  159. const queryObject = {};
  160. if (newQueries.length > 0) {
  161. if (operator === "and") queryObject.$and = newQueries;
  162. else if (operator === "or") queryObject.$or = newQueries;
  163. else if (operator === "nor") queryObject.$nor = newQueries;
  164. }
  165. pipeline.push({ $match: queryObject });
  166. next(null, pipeline);
  167. },
  168. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  169. (pipeline, next) => {
  170. const newSort = Object.fromEntries(
  171. Object.entries(sort).map(([property, direction]) => [
  172. property,
  173. direction === "ascending" ? 1 : -1
  174. ])
  175. );
  176. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  177. next(null, pipeline);
  178. },
  179. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  180. (pipeline, next) => {
  181. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  182. next(null, pipeline);
  183. },
  184. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  185. (pipeline, next) => {
  186. pipeline.push({
  187. $facet: {
  188. count: [{ $count: "count" }],
  189. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  190. }
  191. });
  192. // console.dir(pipeline, { depth: 6 });
  193. next(null, pipeline);
  194. },
  195. // Executes the aggregation pipeline
  196. (pipeline, next) => {
  197. reportModel.aggregate(pipeline).exec((err, result) => {
  198. // console.dir(err);
  199. // console.dir(result, { depth: 6 });
  200. if (err) return next(err);
  201. if (result[0].count.length === 0) return next(null, 0, []);
  202. const { count } = result[0].count[0];
  203. const { documents } = result[0];
  204. // console.log(111, err, result, count, documents[0]);
  205. return next(null, count, documents);
  206. });
  207. }
  208. ],
  209. async (err, count, reports) => {
  210. if (err && err !== true) {
  211. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  212. this.log("ERROR", "REPORTS_GET_DATA", `Failed to get data from reports. "${err}"`);
  213. return cb({ status: "error", message: err });
  214. }
  215. this.log("SUCCESS", "REPORTS_GET_DATA", `Got data from reports successfully.`);
  216. return cb({
  217. status: "success",
  218. message: "Successfully got data from reports.",
  219. data: { data: reports, count }
  220. });
  221. }
  222. );
  223. }),
  224. /**
  225. * Gets a specific report
  226. *
  227. * @param {object} session - the session object automatically added by the websocket
  228. * @param {string} reportId - the id of the report to return
  229. * @param {Function} cb - gets called with the result
  230. */
  231. findOne: isAdminRequired(async function findOne(session, reportId, cb) {
  232. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  233. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  234. async.waterfall(
  235. [
  236. next => reportModel.findOne({ _id: reportId }).exec(next),
  237. (report, next) =>
  238. userModel
  239. .findById(report.createdBy)
  240. .select({ avatar: -1, name: -1, username: -1 })
  241. .exec((err, user) => {
  242. if (!user)
  243. next(err, {
  244. ...report._doc,
  245. createdBy: { _id: report.createdBy }
  246. });
  247. else
  248. next(err, {
  249. ...report._doc,
  250. createdBy: {
  251. avatar: user.avatar,
  252. name: user.name,
  253. username: user.username,
  254. _id: report.createdBy
  255. }
  256. });
  257. })
  258. ],
  259. async (err, report) => {
  260. if (err) {
  261. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  262. this.log("ERROR", "REPORTS_FIND_ONE", `Finding report "${reportId}" failed. "${err}"`);
  263. return cb({ status: "error", message: err });
  264. }
  265. this.log("SUCCESS", "REPORTS_FIND_ONE", `Finding report "${reportId}" successful.`);
  266. return cb({ status: "success", data: { report } });
  267. }
  268. );
  269. }),
  270. /**
  271. * Gets all reports for a songId
  272. *
  273. * @param {object} session - the session object automatically added by the websocket
  274. * @param {string} songId - the id of the song to index reports for
  275. * @param {Function} cb - gets called with the result
  276. */
  277. getReportsForSong: isAdminRequired(async function getReportsForSong(session, songId, cb) {
  278. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  279. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  280. async.waterfall(
  281. [
  282. next =>
  283. reportModel.find({ "song._id": songId, resolved: false }).sort({ createdAt: "desc" }).exec(next),
  284. (_reports, next) => {
  285. const reports = [];
  286. async.each(
  287. _reports,
  288. (report, cb) => {
  289. userModel
  290. .findById(report.createdBy)
  291. .select({ avatar: -1, name: -1, username: -1 })
  292. .exec((err, user) => {
  293. if (!user)
  294. reports.push({
  295. ...report._doc,
  296. createdBy: { _id: report.createdBy }
  297. });
  298. else
  299. reports.push({
  300. ...report._doc,
  301. createdBy: {
  302. avatar: user.avatar,
  303. name: user.name,
  304. username: user.username,
  305. _id: report.createdBy
  306. }
  307. });
  308. return cb(err);
  309. });
  310. },
  311. err => next(err, reports)
  312. );
  313. }
  314. ],
  315. async (err, reports) => {
  316. if (err) {
  317. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  318. this.log("ERROR", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" failed. "${err}"`);
  319. return cb({ status: "error", message: err });
  320. }
  321. this.log("SUCCESS", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" successful.`);
  322. return cb({ status: "success", data: { reports } });
  323. }
  324. );
  325. }),
  326. /**
  327. * Gets all a users reports for a specific songId
  328. *
  329. * @param {object} session - the session object automatically added by the websocket
  330. * @param {string} songId - the id of the song
  331. * @param {Function} cb - gets called with the result
  332. */
  333. myReportsForSong: isLoginRequired(async function myReportsForSong(session, songId, cb) {
  334. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  335. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  336. async.waterfall(
  337. [
  338. next =>
  339. reportModel
  340. .find({ "song._id": songId, createdBy: session.userId, resolved: false })
  341. .sort({ createdAt: "desc" })
  342. .exec(next),
  343. (_reports, next) => {
  344. const reports = [];
  345. async.each(
  346. _reports,
  347. (report, cb) => {
  348. userModel
  349. .findById(report.createdBy)
  350. .select({ avatar: -1, name: -1, username: -1 })
  351. .exec((err, user) => {
  352. if (!user)
  353. reports.push({
  354. ...report._doc,
  355. createdBy: { _id: report.createdBy }
  356. });
  357. else
  358. reports.push({
  359. ...report._doc,
  360. createdBy: {
  361. avatar: user.avatar,
  362. name: user.name,
  363. username: user.username,
  364. _id: report.createdBy
  365. }
  366. });
  367. return cb(err);
  368. });
  369. },
  370. err => next(err, reports)
  371. );
  372. }
  373. ],
  374. async (err, reports) => {
  375. if (err) {
  376. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  377. this.log(
  378. "ERROR",
  379. "MY_REPORTS_FOR_SONG",
  380. `Indexing reports of user ${session.userId} for song "${songId}" failed. "${err}"`
  381. );
  382. return cb({ status: "error", message: err });
  383. }
  384. this.log(
  385. "SUCCESS",
  386. "MY_REPORTS_FOR_SONG",
  387. `Indexing reports of user ${session.userId} for song "${songId}" successful.`
  388. );
  389. return cb({ status: "success", data: { reports } });
  390. }
  391. );
  392. }),
  393. /**
  394. * Resolves a report as a whole
  395. *
  396. * @param {object} session - the session object automatically added by the websocket
  397. * @param {string} reportId - the id of the report that is getting resolved
  398. * @param {Function} cb - gets called with the result
  399. */
  400. resolve: isAdminRequired(async function resolve(session, reportId, cb) {
  401. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  402. async.waterfall(
  403. [
  404. next => {
  405. reportModel.findById(reportId).exec(next);
  406. },
  407. (report, next) => {
  408. if (!report) return next("Report not found.");
  409. report.resolved = true;
  410. return report.save(err => {
  411. if (err) return next(err.message);
  412. return next(null, report.song._id);
  413. });
  414. }
  415. ],
  416. async (err, songId) => {
  417. if (err) {
  418. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  419. this.log(
  420. "ERROR",
  421. "REPORTS_RESOLVE",
  422. `Resolving report "${reportId}" failed by user "${session.userId}". "${err}"`
  423. );
  424. return cb({ status: "error", message: err });
  425. }
  426. CacheModule.runJob("PUB", {
  427. channel: "report.resolve",
  428. value: { reportId, songId }
  429. });
  430. this.log("SUCCESS", "REPORTS_RESOLVE", `User "${session.userId}" resolved report "${reportId}".`);
  431. return cb({
  432. status: "success",
  433. message: "Successfully resolved Report"
  434. });
  435. }
  436. );
  437. }),
  438. /**
  439. * Resolves/Unresolves an issue within a report
  440. *
  441. * @param {object} session - the session object automatically added by the websocket
  442. * @param {string} reportId - the id of the report that is getting resolved
  443. * @param {string} issueId - the id of the issue within the report
  444. * @param {Function} cb - gets called with the result
  445. */
  446. toggleIssue: isAdminRequired(async function toggleIssue(session, reportId, issueId, cb) {
  447. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  448. async.waterfall(
  449. [
  450. next => {
  451. reportModel.findById(reportId).exec(next);
  452. },
  453. (report, next) => {
  454. if (!report) return next("Report not found.");
  455. const issue = report.issues.find(issue => issue._id.toString() === issueId);
  456. issue.resolved = !issue.resolved;
  457. return report.save(err => {
  458. if (err) return next(err.message);
  459. return next(null, issue.resolved, report.song._id);
  460. });
  461. }
  462. ],
  463. async (err, resolved, songId) => {
  464. if (err) {
  465. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  466. this.log(
  467. "ERROR",
  468. "REPORTS_TOGGLE_ISSUE",
  469. `Resolving an issue within report "${reportId}" failed by user "${session.userId}". "${err}"`
  470. );
  471. return cb({ status: "error", message: err });
  472. }
  473. CacheModule.runJob("PUB", {
  474. channel: "report.issue.toggle",
  475. value: { reportId, issueId, songId, resolved }
  476. });
  477. this.log(
  478. "SUCCESS",
  479. "REPORTS_TOGGLE_ISSUE",
  480. `User "${session.userId}" resolved an issue in report "${reportId}".`
  481. );
  482. return cb({
  483. status: "success",
  484. message: "Successfully resolved issue within report"
  485. });
  486. }
  487. );
  488. }),
  489. /**
  490. * Creates a new report
  491. *
  492. * @param {object} session - the session object automatically added by the websocket
  493. * @param {object} report - the object of the report data
  494. * @param {string} report.youtubeId - the youtube id of the song that is being reported
  495. * @param {Array} report.issues - all issues reported (custom or defined)
  496. * @param {Function} cb - gets called with the result
  497. */
  498. create: isLoginRequired(async function create(session, report, cb) {
  499. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  500. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  501. const { youtubeId } = report;
  502. async.waterfall(
  503. [
  504. next => songModel.findOne({ youtubeId }).exec(next),
  505. (song, next) => {
  506. if (!song) return next("Song not found.");
  507. return SongsModule.runJob("GET_SONG", { songId: song._id }, this)
  508. .then(res => next(null, res.song))
  509. .catch(next);
  510. },
  511. (song, next) => {
  512. if (!song) return next("Song not found.");
  513. delete report.youtubeId;
  514. report.song = {
  515. _id: song._id,
  516. youtubeId: song.youtubeId
  517. };
  518. return next(null, { title: song.title, artists: song.artists, thumbnail: song.thumbnail });
  519. },
  520. (song, next) =>
  521. reportModel.create(
  522. {
  523. createdBy: session.userId,
  524. createdAt: Date.now(),
  525. ...report
  526. },
  527. (err, report) => next(err, report, song)
  528. )
  529. ],
  530. async (err, report, song) => {
  531. if (err) {
  532. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  533. this.log(
  534. "ERROR",
  535. "REPORTS_CREATE",
  536. `Creating report for "${report.song._id}" failed by user "${session.userId}". "${err}"`
  537. );
  538. return cb({ status: "error", message: err });
  539. }
  540. ActivitiesModule.runJob("ADD_ACTIVITY", {
  541. userId: session.userId,
  542. type: "song__report",
  543. payload: {
  544. message: `Created a <reportId>${report._id}</reportId> for song <youtubeId>${song.title}</youtubeId>`,
  545. youtubeId: report.song.youtubeId,
  546. reportId: report._id,
  547. thumbnail: song.thumbnail
  548. }
  549. });
  550. CacheModule.runJob("PUB", {
  551. channel: "report.create",
  552. value: report
  553. });
  554. this.log("SUCCESS", "REPORTS_CREATE", `User "${session.userId}" created report for "${youtubeId}".`);
  555. return cb({
  556. status: "success",
  557. message: "Successfully created report"
  558. });
  559. }
  560. );
  561. })
  562. };