server_web_push.go 3.8 KB

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