post.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. let express = require('express')
  2. let router = express.Router()
  3. const Errors = require('../lib/errors')
  4. let { User, Thread, Post, Notification } = require('../models')
  5. router.get('/:post_id', async (req, res) => {
  6. try {
  7. let post = await Post.findById(req.params.post_id, { include: Post.includeOptions() })
  8. if(!post) throw Errors.invalidParameter('id', 'post does not exist')
  9. res.json(post.toJSON())
  10. } catch (e) {
  11. if(e.name === 'invalidParameter') {
  12. res.status(400)
  13. res.json({
  14. errors: [e]
  15. })
  16. } else {
  17. res.status(500)
  18. res.json({
  19. errors: [Errors.unknown]
  20. })
  21. }
  22. }
  23. })
  24. router.all('*', (req, res, next) => {
  25. if(req.session.loggedIn) {
  26. next()
  27. } else {
  28. res.status(401)
  29. res.json({
  30. errors: [Errors.requestNotAuthorized]
  31. })
  32. }
  33. })
  34. router.delete('/:post_id', async (req, res) => {
  35. try {
  36. if(!req.session.admin) {
  37. throw Errors.requestNotAuthorized
  38. } else {
  39. let post = await Post.findById(req.params.post_id)
  40. if(!post) throw Errors.invalidParameter('postId', 'post does not exist')
  41. await post.update({ content: '[This post has been removed by an administrator]', removed: true })
  42. res.json({ success: true })
  43. }
  44. } catch (e) {
  45. if(e.name === 'requestNotAuthorized') {
  46. res.status(401)
  47. res.json({ errors: [e] })
  48. } else if(e.name === 'invalidParameter') {
  49. res.status(400)
  50. res.json({ errors: [e] })
  51. } else {
  52. console.log(e)
  53. res.status(500)
  54. res.json({
  55. errors: [Errors.unknown]
  56. })
  57. }
  58. }
  59. })
  60. router.put('/:post_id/like', async (req, res) => {
  61. try {
  62. let post = await Post.findById(req.params.post_id)
  63. let user = await User.findOne({ where: { username: req.session.username }})
  64. if(!post) throw Errors.invalidParameter('id', 'post does not exist')
  65. if(post.UserId === user.id) throw Errors.cannotLikeOwnPost
  66. await post.addLikes(user)
  67. res.json({ success: true })
  68. } catch (e) {
  69. if(['invalidParameter', 'cannotLikeOwnPost'].includes(e.name)) {
  70. res.status(400)
  71. res.json({
  72. errors: [e]
  73. })
  74. } else{
  75. console.log(e)
  76. res.status(500)
  77. res.json({
  78. errors: [Errors.unknown]
  79. })
  80. }
  81. }
  82. })
  83. router.delete('/:post_id/like', async (req, res) => {
  84. try {
  85. let post = await Post.findById(req.params.post_id)
  86. let user = await User.findOne({ where: { username: req.session.username }})
  87. if(!post) throw Errors.invalidParameter('id', 'post does not exist')
  88. await post.removeLikes(user)
  89. res.json({ success: true })
  90. } catch (e) {
  91. if(e.name === 'invalidParameter') {
  92. res.status(400)
  93. res.json({
  94. errors: [e]
  95. })
  96. } else{
  97. console.log(e)
  98. res.status(500)
  99. res.json({
  100. errors: [Errors.unknown]
  101. })
  102. }
  103. }
  104. })
  105. router.post('/', async (req, res) => {
  106. let validationErrors = []
  107. let thread, replyingToPost, post
  108. try {
  109. if(req.body.content === undefined) {
  110. validationErrors.push(Errors.missingParameter('content'))
  111. } else if(typeof req.body.content !== 'string') {
  112. validationErrors.push(Errors.invalidParameterType('content', 'string'))
  113. } if (req.body.threadId === undefined) {
  114. validationErrors.push(Errors.missingParameter('threadId'))
  115. } else if(!Number.isInteger(req.body.threadId)) {
  116. validationErrors.push(Errors.invalidParameterType('threadId', 'integer'))
  117. } if(req.body.replyingToId !== undefined && !Number.isInteger(req.body.replyingToId)) {
  118. validationErrors.push(Errors.invalidParameterType('replyingToId', 'integer'))
  119. } if(req.body.mentions !== undefined) {
  120. if(Array.isArray(req.body.mentions)) {
  121. if(req.body.mentions.some(m => typeof m !== 'string')) {
  122. validationErrors.push(Errors.invalidParameterType('mention', 'string'))
  123. }
  124. } else {
  125. validationErrors.push(Errors.invalidParameterType('mentions', 'array'))
  126. }
  127. }
  128. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  129. thread = await Thread.findOne({ where: {
  130. id: req.body.threadId
  131. }})
  132. user = await User.findOne({ where: {
  133. username: req.session.username
  134. }})
  135. if(!thread) throw Errors.invalidParameter('threadId', 'thread does not exist')
  136. if(thread.locked) throw Errors.threadLocked
  137. if(req.body.replyingToId) {
  138. replyingToPost = await Post.findById(
  139. req.body.replyingToId,
  140. { include: [Thread, { model: User, attributes: ['username'] }] }
  141. )
  142. if(!replyingToPost) {
  143. throw Errors.invalidParameter('replyingToId', 'post does not exist')
  144. } else if(replyingToPost.Thread.id !== thread.id) {
  145. throw Errors.invalidParameter('replyingToId', 'replies must be in same thread')
  146. } else {
  147. post = await Post.create({ content: req.body.content, postNumber: thread.postsCount })
  148. await post.setReplyingTo(replyingToPost)
  149. await replyingToPost.addReplies(post)
  150. let replyNotification = await Notification.createPostNotification({
  151. usernameTo: replyingToPost.User.username,
  152. userFrom: user,
  153. type: 'reply',
  154. post: post
  155. })
  156. let ioUsers = req.app.get('io-users')
  157. if(ioUsers[replyingToPost.User.username]) {
  158. req.app
  159. .get('io')
  160. .to(ioUsers[replyingToPost.User.username])
  161. .emit('notification', replyNotification.toJSON())
  162. }
  163. }
  164. } else {
  165. post = await Post.create({ content: req.body.content, postNumber: thread.postsCount })
  166. }
  167. await post.setUser(user)
  168. await post.setThread(thread)
  169. await thread.increment('postsCount')
  170. if(req.body.mentions) {
  171. let uniqueMentions = req.body.mentions.filter((mention, pos, self) => {
  172. return self.indexOf(mention) === pos
  173. })
  174. for(var i = 0; i < uniqueMentions.length; i++) {
  175. let mention = uniqueMentions[i]
  176. let ioUsers = req.app.get('io-users')
  177. let mentionNotification = await Notification.createPostNotification({
  178. usernameTo: mention,
  179. userFrom: user,
  180. type: 'mention',
  181. post
  182. })
  183. if(ioUsers[mention]) {
  184. req.app.get('io').to(ioUsers[mention]).emit('notification', mentionNotification.toJSON())
  185. }
  186. }
  187. }
  188. res.json(await post.reload({
  189. include: Post.includeOptions()
  190. }))
  191. req.app.get('io').to('thread/' + thread.id).emit('new post', {
  192. postNumber: thread.postsCount
  193. })
  194. } catch (e) {
  195. if(e === Errors.VALIDATION_ERROR) {
  196. res.status(400)
  197. res.json({
  198. errors: validationErrors
  199. })
  200. } else if(e.name === 'invalidParameter' || e.name === 'threadLocked') {
  201. res.status(400)
  202. res.json({
  203. errors: [e]
  204. })
  205. } else {
  206. console.log(e)
  207. res.status(500)
  208. res.json({
  209. errors: [Errors.unknown]
  210. })
  211. }
  212. }
  213. })
  214. module.exports = router