server_firebase.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. func createFirebaseSubscriber(credentialsFile string, auther auth.Auther) (subscriber, error) {
  17. fb, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsFile(credentialsFile))
  18. if err != nil {
  19. return nil, err
  20. }
  21. msg, err := fb.Messaging(context.Background())
  22. if err != nil {
  23. return nil, err
  24. }
  25. return func(m *message) error {
  26. fbm, err := toFirebaseMessage(m, auther)
  27. if err != nil {
  28. return err
  29. }
  30. _, err = msg.Send(context.Background(), fbm)
  31. return err
  32. }, nil
  33. }
  34. // toFirebaseMessage converts a message to a Firebase message.
  35. //
  36. // Normal messages ("message"):
  37. // - For Android, we can receive data messages from Firebase and process them as code, so we just send all fields
  38. // in the "data" attribute. In the Android app, we then turn those into a notification and display it.
  39. // - On iOS, we are not allowed to receive data-only messages, so we build messages with an "alert" (with title and
  40. // message), and still send the rest of the data along in the "aps" attribute. We can then locally modify the
  41. // message in the Notification Service Extension.
  42. //
  43. // Keepalive messages ("keepalive"):
  44. // - On Android, we subscribe to the "~control" topic, which is used to restart the foreground service (if it died,
  45. // e.g. after an app update). We send these keepalive messages regularly (see Config.FirebaseKeepaliveInterval).
  46. // - On iOS, we subscribe to the "~poll" topic, which is used to poll all topics regularly. This is because iOS
  47. // does not allow any background or scheduled activity at all.
  48. //
  49. // Poll request messages ("poll_request"):
  50. // - Normal messages are turned into poll request messages if anonymous users are not allowed to read the message.
  51. // On Android, this will trigger the app to poll the topic and thereby displaying new messages.
  52. // - If UpstreamBaseURL is set, messages are forwarded as poll requests to an upstream server and then forwarded
  53. // to Firebase here. This is mainly for iOS to support self-hosted servers.
  54. func toFirebaseMessage(m *message, auther auth.Auther) (*messaging.Message, error) {
  55. var data map[string]string // Mostly matches https://ntfy.sh/docs/subscribe/api/#json-message-format
  56. var apnsConfig *messaging.APNSConfig
  57. switch m.Event {
  58. case keepaliveEvent, openEvent:
  59. data = map[string]string{
  60. "id": m.ID,
  61. "time": fmt.Sprintf("%d", m.Time),
  62. "event": m.Event,
  63. "topic": m.Topic,
  64. }
  65. apnsConfig = createAPNSBackgroundConfig(data)
  66. case pollRequestEvent:
  67. data = map[string]string{
  68. "id": m.ID,
  69. "time": fmt.Sprintf("%d", m.Time),
  70. "event": m.Event,
  71. "topic": m.Topic,
  72. "message": m.Message,
  73. "poll_id": m.PollID,
  74. }
  75. apnsConfig = createAPNSAlertConfig(m, data)
  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. apnsConfig = createAPNSAlertConfig(m, data)
  109. } else {
  110. // If anonymous read for a topic is not allowed, we cannot send the message along
  111. // via Firebase. Instead, we send a "poll_request" message, asking the client to poll.
  112. data = map[string]string{
  113. "id": m.ID,
  114. "time": fmt.Sprintf("%d", m.Time),
  115. "event": pollRequestEvent,
  116. "topic": m.Topic,
  117. }
  118. // TODO Handle APNS?
  119. }
  120. }
  121. var androidConfig *messaging.AndroidConfig
  122. if m.Priority >= 4 {
  123. androidConfig = &messaging.AndroidConfig{
  124. Priority: "high",
  125. }
  126. }
  127. return maybeTruncateFCMMessage(&messaging.Message{
  128. Topic: m.Topic,
  129. Data: data,
  130. Android: androidConfig,
  131. APNS: apnsConfig,
  132. }), nil
  133. }
  134. // maybeTruncateFCMMessage performs best-effort truncation of FCM messages.
  135. // The docs say the limit is 4000 characters, but during testing it wasn't quite clear
  136. // what fields matter; so we're just capping the serialized JSON to 4000 bytes.
  137. func maybeTruncateFCMMessage(m *messaging.Message) *messaging.Message {
  138. s, err := json.Marshal(m)
  139. if err != nil {
  140. return m
  141. }
  142. if len(s) > fcmMessageLimit {
  143. over := len(s) - fcmMessageLimit + 16 // = len("truncated":"1",), sigh ...
  144. message, ok := m.Data["message"]
  145. if ok && len(message) > over {
  146. m.Data["truncated"] = "1"
  147. m.Data["message"] = message[:len(message)-over]
  148. }
  149. }
  150. return m
  151. }
  152. // createAPNSAlertConfig creates an APNS config for iOS notifications that show up as an alert (only relevant for iOS).
  153. // We must set the Alert struct ("alert"), and we need to set MutableContent ("mutable-content"), so the Notification Service
  154. // Extension in iOS can modify the message.
  155. func createAPNSAlertConfig(m *message, data map[string]string) *messaging.APNSConfig {
  156. apnsData := make(map[string]interface{})
  157. for k, v := range data {
  158. apnsData[k] = v
  159. }
  160. return &messaging.APNSConfig{
  161. Payload: &messaging.APNSPayload{
  162. CustomData: apnsData,
  163. Aps: &messaging.Aps{
  164. MutableContent: true,
  165. Alert: &messaging.ApsAlert{
  166. Title: m.Title,
  167. Body: maybeTruncateAPNSBodyMessage(m.Message),
  168. },
  169. },
  170. },
  171. }
  172. }
  173. // createAPNSBackgroundConfig creates an APNS config for a silent background message (only relevant for iOS). Apple only
  174. // allows us to send 2-3 of these notifications per hour, and delivery not guaranteed. We use this only for the ~poll
  175. // topic, which triggers the iOS app to poll all topics for changes.
  176. //
  177. // See https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app
  178. func createAPNSBackgroundConfig(data map[string]string) *messaging.APNSConfig {
  179. apnsData := make(map[string]interface{})
  180. for k, v := range data {
  181. apnsData[k] = v
  182. }
  183. return &messaging.APNSConfig{
  184. Headers: map[string]string{
  185. "apns-push-type": "background",
  186. "apns-priority": "5",
  187. },
  188. Payload: &messaging.APNSPayload{
  189. Aps: &messaging.Aps{
  190. ContentAvailable: true,
  191. },
  192. CustomData: apnsData,
  193. },
  194. }
  195. }
  196. // maybeTruncateAPNSBodyMessage truncates the body for APNS.
  197. //
  198. // The "body" of the push notification can contain the entire message, which would count doubly for the overall length
  199. // of the APNS payload. I set a limit of 100 characters before truncating the notification "body" with ellipsis.
  200. // The message would not be changed (unless truncated for being too long). Note: if the payload is too large (>4KB),
  201. // APNS will simply reject / discard the notification, meaning it will never arrive on the iOS device.
  202. func maybeTruncateAPNSBodyMessage(s string) string {
  203. if len(s) >= fcmApnsBodyMessageLimit {
  204. over := len(s) - fcmApnsBodyMessageLimit + 3 // len("...")
  205. return s[:len(s)-over] + "..."
  206. }
  207. return s
  208. }