reports.js 15 KB

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