forked from timehop/apns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
feedback.go
93 lines (73 loc) · 1.75 KB
/
feedback.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
package apns
import (
"bytes"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"time"
)
type Feedback struct {
Conn *Conn
}
type FeedbackTuple struct {
Timestamp time.Time
TokenLength uint16
DeviceToken string
}
func feedbackTupleFromBytes(b []byte) FeedbackTuple {
r := bytes.NewReader(b)
var ts uint32
binary.Read(r, binary.BigEndian, &ts)
var tokLen uint16
binary.Read(r, binary.BigEndian, &tokLen)
tok := make([]byte, tokLen)
binary.Read(r, binary.BigEndian, &tok)
return FeedbackTuple{
Timestamp: time.Unix(int64(ts), 0),
TokenLength: tokLen,
DeviceToken: hex.EncodeToString(tok),
}
}
func NewFeedbackWithCert(gw string, cert tls.Certificate) Feedback {
conn := NewConnWithCert(gw, cert)
return Feedback{Conn: &conn}
}
func NewFeedback(gw string, cert string, key string) (Feedback, error) {
conn, err := NewConn(gw, cert, key)
if err != nil {
return Feedback{}, err
}
return Feedback{Conn: &conn}, nil
}
func NewFeedbackWithFiles(gw string, certFile string, keyFile string) (Feedback, error) {
conn, err := NewConnWithFiles(gw, certFile, keyFile)
if err != nil {
return Feedback{}, err
}
return Feedback{Conn: &conn}, nil
}
// Receive returns a read only channel for APNs feedback. The returned channel
// will close when there is no more data to be read.
func (f Feedback) Receive() <-chan FeedbackTuple {
fc := make(chan FeedbackTuple)
go f.receive(fc)
return fc
}
func (f Feedback) receive(fc chan FeedbackTuple) {
err := f.Conn.Connect()
if err != nil {
close(fc)
return
}
defer f.Conn.Close()
for {
b := make([]byte, 38)
f.Conn.NetConn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
_, err := f.Conn.Read(b)
if err != nil {
close(fc)
return
}
fc <- feedbackTupleFromBytes(b)
}
}