NotificationsHandler.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. const settings = require('@overleaf/settings')
  2. const request = require('request')
  3. const logger = require('logger-sharelatex')
  4. const _ = require('lodash')
  5. const notificationsApi = _.get(settings, ['apis', 'notifications', 'url'])
  6. const oneSecond = 1000
  7. const makeRequest = function (opts, callback) {
  8. if (notificationsApi) {
  9. request(opts, callback)
  10. } else {
  11. callback(null, { statusCode: 200 })
  12. }
  13. }
  14. module.exports = {
  15. getUserNotifications(userId, callback) {
  16. const opts = {
  17. uri: `${notificationsApi}/user/${userId}`,
  18. json: true,
  19. timeout: oneSecond,
  20. method: 'GET',
  21. }
  22. makeRequest(opts, function (err, res, unreadNotifications) {
  23. const statusCode = res ? res.statusCode : 500
  24. if (err || statusCode !== 200) {
  25. logger.err(
  26. { err, statusCode },
  27. 'something went wrong getting notifications'
  28. )
  29. callback(null, [])
  30. } else {
  31. if (unreadNotifications == null) {
  32. unreadNotifications = []
  33. }
  34. callback(null, unreadNotifications)
  35. }
  36. })
  37. },
  38. createNotification(
  39. userId,
  40. key,
  41. templateKey,
  42. messageOpts,
  43. expiryDateTime,
  44. forceCreate,
  45. callback
  46. ) {
  47. if (!callback) {
  48. callback = forceCreate
  49. forceCreate = true
  50. }
  51. const payload = {
  52. key,
  53. messageOpts,
  54. templateKey,
  55. forceCreate,
  56. }
  57. if (expiryDateTime) {
  58. payload.expires = expiryDateTime
  59. }
  60. const opts = {
  61. uri: `${notificationsApi}/user/${userId}`,
  62. timeout: oneSecond,
  63. method: 'POST',
  64. json: payload,
  65. }
  66. makeRequest(opts, callback)
  67. },
  68. markAsReadWithKey(userId, key, callback) {
  69. const opts = {
  70. uri: `${notificationsApi}/user/${userId}`,
  71. method: 'DELETE',
  72. timeout: oneSecond,
  73. json: {
  74. key,
  75. },
  76. }
  77. makeRequest(opts, callback)
  78. },
  79. markAsRead(userId, notificationId, callback) {
  80. const opts = {
  81. method: 'DELETE',
  82. uri: `${notificationsApi}/user/${userId}/notification/${notificationId}`,
  83. timeout: oneSecond,
  84. }
  85. makeRequest(opts, callback)
  86. },
  87. // removes notification by key, without regard for user_id,
  88. // should not be exposed to user via ui/router
  89. markAsReadByKeyOnly(key, callback) {
  90. const opts = {
  91. uri: `${notificationsApi}/key/${key}`,
  92. method: 'DELETE',
  93. timeout: oneSecond,
  94. }
  95. makeRequest(opts, callback)
  96. },
  97. }