-
Notifications
You must be signed in to change notification settings - Fork 46
/
ios_push.py
364 lines (318 loc) · 12.1 KB
/
ios_push.py
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
360
361
362
363
364
# -*- coding: utf-8 -*-
import logging
import redis
from OpenSSL import crypto
import os
import threading
from models import application
from utils.credentials import CertificateCredentials
import config
import time
import tempfile
import OpenSSL
from apns2.client import APNsClient
from apns2.payload import Payload
import collections
sandbox = config.SANDBOX
Notification = collections.namedtuple('Notification', ['token', 'payload', 'collapse_id'])
class APNSConnectionManager:
def __init__(self):
self.pushkit_connections = {}
self.pushkit_timestamps = {}
self.apns_connections = {}
#上次访问的时间戳,丢弃超过20m未用的链接
self.connection_timestamps = {}
self.lock = threading.Lock()
def get_pushkit_connection(self, appid):
self.lock.acquire()
try:
connections = self.pushkit_connections
apns = connections.get(appid)
if apns:
ts = self.pushkit_timestamps[appid]
now = int(time.time())
# > 10minute
if (now - ts) > 20*60:
apns = None
else:
self.pushkit_timestamps[appid] = now
finally:
self.lock.release()
return apns
def remove_pushkit_connection(self, appid):
self.lock.acquire()
try:
connections = self.pushkit_connections
if appid in connections:
logging.debug("pop pushkit connection:%s", appid)
connections.pop(appid)
finally:
self.lock.release()
def set_pushkit_connection(self, appid, connection):
self.lock.acquire()
try:
self.pushkit_connections[appid] = connection
self.pushkit_timestamps[appid] = int(time.time())
finally:
self.lock.release()
def get_apns_connection(self, appid):
self.lock.acquire()
try:
connections = self.apns_connections
apns = connections.get(appid)
if apns:
ts = self.connection_timestamps[appid]
now = int(time.time())
# > 20minute
if (now - ts) > 20*60:
apns = None
else:
self.connection_timestamps[appid] = now
finally:
self.lock.release()
return apns
def remove_apns_connection(self, appid):
self.lock.acquire()
try:
connections = self.apns_connections
if appid in connections:
logging.debug("pop client:%s", appid)
connections.pop(appid)
finally:
self.lock.release()
def set_apns_connection(self, appid, connection):
self.lock.acquire()
try:
self.apns_connections[appid] = connection
self.connection_timestamps[appid] = int(time.time())
finally:
self.lock.release()
class IOSPush(object):
mysql = None
apns_manager = APNSConnectionManager()
bundle_ids = {}
@staticmethod
def gen_pem(p12, secret):
p12 = crypto.load_pkcs12(p12, str(secret))
priv_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
pub_key = crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())
return pub_key, priv_key
@staticmethod
def check_p12_expired(p12, secret):
p12 = crypto.load_pkcs12(p12, str(secret))
return p12.get_certificate().has_expired()
@classmethod
def connect_apns_server(cls, sandbox, p12, secret):
pub_key, priv_key = cls.gen_pem(p12, secret)
f, path = tempfile.mkstemp()
try:
os.write(f, pub_key)
os.write(f, priv_key)
client = APNsClient(CertificateCredentials(path), use_sandbox=sandbox, use_alternative_port=False)
return client
finally:
os.close(f)
os.remove(path)
@classmethod
def get_connection(cls, appid):
apns = cls.apns_manager.get_apns_connection(appid)
if not apns:
p12, secret, timestamp = application.get_p12(cls.mysql, sandbox, appid)
if not p12:
logging.warning("get p12 fail client id:%s", appid)
return None
if cls.check_p12_expired(p12, secret):
logging.warning("p12 expiry client id:%s", appid)
return None
apns = cls.connect_apns_server(sandbox, p12, secret)
cls.apns_manager.set_apns_connection(appid, apns)
return apns
@classmethod
def get_pushkit_connection(cls, appid):
return cls.get_connection(appid)
@classmethod
def get_bundle_id(cls, appid):
if appid in cls.bundle_ids:
return cls.bundle_ids[appid]
bundle_id = application.get_bundle_id(cls.mysql, appid)
if bundle_id:
cls.bundle_ids[appid] = bundle_id
return bundle_id
@classmethod
def voip_push(cls, appid, token, extra=None):
topic = cls.get_bundle_id(appid)
if not topic:
logging.warning("appid:%s no bundle id", appid)
return
voip_topic = topic + ".voip"
payload = Payload(custom=extra)
client = cls.get_pushkit_connection(appid)
try:
client.send_notification(token, payload, voip_topic)
logging.debug("send voip notification:%s success", token)
except OpenSSL.SSL.Error as e:
logging.warning("ssl exception:%s", str(e))
cls.apns_manager.remove_apns_connection(appid)
except Exception as e:
logging.warning("send notification exception:%s %s", str(e), type(e))
cls.apns_manager.remove_apns_connection(appid)
@classmethod
def push(cls, appid, token, alert, sound="default", badge=0, content_available=0, extra=None, collapse_id=None):
topic = cls.get_bundle_id(appid)
if not topic:
logging.warning("appid:%s no bundle id", appid)
return
payload = Payload(alert=alert, sound=sound, badge=badge, content_available=content_available, custom=extra)
client = cls.get_connection(appid)
try:
client.send_notification(token, payload, topic, collapse_id=collapse_id)
logging.debug("send apns:%s %s %s success", token, alert, badge)
except OpenSSL.SSL.Error as e:
logging.warning("ssl exception:%s", str(e))
cls.apns_manager.remove_apns_connection(appid)
except Exception as e:
logging.warning("send notification exception:%s %s", str(e), type(e))
cls.apns_manager.remove_apns_connection(appid)
@classmethod
def push_group_batch(cls, appid, notifications, collapse_id=None):
"""
相同的collapse_id
"""
topic = cls.get_bundle_id(appid)
if not topic:
logging.warning("appid:%s no bundle id", appid)
return
client = cls.get_connection(appid)
try:
results = client.send_notification_batch(notifications, topic, collapse_id=collapse_id)
logging.debug("push group batch results:%s", results)
except OpenSSL.SSL.Error as e:
logging.warning("ssl exception:%s", str(e))
cls.apns_manager.remove_apns_connection(appid)
except Exception as e:
logging.warning("send notification exception:%s %s", str(e), type(e))
cls.apns_manager.remove_apns_connection(appid)
@classmethod
def push_peer_batch(cls, appid, notifications):
"""
不同的collapse_id
"""
topic = cls.get_bundle_id(appid)
if not topic:
logging.warning("appid:%s no bundle id", appid)
return
client = cls.get_connection(appid)
try:
results = cls.send_notification_batch(client, notifications, topic)
logging.debug("push peer batch results:%s", results)
except OpenSSL.SSL.Error as e:
logging.warning("ssl exception:%s", str(e))
cls.apns_manager.remove_apns_connection(appid)
except Exception as e:
logging.warning("send notification exception:%s %s", str(e), type(e))
cls.apns_manager.remove_apns_connection(appid)
@classmethod
def send_notification_batch(cls, client, notifications, topic):
return client.send_notification_batch(notifications, topic)
@classmethod
def receive_p12_update_message(cls):
chan_rds = redis.StrictRedis(host=config.CHAN_REDIS_HOST,
port=config.CHAN_REDIS_PORT,
db=config.CHAN_REDIS_DB,
password=config.CHAN_REDIS_PASSWORD)
sub = chan_rds.pubsub()
sub.subscribe("apns_update_p12_channel")
for msg in sub.listen():
if msg['type'] == 'message':
data = msg['data']
try:
appid = int(data)
except:
logging.warning("invalid app id:%s", data)
continue
logging.info("update app:%s p12", appid)
cls.apns_manager.remove_apns_connection(appid)
cls.apns_manager.remove_pushkit_connection(appid)
@classmethod
def update_p12_thread(cls):
while True:
try:
cls.receive_p12_update_message()
except Exception as e:
logging.exception(e)
@classmethod
def start(cls):
t = threading.Thread(target=cls.update_p12_thread, args=())
t.setDaemon(True)
t.start()
def test_alert(sandbox):
f = open("imdemo.p12", "rb")
p12 = f.read()
f.close()
token = "7b2a23d466cf2557fb4fa573e1cc5f63088cd060def124a9eca97ab251be08b5"
alert = u"测试ios推送"
badge = 1
sound = "default"
topic = "com.beetle.im.demo"
print("p12", len(p12))
extra = {"test":"hahah"}
client = IOSPush.connect_apns_server(sandbox, p12, "")
payload = Payload(alert=alert, sound=sound, badge=badge, custom=extra)
try:
client.send_notification(token, payload, topic)
time.sleep(1)
except OpenSSL.SSL.Error as e:
err = e.message[0][2]
print("certificate expired" in err)
print("ssl exception:", e, type(e), dir(e), e.args, e.message)
raise e
except Exception as e:
print("exception:", e, type(e), dir(e), e.args, e.message)
raise e
def test_content(sandbox):
f = open("imdemo.p12", "rb")
p12 = f.read()
f.close()
print("p12", len(p12))
token = "7b2a23d466cf2557fb4fa573e1cc5f63088cd060def124a9eca97ab251be08b5"
extra = {"xiaowei":{"new":1}}
topic = "com.beetle.im.demo"
client = IOSPush.connect_apns_server(sandbox, p12, "")
payload = Payload(content_available=1, custom=extra)
try:
client.send_notification(token, payload, topic)
time.sleep(1)
except OpenSSL.SSL.Error as e:
err = e.message[0][2]
print("certificate expired" in err)
print("ssl exception:", e, type(e), dir(e), e.args, e.message)
raise e
except Exception as e:
print("exception:", e, type(e), dir(e), e.args, e.message)
raise e
def test_pushkit(sandbox):
f = open("imdemo.p12", "rb")
p12 = f.read()
f.close()
print("p12", len(p12))
token = "d8ac6543fb492ae56c12c47ba254ee094ce58e1001f28543af9c337d6e674f8c"
topic = "com.beetle.im.demo.voip"
extra = {"voip":{"channel_id":"1", "command":"dial"}}
payload = Payload(custom=extra)
client = IOSPush.connect_apns_server(sandbox, p12, "")
try:
client.send_notification(token, payload, topic)
time.sleep(1)
except OpenSSL.SSL.Error as e:
err = e.message[0][2]
print("certificate expired" in err)
print("ssl exception:", e, type(e), dir(e), e.args, e.message)
raise e
except Exception as e:
print("exception:", e, type(e), dir(e), e.args, e.message)
raise e
if __name__ == "__main__":
sandbox = True
test_pushkit(sandbox)
test_content(sandbox)
test_alert(sandbox)