server_web_push.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/SherClockHolmes/webpush-go"
  6. "heckel.io/ntfy/log"
  7. "net/http"
  8. "strings"
  9. )
  10. func (s *Server) handleTopicWebPushSubscribe(w http.ResponseWriter, r *http.Request, v *visitor) error {
  11. var username string
  12. u := v.User()
  13. if u != nil {
  14. username = u.Name
  15. }
  16. var sub webPushSubscribePayload
  17. err := json.NewDecoder(r.Body).Decode(&sub)
  18. if err != nil || sub.BrowserSubscription.Endpoint == "" || sub.BrowserSubscription.Keys.P256dh == "" || sub.BrowserSubscription.Keys.Auth == "" {
  19. return errHTTPBadRequestWebPushSubscriptionInvalid
  20. }
  21. topic, err := fromContext[*topic](r, contextTopic)
  22. if err != nil {
  23. return err
  24. }
  25. err = s.webPush.AddSubscription(topic.ID, username, sub)
  26. if err != nil {
  27. return err
  28. }
  29. return s.writeJSON(w, newSuccessResponse())
  30. }
  31. func (s *Server) handleTopicWebPushUnsubscribe(w http.ResponseWriter, r *http.Request, _ *visitor) error {
  32. var payload webPushUnsubscribePayload
  33. err := json.NewDecoder(r.Body).Decode(&payload)
  34. if err != nil {
  35. return errHTTPBadRequestWebPushSubscriptionInvalid
  36. }
  37. topic, err := fromContext[*topic](r, contextTopic)
  38. if err != nil {
  39. return err
  40. }
  41. err = s.webPush.RemoveSubscription(topic.ID, payload.Endpoint)
  42. if err != nil {
  43. return err
  44. }
  45. return s.writeJSON(w, newSuccessResponse())
  46. }
  47. func (s *Server) publishToWebPushEndpoints(v *visitor, m *message) {
  48. subscriptions, err := s.webPush.GetSubscriptionsForTopic(m.Topic)
  49. if err != nil {
  50. logvm(v, m).Err(err).Warn("Unable to publish web push messages")
  51. return
  52. }
  53. ctx := log.Context{"topic": m.Topic, "message_id": m.ID, "total_count": len(subscriptions)}
  54. // Importing the emojis in the service worker would add unnecessary complexity,
  55. // simply do it here for web push notifications instead
  56. var titleWithDefault string
  57. var formattedTitle string
  58. emojis, _, err := toEmojis(m.Tags)
  59. if err != nil {
  60. logvm(v, m).Err(err).Fields(ctx).Debug("Unable to publish web push message")
  61. return
  62. }
  63. if m.Title == "" {
  64. titleWithDefault = m.Topic
  65. } else {
  66. titleWithDefault = m.Title
  67. }
  68. if len(emojis) > 0 {
  69. formattedTitle = fmt.Sprintf("%s %s", strings.Join(emojis[:], " "), titleWithDefault)
  70. } else {
  71. formattedTitle = titleWithDefault
  72. }
  73. for i, xi := range subscriptions {
  74. go func(i int, sub webPushSubscription) {
  75. ctx := log.Context{"endpoint": sub.BrowserSubscription.Endpoint, "username": sub.Username, "topic": m.Topic, "message_id": m.ID}
  76. payload := &webPushPayload{
  77. SubscriptionID: fmt.Sprintf("%s/%s", s.config.BaseURL, m.Topic),
  78. Message: *m,
  79. FormattedTitle: formattedTitle,
  80. }
  81. jsonPayload, err := json.Marshal(payload)
  82. if err != nil {
  83. logvm(v, m).Err(err).Fields(ctx).Debug("Unable to publish web push message")
  84. return
  85. }
  86. resp, err := webpush.SendNotification(jsonPayload, &sub.BrowserSubscription, &webpush.Options{
  87. Subscriber: s.config.WebPushEmailAddress,
  88. VAPIDPublicKey: s.config.WebPushPublicKey,
  89. VAPIDPrivateKey: s.config.WebPushPrivateKey,
  90. // deliverability on iOS isn't great with lower urgency values,
  91. // and thus we can't really map lower ntfy priorities to lower urgency values
  92. Urgency: webpush.UrgencyHigh,
  93. })
  94. if err != nil {
  95. logvm(v, m).Err(err).Fields(ctx).Debug("Unable to publish web push message")
  96. err = s.webPush.ExpireWebPushEndpoint(sub.BrowserSubscription.Endpoint)
  97. if err != nil {
  98. logvm(v, m).Err(err).Fields(ctx).Warn("Unable to expire subscription")
  99. }
  100. return
  101. }
  102. // May want to handle at least 429 differently, but for now treat all errors the same
  103. if !(200 <= resp.StatusCode && resp.StatusCode <= 299) {
  104. logvm(v, m).Fields(ctx).Field("response", resp).Debug("Unable to publish web push message")
  105. err = s.webPush.ExpireWebPushEndpoint(sub.BrowserSubscription.Endpoint)
  106. if err != nil {
  107. logvm(v, m).Err(err).Fields(ctx).Warn("Unable to expire subscription")
  108. }
  109. return
  110. }
  111. }(i, xi)
  112. }
  113. }