server_firebase.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "strings"
  7. firebase "firebase.google.com/go"
  8. "firebase.google.com/go/messaging"
  9. "google.golang.org/api/option"
  10. "heckel.io/ntfy/auth"
  11. )
  12. const (
  13. fcmMessageLimit = 4000
  14. fcmApnsBodyMessageLimit = 100
  15. )
  16. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  17. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  18. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  19. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  20. s, err := json.Marshal(m)
  21. if err != nil {
  22. return m
  23. }
  24. if len(s) > fcmMessageLimit {
  25. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  26. message, ok := m.Data["message"]
  27. if ok && len(message) > over {
  28. m.Data["truncated"] = "1"
  29. m.Data["message"] = message[:len(message)-over]
  30. }
  31. }
  32. return m
  33. }
  34. // maybeTruncateAPNSBodyMessage truncates the body for APNS.
  35. //
  36. // The "body" of the push notification can contain the entire message, which would count doubly for the overall length
  37. // of the APNS payload. I set a limit of 100 characters before truncating the notification "body" with ellipsis.
  38. // The message would not be changed (unless truncated for being too long). Note: if the payload is too large (>4KB),
  39. // APNS will simply reject / discard the notification, meaning it will never arrive on the iOS device.
  40. func maybeTruncateAPNSBodyMessage(s string) string {
  41. if len(s) >= fcmApnsBodyMessageLimit {
  42. over := len(s) - fcmApnsBodyMessageLimit + 3 // len("...")
  43. return s[:len(s)-over] + "..."
  44. }
  45. return s
  46. }
  47. func createFirebaseSubscriber(credentialsFile string, auther auth.Auther) (subscriber, error) {
  48. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(credentialsFile))
  49. if err != nil {
  50. return nil, err
  51. }
  52. msg, err := fb.Messaging(context.Background())
  53. if err != nil {
  54. return nil, err
  55. }
  56. return func(m *message) error {
  57. fbm, err := toFirebaseMessage(m, auther)
  58. if err != nil {
  59. return err
  60. }
  61. _, err = msg.Send(context.Background(), fbm)
  62. return err
  63. }, nil
  64. }
  65. func toFirebaseMessage(m *message, auther auth.Auther) (*messaging.Message, error) {
  66. var data map[string]string // Mostly matches https://ntfy.sh/docs/subscribe/api/#json-message-format
  67. var apnsConfig *messaging.APNSConfig
  68. switch m.Event {
  69. case keepaliveEvent, openEvent:
  70. data = map[string]string{
  71. "id": m.ID,
  72. "time": fmt.Sprintf("%d", m.Time),
  73. "event": m.Event,
  74. "topic": m.Topic,
  75. }
  76. case messageEvent:
  77. allowForward := true
  78. if auther != nil {
  79. allowForward = auther.Authorize(nil, m.Topic, auth.PermissionRead) == nil
  80. }
  81. if allowForward {
  82. data = map[string]string{
  83. "id": m.ID,
  84. "time": fmt.Sprintf("%d", m.Time),
  85. "event": m.Event,
  86. "topic": m.Topic,
  87. "priority": fmt.Sprintf("%d", m.Priority),
  88. "tags": strings.Join(m.Tags, ","),
  89. "click": m.Click,
  90. "title": m.Title,
  91. "message": m.Message,
  92. "encoding": m.Encoding,
  93. }
  94. if len(m.Actions) > 0 {
  95. actions, err := json.Marshal(m.Actions)
  96. if err != nil {
  97. return nil, err
  98. }
  99. data["actions"] = string(actions)
  100. }
  101. if m.Attachment != nil {
  102. data["attachment_name"] = m.Attachment.Name
  103. data["attachment_type"] = m.Attachment.Type
  104. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  105. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  106. data["attachment_url"] = m.Attachment.URL
  107. }
  108. apnsData := make(map[string]interface{})
  109. for k, v := range data {
  110. apnsData[k] = v
  111. }
  112. apnsConfig = &messaging.APNSConfig{
  113. Payload: &messaging.APNSPayload{
  114. CustomData: apnsData,
  115. Aps: &messaging.Aps{
  116. MutableContent: true,
  117. Alert: &messaging.ApsAlert{
  118. Title: m.Title,
  119. Body: maybeTruncateAPNSBodyMessage(m.Message),
  120. },
  121. },
  122. },
  123. }
  124. } else {
  125. // If anonymous read for a topic is not allowed, we cannot send the message along
  126. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  127. data = map[string]string{
  128. "id": m.ID,
  129. "time": fmt.Sprintf("%d", m.Time),
  130. "event": pollRequestEvent,
  131. "topic": m.Topic,
  132. }
  133. }
  134. }
  135. var androidConfig *messaging.AndroidConfig
  136. if m.Priority >= 4 {
  137. androidConfig = &messaging.AndroidConfig{
  138. Priority: "high",
  139. }
  140. }
  141. return maybeTruncateFCMMessage(&messaging.Message{
  142. Topic: m.Topic,
  143. Data: data,
  144. Android: androidConfig,
  145. APNS: apnsConfig,
  146. }), nil
  147. }