reports.js 17 KB

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