messaging

package
v3.13.0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2020 License: Apache-2.0 Imports: 19 Imported by: 400

Documentation

Overview

Package messaging contains functions for sending messages and managing device subscriptions with Firebase Cloud Messaging (FCM).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsInternal

func IsInternal(err error) bool

IsInternal checks if the given error was due to an internal server error.

func IsInvalidAPNSCredentials

func IsInvalidAPNSCredentials(err error) bool

IsInvalidAPNSCredentials checks if the given error was due to invalid APNS certificate or auth key.

func IsInvalidArgument

func IsInvalidArgument(err error) bool

IsInvalidArgument checks if the given error was due to an invalid argument in the request.

func IsMessageRateExceeded

func IsMessageRateExceeded(err error) bool

IsMessageRateExceeded checks if the given error was due to the client exceeding a quota.

func IsMismatchedCredential

func IsMismatchedCredential(err error) bool

IsMismatchedCredential checks if the given error was due to an invalid credential or permission error.

func IsRegistrationTokenNotRegistered

func IsRegistrationTokenNotRegistered(err error) bool

IsRegistrationTokenNotRegistered checks if the given error was due to a registration token that became invalid.

func IsServerUnavailable

func IsServerUnavailable(err error) bool

IsServerUnavailable checks if the given error was due to the backend server being temporarily unavailable.

func IsTooManyTopics

func IsTooManyTopics(err error) bool

IsTooManyTopics checks if the given error was due to the client exceeding the allowed number of topics.

func IsUnknown

func IsUnknown(err error) bool

IsUnknown checks if the given error was due to unknown error returned by the backend server.

Types

type APNSConfig

type APNSConfig struct {
	Headers    map[string]string `json:"headers,omitempty"`
	Payload    *APNSPayload      `json:"payload,omitempty"`
	FCMOptions *APNSFCMOptions   `json:"fcm_options,omitempty"`
}

APNSConfig contains messaging options specific to the Apple Push Notification Service (APNS).

See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html for more details on supported headers and payload keys.

type APNSFCMOptions

type APNSFCMOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
	ImageURL       string `json:"image,omitempty"`
}

APNSFCMOptions contains additional options for features provided by the FCM Aps SDK.

type APNSPayload

type APNSPayload struct {
	Aps        *Aps                   `json:"aps,omitempty"`
	CustomData map[string]interface{} `json:"-"`
}

APNSPayload is the payload that can be included in an APNS message.

The payload mainly consists of the aps dictionary. Additionally it may contain arbitrary key-values pairs as custom data fields.

See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html for a full list of supported payload fields.

func (*APNSPayload) MarshalJSON

func (p *APNSPayload) MarshalJSON() ([]byte, error)

MarshalJSON marshals an APNSPayload into JSON (for internal use only).

func (*APNSPayload) UnmarshalJSON

func (p *APNSPayload) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into an APNSPayload (for internal use only).

type AndroidConfig

type AndroidConfig struct {
	CollapseKey           string               `json:"collapse_key,omitempty"`
	Priority              string               `json:"priority,omitempty"` // one of "normal" or "high"
	TTL                   *time.Duration       `json:"-"`
	RestrictedPackageName string               `json:"restricted_package_name,omitempty"`
	Data                  map[string]string    `json:"data,omitempty"` // if specified, overrides the Data field on Message type
	Notification          *AndroidNotification `json:"notification,omitempty"`
	FCMOptions            *AndroidFCMOptions   `json:"fcm_options,omitempty"`
}

AndroidConfig contains messaging options specific to the Android platform.

func (*AndroidConfig) MarshalJSON

func (a *AndroidConfig) MarshalJSON() ([]byte, error)

MarshalJSON marshals an AndroidConfig into JSON (for internal use only).

func (*AndroidConfig) UnmarshalJSON

func (a *AndroidConfig) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into an AndroidConfig (for internal use only).

type AndroidFCMOptions

type AndroidFCMOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
}

AndroidFCMOptions contains additional options for features provided by the FCM Android SDK.

type AndroidNotification

type AndroidNotification struct {
	Title                 string                        `json:"title,omitempty"` // if specified, overrides the Title field of the Notification type
	Body                  string                        `json:"body,omitempty"`  // if specified, overrides the Body field of the Notification type
	Icon                  string                        `json:"icon,omitempty"`
	Color                 string                        `json:"color,omitempty"` // notification color in #RRGGBB format
	Sound                 string                        `json:"sound,omitempty"`
	Tag                   string                        `json:"tag,omitempty"`
	ClickAction           string                        `json:"click_action,omitempty"`
	BodyLocKey            string                        `json:"body_loc_key,omitempty"`
	BodyLocArgs           []string                      `json:"body_loc_args,omitempty"`
	TitleLocKey           string                        `json:"title_loc_key,omitempty"`
	TitleLocArgs          []string                      `json:"title_loc_args,omitempty"`
	ChannelID             string                        `json:"channel_id,omitempty"`
	ImageURL              string                        `json:"image,omitempty"`
	Ticker                string                        `json:"ticker,omitempty"`
	Sticky                bool                          `json:"sticky,omitempty"`
	EventTimestamp        *time.Time                    `json:"-"`
	LocalOnly             bool                          `json:"local_only,omitempty"`
	Priority              AndroidNotificationPriority   `json:"-"`
	VibrateTimingMillis   []int64                       `json:"-"`
	DefaultVibrateTimings bool                          `json:"default_vibrate_timings,omitempty"`
	DefaultSound          bool                          `json:"default_sound,omitempty"`
	LightSettings         *LightSettings                `json:"light_settings,omitempty"`
	DefaultLightSettings  bool                          `json:"default_light_settings,omitempty"`
	Visibility            AndroidNotificationVisibility `json:"-"`
	NotificationCount     *int                          `json:"notification_count,omitempty"`
}

AndroidNotification is a notification to send to Android devices.

func (*AndroidNotification) MarshalJSON

func (a *AndroidNotification) MarshalJSON() ([]byte, error)

MarshalJSON marshals an AndroidNotification into JSON (for internal use only).

func (*AndroidNotification) UnmarshalJSON

func (a *AndroidNotification) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into an AndroidNotification (for internal use only).

type AndroidNotificationPriority

type AndroidNotificationPriority int

AndroidNotificationPriority represents the priority levels of a notification.

const (

	// PriorityMin is the lowest notification priority. Notifications with this priority might not
	// be shown to the user except under special circumstances, such as detailed notification logs.
	PriorityMin AndroidNotificationPriority

	// PriorityLow is a lower notification priority. The UI may choose to show the notifications
	// smaller, or at a different position in the list, compared with notifications with PriorityDefault.
	PriorityLow

	// PriorityDefault is the default notification priority. If the application does not prioritize
	// its own notifications, use this value for all notifications.
	PriorityDefault

	// PriorityHigh is a higher notification priority. Use this for more important
	// notifications or alerts. The UI may choose to show these notifications larger, or at a
	// different position in the notification lists, compared with notifications with PriorityDefault.
	PriorityHigh

	// PriorityMax is the highest notification priority. Use this for the application's most
	// important items that require the user's prompt attention or input.
	PriorityMax
)

type AndroidNotificationVisibility

type AndroidNotificationVisibility int

AndroidNotificationVisibility represents the different visibility levels of a notification.

const (

	// VisibilityPrivate shows this notification on all lockscreens, but conceal sensitive or
	// private information on secure lockscreens.
	VisibilityPrivate AndroidNotificationVisibility

	// VisibilityPublic shows this notification in its entirety on all lockscreens.
	VisibilityPublic

	// VisibilitySecret does not reveal any part of this notification on a secure lockscreen.
	VisibilitySecret
)

type Aps

type Aps struct {
	AlertString      string                 `json:"-"`
	Alert            *ApsAlert              `json:"-"`
	Badge            *int                   `json:"badge,omitempty"`
	Sound            string                 `json:"-"`
	CriticalSound    *CriticalSound         `json:"-"`
	ContentAvailable bool                   `json:"-"`
	MutableContent   bool                   `json:"-"`
	Category         string                 `json:"category,omitempty"`
	ThreadID         string                 `json:"thread-id,omitempty"`
	CustomData       map[string]interface{} `json:"-"`
}

Aps represents the aps dictionary that may be included in an APNSPayload.

Alert may be specified as a string (via the AlertString field), or as a struct (via the Alert field).

func (*Aps) MarshalJSON

func (a *Aps) MarshalJSON() ([]byte, error)

MarshalJSON marshals an Aps into JSON (for internal use only).

func (*Aps) UnmarshalJSON

func (a *Aps) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into an Aps (for internal use only).

type ApsAlert

type ApsAlert struct {
	Title           string   `json:"title,omitempty"` // if specified, overrides the Title field of the Notification type
	SubTitle        string   `json:"subtitle,omitempty"`
	Body            string   `json:"body,omitempty"` // if specified, overrides the Body field of the Notification type
	LocKey          string   `json:"loc-key,omitempty"`
	LocArgs         []string `json:"loc-args,omitempty"`
	TitleLocKey     string   `json:"title-loc-key,omitempty"`
	TitleLocArgs    []string `json:"title-loc-args,omitempty"`
	SubTitleLocKey  string   `json:"subtitle-loc-key,omitempty"`
	SubTitleLocArgs []string `json:"subtitle-loc-args,omitempty"`
	ActionLocKey    string   `json:"action-loc-key,omitempty"`
	LaunchImage     string   `json:"launch-image,omitempty"`
}

ApsAlert is the alert payload that can be included in an Aps.

See https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html for supported fields.

type BatchResponse

type BatchResponse struct {
	SuccessCount int
	FailureCount int
	Responses    []*SendResponse
}

BatchResponse represents the response from the `SendAll()` and `SendMulticast()` APIs.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the interface for the Firebase Cloud Messaging (FCM) service.

func NewClient

func NewClient(ctx context.Context, c *internal.MessagingConfig) (*Client, error)

NewClient creates a new instance of the Firebase Cloud Messaging Client.

This function can only be invoked from within the SDK. Client applications should access the the messaging service through firebase.App.

func (Client) Send

func (c Client) Send(ctx context.Context, message *Message) (string, error)

Send sends a Message to Firebase Cloud Messaging.

The Message must specify exactly one of Token, Topic and Condition fields. FCM will customize the message for each target platform based on the arguments specified in the Message.

func (Client) SendAll

func (c Client) SendAll(ctx context.Context, messages []*Message) (*BatchResponse, error)

SendAll sends the messages in the given array via Firebase Cloud Messaging.

The messages array may contain up to 500 messages. SendAll employs batching to send the entire array of mssages as a single RPC call. Compared to the `Send()` function, this is a significantly more efficient way to send multiple messages. The responses list obtained from the return value corresponds to the order of the input messages. An error from SendAll indicates a total failure -- i.e. none of the messages in the array could be sent. Partial failures are indicated by a `BatchResponse` return value.

func (Client) SendAllDryRun

func (c Client) SendAllDryRun(ctx context.Context, messages []*Message) (*BatchResponse, error)

SendAllDryRun sends the messages in the given array via Firebase Cloud Messaging in the dry run (validation only) mode.

This function does not actually deliver any messages to target devices. Instead, it performs all the SDK-level and backend validations on the messages, and emulates the send operation.

The messages array may contain up to 500 messages. SendAllDryRun employs batching to send the entire array of mssages as a single RPC call. Compared to the `SendDryRun()` function, this is a significantly more efficient way to validate sending multiple messages. The responses list obtained from the return value corresponds to the order of the input messages. An error from SendAllDryRun indicates a total failure -- i.e. none of the messages in the array could be sent for validation. Partial failures are indicated by a `BatchResponse` return value.

func (Client) SendDryRun

func (c Client) SendDryRun(ctx context.Context, message *Message) (string, error)

SendDryRun sends a Message to Firebase Cloud Messaging in the dry run (validation only) mode.

This function does not actually deliver the message to target devices. Instead, it performs all the SDK-level and backend validations on the message, and emulates the send operation.

func (Client) SendMulticast

func (c Client) SendMulticast(ctx context.Context, message *MulticastMessage) (*BatchResponse, error)

SendMulticast sends the given multicast message to all the FCM registration tokens specified.

The tokens array in MulticastMessage may contain up to 500 tokens. SendMulticast uses the `SendAll()` function to send the given message to all the target recipients. The responses list obtained from the return value corresponds to the order of the input tokens. An error from SendMulticast indicates a total failure -- i.e. the message could not be sent to any of the recipients. Partial failures are indicated by a `BatchResponse` return value.

func (Client) SendMulticastDryRun

func (c Client) SendMulticastDryRun(ctx context.Context, message *MulticastMessage) (*BatchResponse, error)

SendMulticastDryRun sends the given multicast message to all the specified FCM registration tokens in the dry run (validation only) mode.

This function does not actually deliver any messages to target devices. Instead, it performs all the SDK-level and backend validations on the messages, and emulates the send operation.

The tokens array in MulticastMessage may contain up to 500 tokens. SendMulticastDryRun uses the `SendAllDryRun()` function to send the given message. The responses list obtained from the return value corresponds to the order of the input tokens. An error from SendMulticastDryRun indicates a total failure -- i.e. none of the messages were sent to FCM for validation. Partial failures are indicated by a `BatchResponse` return value.

func (Client) SubscribeToTopic

func (c Client) SubscribeToTopic(ctx context.Context, tokens []string, topic string) (*TopicManagementResponse, error)

SubscribeToTopic subscribes a list of registration tokens to a topic.

The tokens list must not be empty, and have at most 1000 tokens.

func (Client) UnsubscribeFromTopic

func (c Client) UnsubscribeFromTopic(ctx context.Context, tokens []string, topic string) (*TopicManagementResponse, error)

UnsubscribeFromTopic unsubscribes a list of registration tokens from a topic.

The tokens list must not be empty, and have at most 1000 tokens.

type CriticalSound

type CriticalSound struct {
	Critical bool    `json:"-"`
	Name     string  `json:"name,omitempty"`
	Volume   float64 `json:"volume,omitempty"`
}

CriticalSound is the sound payload that can be included in an Aps.

func (*CriticalSound) MarshalJSON

func (cs *CriticalSound) MarshalJSON() ([]byte, error)

MarshalJSON marshals a CriticalSound into JSON (for internal use only).

func (*CriticalSound) UnmarshalJSON

func (cs *CriticalSound) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into a CriticalSound (for internal use only).

type ErrorInfo

type ErrorInfo struct {
	Index  int
	Reason string
}

ErrorInfo is a topic management error.

type FCMOptions

type FCMOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
}

FCMOptions contains additional options to use across all platforms.

type LightSettings

type LightSettings struct {
	Color                  string
	LightOnDurationMillis  int64
	LightOffDurationMillis int64
}

LightSettings to control notification LED.

func (*LightSettings) MarshalJSON

func (l *LightSettings) MarshalJSON() ([]byte, error)

MarshalJSON marshals an LightSettings into JSON (for internal use only).

func (*LightSettings) UnmarshalJSON

func (l *LightSettings) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into an LightSettings (for internal use only).

type Message

type Message struct {
	Data         map[string]string `json:"data,omitempty"`
	Notification *Notification     `json:"notification,omitempty"`
	Android      *AndroidConfig    `json:"android,omitempty"`
	Webpush      *WebpushConfig    `json:"webpush,omitempty"`
	APNS         *APNSConfig       `json:"apns,omitempty"`
	FCMOptions   *FCMOptions       `json:"fcm_options,omitempty"`
	Token        string            `json:"token,omitempty"`
	Topic        string            `json:"-"`
	Condition    string            `json:"condition,omitempty"`
}

Message to be sent via Firebase Cloud Messaging.

Message contains payload data, recipient information and platform-specific configuration options. A Message must specify exactly one of Token, Topic or Condition fields. Apart from that a Message may specify any combination of Data, Notification, Android, Webpush and APNS fields. See https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages for more details on how the backend FCM servers handle different message parameters.

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

MarshalJSON marshals a Message into JSON (for internal use only).

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into a Message (for internal use only).

type MulticastMessage

type MulticastMessage struct {
	Tokens       []string
	Data         map[string]string
	Notification *Notification
	Android      *AndroidConfig
	Webpush      *WebpushConfig
	APNS         *APNSConfig
}

MulticastMessage represents a message that can be sent to multiple devices via Firebase Cloud Messaging (FCM).

It contains payload information as well as the list of device registration tokens to which the message should be sent. A single MulticastMessage may contain up to 500 registration tokens.

type Notification

type Notification struct {
	Title    string `json:"title,omitempty"`
	Body     string `json:"body,omitempty"`
	ImageURL string `json:"image,omitempty"`
}

Notification is the basic notification template to use across all platforms.

type SendResponse

type SendResponse struct {
	Success   bool
	MessageID string
	Error     error
}

SendResponse represents the status of an individual message that was sent as part of a batch request.

type TopicManagementResponse

type TopicManagementResponse struct {
	SuccessCount int
	FailureCount int
	Errors       []*ErrorInfo
}

TopicManagementResponse is the result produced by topic management operations.

TopicManagementResponse provides an overview of how many input tokens were successfully handled, and how many failed. In case of failures, the Errors list provides specific details concerning each error.

type WebpushConfig

type WebpushConfig struct {
	Headers      map[string]string    `json:"headers,omitempty"`
	Data         map[string]string    `json:"data,omitempty"`
	Notification *WebpushNotification `json:"notification,omitempty"`
	FcmOptions   *WebpushFcmOptions   `json:"fcm_options,omitempty"`
}

WebpushConfig contains messaging options specific to the WebPush protocol.

See https://tools.ietf.org/html/rfc8030#section-5 for additional details, and supported headers.

type WebpushFcmOptions

type WebpushFcmOptions struct {
	Link string `json:"link,omitempty"`
}

WebpushFcmOptions contains additional options for features provided by the FCM web SDK.

type WebpushNotification

type WebpushNotification struct {
	Actions            []*WebpushNotificationAction `json:"actions,omitempty"`
	Title              string                       `json:"title,omitempty"` // if specified, overrides the Title field of the Notification type
	Body               string                       `json:"body,omitempty"`  // if specified, overrides the Body field of the Notification type
	Icon               string                       `json:"icon,omitempty"`
	Badge              string                       `json:"badge,omitempty"`
	Direction          string                       `json:"dir,omitempty"` // one of 'ltr' or 'rtl'
	Data               interface{}                  `json:"data,omitempty"`
	Image              string                       `json:"image,omitempty"`
	Language           string                       `json:"lang,omitempty"`
	Renotify           bool                         `json:"renotify,omitempty"`
	RequireInteraction bool                         `json:"requireInteraction,omitempty"`
	Silent             bool                         `json:"silent,omitempty"`
	Tag                string                       `json:"tag,omitempty"`
	TimestampMillis    *int64                       `json:"timestamp,omitempty"`
	Vibrate            []int                        `json:"vibrate,omitempty"`
	CustomData         map[string]interface{}
}

WebpushNotification is a notification to send via WebPush protocol.

See https://developer.mozilla.org/en-US/docs/Web/API/notification/Notification for additional details.

func (*WebpushNotification) MarshalJSON

func (n *WebpushNotification) MarshalJSON() ([]byte, error)

MarshalJSON marshals a WebpushNotification into JSON (for internal use only).

func (*WebpushNotification) UnmarshalJSON

func (n *WebpushNotification) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a JSON string into a WebpushNotification (for internal use only).

type WebpushNotificationAction

type WebpushNotificationAction struct {
	Action string `json:"action,omitempty"`
	Title  string `json:"title,omitempty"`
	Icon   string `json:"icon,omitempty"`
}

WebpushNotificationAction represents an action that can be performed upon receiving a WebPush notification.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL