apns

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2020 License: MIT Imports: 14 Imported by: 1

README

apns

GoDoc Build Status Go Report Card

Golang client library for Apple Push Notification service via HTTP2. More information on Apple Push Notification Service

Getting Started

Here is a simple example illustrating how to use APNS library:

package main

import (
	"github.com/edganiukov/apns"
)

func main() {
	data, err := ioutil.ReadFile("private_key.pem")
	if err != nil {
		log.Fatal(err)
	}

	c, err := apns.NewClient(
		apns.WithJWT(data, "key_identifier", "team_identifier"),
		apns.WithBundleID("bundle_idetifier"),
		apns.WithMaxIdleConnections(10),
		apns.WithTimeout(5*time.Second),
	)
	if err != nil {
		/* ... */
	}
	resp, err := c.Send("<device token>",
		apns.Payload{
			APS: apns.APS{
				Alert: apns.Alert{
					Title: "Test Push",
					Body:  "Hi world",
				},
			},
		},
		apns.WithExpiration(10),
		apns.WithCollapseID("test-collapse-id"),
		apns.WithPriority(5),
	)

	if err != nil {
		/* ... */
	}
}

In case, if you wanna use TLS certificate instead of JWT Token, then should use apns.WithCertificate and apns.WithBundleID CallOptions to specify certificate and bundle ID, that are needed to send pushes.

Documentation

Index

Constants

View Source
const (
	DevelopmentGateway = "https://api.development.push.apple.com"
	ProductionGateway  = "https://api.push.apple.com"
)

APN service endpoint URLs.

Variables

View Source
var (
	ErrBadCollapseID               = errors.New("collapse identifier exceeds the maximum allowed size")
	ErrBadDeviceToken              = errors.New("specified device token was bad")
	ErrBadExpirationDate           = errors.New("apns-expiration value is bad")
	ErrBadMessageID                = errors.New("apns-id value is bad")
	ErrBadPriority                 = errors.New("apns-priority value is bad")
	ErrBadTopic                    = errors.New("apns-topic was invalid")
	ErrDeviceTokenNotForTopic      = errors.New("device token does not match the specified topic")
	ErrDuplicateHeaders            = errors.New("one or more headers were repeated")
	ErrIdleTimeout                 = connError("idle time out")
	ErrMissingDeviceToken          = errors.New("device token is not specified in the request path")
	ErrMissingTopic                = errors.New("apns-topic header of the request was not specified and was required")
	ErrPayloadEmpty                = errors.New("message payload was empty")
	ErrTopicDisallowed             = errors.New("pushing to this topic is not allowed")
	ErrBadCertificate              = errors.New("certificate was bad")
	ErrBadCertificateEnvironment   = errors.New("client certificate was for the wrong environment")
	ErrExpiredProviderToken        = errors.New("provider token is stale and a new token should be generated")
	ErrForbidden                   = errors.New("specified action is not allowed")
	ErrInvalidProviderToken        = errors.New("provider token is not valid or the token signature could not be verified")
	ErrMissingProviderToken        = errors.New("no provider certificate was used to connect to APNs and Authorization header was missing")
	ErrBadPath                     = errors.New("request contained a bad :path value")
	ErrMethodNotAllowed            = errors.New("specified method was not POST")
	ErrUnregistered                = errors.New("device token is inactive for the specified topic")
	ErrPayloadTooLarge             = errors.New("message payload was too large")
	ErrTooManyProviderTokenUpdates = errors.New("provider token is being updated too often")
	ErrTooManyRequests             = errors.New("too many requests were made consecutively to the same device token")
	ErrInternalServerError         = serverError("an internal server error occurred")
	ErrServiceUnavailable          = serverError("service is unavailable")
	ErrShutdown                    = serverError("the server is shutting down")
)

Possible error codes included in the reason key of a response’s JSON payload.

Functions

This section is empty.

Types

type APS

type APS struct {
	// Alert dictionary.
	Alert Alert `json:"alert,omitempty"`

	// Badge to display on the app icon.
	Badge *int `json:"badge,omitempty"`

	// Sound is the name of a sound file to play as an alert.
	Sound string `json:"sound,omitempty"`

	// ThreadID presents the app-specific identifier for grouping notifications.
	ThreadID string `json:"thread-id,omitempty"`

	// Category identifier for custom actions in iOS 8 or newer.
	Category string `json:"category,omitempty"`

	// Content available apps launched in the background or resumed.
	ContentAvailable *int `json:"content-available,omitempty"`

	// The notification service app extension flag. If the value is 1, the system passes the notification to your notification service app extension before delivery.
	MutableContent *int `json:"mutable-content,omitempty"`

	// The identifier of the window brought forward. The value of this key will be populated on the UNNotificationContent object created from the push payload.
	TargetContentID string `json:"target-content-id,omitempty"`
}

APS is Apple's reserved payload.

type Alert

type Alert struct {
	Title           string   `json:"title,omitempty"`
	Subtitle        string   `json:"subtitle,omitempty"`
	Body            string   `json:"body,omitempty"`
	LaunchImage     string   `json:"launch-image,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"`
	LocKey          string   `json:"loc-key,omitempty"`
	LocArgs         []string `json:"loc-args,omitempty"`
}

Alert represents aler dictionary.

type Client

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

Client represents the Apple Push Notification Service that you send notifications to.

func NewClient

func NewClient(opts ...ClientOption) (*Client, error)

NewClient creates new AONS client based on defined Options.

func (*Client) Send

func (c *Client) Send(token string, p Payload, opts ...SendOption) (*Response, error)

Send sends Notification to the APN service.

type ClientOption

type ClientOption func(c *Client) error

ClientOption defines athe APNS Client option.

func WithBundleID

func WithBundleID(bundleID string) ClientOption

WithBundleID sets HTTP2 header `apns-topic` with is bundle ID of an app. The certificate you create in your developer account must include the capability for this topic. If your certificate includes multiple topics, you must specify a value for this header. If you omit this request header and your APNs certificate does not specify multiple topics, the APNs server uses the certificate’s Subject as the default topic. If you are using a provider token instead of a certificate, you must specify a value for this request header. The topic you provide should be provisioned for the your team named in your developer account.

func WithCertificate

func WithCertificate(crt tls.Certificate) ClientOption

WithCertificate is Option to configure TLS certificates for HTTP connection. Certificates should be used with BundleID, that is possible to set by `WithBundleID` option.

func WithEndpoint

func WithEndpoint(endpoint string) ClientOption

WithEndpoint specifies custom APN endpoint. Useful for test propose.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets custom HTTP Client.

func WithJWT added in v0.1.1

func WithJWT(privateKey []byte, keyID string, issuer string) ClientOption

WithJWT sets the JWT struct that authorizes APNs to send push notifications for the specified topics. The token is in Base64URL-encoded JWT format, specified as `bearer <provider token>`.

func WithMaxIdleConnections

func WithMaxIdleConnections(maxIdleConn int) ClientOption

WithMaxIdleConnections sets maximum number of the idle HTTP connection that can be reused in order do not create new connection.

func WithTimeout

func WithTimeout(t time.Duration) ClientOption

WithTimeout sets HTTP Client timeout.

type JWT added in v0.1.1

type JWT struct {
	PrivateKey *ecdsa.PrivateKey
	Issuer     string
	KeyID      string
}

JWT represents data for JWT token generation.

type Payload

type Payload struct {
	APS          APS
	CustomValues map[string]interface{}
}

Payload repsresents a data structure for APN notification.

func (Payload) MarshalJSON

func (p Payload) MarshalJSON() ([]byte, error)

MarshalJSON converts Payload structure to the byte array. Implements json.Marshaler interface.

type Response

type Response struct {
	NotificationID string
	Timestamp      int64
	Error          error
}

Response represents response object from APN service.

func (*Response) UnmarshalJSON

func (r *Response) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type SendOption

type SendOption func(h http.Header)

SendOption allows to set custom Headers for each notification, such apns-id, expiration time, priority, etc.

func WithCollapseID

func WithCollapseID(id string) SendOption

WithCollapseID sets commond idetifier for Multiple notifications, which will be displayed to the user as a single notification. The value of this key must not exceed 64 bytes.

func WithExpiration

func WithExpiration(timeExpr int) SendOption

WithExpiration sets a headers, that identifies the date when the notification is no longer valid and can be discarded. If this value is nonzero, APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed if it is unable to deliver the notification the first time. If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.

func WithNotificationID

func WithNotificationID(id string) SendOption

WithNotificationID sets a canonical UUID that identifies the notification. If there is an error sending the notification, APNs uses this value to identify the notification to your server. The canonical form is 32 lowercase hexadecimal digits, displayed in five groups separated by hyphens in the form 8-4-4-4-12. If you omit this option, a new UUID is created by APNs and returned in the response.

func WithPriority

func WithPriority(priority int) SendOption

WithPriority specifies the priority of the notification. Specify one of the following values: * 10 - Send the push message immediately. Notifications with this priority must trigger an alert, sound, or badge on the target device. It is an error to use this priority for a push notification that contains only the content-available key. * 5 - Send the push message at a time that takes into account power considerations for the device. Notifications with this priority might be grouped and delivered in bursts. They are throttled, and in some cases are not delivered.

Jump to

Keyboard shortcuts

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