reports.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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: Number(data) };
  145. } else if (filterType === "numberLesser") {
  146. newQuery[filter.property] = { $lt: Number(data) };
  147. } else if (filterType === "numberGreater") {
  148. newQuery[filter.property] = { $gt: Number(data) };
  149. } else if (filterType === "numberGreaterEqual") {
  150. newQuery[filter.property] = { $gte: Number(data) };
  151. } else if (filterType === "numberEquals") {
  152. newQuery[filter.property] = { $eq: Number(data) };
  153. } else if (filterType === "boolean") {
  154. newQuery[filter.property] = { $eq: !!data };
  155. }
  156. if (filter.property === "createdBy")
  157. return { $or: [newQuery, { createdByUsername: newQuery.createdBy }] };
  158. return newQuery;
  159. });
  160. if (queryError) next(queryError);
  161. const queryObject = {};
  162. if (newQueries.length > 0) {
  163. if (operator === "and") queryObject.$and = newQueries;
  164. else if (operator === "or") queryObject.$or = newQueries;
  165. else if (operator === "nor") queryObject.$nor = newQueries;
  166. }
  167. pipeline.push({ $match: queryObject });
  168. next(null, pipeline);
  169. },
  170. // Adds sort stage to aggregation pipeline if there is at least one column being sorted, responsible for sorting data
  171. (pipeline, next) => {
  172. const newSort = Object.fromEntries(
  173. Object.entries(sort).map(([property, direction]) => [
  174. property,
  175. direction === "ascending" ? 1 : -1
  176. ])
  177. );
  178. if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
  179. next(null, pipeline);
  180. },
  181. // Adds first project stage to aggregation pipeline, responsible for including only the requested properties
  182. (pipeline, next) => {
  183. pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
  184. next(null, pipeline);
  185. },
  186. // Adds the facet stage to aggregation pipeline, responsible for returning a total document count, skipping and limitting the documents that will be returned
  187. (pipeline, next) => {
  188. pipeline.push({
  189. $facet: {
  190. count: [{ $count: "count" }],
  191. documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
  192. }
  193. });
  194. // console.dir(pipeline, { depth: 6 });
  195. next(null, pipeline);
  196. },
  197. // Executes the aggregation pipeline
  198. (pipeline, next) => {
  199. reportModel.aggregate(pipeline).exec((err, result) => {
  200. // console.dir(err);
  201. // console.dir(result, { depth: 6 });
  202. if (err) return next(err);
  203. if (result[0].count.length === 0) return next(null, 0, []);
  204. const { count } = result[0].count[0];
  205. const { documents } = result[0];
  206. // console.log(111, err, result, count, documents[0]);
  207. return next(null, count, documents);
  208. });
  209. }
  210. ],
  211. async (err, count, reports) => {
  212. if (err && err !== true) {
  213. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  214. this.log("ERROR", "REPORTS_GET_DATA", `Failed to get data from reports. "${err}"`);
  215. return cb({ status: "error", message: err });
  216. }
  217. this.log("SUCCESS", "REPORTS_GET_DATA", `Got data from reports successfully.`);
  218. return cb({
  219. status: "success",
  220. message: "Successfully got data from reports.",
  221. data: { data: reports, count }
  222. });
  223. }
  224. );
  225. }),
  226. /**
  227. * Gets a specific report
  228. *
  229. * @param {object} session - the session object automatically added by the websocket
  230. * @param {string} reportId - the id of the report to return
  231. * @param {Function} cb - gets called with the result
  232. */
  233. findOne: isAdminRequired(async function findOne(session, reportId, cb) {
  234. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  235. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  236. async.waterfall(
  237. [
  238. next => reportModel.findOne({ _id: reportId }).exec(next),
  239. (report, next) =>
  240. userModel
  241. .findById(report.createdBy)
  242. .select({ avatar: -1, name: -1, username: -1 })
  243. .exec((err, user) => {
  244. if (!user)
  245. next(err, {
  246. ...report._doc,
  247. createdBy: { _id: report.createdBy }
  248. });
  249. else
  250. next(err, {
  251. ...report._doc,
  252. createdBy: {
  253. avatar: user.avatar,
  254. name: user.name,
  255. username: user.username,
  256. _id: report.createdBy
  257. }
  258. });
  259. })
  260. ],
  261. async (err, report) => {
  262. if (err) {
  263. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  264. this.log("ERROR", "REPORTS_FIND_ONE", `Finding report "${reportId}" failed. "${err}"`);
  265. return cb({ status: "error", message: err });
  266. }
  267. this.log("SUCCESS", "REPORTS_FIND_ONE", `Finding report "${reportId}" successful.`);
  268. return cb({ status: "success", data: { report } });
  269. }
  270. );
  271. }),
  272. /**
  273. * Gets all reports for a songId
  274. *
  275. * @param {object} session - the session object automatically added by the websocket
  276. * @param {string} songId - the id of the song to index reports for
  277. * @param {Function} cb - gets called with the result
  278. */
  279. getReportsForSong: isAdminRequired(async function getReportsForSong(session, songId, cb) {
  280. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  281. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  282. async.waterfall(
  283. [
  284. next =>
  285. reportModel.find({ "song._id": songId, resolved: false }).sort({ createdAt: "desc" }).exec(next),
  286. (_reports, next) => {
  287. const reports = [];
  288. async.each(
  289. _reports,
  290. (report, cb) => {
  291. userModel
  292. .findById(report.createdBy)
  293. .select({ avatar: -1, name: -1, username: -1 })
  294. .exec((err, user) => {
  295. if (!user)
  296. reports.push({
  297. ...report._doc,
  298. createdBy: { _id: report.createdBy }
  299. });
  300. else
  301. reports.push({
  302. ...report._doc,
  303. createdBy: {
  304. avatar: user.avatar,
  305. name: user.name,
  306. username: user.username,
  307. _id: report.createdBy
  308. }
  309. });
  310. return cb(err);
  311. });
  312. },
  313. err => next(err, reports)
  314. );
  315. }
  316. ],
  317. async (err, reports) => {
  318. if (err) {
  319. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  320. this.log("ERROR", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" failed. "${err}"`);
  321. return cb({ status: "error", message: err });
  322. }
  323. this.log("SUCCESS", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" successful.`);
  324. return cb({ status: "success", data: { reports } });
  325. }
  326. );
  327. }),
  328. /**
  329. * Gets all a users reports for a specific songId
  330. *
  331. * @param {object} session - the session object automatically added by the websocket
  332. * @param {string} songId - the id of the song
  333. * @param {Function} cb - gets called with the result
  334. */
  335. myReportsForSong: isLoginRequired(async function myReportsForSong(session, songId, cb) {
  336. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  337. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  338. async.waterfall(
  339. [
  340. next =>
  341. reportModel
  342. .find({ "song._id": songId, createdBy: session.userId, resolved: false })
  343. .sort({ createdAt: "desc" })
  344. .exec(next),
  345. (_reports, next) => {
  346. const reports = [];
  347. async.each(
  348. _reports,
  349. (report, cb) => {
  350. userModel
  351. .findById(report.createdBy)
  352. .select({ avatar: -1, name: -1, username: -1 })
  353. .exec((err, user) => {
  354. if (!user)
  355. reports.push({
  356. ...report._doc,
  357. createdBy: { _id: report.createdBy }
  358. });
  359. else
  360. reports.push({
  361. ...report._doc,
  362. createdBy: {
  363. avatar: user.avatar,
  364. name: user.name,
  365. username: user.username,
  366. _id: report.createdBy
  367. }
  368. });
  369. return cb(err);
  370. });
  371. },
  372. err => next(err, reports)
  373. );
  374. }
  375. ],
  376. async (err, reports) => {
  377. if (err) {
  378. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  379. this.log(
  380. "ERROR",
  381. "MY_REPORTS_FOR_SONG",
  382. `Indexing reports of user ${session.userId} for song "${songId}" failed. "${err}"`
  383. );
  384. return cb({ status: "error", message: err });
  385. }
  386. this.log(
  387. "SUCCESS",
  388. "MY_REPORTS_FOR_SONG",
  389. `Indexing reports of user ${session.userId} for song "${songId}" successful.`
  390. );
  391. return cb({ status: "success", data: { reports } });
  392. }
  393. );
  394. }),
  395. /**
  396. * Resolves a report as a whole
  397. *
  398. * @param {object} session - the session object automatically added by the websocket
  399. * @param {string} reportId - the id of the report that is getting resolved
  400. * @param {Function} cb - gets called with the result
  401. */
  402. resolve: isAdminRequired(async function resolve(session, reportId, cb) {
  403. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  404. async.waterfall(
  405. [
  406. next => {
  407. reportModel.findById(reportId).exec(next);
  408. },
  409. (report, next) => {
  410. if (!report) return next("Report not found.");
  411. report.resolved = true;
  412. return report.save(err => {
  413. if (err) return next(err.message);
  414. return next(null, report.song._id);
  415. });
  416. }
  417. ],
  418. async (err, songId) => {
  419. if (err) {
  420. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  421. this.log(
  422. "ERROR",
  423. "REPORTS_RESOLVE",
  424. `Resolving report "${reportId}" failed by user "${session.userId}". "${err}"`
  425. );
  426. return cb({ status: "error", message: err });
  427. }
  428. CacheModule.runJob("PUB", {
  429. channel: "report.resolve",
  430. value: { reportId, songId }
  431. });
  432. this.log("SUCCESS", "REPORTS_RESOLVE", `User "${session.userId}" resolved report "${reportId}".`);
  433. return cb({
  434. status: "success",
  435. message: "Successfully resolved Report"
  436. });
  437. }
  438. );
  439. }),
  440. /**
  441. * Resolves/Unresolves an issue within a report
  442. *
  443. * @param {object} session - the session object automatically added by the websocket
  444. * @param {string} reportId - the id of the report that is getting resolved
  445. * @param {string} issueId - the id of the issue within the report
  446. * @param {Function} cb - gets called with the result
  447. */
  448. toggleIssue: isAdminRequired(async function toggleIssue(session, reportId, issueId, cb) {
  449. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  450. async.waterfall(
  451. [
  452. next => {
  453. reportModel.findById(reportId).exec(next);
  454. },
  455. (report, next) => {
  456. if (!report) return next("Report not found.");
  457. const issue = report.issues.find(issue => issue._id.toString() === issueId);
  458. issue.resolved = !issue.resolved;
  459. return report.save(err => {
  460. if (err) return next(err.message);
  461. return next(null, issue.resolved, report.song._id);
  462. });
  463. }
  464. ],
  465. async (err, resolved, songId) => {
  466. if (err) {
  467. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  468. this.log(
  469. "ERROR",
  470. "REPORTS_TOGGLE_ISSUE",
  471. `Resolving an issue within report "${reportId}" failed by user "${session.userId}". "${err}"`
  472. );
  473. return cb({ status: "error", message: err });
  474. }
  475. CacheModule.runJob("PUB", {
  476. channel: "report.issue.toggle",
  477. value: { reportId, issueId, songId, resolved }
  478. });
  479. this.log(
  480. "SUCCESS",
  481. "REPORTS_TOGGLE_ISSUE",
  482. `User "${session.userId}" resolved an issue in report "${reportId}".`
  483. );
  484. return cb({
  485. status: "success",
  486. message: "Successfully resolved issue within report"
  487. });
  488. }
  489. );
  490. }),
  491. /**
  492. * Creates a new report
  493. *
  494. * @param {object} session - the session object automatically added by the websocket
  495. * @param {object} report - the object of the report data
  496. * @param {string} report.youtubeId - the youtube id of the song that is being reported
  497. * @param {Array} report.issues - all issues reported (custom or defined)
  498. * @param {Function} cb - gets called with the result
  499. */
  500. create: isLoginRequired(async function create(session, report, cb) {
  501. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  502. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  503. const { youtubeId } = report;
  504. async.waterfall(
  505. [
  506. next => songModel.findOne({ youtubeId }).exec(next),
  507. (song, next) => {
  508. if (!song) return next("Song not found.");
  509. return SongsModule.runJob("GET_SONG", { songId: song._id }, this)
  510. .then(res => next(null, res.song))
  511. .catch(next);
  512. },
  513. (song, next) => {
  514. if (!song) return next("Song not found.");
  515. delete report.youtubeId;
  516. report.song = {
  517. _id: song._id,
  518. youtubeId: song.youtubeId
  519. };
  520. return next(null, { title: song.title, artists: song.artists, thumbnail: song.thumbnail });
  521. },
  522. (song, next) =>
  523. reportModel.create(
  524. {
  525. createdBy: session.userId,
  526. createdAt: Date.now(),
  527. ...report
  528. },
  529. (err, report) => next(err, report, song)
  530. )
  531. ],
  532. async (err, report, song) => {
  533. if (err) {
  534. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  535. this.log(
  536. "ERROR",
  537. "REPORTS_CREATE",
  538. `Creating report for "${report.song._id}" failed by user "${session.userId}". "${err}"`
  539. );
  540. return cb({ status: "error", message: err });
  541. }
  542. ActivitiesModule.runJob("ADD_ACTIVITY", {
  543. userId: session.userId,
  544. type: "song__report",
  545. payload: {
  546. message: `Created a <reportId>${report._id}</reportId> for song <youtubeId>${song.title}</youtubeId>`,
  547. youtubeId: report.song.youtubeId,
  548. reportId: report._id,
  549. thumbnail: song.thumbnail
  550. }
  551. });
  552. CacheModule.runJob("PUB", {
  553. channel: "report.create",
  554. value: report
  555. });
  556. this.log("SUCCESS", "REPORTS_CREATE", `User "${session.userId}" created report for "${youtubeId}".`);
  557. return cb({
  558. status: "success",
  559. message: "Successfully created report"
  560. });
  561. }
  562. );
  563. })
  564. };