server_firebase.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. // Silent notification; only 2-3 per hour are allowed; delivery not guaranteed
  77. // See https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
  78. apnsData := make(map[string]interface{})
  79. for k, v := range data {
  80. apnsData[k] = v
  81. }
  82. apnsConfig = &messaging.APNSConfig{
  83. Headers: map[string]string{
  84. "apns-push-type": "background",
  85. "apns-priority": "5",
  86. },
  87. Payload: &messaging.APNSPayload{
  88. Aps: &messaging.Aps{
  89. ContentAvailable: true,
  90. },
  91. CustomData: apnsData,
  92. },
  93. }
  94. case messageEvent:
  95. allowForward := true
  96. if auther != nil {
  97. allowForward = auther.Authorize(nil, m.Topic, auth.PermissionRead) == nil
  98. }
  99. if allowForward {
  100. data = map[string]string{
  101. "id": m.ID,
  102. "time": fmt.Sprintf("%d", m.Time),
  103. "event": m.Event,
  104. "topic": m.Topic,
  105. "priority": fmt.Sprintf("%d", m.Priority),
  106. "tags": strings.Join(m.Tags, ","),
  107. "click": m.Click,
  108. "title": m.Title,
  109. "message": m.Message,
  110. "encoding": m.Encoding,
  111. }
  112. if len(m.Actions) > 0 {
  113. actions, err := json.Marshal(m.Actions)
  114. if err != nil {
  115. return nil, err
  116. }
  117. data["actions"] = string(actions)
  118. }
  119. if m.Attachment != nil {
  120. data["attachment_name"] = m.Attachment.Name
  121. data["attachment_type"] = m.Attachment.Type
  122. data["attachment_size"] = fmt.Sprintf("%d", m.Attachment.Size)
  123. data["attachment_expires"] = fmt.Sprintf("%d", m.Attachment.Expires)
  124. data["attachment_url"] = m.Attachment.URL
  125. }
  126. apnsData := make(map[string]interface{})
  127. for k, v := range data {
  128. apnsData[k] = v
  129. }
  130. apnsConfig = &messaging.APNSConfig{
  131. Payload: &messaging.APNSPayload{
  132. CustomData: apnsData,
  133. Aps: &messaging.Aps{
  134. MutableContent: true,
  135. Alert: &messaging.ApsAlert{
  136. Title: m.Title,
  137. Body: maybeTruncateAPNSBodyMessage(m.Message),
  138. },
  139. },
  140. },
  141. }
  142. } else {
  143. // If anonymous read for a topic is not allowed, we cannot send the message along
  144. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  145. data = map[string]string{
  146. "id": m.ID,
  147. "time": fmt.Sprintf("%d", m.Time),
  148. "event": pollRequestEvent,
  149. "topic": m.Topic,
  150. }
  151. }
  152. }
  153. var androidConfig *messaging.AndroidConfig
  154. if m.Priority >= 4 {
  155. androidConfig = &messaging.AndroidConfig{
  156. Priority: "high",
  157. }
  158. }
  159. return maybeTruncateFCMMessage(&messaging.Message{
  160. Topic: m.Topic,
  161. Data: data,
  162. Android: androidConfig,
  163. APNS: apnsConfig,
  164. }), nil
  165. }