reports.js 17 KB

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