fcm

package module
v0.0.0-...-67b3f37 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2019 License: GPL-2.0 Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 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
}

FcmClient stores the key and the Message (FcmMsg)

func NewFcmClient

func NewFcmClient(apiKey string) *FcmClient

NewFcmClient init and create fcm client

func (*FcmClient) ApnsBatchImportRequest

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

ApnsBatchImportRequest apns import requst

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) Send

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

Send to fcm

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 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
}

FcmMsg represents fcm response message - (tokens and topics)

func (*FcmResponseStatus) GetRetryAfterTime

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

GetRetryAfterTime converts 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 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"`
}

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

Jump to

Keyboard shortcuts

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