reports.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. * @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: useHasPermission(
  90. "admin.view.reports",
  91. async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  92. async.waterfall(
  93. [
  94. next => {
  95. DBModule.runJob(
  96. "GET_DATA",
  97. {
  98. page,
  99. pageSize,
  100. properties,
  101. sort,
  102. queries,
  103. operator,
  104. modelName: "report",
  105. blacklistedProperties: [],
  106. specialProperties: {
  107. createdBy: [
  108. {
  109. $addFields: {
  110. createdByOID: {
  111. $convert: {
  112. input: "$createdBy",
  113. to: "objectId",
  114. onError: "unknown",
  115. onNull: "unknown"
  116. }
  117. }
  118. }
  119. },
  120. {
  121. $lookup: {
  122. from: "users",
  123. localField: "createdByOID",
  124. foreignField: "_id",
  125. as: "createdByUser"
  126. }
  127. },
  128. {
  129. $unwind: {
  130. path: "$createdByUser",
  131. preserveNullAndEmptyArrays: true
  132. }
  133. },
  134. {
  135. $addFields: {
  136. createdByUsername: {
  137. $ifNull: ["$createdByUser.username", "unknown"]
  138. }
  139. }
  140. },
  141. {
  142. $project: {
  143. createdByOID: 0,
  144. createdByUser: 0
  145. }
  146. }
  147. ]
  148. },
  149. specialQueries: {
  150. createdBy: newQuery => ({
  151. $or: [newQuery, { createdByUsername: newQuery.createdBy }]
  152. })
  153. }
  154. },
  155. this
  156. )
  157. .then(response => {
  158. next(null, response);
  159. })
  160. .catch(err => {
  161. next(err);
  162. });
  163. }
  164. ],
  165. async (err, response) => {
  166. if (err && err !== true) {
  167. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  168. this.log("ERROR", "REPORTS_GET_DATA", `Failed to get data from reports. "${err}"`);
  169. return cb({ status: "error", message: err });
  170. }
  171. this.log("SUCCESS", "REPORTS_GET_DATA", `Got data from reports successfully.`);
  172. return cb({
  173. status: "success",
  174. message: "Successfully got data from reports.",
  175. data: response
  176. });
  177. }
  178. );
  179. }
  180. ),
  181. /**
  182. * Gets a specific report
  183. * @param {object} session - the session object automatically added by the websocket
  184. * @param {string} reportId - the id of the report to return
  185. * @param {Function} cb - gets called with the result
  186. */
  187. findOne: useHasPermission("reports.get", async function findOne(session, reportId, cb) {
  188. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  189. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  190. async.waterfall(
  191. [
  192. next => reportModel.findOne({ _id: reportId }).exec(next),
  193. (report, next) =>
  194. userModel
  195. .findById(report.createdBy)
  196. .select({ avatar: -1, name: -1, username: -1 })
  197. .exec((err, user) => {
  198. if (!user)
  199. next(err, {
  200. ...report._doc,
  201. createdBy: { _id: report.createdBy }
  202. });
  203. else
  204. next(err, {
  205. ...report._doc,
  206. createdBy: {
  207. avatar: user.avatar,
  208. name: user.name,
  209. username: user.username,
  210. _id: report.createdBy
  211. }
  212. });
  213. })
  214. ],
  215. async (err, report) => {
  216. if (err) {
  217. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  218. this.log("ERROR", "REPORTS_FIND_ONE", `Finding report "${reportId}" failed. "${err}"`);
  219. return cb({ status: "error", message: err });
  220. }
  221. this.log("SUCCESS", "REPORTS_FIND_ONE", `Finding report "${reportId}" successful.`);
  222. return cb({ status: "success", data: { report } });
  223. }
  224. );
  225. }),
  226. /**
  227. * Gets all reports for a songId
  228. * @param {object} session - the session object automatically added by the websocket
  229. * @param {string} songId - the id of the song to index reports for
  230. * @param {Function} cb - gets called with the result
  231. */
  232. getReportsForSong: useHasPermission("reports.get", async function getReportsForSong(session, songId, cb) {
  233. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  234. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  235. async.waterfall(
  236. [
  237. next =>
  238. reportModel.find({ "song._id": songId, resolved: false }).sort({ createdAt: "desc" }).exec(next),
  239. (_reports, next) => {
  240. const reports = [];
  241. async.each(
  242. _reports,
  243. (report, cb) => {
  244. userModel
  245. .findById(report.createdBy)
  246. .select({ avatar: -1, name: -1, username: -1 })
  247. .exec((err, user) => {
  248. if (!user)
  249. reports.push({
  250. ...report._doc,
  251. createdBy: { _id: report.createdBy }
  252. });
  253. else
  254. reports.push({
  255. ...report._doc,
  256. createdBy: {
  257. avatar: user.avatar,
  258. name: user.name,
  259. username: user.username,
  260. _id: report.createdBy
  261. }
  262. });
  263. return cb(err);
  264. });
  265. },
  266. err => next(err, reports)
  267. );
  268. }
  269. ],
  270. async (err, reports) => {
  271. if (err) {
  272. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  273. this.log("ERROR", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" failed. "${err}"`);
  274. return cb({ status: "error", message: err });
  275. }
  276. this.log("SUCCESS", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" successful.`);
  277. return cb({ status: "success", data: { reports } });
  278. }
  279. );
  280. }),
  281. /**
  282. * Gets all a users reports for a specific songId
  283. * @param {object} session - the session object automatically added by the websocket
  284. * @param {string} songId - the id of the song
  285. * @param {Function} cb - gets called with the result
  286. */
  287. myReportsForSong: isLoginRequired(async function myReportsForSong(session, songId, cb) {
  288. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  289. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  290. async.waterfall(
  291. [
  292. next =>
  293. reportModel
  294. .find({ "song._id": songId, createdBy: session.userId, resolved: false })
  295. .sort({ createdAt: "desc" })
  296. .exec(next),
  297. (_reports, next) => {
  298. const reports = [];
  299. async.each(
  300. _reports,
  301. (report, cb) => {
  302. userModel
  303. .findById(report.createdBy)
  304. .select({ avatar: -1, name: -1, username: -1 })
  305. .exec((err, user) => {
  306. if (!user)
  307. reports.push({
  308. ...report._doc,
  309. createdBy: { _id: report.createdBy }
  310. });
  311. else
  312. reports.push({
  313. ...report._doc,
  314. createdBy: {
  315. avatar: user.avatar,
  316. name: user.name,
  317. username: user.username,
  318. _id: report.createdBy
  319. }
  320. });
  321. return cb(err);
  322. });
  323. },
  324. err => next(err, reports)
  325. );
  326. }
  327. ],
  328. async (err, reports) => {
  329. if (err) {
  330. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  331. this.log(
  332. "ERROR",
  333. "MY_REPORTS_FOR_SONG",
  334. `Indexing reports of user ${session.userId} for song "${songId}" failed. "${err}"`
  335. );
  336. return cb({ status: "error", message: err });
  337. }
  338. this.log(
  339. "SUCCESS",
  340. "MY_REPORTS_FOR_SONG",
  341. `Indexing reports of user ${session.userId} for song "${songId}" successful.`
  342. );
  343. return cb({ status: "success", data: { reports } });
  344. }
  345. );
  346. }),
  347. /**
  348. * Resolves a report as a whole
  349. * @param {object} session - the session object automatically added by the websocket
  350. * @param {string} reportId - the id of the report that is getting resolved
  351. * @param {boolean} resolved - whether to set to resolved to true or false
  352. * @param {Function} cb - gets called with the result
  353. */
  354. resolve: useHasPermission("reports.update", async function resolve(session, reportId, resolved, cb) {
  355. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  356. async.waterfall(
  357. [
  358. next => {
  359. reportModel.findById(reportId).exec(next);
  360. },
  361. (report, next) => {
  362. if (!report) return next("Report not found.");
  363. report.resolved = resolved;
  364. return report.save(err => {
  365. if (err) return next(err.message);
  366. return next(null, report.song._id);
  367. });
  368. }
  369. ],
  370. async (err, songId) => {
  371. if (err) {
  372. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  373. this.log(
  374. "ERROR",
  375. "REPORTS_RESOLVE",
  376. `${resolved ? "R" : "Unr"}esolving report "${reportId}" failed by user "${
  377. session.userId
  378. }". "${err}"`
  379. );
  380. return cb({ status: "error", message: err });
  381. }
  382. CacheModule.runJob("PUB", {
  383. channel: "report.resolve",
  384. value: { reportId, songId, resolved }
  385. });
  386. CacheModule.runJob("PUB", {
  387. channel: "report.update",
  388. value: { reportId }
  389. });
  390. this.log(
  391. "SUCCESS",
  392. "REPORTS_RESOLVE",
  393. `User "${session.userId}" ${resolved ? "" : "un"}resolved report "${reportId}".`
  394. );
  395. return cb({
  396. status: "success",
  397. message: `Successfully ${resolved ? "" : "un"}resolved Report`
  398. });
  399. }
  400. );
  401. }),
  402. /**
  403. * Resolves/Unresolves an issue within a report
  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: useHasPermission("reports.update", 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. * @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.mediaSource - the media source 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 { mediaSource } = report;
  468. async.waterfall(
  469. [
  470. next => songModel.findOne({ mediaSource }).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.mediaSource;
  480. report.song = {
  481. _id: song._id,
  482. mediaSource: song.mediaSource
  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 <mediaSource>${song.title}</mediaSource>`,
  511. mediaSource: report.song.mediaSource,
  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 "${mediaSource}".`);
  521. return cb({
  522. status: "success",
  523. message: "Successfully created report"
  524. });
  525. }
  526. );
  527. }),
  528. /**
  529. * Removes a report
  530. * @param {object} session - the session object automatically added by the websocket
  531. * @param {object} reportId - the id of the report item we want to remove
  532. * @param {Function} cb - gets called with the result
  533. */
  534. remove: useHasPermission("reports.remove", async function remove(session, reportId, cb) {
  535. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  536. async.waterfall(
  537. [
  538. next => {
  539. if (!reportId) return next("Please provide a report item id to remove.");
  540. return next();
  541. },
  542. next => {
  543. reportModel.deleteOne({ _id: reportId }, err => next(err));
  544. }
  545. ],
  546. async err => {
  547. if (err) {
  548. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  549. this.log(
  550. "ERROR",
  551. "REPORT_REMOVE",
  552. `Removing report "${reportId}" failed for user "${session.userId}". "${err}"`
  553. );
  554. return cb({ status: "error", message: err });
  555. }
  556. CacheModule.runJob("PUB", { channel: "report.remove", value: reportId });
  557. this.log(
  558. "SUCCESS",
  559. "REPORT_REMOVE",
  560. `Removing report "${reportId}" successful by user "${session.userId}".`
  561. );
  562. return cb({
  563. status: "success",
  564. message: "Successfully removed report"
  565. });
  566. }
  567. );
  568. })
  569. };