reports.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. "reports.getData",
  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.findOne", 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(
  236. "reports.getReportsForSong",
  237. async function getReportsForSong(session, songId, cb) {
  238. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  239. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  240. async.waterfall(
  241. [
  242. next =>
  243. reportModel
  244. .find({ "song._id": songId, resolved: false })
  245. .sort({ createdAt: "desc" })
  246. .exec(next),
  247. (_reports, next) => {
  248. const reports = [];
  249. async.each(
  250. _reports,
  251. (report, cb) => {
  252. userModel
  253. .findById(report.createdBy)
  254. .select({ avatar: -1, name: -1, username: -1 })
  255. .exec((err, user) => {
  256. if (!user)
  257. reports.push({
  258. ...report._doc,
  259. createdBy: { _id: report.createdBy }
  260. });
  261. else
  262. reports.push({
  263. ...report._doc,
  264. createdBy: {
  265. avatar: user.avatar,
  266. name: user.name,
  267. username: user.username,
  268. _id: report.createdBy
  269. }
  270. });
  271. return cb(err);
  272. });
  273. },
  274. err => next(err, reports)
  275. );
  276. }
  277. ],
  278. async (err, reports) => {
  279. if (err) {
  280. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  281. this.log(
  282. "ERROR",
  283. "GET_REPORTS_FOR_SONG",
  284. `Indexing reports for song "${songId}" failed. "${err}"`
  285. );
  286. return cb({ status: "error", message: err });
  287. }
  288. this.log("SUCCESS", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" successful.`);
  289. return cb({ status: "success", data: { reports } });
  290. }
  291. );
  292. }
  293. ),
  294. /**
  295. * Gets all a users reports for a specific songId
  296. *
  297. * @param {object} session - the session object automatically added by the websocket
  298. * @param {string} songId - the id of the song
  299. * @param {Function} cb - gets called with the result
  300. */
  301. myReportsForSong: isLoginRequired(async function myReportsForSong(session, songId, cb) {
  302. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  303. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  304. async.waterfall(
  305. [
  306. next =>
  307. reportModel
  308. .find({ "song._id": songId, createdBy: session.userId, resolved: false })
  309. .sort({ createdAt: "desc" })
  310. .exec(next),
  311. (_reports, next) => {
  312. const reports = [];
  313. async.each(
  314. _reports,
  315. (report, cb) => {
  316. userModel
  317. .findById(report.createdBy)
  318. .select({ avatar: -1, name: -1, username: -1 })
  319. .exec((err, user) => {
  320. if (!user)
  321. reports.push({
  322. ...report._doc,
  323. createdBy: { _id: report.createdBy }
  324. });
  325. else
  326. reports.push({
  327. ...report._doc,
  328. createdBy: {
  329. avatar: user.avatar,
  330. name: user.name,
  331. username: user.username,
  332. _id: report.createdBy
  333. }
  334. });
  335. return cb(err);
  336. });
  337. },
  338. err => next(err, reports)
  339. );
  340. }
  341. ],
  342. async (err, reports) => {
  343. if (err) {
  344. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  345. this.log(
  346. "ERROR",
  347. "MY_REPORTS_FOR_SONG",
  348. `Indexing reports of user ${session.userId} for song "${songId}" failed. "${err}"`
  349. );
  350. return cb({ status: "error", message: err });
  351. }
  352. this.log(
  353. "SUCCESS",
  354. "MY_REPORTS_FOR_SONG",
  355. `Indexing reports of user ${session.userId} for song "${songId}" successful.`
  356. );
  357. return cb({ status: "success", data: { reports } });
  358. }
  359. );
  360. }),
  361. /**
  362. * Resolves a report as a whole
  363. *
  364. * @param {object} session - the session object automatically added by the websocket
  365. * @param {string} reportId - the id of the report that is getting resolved
  366. * @param {boolean} resolved - whether to set to resolved to true or false
  367. * @param {Function} cb - gets called with the result
  368. */
  369. resolve: useHasPermission("reports.resolve", async function resolve(session, reportId, resolved, cb) {
  370. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  371. async.waterfall(
  372. [
  373. next => {
  374. reportModel.findById(reportId).exec(next);
  375. },
  376. (report, next) => {
  377. if (!report) return next("Report not found.");
  378. report.resolved = resolved;
  379. return report.save(err => {
  380. if (err) return next(err.message);
  381. return next(null, report.song._id);
  382. });
  383. }
  384. ],
  385. async (err, songId) => {
  386. if (err) {
  387. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  388. this.log(
  389. "ERROR",
  390. "REPORTS_RESOLVE",
  391. `${resolved ? "R" : "Unr"}esolving report "${reportId}" failed by user "${
  392. session.userId
  393. }". "${err}"`
  394. );
  395. return cb({ status: "error", message: err });
  396. }
  397. CacheModule.runJob("PUB", {
  398. channel: "report.resolve",
  399. value: { reportId, songId, resolved }
  400. });
  401. CacheModule.runJob("PUB", {
  402. channel: "report.update",
  403. value: { reportId }
  404. });
  405. this.log(
  406. "SUCCESS",
  407. "REPORTS_RESOLVE",
  408. `User "${session.userId}" ${resolved ? "" : "un"}resolved report "${reportId}".`
  409. );
  410. return cb({
  411. status: "success",
  412. message: `Successfully ${resolved ? "" : "un"}resolved Report`
  413. });
  414. }
  415. );
  416. }),
  417. /**
  418. * Resolves/Unresolves an issue within a report
  419. *
  420. * @param {object} session - the session object automatically added by the websocket
  421. * @param {string} reportId - the id of the report that is getting resolved
  422. * @param {string} issueId - the id of the issue within the report
  423. * @param {Function} cb - gets called with the result
  424. */
  425. toggleIssue: useHasPermission("reports.toggleIssue", async function toggleIssue(session, reportId, issueId, cb) {
  426. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  427. async.waterfall(
  428. [
  429. next => {
  430. reportModel.findById(reportId).exec(next);
  431. },
  432. (report, next) => {
  433. if (!report) return next("Report not found.");
  434. const issue = report.issues.find(issue => issue._id.toString() === issueId);
  435. issue.resolved = !issue.resolved;
  436. return report.save(err => {
  437. if (err) return next(err.message);
  438. return next(null, issue.resolved, report.song._id);
  439. });
  440. }
  441. ],
  442. async (err, resolved, songId) => {
  443. if (err) {
  444. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  445. this.log(
  446. "ERROR",
  447. "REPORTS_TOGGLE_ISSUE",
  448. `Resolving an issue within report "${reportId}" failed by user "${session.userId}". "${err}"`
  449. );
  450. return cb({ status: "error", message: err });
  451. }
  452. CacheModule.runJob("PUB", {
  453. channel: "report.issue.toggle",
  454. value: { reportId, issueId, songId, resolved }
  455. });
  456. CacheModule.runJob("PUB", {
  457. channel: "report.update",
  458. value: { reportId }
  459. });
  460. this.log(
  461. "SUCCESS",
  462. "REPORTS_TOGGLE_ISSUE",
  463. `User "${session.userId}" resolved an issue in report "${reportId}".`
  464. );
  465. return cb({
  466. status: "success",
  467. message: "Successfully resolved issue within report"
  468. });
  469. }
  470. );
  471. }),
  472. /**
  473. * Creates a new report
  474. *
  475. * @param {object} session - the session object automatically added by the websocket
  476. * @param {object} report - the object of the report data
  477. * @param {string} report.youtubeId - the youtube id of the song that is being reported
  478. * @param {Array} report.issues - all issues reported (custom or defined)
  479. * @param {Function} cb - gets called with the result
  480. */
  481. create: isLoginRequired(async function create(session, report, cb) {
  482. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  483. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  484. const { youtubeId } = report;
  485. async.waterfall(
  486. [
  487. next => songModel.findOne({ youtubeId }).exec(next),
  488. (song, next) => {
  489. if (!song) return next("Song not found.");
  490. return SongsModule.runJob("GET_SONG", { songId: song._id }, this)
  491. .then(res => next(null, res.song))
  492. .catch(next);
  493. },
  494. (song, next) => {
  495. if (!song) return next("Song not found.");
  496. delete report.youtubeId;
  497. report.song = {
  498. _id: song._id,
  499. youtubeId: song.youtubeId
  500. };
  501. return next(null, { title: song.title, artists: song.artists, thumbnail: song.thumbnail });
  502. },
  503. (song, next) =>
  504. reportModel.create(
  505. {
  506. createdBy: session.userId,
  507. createdAt: Date.now(),
  508. ...report
  509. },
  510. (err, report) => next(err, report, song)
  511. )
  512. ],
  513. async (err, report, song) => {
  514. if (err) {
  515. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  516. this.log(
  517. "ERROR",
  518. "REPORTS_CREATE",
  519. `Creating report for "${report.song._id}" failed by user "${session.userId}". "${err}"`
  520. );
  521. return cb({ status: "error", message: err });
  522. }
  523. ActivitiesModule.runJob("ADD_ACTIVITY", {
  524. userId: session.userId,
  525. type: "song__report",
  526. payload: {
  527. message: `Created a <reportId>${report._id}</reportId> for song <youtubeId>${song.title}</youtubeId>`,
  528. youtubeId: report.song.youtubeId,
  529. reportId: report._id,
  530. thumbnail: song.thumbnail
  531. }
  532. });
  533. CacheModule.runJob("PUB", {
  534. channel: "report.create",
  535. value: report
  536. });
  537. this.log("SUCCESS", "REPORTS_CREATE", `User "${session.userId}" created report for "${youtubeId}".`);
  538. return cb({
  539. status: "success",
  540. message: "Successfully created report"
  541. });
  542. }
  543. );
  544. }),
  545. /**
  546. * Removes a report
  547. *
  548. * @param {object} session - the session object automatically added by the websocket
  549. * @param {object} reportId - the id of the report item we want to remove
  550. * @param {Function} cb - gets called with the result
  551. */
  552. remove: useHasPermission("reports.remove", async function remove(session, reportId, cb) {
  553. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  554. async.waterfall(
  555. [
  556. next => {
  557. if (!reportId) return next("Please provide a report item id to remove.");
  558. return next();
  559. },
  560. next => {
  561. reportModel.deleteOne({ _id: reportId }, err => next(err));
  562. }
  563. ],
  564. async err => {
  565. if (err) {
  566. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  567. this.log(
  568. "ERROR",
  569. "REPORT_REMOVE",
  570. `Removing report "${reportId}" failed for user "${session.userId}". "${err}"`
  571. );
  572. return cb({ status: "error", message: err });
  573. }
  574. CacheModule.runJob("PUB", { channel: "report.remove", value: reportId });
  575. this.log(
  576. "SUCCESS",
  577. "REPORT_REMOVE",
  578. `Removing report "${reportId}" successful by user "${session.userId}".`
  579. );
  580. return cb({
  581. status: "success",
  582. message: "Successfully removed report"
  583. });
  584. }
  585. );
  586. })
  587. };