reports.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. 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 {boolean} resolved - whether to set to resolved to true or false
  335. * @param {Function} cb - gets called with the result
  336. */
  337. resolve: isAdminRequired(async function resolve(session, reportId, resolved, cb) {
  338. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  339. async.waterfall(
  340. [
  341. next => {
  342. reportModel.findById(reportId).exec(next);
  343. },
  344. (report, next) => {
  345. if (!report) return next("Report not found.");
  346. report.resolved = resolved;
  347. return report.save(err => {
  348. if (err) return next(err.message);
  349. return next(null, report.song._id);
  350. });
  351. }
  352. ],
  353. async (err, songId) => {
  354. if (err) {
  355. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  356. this.log(
  357. "ERROR",
  358. "REPORTS_RESOLVE",
  359. `${resolved ? "R" : "Unr"}esolving report "${reportId}" failed by user "${
  360. session.userId
  361. }". "${err}"`
  362. );
  363. return cb({ status: "error", message: err });
  364. }
  365. CacheModule.runJob("PUB", {
  366. channel: "report.resolve",
  367. value: { reportId, songId, resolved }
  368. });
  369. this.log(
  370. "SUCCESS",
  371. "REPORTS_RESOLVE",
  372. `User "${session.userId}" ${resolved ? "" : "un"}resolved report "${reportId}".`
  373. );
  374. return cb({
  375. status: "success",
  376. message: `Successfully ${resolved ? "" : "un"}resolved Report`
  377. });
  378. }
  379. );
  380. }),
  381. /**
  382. * Resolves/Unresolves an issue within a report
  383. *
  384. * @param {object} session - the session object automatically added by the websocket
  385. * @param {string} reportId - the id of the report that is getting resolved
  386. * @param {string} issueId - the id of the issue within the report
  387. * @param {Function} cb - gets called with the result
  388. */
  389. toggleIssue: isAdminRequired(async function toggleIssue(session, reportId, issueId, cb) {
  390. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  391. async.waterfall(
  392. [
  393. next => {
  394. reportModel.findById(reportId).exec(next);
  395. },
  396. (report, next) => {
  397. if (!report) return next("Report not found.");
  398. const issue = report.issues.find(issue => issue._id.toString() === issueId);
  399. issue.resolved = !issue.resolved;
  400. return report.save(err => {
  401. if (err) return next(err.message);
  402. return next(null, issue.resolved, report.song._id);
  403. });
  404. }
  405. ],
  406. async (err, resolved, songId) => {
  407. if (err) {
  408. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  409. this.log(
  410. "ERROR",
  411. "REPORTS_TOGGLE_ISSUE",
  412. `Resolving an issue within report "${reportId}" failed by user "${session.userId}". "${err}"`
  413. );
  414. return cb({ status: "error", message: err });
  415. }
  416. CacheModule.runJob("PUB", {
  417. channel: "report.issue.toggle",
  418. value: { reportId, issueId, songId, resolved }
  419. });
  420. this.log(
  421. "SUCCESS",
  422. "REPORTS_TOGGLE_ISSUE",
  423. `User "${session.userId}" resolved an issue in report "${reportId}".`
  424. );
  425. return cb({
  426. status: "success",
  427. message: "Successfully resolved issue within report"
  428. });
  429. }
  430. );
  431. }),
  432. /**
  433. * Creates a new report
  434. *
  435. * @param {object} session - the session object automatically added by the websocket
  436. * @param {object} report - the object of the report data
  437. * @param {string} report.youtubeId - the youtube id of the song that is being reported
  438. * @param {Array} report.issues - all issues reported (custom or defined)
  439. * @param {Function} cb - gets called with the result
  440. */
  441. create: isLoginRequired(async function create(session, report, cb) {
  442. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  443. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  444. const { youtubeId } = report;
  445. async.waterfall(
  446. [
  447. next => songModel.findOne({ youtubeId }).exec(next),
  448. (song, next) => {
  449. if (!song) return next("Song not found.");
  450. return SongsModule.runJob("GET_SONG", { songId: song._id }, this)
  451. .then(res => next(null, res.song))
  452. .catch(next);
  453. },
  454. (song, next) => {
  455. if (!song) return next("Song not found.");
  456. delete report.youtubeId;
  457. report.song = {
  458. _id: song._id,
  459. youtubeId: song.youtubeId
  460. };
  461. return next(null, { title: song.title, artists: song.artists, thumbnail: song.thumbnail });
  462. },
  463. (song, next) =>
  464. reportModel.create(
  465. {
  466. createdBy: session.userId,
  467. createdAt: Date.now(),
  468. ...report
  469. },
  470. (err, report) => next(err, report, song)
  471. )
  472. ],
  473. async (err, report, song) => {
  474. if (err) {
  475. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  476. this.log(
  477. "ERROR",
  478. "REPORTS_CREATE",
  479. `Creating report for "${report.song._id}" failed by user "${session.userId}". "${err}"`
  480. );
  481. return cb({ status: "error", message: err });
  482. }
  483. ActivitiesModule.runJob("ADD_ACTIVITY", {
  484. userId: session.userId,
  485. type: "song__report",
  486. payload: {
  487. message: `Created a <reportId>${report._id}</reportId> for song <youtubeId>${song.title}</youtubeId>`,
  488. youtubeId: report.song.youtubeId,
  489. reportId: report._id,
  490. thumbnail: song.thumbnail
  491. }
  492. });
  493. CacheModule.runJob("PUB", {
  494. channel: "report.create",
  495. value: report
  496. });
  497. this.log("SUCCESS", "REPORTS_CREATE", `User "${session.userId}" created report for "${youtubeId}".`);
  498. return cb({
  499. status: "success",
  500. message: "Successfully created report"
  501. });
  502. }
  503. );
  504. }),
  505. /**
  506. * Removes a report
  507. *
  508. * @param {object} session - the session object automatically added by the websocket
  509. * @param {object} reportId - the id of the report item we want to remove
  510. * @param {Function} cb - gets called with the result
  511. */
  512. remove: isAdminRequired(async function remove(session, reportId, cb) {
  513. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  514. async.waterfall(
  515. [
  516. next => {
  517. if (!reportId) return next("Please provide a report item id to remove.");
  518. return next();
  519. },
  520. next => {
  521. reportModel.deleteOne({ _id: reportId }, err => next(err));
  522. }
  523. ],
  524. async err => {
  525. if (err) {
  526. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  527. this.log(
  528. "ERROR",
  529. "REPORT_REMOVE",
  530. `Removing report "${reportId}" failed for user "${session.userId}". "${err}"`
  531. );
  532. return cb({ status: "error", message: err });
  533. }
  534. CacheModule.runJob("PUB", { channel: "report.remove", value: reportId });
  535. this.log(
  536. "SUCCESS",
  537. "REPORT_REMOVE",
  538. `Removing report "${reportId}" successful by user "${session.userId}".`
  539. );
  540. return cb({
  541. status: "success",
  542. message: "Successfully removed report"
  543. });
  544. }
  545. );
  546. })
  547. };