reports.js 15 KB

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