reports.js 15 KB

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