forked from sideshow/apns2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
359 lines (304 loc) · 9.91 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Package apns2 is a go Apple Push Notification Service (APNs) provider that
// allows you to send remote notifications to your iOS, tvOS, and OS X
// apps, using the new APNs HTTP/2 network protocol.
package apns2
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"time"
"crypto/rand"
"sync"
"github.com/gngeorgiev/apns2/token"
"golang.org/x/net/http2"
)
// Apple HTTP/2 Development & Production urls
const (
HostDevelopment = "https://api.sandbox.push.apple.com"
HostProduction = "https://api.push.apple.com"
)
var (
// DefaultHost is a mutable var for testing purposes
DefaultHost = HostDevelopment
// TLSDialTimeout is the maximum amount of time a dial will wait for a connect
// to complete.
TLSDialTimeout = 20 * time.Second
// HTTPClientTimeout specifies a time limit for requests made by the
// HTTPClient. The timeout includes connection time, any redirects,
// and reading the response body.
HTTPClientTimeout = 60 * time.Second
// TCPKeepAlive specifies the keep-alive period for an active network
// connection. If zero, keep-alives are not enabled.
TCPKeepAlive = 60 * time.Second
// ErrPingingStopped is returned when the pinging of a client is stopped
ErrPingingStopped = errors.New("pinging stopped")
)
// DialTLS is the default dial function for creating TLS connections for
// non-proxied HTTPS requests.
var DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: TLSDialTimeout,
KeepAlive: TCPKeepAlive,
}
return tls.DialWithDialer(dialer, network, addr, cfg)
}
// Client represents a connection with the APNs
type Client struct {
Host string
Certificate tls.Certificate
Token *token.Token
HTTPClient *http.Client
pingingMutex sync.Mutex
pinging bool
stopPinging chan struct{}
pingInterval time.Duration
connMutex sync.Mutex
conn *tls.Conn
}
// A Context carries a deadline, a cancellation signal, and other values across
// API boundaries. Context's methods may be called by multiple goroutines
// simultaneously.
type Context interface {
context.Context
}
type connectionCloser interface {
CloseIdleConnections()
}
func newDefaultClient() *Client {
client := &Client{}
client.Host = DefaultHost
client.stopPinging = make(chan struct{})
client.HTTPClient = &http.Client{
Timeout: HTTPClientTimeout,
}
return client
}
func newClientWithHttp2Transport() *Client {
client := newDefaultClient()
t := &http2.Transport{}
t.DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) {
conn, err := DialTLS(network, addr, cfg)
if err != nil {
return nil, err
}
client.setConnection(conn.(*tls.Conn))
return conn, nil
}
client.HTTPClient.Transport = t
return client
}
// NewClient returns a new Client with an underlying http.Client configured with
// the correct APNs HTTP/2 transport settings. It does not connect to the APNs
// until the first Notification is sent via the Push method.
//
// As per the Apple APNs Provider API, you should keep a handle on this client
// so that you can keep your connections with APNs open across multiple
// notifications; don’t repeatedly open and close connections. APNs treats rapid
// connection and disconnection as a denial-of-service attack.
//
// If your use case involves multiple long-lived connections, consider using
// the ClientManager, which manages clients for you.
func NewClient(certificate tls.Certificate) *Client {
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{certificate},
}
if len(certificate.Certificate) > 0 {
tlsConfig.BuildNameToCertificate()
}
client := newClientWithHttp2Transport()
client.HTTPClient.Transport.(*http2.Transport).TLSClientConfig = tlsConfig
client.Certificate = certificate
return client
}
//EnablePinging starts pinging the last opened connection. This way, there's always one connection
//kept alive which allows for quick send of push notifications
func (c *Client) EnablePinging(pingInterval time.Duration, pingErrorCh chan error) {
//lets make sure that the old goroutine has exited in case the user calls this method multiple times
c.DisablePinging()
c.pingingMutex.Lock()
defer c.pingingMutex.Unlock()
c.pinging = true
c.pingInterval = pingInterval
go func() {
t := time.NewTicker(pingInterval)
var framer *http2.Framer
for {
select {
case <-t.C:
conn := c.getConnection()
if conn == nil {
continue
}
if framer == nil {
framer = http2.NewFramer(conn, conn)
}
var p [8]byte
rand.Read(p[:])
err := framer.WritePing(false, p)
if err != nil {
c.setConnection(nil)
framer = nil
if pingErrorCh != nil {
pingErrorCh <- err
}
}
case <-c.stopPinging:
t.Stop()
framer = nil
if pingErrorCh != nil {
pingErrorCh <- ErrPingingStopped
}
return
}
}
}()
}
//DisablePinging stops the pinging
func (c *Client) DisablePinging() {
c.pingingMutex.Lock()
defer c.pingingMutex.Unlock()
if c.pinging {
c.stopPinging <- struct{}{}
}
c.pinging = false
}
// NewTokenClient returns a new Client with an underlying http.Client configured
// with the correct APNs HTTP/2 transport settings. It does not connect to the APNs
// until the first Notification is sent via the Push method.
//
// As per the Apple APNs Provider API, you should keep a handle on this client
// so that you can keep your connections with APNs open across multiple
// notifications; don’t repeatedly open and close connections. APNs treats rapid
// connection and disconnection as a denial-of-service attack.
func NewTokenClient(token *token.Token) *Client {
client := newClientWithHttp2Transport()
client.Token = token
return client
}
// Development sets the Client to use the APNs development push endpoint.
func (c *Client) Development() *Client {
c.Host = HostDevelopment
return c
}
// Production sets the Client to use the APNs production push endpoint.
func (c *Client) Production() *Client {
c.Host = HostProduction
return c
}
//IsPinging returns whether the client is currently pinging the APNS servers
func (c *Client) IsPinging() bool {
c.pingingMutex.Lock()
defer c.pingingMutex.Unlock()
return c.pinging
}
//GetPingInterval returns the ping interval, if set on EnablePinging
func (c *Client) GetPingInterval() time.Duration {
return c.pingInterval
}
// Push sends a Notification to the APNs gateway. If the underlying http.Client
// is not currently connected, this method will attempt to reconnect
// transparently before sending the notification. It will return a Response
// indicating whether the notification was accepted or rejected by the APNs
// gateway, or an error if something goes wrong.
//
// Use PushWithContext if you need better cancellation and timeout control.
func (c *Client) Push(n *Notification) (*Response, error) {
return c.PushWithContext(nil, n)
}
// PushWithContext sends a Notification to the APNs gateway. Context carries a
// deadline and a cancellation signal and allows you to close long running
// requests when the context timeout is exceeded. Context can be nil, for
// backwards compatibility.
//
// If the underlying http.Client is not currently connected, this method will
// attempt to reconnect transparently before sending the notification. It will
// return a Response indicating whether the notification was accepted or
// rejected by the APNs gateway, or an error if something goes wrong.
func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error) {
return c.PushWithHostContext(ctx, c.Host, n)
}
//PushWithHostContext sends a push with the specified host and context
//useful when one client needs to send dev and prod notifications in a concurrent environment
func (c *Client) PushWithHostContext(ctx Context, host string, n *Notification) (*Response, error) {
payload, err := json.Marshal(n)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%v/3/device/%v", host, n.DeviceToken)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
if err != nil {
return nil, err
}
if c.Token != nil {
c.setTokenHeader(req)
}
setHeaders(req, n)
httpRes, err := c.requestWithContext(ctx, req)
if err != nil {
return nil, err
}
defer httpRes.Body.Close()
response := &Response{}
response.StatusCode = httpRes.StatusCode
response.ApnsID = httpRes.Header.Get("apns-id")
decoder := json.NewDecoder(httpRes.Body)
if err := decoder.Decode(&response); err != nil && err != io.EOF {
return &Response{}, err
}
return response, nil
}
// CloseIdleConnections closes any underlying connections which were previously
// connected from previous requests but are now sitting idle. It will not
// interrupt any connections currently in use.
func (c *Client) CloseIdleConnections() {
c.HTTPClient.Transport.(connectionCloser).CloseIdleConnections()
}
func (c *Client) setTokenHeader(r *http.Request) {
bearer := c.Token.GenerateIfExpired()
r.Header.Set("authorization", fmt.Sprintf("bearer %v", bearer))
}
func (c *Client) getConnection() *tls.Conn {
c.connMutex.Lock()
defer c.connMutex.Unlock()
return c.conn
}
func (c *Client) setConnection(conn *tls.Conn) {
c.connMutex.Lock()
c.conn = conn
c.connMutex.Unlock()
}
func setHeaders(r *http.Request, n *Notification) {
r.Header.Set("Content-Type", "application/json; charset=utf-8")
if n.Topic != "" {
r.Header.Set("apns-topic", n.Topic)
}
if n.ApnsID != "" {
r.Header.Set("apns-id", n.ApnsID)
}
if n.CollapseID != "" {
r.Header.Set("apns-collapse-id", n.CollapseID)
}
if n.Priority > 0 {
r.Header.Set("apns-priority", fmt.Sprintf("%v", n.Priority))
}
if !n.Expiration.IsZero() {
r.Header.Set("apns-expiration", fmt.Sprintf("%v", n.Expiration.Unix()))
}
if n.PushType != "" {
r.Header.Set("apns-push-type", string(n.PushType))
} else {
r.Header.Set("apns-push-type", string(PushTypeAlert))
}
}
func (c *Client) requestWithContext(ctx Context, req *http.Request) (*http.Response, error) {
if ctx != nil {
req = req.WithContext(ctx)
}
return c.HTTPClient.Do(req)
}