reports.js 16 KB

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