-
Notifications
You must be signed in to change notification settings - Fork 11
/
ios_push.go
163 lines (143 loc) · 3.39 KB
/
ios_push.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
package PushSDK
import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/dgrijalva/jwt-go"
"io/ioutil"
"sync"
"time"
)
type IOS struct {
sync.Mutex
KeyId string `json:"key_id"`
TeamId string `json:"team_id"`
BundleId string `json:"bundle_id"`
AuthTokenPath string `json:"auth_token_path"`
Bearer string `json:"bearer"`
IssuedAt int64 `json:"issued_at"`
}
type IOSFields struct {
Aps Aps `json:"aps"`
}
type Aps struct {
Alert Alert `json:"alert"`
Badge int `json:"badge"` // 右上角小图标
}
type Alert struct {
Title string `json:"title"`
Body string `json:"body"`
}
func (i *IOS) initMessage(m *Message) string {
fields := IOSFields{
Aps: Aps{
Alert: Alert{
Title: m.Title,
Body: m.Desc,
},
Badge: 1,
},
}
fieldsStr, _ := json.Marshal(fields)
return string(fieldsStr)
}
const (
IOSProductionHost = "https://api.development.push.apple.com"
IOSMessageURL = "/3/device/"
IOSTokenTimeout = 3000
)
const (
IOSSuccess = 200 // 成功
IOSErrorRequest = 400 // 错误的请求
IOSErrorAuthToken = 403
IOSErrorMethod = 405
IOSTimeOutDeviceToken = 410
IOSNotificationPayloadTooLarge = 413
IOSTooManyRequest = 429
IOSInternalServerError = 500
IOSServerUnavailable = 503
)
type IOSResult struct {
ApnsId string `json:"apns-id"`
Status int `json:"status"`
Reason string `json:"reason"`
}
type ErrResult struct {
Reason string `json:"reason"`
}
func (i *IOS) SendMessage(m *Message, token []string) (*Response, error) {
response := &Response{}
forms := i.initMessage(m)
header := make(map[string]string)
header["apns-topic"] = i.BundleId
header["Authorization"] = fmt.Sprintf("bearer %s", i.Bearer)
header["apns-id"] = m.ApnsId
for _, v := range token {
requestUrl := IOSProductionHost + IOSMessageURL + v
body, err := postReqJson(requestUrl, forms, header)
if err != nil {
response.Code = HTTPERROR
return response, err
}
fmt.Println("result-ios", string(body))
if string(body) != "" {
var errRes = &ErrResult{}
err = json.Unmarshal(body, errRes)
response.Code = SendError
response.Reason = errRes.Reason
break
}
}
return response, nil
}
func GetAuthTokenIOS(authTokenPath string, keyID string, teamID string) (string, error) {
tokenBytes, err := ioutil.ReadFile(authTokenPath)
if err != nil {
return "", err
}
block, _ := pem.Decode(tokenBytes)
if block == nil {
return "", errors.New("Auth token does not seem to be a valid .p8 key file")
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return "", err
}
jwtToken := &jwt.Token{
Header: map[string]interface{}{
"alg": "ES256",
"kid": keyID,
},
Claims: jwt.MapClaims{
"iss": teamID,
"iat": time.Now().Unix(),
},
Method: jwt.SigningMethodES256,
}
bearer, err := jwtToken.SignedString(key)
if err != nil {
return "", err
}
return bearer, nil
}
func (i *IOS) generateIfExpired() string {
i.Lock()
defer i.Unlock()
if i.Expired() {
i.Generate()
}
return i.Bearer
}
func (i *IOS) Expired() bool {
return time.Now().Unix() >= (i.IssuedAt + IOSTokenTimeout)
}
func (i *IOS) Generate() (bool, error) {
bearer, err := GetAuthTokenIOS(i.AuthTokenPath, i.KeyId, i.TeamId)
if bearer != "" {
i.Bearer = bearer
i.IssuedAt = time.Now().Unix()
}
return true, err
}