Categorygithub.com/sideshow/apns2
modulepackage
0.25.0
Repository: https://github.com/sideshow/apns2.git
Documentation: pkg.go.dev

# README

APNS/2

APNS/2 is a go package designed for simple, flexible and fast Apple Push Notifications on iOS, OSX and Safari using the new HTTP/2 Push provider API.

Build Status Coverage Status GoDoc

Features

  • Uses new Apple APNs HTTP/2 connection
  • Fast - See notes on speed
  • Works with go 1.7 and later
  • Supports new Apple Token Based Authentication (JWT)
  • Supports new iOS 10 features such as Collapse IDs, Subtitles and Mutable Notifications
  • Supports new iOS 15 features interruptionLevel and relevanceScore
  • Supports persistent connections to APNs
  • Supports VoIP/PushKit notifications (iOS 8 and later)
  • Modular & easy to use
  • Tested and working in APNs production environment

Install

  • Make sure you have Go installed and have set your GOPATH.
  • Install apns2:
go get -u github.com/sideshow/apns2

If you are running the test suite you will also need to install testify:

go get -u github.com/stretchr/testify

Example

package main

import (
  "log"
  "fmt"

  "github.com/sideshow/apns2"
  "github.com/sideshow/apns2/certificate"
)

func main() {

  cert, err := certificate.FromP12File("../cert.p12", "")
  if err != nil {
    log.Fatal("Cert Error:", err)
  }

  notification := &apns2.Notification{}
  notification.DeviceToken = "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7"
  notification.Topic = "com.sideshow.Apns2"
  notification.Payload = []byte(`{"aps":{"alert":"Hello!"}}`) // See Payload section below

  // If you want to test push notifications for builds running directly from XCode (Development), use
  // client := apns2.NewClient(cert).Development()
  // For apps published to the app store or installed as an ad-hoc distribution use Production()

  client := apns2.NewClient(cert).Production()
  res, err := client.Push(notification)

  if err != nil {
    log.Fatal("Error:", err)
  }

  fmt.Printf("%v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}

JWT Token Example

Instead of using a .p12 or .pem certificate as above, you can optionally use APNs JWT Provider Authentication Tokens. First you will need a signing key (.p8 file), Key ID and Team ID from Apple. Once you have these details, you can create a new client:

authKey, err := token.AuthKeyFromFile("../AuthKey_XXX.p8")
if err != nil {
  log.Fatal("token error:", err)
}

token := &token.Token{
  AuthKey: authKey,
  // KeyID from developer account (Certificates, Identifiers & Profiles -> Keys)
  KeyID:   "ABC123DEFG",
  // TeamID from developer account (View Account -> Membership)
  TeamID:  "DEF123GHIJ",
}
...

client := apns2.NewTokenClient(token)
res, err := client.Push(notification)
  • You can use one APNs signing key to authenticate tokens for multiple apps.
  • A signing key works for both the development and production environments.
  • A signing key doesn’t expire but can be revoked.

Notification

At a minimum, a Notification needs a DeviceToken, a Topic and a Payload.

notification := &apns2.Notification{
  DeviceToken: "11aa01229f15f0f0c52029d8cf8cd0aeaf2365fe4cebc4af26cd6d76b7919ef7",
  Topic: "com.sideshow.Apns2",
  Payload: []byte(`{"aps":{"alert":"Hello!"}}`),
}

You can also set an optional ApnsID, Expiration or Priority.

notification.ApnsID =  "40636A2C-C093-493E-936A-2A4333C06DEA"
notification.Expiration = time.Now()
notification.Priority = apns2.PriorityLow

Payload

You can use raw bytes for the notification.Payload as above, or you can use the payload builder package which makes it easy to construct APNs payloads.

// {"aps":{"alert":"hello","badge":1},"key":"val"}

payload := payload.NewPayload().Alert("hello").Badge(1).Custom("key", "val")

notification.Payload = payload
client.Push(notification)

Refer to the payload docs for more info.

Response, Error handling

APNS/2 draws the distinction between a valid response from Apple indicating whether or not the Notification was sent or not, and an unrecoverable or unexpected Error;

  • An Error is returned if a non-recoverable error occurs, i.e. if there is a problem with the underlying http.Client connection or Certificate, the payload was not sent, or a valid Response was not received.
  • A Response is returned if the payload was successfully sent to Apple and a documented response was received. This struct will contain more information about whether or not the push notification succeeded, its apns-id and if applicable, more information around why it did not succeed.

To check if a Notification was successfully sent;

res, err := client.Push(notification)
if err != nil {
  log.Println("There was an error", err)
  return
}

if res.Sent() {
  log.Println("Sent:", res.ApnsID)
} else {
  fmt.Printf("Not Sent: %v %v %v\n", res.StatusCode, res.ApnsID, res.Reason)
}

Context & Timeouts

For better control over request cancellations and timeouts APNS/2 supports contexts. Using a context can be helpful if you want to cancel all pushes when the parent process is cancelled, or need finer grained control over individual push timeouts. See the Google post for more information on contexts.

ctx, cancel = context.WithTimeout(context.Background(), 10 * time.Second)
res, err := client.PushWithContext(ctx, notification)
defer cancel()

Speed & Performance

Also see the wiki page on APNS HTTP 2 Push Speed.

For best performance, you should hold on to an apns2.Client instance and not re-create it every push. The underlying TLS connection itself can take a few seconds to connect and negotiate, so if you are setting up an apns2.Client and tearing it down every push, then this will greatly affect performance. (Apple suggest keeping the connection open all the time).

You should also limit the amount of apns2.Client instances. The underlying transport has a http connection pool itself, so a single client instance will be enough for most users (One instance can potentially do 4,000+ pushes per second). If you need more than this then one instance per CPU core is a good starting point.

Speed is greatly affected by the location of your server and the quality of your network connection. If you're just testing locally, behind a proxy or if your server is outside USA then you're not going to get great performance. With a good server located in AWS, you should be able to get decent throughput.

Command line tool

APNS/2 has a command line tool that can be installed with go get github.com/sideshow/apns2/apns2. Usage:

apns2 --help
usage: apns2 --certificate-path=CERTIFICATE-PATH --topic=TOPIC [<flags>]

Listens to STDIN to send notifications and writes APNS response code and reason to STDOUT.

The expected format is: <DeviceToken> <APNS Payload>
Example: aff0c63d9eaa63ad161bafee732d5bc2c31f66d552054718ff19ce314371e5d0 {"aps": {"alert": "hi"}}
Flags:
      --help               Show context-sensitive help (also try --help-long and --help-man).
  -c, --certificate-path=CERTIFICATE-PATH
                           Path to certificate file.
  -t, --topic=TOPIC        The topic of the remote notification, which is typically the bundle ID for your app
  -m, --mode="production"  APNS server to send notifications to. `production` or `development`. Defaults to `production`
      --version            Show application version.

License

The MIT License (MIT)

Copyright (c) 2016 Adam Jones

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Packages

Package certificate contains functions to load an Apple APNs PKCS#12 or PEM certificate from either an in memory byte array or a local file.
Package payload is a helper package which contains a payload builder to make constructing notification payloads easier.

# Functions

NewClient returns a new Client with an underlying http.Client configured with the correct APNs HTTP/2 transport settings.
NewClientManager returns a new ClientManager for prolonged, concurrent usage of multiple APNs clients.
NewTokenClient returns a new Client with an underlying http.Client configured with the correct APNs HTTP/2 transport settings.

# Constants

Apple HTTP/2 Development & Production urls.
Apple HTTP/2 Development & Production urls.
PriorityHigh will tell APNs to send the push message immediately.
PriorityLow will tell APNs to send the push message at a time that takes into account power considerations for the device.
PushTypeAlert is used for notifications that trigger a user interaction — for example, an alert, badge, or sound.
PushTypeBackground is used for notifications that deliver content in the background, and don’t trigger any user interactions.
PushTypeComplication is used for notifications that contain update information for a watchOS app’s complications.
PushTypeFileProvider is used to signal changes to a File Provider extension.
PushTypeLiveActivity is used for Live Activities that display various real-time information.
PushTypeLocation is used for notifications that request a user’s location.
PushTypeMDM is used for notifications that tell managed devices to contact the MDM server.
PushTypePushToTalk is used for notifications that provide information about the push to talk.
PushTypeVOIP is used for notifications that provide information about an incoming Voice-over-IP (VoIP) call.
403 The certificate was bad.
403 The client certificate was for the wrong environment.
400 The collapse identifier exceeds the maximum allowed size.
400 The specified device token was bad.
400 The apns-expiration value is bad.
400 The apns-id value is bad.
404 The request contained a bad :path value.
400 The apns-priority value is bad.
400 The apns-topic was invalid.
400 The device token does not match the specified topic.
400 One or more headers were repeated.
403 The provider token is stale and a new token should be generated.
410 The device token has expired.
403 The specified action is not allowed.
400 Idle time out.
500 An internal server error occurred.
403 The provider token is not valid or the token signature could not be verified.
400 The apns-push-type value is invalid.
405 The specified :method was not POST.
400 The device token is not specified in the request :path.
403 No provider certificate was used to connect to APNs and Authorization header was missing or no provider token was specified.
400 The apns-topic header of the request was not specified and was required.
400 The message payload was empty.
413 The message payload was too large.
503 The service is unavailable.
503 The server is shutting down.
429 The provider token is being updated too often.
429 Too many requests were made consecutively to the same device token.
400 Pushing to this topic is not allowed.
410 The device token is inactive for the specified topic.
StatusSent is a 200 response.

# Variables

DefaultHost is a mutable var for testing purposes.
DialTLS is the default dial function for creating TLS connections for non-proxied HTTPS requests.
HTTPClientTimeout specifies a time limit for requests made by the HTTPClient.
ReadIdleTimeout is the timeout after which a health check using a ping frame will be carried out if no frame is received on the connection.
TCPKeepAlive specifies the keep-alive period for an active network connection.
TLSDialTimeout is the maximum amount of time a dial will wait for a connect to complete.

# Structs

Client represents a connection with the APNs.
ClientManager is a way to manage multiple connections to the APNs.
Notification represents the the data and metadata for a APNs Remote Notification.
Response represents a result from the APNs gateway indicating whether a notification was accepted or rejected and (if applicable) the metadata surrounding the rejection.
Time represents a device uninstall time.

# Interfaces

A Context carries a deadline, a cancellation signal, and other values across API boundaries.

# Type aliases

EPushType defines the value for the apns-push-type header.