reports.js 17 KB

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