fcm

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 5, 2024 License: GPL-2.0 Imports: 12 Imported by: 0

README

go-fcm : FCM Library for Go

Donate AUR

Firebase Cloud Messaging ( FCM ) Library using golang ( Go )

This library uses HTTP/JSON Firebase Cloud Messaging connection server protocol

Features
  • Send messages to a topic
  • Send messages to a device list
  • Message can be a notification or data payload
  • Supports condition attribute (fcm only)
  • Instace Id Features
    • Get info about app Instance
    • Subscribe app Instance to a topic
    • Batch Subscribe/Unsubscribe to/from a topic
    • Create registration tokens for APNs tokens

Usage

go get github.com/NaySoftware/go-fcm

Docs - go-fcm API

https://godoc.org/github.com/NaySoftware/go-fcm
Firebase Cloud Messaging HTTP Protocol Specs
https://firebase.google.com/docs/cloud-messaging/http-server-ref
Firebase Cloud Messaging Developer docs
https://firebase.google.com/docs/cloud-messaging/
(Google) Instance Id Server Reference
https://developers.google.com/instance-id/reference/server
Notes

a note from firebase console

Firebase Cloud Messaging tokens have replaced server keys for
sending messages. While you may continue to use them, support
is being deprecated for server keys.
Firebase Cloud Messaging token ( new token )

serverKey variable will also hold the new FCM token by Firebase Cloud Messaging

Firebase Cloud Messaging token can be found in:

  1. Firebase project settings
  2. Cloud Messaging
  3. then copy the Firebase Cloud Messaging token
Server Key

serverKey is the server key by Firebase Cloud Messaging

Server Key can be found in:

  1. Firebase project settings
  2. Cloud Messaging
  3. then copy the server key

[will be deprecated by firabase as mentioned above!]

Retry mechanism

Retry should be implemented based on the requirements. Sending a request will result with a "FcmResponseStatus" struct, which holds a detailed information based on the Firebase Response, with RetryAfter (response header) if available - with a failed request. its recommended to use a backoff time to retry the request - (if RetryAfter header is not available).

Examples

Send to A topic

package main

import (
	"fmt"
    "github.com/NaySoftware/go-fcm"
)

const (
	 serverKey = "YOUR-KEY"
     topic = "/topics/someTopic"
)

func main() {

	data := map[string]string{
		"msg": "Hello World1",
		"sum": "Happy Day",
	}

	c := fcm.NewFcmClient(serverKey)
	c.NewFcmMsgTo(topic, data)


	status, err := c.Send()


	if err == nil {
    status.PrintResults()
	} else {
		fmt.Println(err)
	}

}


Send to a list of Devices (tokens)

package main

import (
	"fmt"
    "github.com/NaySoftware/go-fcm"
)

const (
	 serverKey = "YOUR-KEY"
)

func main() {

	data := map[string]string{
		"msg": "Hello World1",
		"sum": "Happy Day",
	}

  ids := []string{
      "token1",
  }


  xds := []string{
      "token5",
      "token6",
      "token7",
  }

	c := fcm.NewFcmClient(serverKey)
    c.NewFcmRegIdsMsg(ids, data)
    c.AppendDevices(xds)

	status, err := c.Send()


	if err == nil {
    status.PrintResults()
	} else {
		fmt.Println(err)
	}

}



Documentation

Index

Constants

View Source
const (

	// MAX_TTL the default ttl for a notification
	MAX_TTL = 2419200
	// Priority_HIGH notification priority
	Priority_HIGH = "high"
	// Priority_NORMAL notification priority
	Priority_NORMAL = "normal"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AndroidConfig

type AndroidConfig struct {
	CollapseKey           string                     `json:"collapse_key,omitempty"`
	Priority              string                     `json:"priority,omitempty"`
	Ttl                   string                     `json:"ttl,omitempty"`
	RestrictedPackageName string                     `json:"restricted_package_name,omitempty"`
	Data                  map[string]string          `json:"data,omitempty"`
	Notification          AndroidNotificationPayload `json:"notification,omitempty"`
}

AndroidConfig represents the configuration options for Android notifications

type AndroidNotificationPayload

type AndroidNotificationPayload struct {
	Title             string `json:"title,omitempty"`
	Body              string `json:"body,omitempty"`
	Icon              string `json:"icon,omitempty"`
	Color             string `json:"color,omitempty"`
	Sound             string `json:"sound,omitempty"`
	NotificationCount int    `json:"notification_count,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"`
}

AndroidNotificationPayload represents the notification payload specific to Android

type ApnsBatchRequest

type ApnsBatchRequest struct {
	App        string   `json:"application,omitempty"`
	Sandbox    bool     `json:"sandbox,omitempty"`
	ApnsTokens []string `json:"apns_tokens,omitempty"`
}

ApnsBatchRequest apns import request

func (*ApnsBatchRequest) ToByte

func (this *ApnsBatchRequest) ToByte() ([]byte, error)

ToByte converts ApnsBatchRequest to a byte

type ApnsBatchResponse

type ApnsBatchResponse struct {
	Results    []map[string]string `json:"results,omitempty"`
	Error      string              `json:"error,omitempty"`
	Status     string
	StatusCode int
}

ApnsBatchResponse apns import response

func (*ApnsBatchResponse) PrintResults

func (this *ApnsBatchResponse) PrintResults()

PrintResults prints ApnsBatchResponse, for faster debugging

type BatchRequest

type BatchRequest struct {
	To        string   `json:"to,omitempty"`
	RegTokens []string `json:"registration_tokens,omitempty"`
}

BatchRequest add/remove request

type BatchResponse

type BatchResponse struct {
	Error      string              `json:"error,omitempty"`
	Results    []map[string]string `json:"results,omitempty"`
	Status     string
	StatusCode int
}

BatchResponse add/remove response

func (*BatchResponse) PrintResults

func (this *BatchResponse) PrintResults()

PrintResults prints BatchResponse, for faster debugging

type FcmClient

type FcmClient struct {
	ApiKey      string
	Message     FcmMsg
	UseV1Api    bool   // Flag to switch between legacy and v1 API
	V1ProjectID string // Project ID required for v1 API
	// contains filtered or unexported fields
}

FcmClient stores the key and the Message (FcmMsg)

func NewFcmClient

func NewFcmClient(apiKey string, gcmCredentials GcmCredentialsV2) *FcmClient

NewFcmClient init and create fcm client func NewFcmClient(apiKey string, useV1Api bool, v1ProjectID string, gcmCredentials GcmCredentialsV2) *FcmClient {

func (*FcmClient) ApnsBatchImportRequest

func (this *FcmClient) ApnsBatchImportRequest(apnsReq *ApnsBatchRequest) (*ApnsBatchResponse, error)

ApnsBatchImportRequest apns import requst

func (*FcmClient) AppendDevices

func (this *FcmClient) AppendDevices(list []string) *FcmClient

AppendDevices adds more devices/tokens to the Fcm request

func (*FcmClient) BatchSubscribeToTopic

func (this *FcmClient) BatchSubscribeToTopic(tokens []string, topic string) (*BatchResponse, error)

BatchSubscribeToTopic subscribes (many) devices/tokens to a given topic

func (*FcmClient) BatchUnsubscribeFromTopic

func (this *FcmClient) BatchUnsubscribeFromTopic(tokens []string, topic string) (*BatchResponse, error)

BatchUnsubscribeFromTopic unsubscribes (many) devices/tokens from a given topic

func (*FcmClient) GetInfo

func (this *FcmClient) GetInfo(withDetails bool, instanceIdToken string) (*InstanceIdInfoResponse, error)

GetInfo gets the instance id info

func (*FcmClient) NewFcmMsgTo

func (this *FcmClient) NewFcmMsgTo(to string, body interface{}) *FcmClient

NewFcmMsgTo sets the targeted token/topic and the data payload

func (*FcmClient) NewFcmRegIdsMsg

func (this *FcmClient) NewFcmRegIdsMsg(list []string, body interface{}) *FcmClient

NewFcmRegIdsMsg gets a list of devices with data payload

func (*FcmClient) NewFcmTopicMsg

func (this *FcmClient) NewFcmTopicMsg(to string, body map[string]string) *FcmClient

NewFcmTopicMsg sets the targeted token/topic and the data payload

func (*FcmClient) Send

func (this *FcmClient) Send() (*FcmResponseStatus, error)

Send to fcm

func (*FcmClient) SetCollapseKey

func (this *FcmClient) SetCollapseKey(val string) *FcmClient

SetCollapseKey This parameter identifies a group of messages (e.g., with collapse_key: "Updates Available") that can be collapsed, so that only the last message gets sent when delivery can be resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active (see delay_while_idle).

func (*FcmClient) SetCondition

func (this *FcmClient) SetCondition(condition string) *FcmClient

SetCondition to set a logical expression of conditions that determine the message target

func (*FcmClient) SetContentAvailable

func (this *FcmClient) SetContentAvailable(isContentAvailable bool) *FcmClient

SetContentAvailable On iOS, use this field to represent content-available in the APNS payload. When a notification or message is sent and this is set to true, an inactive client app is awoken. On Android, data messages wake the app by default. On Chrome, currently not supported.

func (*FcmClient) SetDelayWhileIdle

func (this *FcmClient) SetDelayWhileIdle(isDelayWhileIdle bool) *FcmClient

SetDelayWhileIdle When this parameter is set to true, it indicates that the message should not be sent until the device becomes active. The default value is false.

func (*FcmClient) SetDryRun

func (this *FcmClient) SetDryRun(drun bool) *FcmClient

SetDryRun This parameter, when set to true, allows developers to test a request without actually sending a message. The default value is false

func (*FcmClient) SetMsgData

func (this *FcmClient) SetMsgData(body interface{}) *FcmClient

SetMsgData sets data payload

func (*FcmClient) SetNotificationPayload

func (this *FcmClient) SetNotificationPayload(payload *NotificationPayload) *FcmClient

SetNotificationPayload sets the notification payload based on the specs https://firebase.google.com/docs/cloud-messaging/http-server-ref

func (*FcmClient) SetPriority

func (this *FcmClient) SetPriority(p string) *FcmClient

SetPriority Sets the priority of the message. Priority_HIGH or Priority_NORMAL

func (*FcmClient) SetRestrictedPackageName

func (this *FcmClient) SetRestrictedPackageName(pkg string) *FcmClient

SetRestrictedPackageName This parameter specifies the package name of the application where the registration tokens must match in order to receive the message.

func (*FcmClient) SetTimeToLive

func (this *FcmClient) SetTimeToLive(ttl int) *FcmClient

SetTimeToLive This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks. For more information, see https://firebase.google.com/docs/cloud-messaging/concept-options#ttl

func (*FcmClient) SubscribeToTopic

func (this *FcmClient) SubscribeToTopic(instanceIdToken string, topic string) (*SubscribeResponse, error)

SubscribeToTopic subscribes a single device/token to a topic

type FcmMsg

type FcmMsg struct {
	Data                  interface{}         `json:"data,omitempty"`
	To                    string              `json:"to,omitempty"`
	RegistrationIds       []string            `json:"registration_ids,omitempty"`
	CollapseKey           string              `json:"collapse_key,omitempty"`
	Priority              string              `json:"priority,omitempty"`
	Notification          NotificationPayload `json:"notification,omitempty"`
	ContentAvailable      bool                `json:"content_available,omitempty"`
	DelayWhileIdle        bool                `json:"delay_while_idle,omitempty"`
	TimeToLive            int                 `json:"time_to_live,omitempty"`
	RestrictedPackageName string              `json:"restricted_package_name,omitempty"`
	DryRun                bool                `json:"dry_run,omitempty"`
	Condition             string              `json:"condition,omitempty"`
}

FcmMsg represents fcm request message

type FcmMsgV1

type FcmMsgV1 struct {
	Message V1Message `json:"message"`
}

FcmMsgV1 represents the v1 FCM request message

type FcmOptions

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

FcmOptions represents the options for FCM messages

type FcmResponseStatus

type FcmResponseStatus struct {
	Ok            bool
	StatusCode    int
	MulticastId   int64               `json:"multicast_id"`
	Success       int                 `json:"success"`
	Fail          int                 `json:"failure"`
	Canonical_ids int                 `json:"canonical_ids"`
	Results       []map[string]string `json:"results,omitempty"`
	MsgId         int64               `json:"message_id,omitempty"`
	Err           string              `json:"error,omitempty"`
	RetryAfter    string
}

FcmResponseStatus represents fcm response message - (tokens and topics)

func (*FcmResponseStatus) GetRetryAfterTime

func (this *FcmResponseStatus) GetRetryAfterTime() (t time.Duration, e error)

GetRetryAfterTime fs the retrey after response header to a time.Duration

func (*FcmResponseStatus) IsTimeout

func (this *FcmResponseStatus) IsTimeout() bool

IsTimeout check whether the response timeout based on http response status code and if any error is retryable

func (*FcmResponseStatus) PrintResults

func (this *FcmResponseStatus) PrintResults()

PrintResults prints the FcmResponseStatus results for fast using and debugging

type FcmV1Error

type FcmV1Error struct {
	Code    int                `json:"code"`
	Message string             `json:"message"`
	Status  string             `json:"status"`
	Details []FcmV1ErrorDetail `json:"details"`
}

type FcmV1ErrorDetail

type FcmV1ErrorDetail struct {
	Type      string `json:"@type"`
	ErrorCode string `json:"errorCode"`
}

type FcmV1Response

type FcmV1Response struct {
	Name  string     `json:"name"`
	Error FcmV1Error `json:"error"`
}

type GcmCredentialsV2

type GcmCredentialsV2 struct {
	Type                    string `json:"type" bson:"type"`
	ProjectID               string `json:"project_id" bson:"project_id"`
	PrivateKeyID            string `json:"private_key_id" bson:"private_key_id"`
	PrivateKey              string `json:"private_key" bson:"private_key"`
	ClientEmail             string `json:"client_email" bson:"client_email"`
	ClientID                string `json:"client_id" bson:"client_id"`
	AuthURI                 string `json:"auth_uri" bson:"auth_uri"`
	TokenURI                string `json:"token_uri" bson:"token_uri"`
	AuthProviderX509CertURL string `json:"auth_provider_x509_cert_url" bson:"auth_provider_x509_cert_url"`
	ClientX509CertURL       string `json:"client_x509_cert_url" bson:"client_x509_cert_url"`
}

GcmCredentialsV2 represents the structure for credentials (assuming this is defined)

type InstanceIdInfoResponse

type InstanceIdInfoResponse struct {
	Application        string                                  `json:"application,omitempty"`
	AuthorizedEntity   string                                  `json:"authorizedEntity,omitempty"`
	ApplicationVersion string                                  `json:"applicationVersion,omitempty"`
	AppSigner          string                                  `json:"appSigner,omitempty"`
	AttestStatus       string                                  `json:"attestStatus,omitempty"`
	Platform           string                                  `json:"platform,omitempty"`
	ConnectionType     string                                  `json:"connectionType,omitempty"`
	ConnectDate        string                                  `json:"connectDate,omitempty"`
	Error              string                                  `json:"error,omitempty"`
	Rel                map[string]map[string]map[string]string `json:"rel,omitempty"`
}

InstanceIdInfoResponse response for instance id info request

func (*InstanceIdInfoResponse) PrintResults

func (this *InstanceIdInfoResponse) PrintResults()

PrintResults prints InstanceIdInfoResponse, for faster debugging

type NotificationPayload

type NotificationPayload struct {
	Title            string `json:"title,omitempty"`
	Body             string `json:"body,omitempty"`
	Icon             string `json:"icon,omitempty"`
	Sound            string `json:"sound,omitempty"`
	Badge            string `json:"badge,omitempty"`
	Tag              string `json:"tag,omitempty"`
	Color            string `json:"color,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"`
	AndroidChannelID string `json:"android_channel_id,omitempty"`
}

NotificationPayload notification message payload

type SubscribeResponse

type SubscribeResponse struct {
	Error      string `json:"error,omitempty"`
	Status     string
	StatusCode int
}

SubscribeResponse response for single topic subscribtion

func (*SubscribeResponse) PrintResults

func (this *SubscribeResponse) PrintResults()

PrintResults prints SubscribeResponse, for faster debugging

type V1Message

type V1Message struct {
	Token        string              `json:"token,omitempty"`
	Topic        string              `json:"topic,omitempty"`
	Condition    string              `json:"condition,omitempty"`
	Notification NotificationPayload `json:"notification,omitempty"`
	Data         map[string]string   `json:"data,omitempty"`
	Android      *AndroidConfig      `json:"android,omitempty"`
	FcmOptions   *FcmOptions         `json:"fcm_options,omitempty"`
}

Jump to

Keyboard shortcuts

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