reports.js 15 KB

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