news.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import async from "async";
  2. import isLoginSometimesRequired from "../hooks/loginSometimesRequired";
  3. import { useHasPermission } from "../hooks/hasPermission";
  4. // eslint-disable-next-line
  5. import moduleManager from "../../index";
  6. const DBModule = moduleManager.modules.db;
  7. const UtilsModule = moduleManager.modules.utils;
  8. const WSModule = moduleManager.modules.ws;
  9. const CacheModule = moduleManager.modules.cache;
  10. CacheModule.runJob("SUB", {
  11. channel: "news.create",
  12. cb: news => {
  13. WSModule.runJob("EMIT_TO_ROOM", {
  14. room: "admin.news",
  15. args: ["event:admin.news.created", { data: { news } }]
  16. });
  17. if (news.status === "published")
  18. WSModule.runJob("EMIT_TO_ROOM", {
  19. room: "news",
  20. args: ["event:news.created", { data: { news } }]
  21. });
  22. }
  23. });
  24. CacheModule.runJob("SUB", {
  25. channel: "news.remove",
  26. cb: newsId => {
  27. WSModule.runJob("EMIT_TO_ROOM", {
  28. room: "admin.news",
  29. args: ["event:admin.news.deleted", { data: { newsId } }]
  30. });
  31. WSModule.runJob("EMIT_TO_ROOM", {
  32. room: "news",
  33. args: ["event:news.deleted", { data: { newsId } }]
  34. });
  35. }
  36. });
  37. CacheModule.runJob("SUB", {
  38. channel: "news.update",
  39. cb: news => {
  40. WSModule.runJob("EMIT_TO_ROOM", {
  41. room: "admin.news",
  42. args: ["event:admin.news.updated", { data: { news } }]
  43. });
  44. WSModule.runJob("EMIT_TO_ROOM", {
  45. room: "news",
  46. args: ["event:news.updated", { data: { news } }]
  47. });
  48. }
  49. });
  50. export default {
  51. /**
  52. * Gets news items, used in the admin news page by the AdvancedTable component
  53. * @param {object} session - the session object automatically added by the websocket
  54. * @param page - the page
  55. * @param pageSize - the size per page
  56. * @param properties - the properties to return for each news item
  57. * @param sort - the sort object
  58. * @param queries - the queries array
  59. * @param operator - the operator for queries
  60. * @param cb
  61. */
  62. getData: useHasPermission(
  63. "admin.view.news",
  64. async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  65. async.waterfall(
  66. [
  67. next => {
  68. DBModule.runJob(
  69. "GET_DATA",
  70. {
  71. page,
  72. pageSize,
  73. properties,
  74. sort,
  75. queries,
  76. operator,
  77. modelName: "news",
  78. blacklistedProperties: [],
  79. specialProperties: {
  80. createdBy: [
  81. {
  82. $addFields: {
  83. createdByOID: {
  84. $convert: {
  85. input: "$createdBy",
  86. to: "objectId",
  87. onError: "unknown",
  88. onNull: "unknown"
  89. }
  90. }
  91. }
  92. },
  93. {
  94. $lookup: {
  95. from: "users",
  96. localField: "createdByOID",
  97. foreignField: "_id",
  98. as: "createdByUser"
  99. }
  100. },
  101. {
  102. $unwind: {
  103. path: "$createdByUser",
  104. preserveNullAndEmptyArrays: true
  105. }
  106. },
  107. {
  108. $addFields: {
  109. createdByUsername: {
  110. $ifNull: ["$createdByUser.username", "unknown"]
  111. }
  112. }
  113. },
  114. {
  115. $project: {
  116. createdByOID: 0,
  117. createdByUser: 0
  118. }
  119. }
  120. ]
  121. },
  122. specialQueries: {
  123. createdBy: newQuery => ({
  124. $or: [newQuery, { createdByUsername: newQuery.createdBy }]
  125. })
  126. }
  127. },
  128. this
  129. )
  130. .then(response => {
  131. next(null, response);
  132. })
  133. .catch(err => {
  134. next(err);
  135. });
  136. }
  137. ],
  138. async (err, response) => {
  139. if (err && err !== true) {
  140. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  141. this.log("ERROR", "NEWS_GET_DATA", `Failed to get data from news. "${err}"`);
  142. return cb({ status: "error", message: err });
  143. }
  144. this.log("SUCCESS", "NEWS_GET_DATA", `Got data from news successfully.`);
  145. return cb({
  146. status: "success",
  147. message: "Successfully got data from news.",
  148. data: response
  149. });
  150. }
  151. );
  152. }
  153. ),
  154. /**
  155. * Gets all news items that are published
  156. * @param {object} session - the session object automatically added by the websocket
  157. * @param {Function} cb - gets called with the result
  158. */
  159. getPublished: isLoginSometimesRequired(async function getPublished(session, cb) {
  160. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  161. async.waterfall(
  162. [
  163. next => {
  164. newsModel.find({ status: "published" }).sort({ createdAt: "desc" }).exec(next);
  165. }
  166. ],
  167. async (err, news) => {
  168. if (err) {
  169. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  170. this.log("ERROR", "NEWS_INDEX", `Indexing news failed. "${err}"`);
  171. return cb({ status: "error", message: err });
  172. }
  173. this.log("SUCCESS", "NEWS_INDEX", `Indexing news successful.`, false);
  174. return cb({ status: "success", data: { news } });
  175. }
  176. );
  177. }),
  178. /**
  179. * Gets a news item by id
  180. * @param {object} session - the session object automatically added by the websocket
  181. * @param {string} newsId - the news item id
  182. * @param {Function} cb - gets called with the result
  183. */
  184. getNewsFromId: isLoginSometimesRequired(async function getNewsFromId(session, newsId, cb) {
  185. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  186. async.waterfall(
  187. [
  188. next => {
  189. newsModel.findById(newsId, next);
  190. }
  191. ],
  192. async (err, news) => {
  193. if (err) {
  194. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  195. this.log("ERROR", "GET_NEWS_FROM_ID", `Getting news item ${newsId} failed. "${err}"`);
  196. return cb({ status: "error", message: err });
  197. }
  198. this.log("SUCCESS", "GET_NEWS_FROM_ID", `Got news item ${newsId} successfully.`, false);
  199. return cb({ status: "success", data: { news } });
  200. }
  201. );
  202. }),
  203. /**
  204. * Creates a news item
  205. * @param {object} session - the session object automatically added by the websocket
  206. * @param {object} data - the object of the news data
  207. * @param {Function} cb - gets called with the result
  208. */
  209. create: useHasPermission("news.create", async function create(session, data, cb) {
  210. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  211. async.waterfall(
  212. [
  213. next => {
  214. data.createdBy = session.userId;
  215. data.createdAt = Date.now();
  216. newsModel.create(data, next);
  217. }
  218. ],
  219. async (err, news) => {
  220. if (err) {
  221. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  222. this.log("ERROR", "NEWS_CREATE", `Creating news failed. "${err}"`);
  223. return cb({ status: "error", message: err });
  224. }
  225. CacheModule.runJob("PUB", { channel: "news.create", value: news });
  226. this.log("SUCCESS", "NEWS_CREATE", `Creating news successful.`);
  227. return cb({
  228. status: "success",
  229. message: "Successfully created News"
  230. });
  231. }
  232. );
  233. }),
  234. /**
  235. * Gets the latest news item
  236. * @param {object} session - the session object automatically added by the websocket
  237. * @param {boolean} newUser - whether the user requesting the newest news is a new user
  238. * @param {Function} cb - gets called with the result
  239. */
  240. newest: isLoginSometimesRequired(async function newest(session, newUser, cb) {
  241. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  242. const query = { status: "published" };
  243. if (newUser) query.showToNewUsers = true;
  244. async.waterfall(
  245. [next => newsModel.findOne(query).sort({ createdAt: "desc" }).exec(next)],
  246. async (err, news) => {
  247. if (err) {
  248. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  249. this.log("ERROR", "NEWS_NEWEST", `Getting the latest news failed. "${err}"`);
  250. return cb({ status: "error", message: err });
  251. }
  252. this.log("SUCCESS", "NEWS_NEWEST", `Successfully got the latest news.`, false);
  253. return cb({ status: "success", data: { news } });
  254. }
  255. );
  256. }),
  257. /**
  258. * Removes a news item
  259. * @param {object} session - the session object automatically added by the websocket
  260. * @param {object} newsId - the id of the news item we want to remove
  261. * @param {Function} cb - gets called with the result
  262. */
  263. remove: useHasPermission("news.remove", async function remove(session, newsId, cb) {
  264. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  265. async.waterfall(
  266. [
  267. next => {
  268. if (!newsId) return next("Please provide a news item id to update.");
  269. return next();
  270. },
  271. next => {
  272. newsModel.deleteOne({ _id: newsId }, err => next(err));
  273. }
  274. ],
  275. async err => {
  276. if (err) {
  277. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  278. this.log(
  279. "ERROR",
  280. "NEWS_REMOVE",
  281. `Removing news "${newsId}" failed for user "${session.userId}". "${err}"`
  282. );
  283. return cb({ status: "error", message: err });
  284. }
  285. CacheModule.runJob("PUB", { channel: "news.remove", value: newsId });
  286. this.log("SUCCESS", "NEWS_REMOVE", `Removing news "${newsId}" successful by user "${session.userId}".`);
  287. return cb({
  288. status: "success",
  289. message: "Successfully removed News"
  290. });
  291. }
  292. );
  293. }),
  294. /**
  295. * Updates a news item
  296. * @param {object} session - the session object automatically added by the websocket
  297. * @param {string} newsId - the id of the news item
  298. * @param {object} item - the news item object
  299. * @param {string} item.status - the status of the news e.g. published
  300. * @param {string} item.title - taken from a level-1 heading at the top of the markdown
  301. * @param {string} item.markdown - the markdown that forms the content of the news
  302. * @param {Function} cb - gets called with the result
  303. */
  304. update: useHasPermission("news.update", async function update(session, newsId, item, cb) {
  305. const newsModel = await DBModule.runJob("GET_MODEL", { modelName: "news" }, this);
  306. async.waterfall(
  307. [
  308. next => {
  309. if (!newsId) return next("Please provide a news item id to update.");
  310. return next();
  311. },
  312. next => {
  313. newsModel.updateOne({ _id: newsId }, item, { upsert: true }, err => next(err));
  314. }
  315. ],
  316. async err => {
  317. if (err) {
  318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  319. this.log(
  320. "ERROR",
  321. "NEWS_UPDATE",
  322. `Updating news item "${newsId}" failed for user "${session.userId}". "${err}"`
  323. );
  324. return cb({ status: "error", message: err });
  325. }
  326. CacheModule.runJob("PUB", { channel: "news.update", value: { ...item, _id: newsId } });
  327. this.log(
  328. "SUCCESS",
  329. "NEWS_UPDATE",
  330. `Updating news item "${newsId}" successful for user "${session.userId}".`
  331. );
  332. return cb({
  333. status: "success",
  334. message: "Successfully updated news item"
  335. });
  336. }
  337. );
  338. })
  339. };