reports.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. export default {
  53. /**
  54. * Gets reports, used in the admin reports page by the AdvancedTable component
  55. *
  56. * @param {object} session - the session object automatically added by the websocket
  57. * @param page - the page
  58. * @param pageSize - the size per page
  59. * @param properties - the properties to return for each user
  60. * @param sort - the sort object
  61. * @param queries - the queries array
  62. * @param operator - the operator for queries
  63. * @param cb
  64. */
  65. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  66. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  67. async.waterfall(
  68. [
  69. next => {
  70. const newQueries = queries.map(query => {
  71. const { data, filter, filterType } = query;
  72. const newQuery = {};
  73. if (filterType === "regex") {
  74. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  75. } else if (filterType === "contains") {
  76. newQuery[filter.property] = new RegExp(
  77. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  78. "i"
  79. );
  80. } else if (filterType === "exact") {
  81. newQuery[filter.property] = data.toString();
  82. } else if (filterType === "datetimeBefore") {
  83. newQuery[filter.property] = { $lte: new Date(data) };
  84. } else if (filterType === "datetimeAfter") {
  85. newQuery[filter.property] = { $gte: new Date(data) };
  86. }
  87. return newQuery;
  88. });
  89. const queryObject = {};
  90. if (newQueries.length > 0) {
  91. if (operator === "and") queryObject.$and = newQueries;
  92. else if (operator === "or") queryObject.$or = newQueries;
  93. else if (operator === "nor") queryObject.$nor = newQueries;
  94. }
  95. next(null, queryObject);
  96. },
  97. (queryObject, next) => {
  98. reportModel.find(queryObject).count((err, count) => {
  99. next(err, queryObject, count);
  100. });
  101. },
  102. (queryObject, count, next) => {
  103. reportModel
  104. .find(queryObject)
  105. .sort(sort)
  106. .skip(pageSize * (page - 1))
  107. .limit(pageSize)
  108. .select(properties.join(" "))
  109. .exec((err, reports) => {
  110. next(err, count, reports);
  111. });
  112. }
  113. ],
  114. async (err, count, reports) => {
  115. if (err && err !== true) {
  116. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  117. this.log("ERROR", "REPORTS_GET_DATA", `Failed to get data from reports. "${err}"`);
  118. return cb({ status: "error", message: err });
  119. }
  120. this.log("SUCCESS", "REPORTS_GET_DATA", `Got data from reports successfully.`);
  121. return cb({
  122. status: "success",
  123. message: "Successfully got data from reports.",
  124. data: { data: reports, count }
  125. });
  126. }
  127. );
  128. }),
  129. /**
  130. * Gets a specific report
  131. *
  132. * @param {object} session - the session object automatically added by the websocket
  133. * @param {string} reportId - the id of the report to return
  134. * @param {Function} cb - gets called with the result
  135. */
  136. findOne: isAdminRequired(async function findOne(session, reportId, cb) {
  137. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  138. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  139. async.waterfall(
  140. [
  141. next => reportModel.findOne({ _id: reportId }).exec(next),
  142. (report, next) =>
  143. userModel
  144. .findById(report.createdBy)
  145. .select({ avatar: -1, name: -1, username: -1 })
  146. .exec((err, user) => {
  147. if (!user)
  148. next(err, {
  149. ...report._doc,
  150. createdBy: { _id: report.createdBy }
  151. });
  152. else
  153. next(err, {
  154. ...report._doc,
  155. createdBy: {
  156. avatar: user.avatar,
  157. name: user.name,
  158. username: user.username,
  159. _id: report.createdBy
  160. }
  161. });
  162. })
  163. ],
  164. async (err, report) => {
  165. if (err) {
  166. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  167. this.log("ERROR", "REPORTS_FIND_ONE", `Finding report "${reportId}" failed. "${err}"`);
  168. return cb({ status: "error", message: err });
  169. }
  170. this.log("SUCCESS", "REPORTS_FIND_ONE", `Finding report "${reportId}" successful.`);
  171. return cb({ status: "success", data: { report } });
  172. }
  173. );
  174. }),
  175. /**
  176. * Gets all reports for a songId
  177. *
  178. * @param {object} session - the session object automatically added by the websocket
  179. * @param {string} songId - the id of the song to index reports for
  180. * @param {Function} cb - gets called with the result
  181. */
  182. getReportsForSong: isAdminRequired(async function getReportsForSong(session, songId, cb) {
  183. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  184. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  185. async.waterfall(
  186. [
  187. next =>
  188. reportModel.find({ "song._id": songId, resolved: false }).sort({ createdAt: "desc" }).exec(next),
  189. (_reports, next) => {
  190. const reports = [];
  191. async.each(
  192. _reports,
  193. (report, cb) => {
  194. userModel
  195. .findById(report.createdBy)
  196. .select({ avatar: -1, name: -1, username: -1 })
  197. .exec((err, user) => {
  198. if (!user)
  199. reports.push({
  200. ...report._doc,
  201. createdBy: { _id: report.createdBy }
  202. });
  203. else
  204. reports.push({
  205. ...report._doc,
  206. createdBy: {
  207. avatar: user.avatar,
  208. name: user.name,
  209. username: user.username,
  210. _id: report.createdBy
  211. }
  212. });
  213. return cb(err);
  214. });
  215. },
  216. err => next(err, reports)
  217. );
  218. }
  219. ],
  220. async (err, reports) => {
  221. if (err) {
  222. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  223. this.log("ERROR", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" failed. "${err}"`);
  224. return cb({ status: "error", message: err });
  225. }
  226. this.log("SUCCESS", "GET_REPORTS_FOR_SONG", `Indexing reports for song "${songId}" successful.`);
  227. return cb({ status: "success", data: { reports } });
  228. }
  229. );
  230. }),
  231. /**
  232. * Gets all a users reports for a specific songId
  233. *
  234. * @param {object} session - the session object automatically added by the websocket
  235. * @param {string} songId - the id of the song
  236. * @param {Function} cb - gets called with the result
  237. */
  238. myReportsForSong: isLoginRequired(async function myReportsForSong(session, songId, cb) {
  239. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  240. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  241. async.waterfall(
  242. [
  243. next =>
  244. reportModel
  245. .find({ "song._id": songId, createdBy: session.userId, resolved: false })
  246. .sort({ createdAt: "desc" })
  247. .exec(next),
  248. (_reports, next) => {
  249. const reports = [];
  250. async.each(
  251. _reports,
  252. (report, cb) => {
  253. userModel
  254. .findById(report.createdBy)
  255. .select({ avatar: -1, name: -1, username: -1 })
  256. .exec((err, user) => {
  257. if (!user)
  258. reports.push({
  259. ...report._doc,
  260. createdBy: { _id: report.createdBy }
  261. });
  262. else
  263. reports.push({
  264. ...report._doc,
  265. createdBy: {
  266. avatar: user.avatar,
  267. name: user.name,
  268. username: user.username,
  269. _id: report.createdBy
  270. }
  271. });
  272. return cb(err);
  273. });
  274. },
  275. err => next(err, reports)
  276. );
  277. }
  278. ],
  279. async (err, reports) => {
  280. if (err) {
  281. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  282. this.log(
  283. "ERROR",
  284. "MY_REPORTS_FOR_SONG",
  285. `Indexing reports of user ${session.userId} for song "${songId}" failed. "${err}"`
  286. );
  287. return cb({ status: "error", message: err });
  288. }
  289. this.log(
  290. "SUCCESS",
  291. "MY_REPORTS_FOR_SONG",
  292. `Indexing reports of user ${session.userId} for song "${songId}" successful.`
  293. );
  294. return cb({ status: "success", data: { reports } });
  295. }
  296. );
  297. }),
  298. /**
  299. * Resolves a report as a whole
  300. *
  301. * @param {object} session - the session object automatically added by the websocket
  302. * @param {string} reportId - the id of the report that is getting resolved
  303. * @param {Function} cb - gets called with the result
  304. */
  305. resolve: isAdminRequired(async function resolve(session, reportId, cb) {
  306. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  307. async.waterfall(
  308. [
  309. next => {
  310. reportModel.findById(reportId).exec(next);
  311. },
  312. (report, next) => {
  313. if (!report) return next("Report not found.");
  314. report.resolved = true;
  315. return report.save(err => {
  316. if (err) return next(err.message);
  317. return next(null, report.song._id);
  318. });
  319. }
  320. ],
  321. async (err, songId) => {
  322. if (err) {
  323. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  324. this.log(
  325. "ERROR",
  326. "REPORTS_RESOLVE",
  327. `Resolving report "${reportId}" failed by user "${session.userId}". "${err}"`
  328. );
  329. return cb({ status: "error", message: err });
  330. }
  331. CacheModule.runJob("PUB", {
  332. channel: "report.resolve",
  333. value: { reportId, songId }
  334. });
  335. this.log("SUCCESS", "REPORTS_RESOLVE", `User "${session.userId}" resolved report "${reportId}".`);
  336. return cb({
  337. status: "success",
  338. message: "Successfully resolved Report"
  339. });
  340. }
  341. );
  342. }),
  343. /**
  344. * Resolves/Unresolves an issue within a report
  345. *
  346. * @param {object} session - the session object automatically added by the websocket
  347. * @param {string} reportId - the id of the report that is getting resolved
  348. * @param {string} issueId - the id of the issue within the report
  349. * @param {Function} cb - gets called with the result
  350. */
  351. toggleIssue: isAdminRequired(async function toggleIssue(session, reportId, issueId, cb) {
  352. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  353. async.waterfall(
  354. [
  355. next => {
  356. reportModel.findById(reportId).exec(next);
  357. },
  358. (report, next) => {
  359. if (!report) return next("Report not found.");
  360. const issue = report.issues.find(issue => issue._id.toString() === issueId);
  361. issue.resolved = !issue.resolved;
  362. return report.save(err => {
  363. if (err) return next(err.message);
  364. return next(null, issue.resolved, report.song._id);
  365. });
  366. }
  367. ],
  368. async (err, resolved, songId) => {
  369. if (err) {
  370. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  371. this.log(
  372. "ERROR",
  373. "REPORTS_TOGGLE_ISSUE",
  374. `Resolving an issue within report "${reportId}" failed by user "${session.userId}". "${err}"`
  375. );
  376. return cb({ status: "error", message: err });
  377. }
  378. CacheModule.runJob("PUB", {
  379. channel: "report.issue.toggle",
  380. value: { reportId, issueId, songId, resolved }
  381. });
  382. this.log(
  383. "SUCCESS",
  384. "REPORTS_TOGGLE_ISSUE",
  385. `User "${session.userId}" resolved an issue in report "${reportId}".`
  386. );
  387. return cb({
  388. status: "success",
  389. message: "Successfully resolved issue within report"
  390. });
  391. }
  392. );
  393. }),
  394. /**
  395. * Creates a new report
  396. *
  397. * @param {object} session - the session object automatically added by the websocket
  398. * @param {object} report - the object of the report data
  399. * @param {string} report.youtubeId - the youtube id of the song that is being reported
  400. * @param {Array} report.issues - all issues reported (custom or defined)
  401. * @param {Function} cb - gets called with the result
  402. */
  403. create: isLoginRequired(async function create(session, report, cb) {
  404. const reportModel = await DBModule.runJob("GET_MODEL", { modelName: "report" }, this);
  405. const songModel = await DBModule.runJob("GET_MODEL", { modelName: "song" }, this);
  406. const { youtubeId } = report;
  407. async.waterfall(
  408. [
  409. next => songModel.findOne({ youtubeId }).exec(next),
  410. (song, next) => {
  411. if (!song) return next("Song not found.");
  412. return SongsModule.runJob("GET_SONG", { songId: song._id }, this)
  413. .then(res => next(null, res.song))
  414. .catch(next);
  415. },
  416. (song, next) => {
  417. if (!song) return next("Song not found.");
  418. delete report.youtubeId;
  419. report.song = {
  420. _id: song._id,
  421. youtubeId: song.youtubeId
  422. };
  423. return next(null, { title: song.title, artists: song.artists, thumbnail: song.thumbnail });
  424. },
  425. (song, next) =>
  426. reportModel.create(
  427. {
  428. createdBy: session.userId,
  429. createdAt: Date.now(),
  430. ...report
  431. },
  432. (err, report) => next(err, report, song)
  433. )
  434. ],
  435. async (err, report, song) => {
  436. if (err) {
  437. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  438. this.log(
  439. "ERROR",
  440. "REPORTS_CREATE",
  441. `Creating report for "${report.song._id}" failed by user "${session.userId}". "${err}"`
  442. );
  443. return cb({ status: "error", message: err });
  444. }
  445. ActivitiesModule.runJob("ADD_ACTIVITY", {
  446. userId: session.userId,
  447. type: "song__report",
  448. payload: {
  449. message: `Created a <reportId>${report._id}</reportId> for song <youtubeId>${song.title}</youtubeId>`,
  450. youtubeId: report.song.youtubeId,
  451. reportId: report._id,
  452. thumbnail: song.thumbnail
  453. }
  454. });
  455. CacheModule.runJob("PUB", {
  456. channel: "report.create",
  457. value: report
  458. });
  459. this.log("SUCCESS", "REPORTS_CREATE", `User "${session.userId}" created report for "${youtubeId}".`);
  460. return cb({
  461. status: "success",
  462. message: "Successfully created report"
  463. });
  464. }
  465. );
  466. })
  467. };