PushService.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # -*- coding: utf-8 -*-
  2. """
  3. @Time : 2022/5/19 11:43
  4. @Auth : Locky
  5. @File :PushService.py
  6. @IDE :PyCharm
  7. """
  8. import hashlib
  9. import json
  10. import logging
  11. import os
  12. import time
  13. import apns2
  14. import jpush
  15. import requests
  16. from pyfcm import FCMNotification
  17. from AnsjerPush.config import APP_BUNDLE_DICT, APNS_MODE, BASE_DIR, APNS_CONFIG, FCM_CONFIG, JPUSH_CONFIG, XMPUSH_CONFIG \
  18. , VIVOPUSH_CONFIG, OPPOPUSH_CONFIG, MEIZUPUSH_CONFIG, CONFIG_INFO
  19. from Model.models import UidPushModel
  20. from Object.RedisObject import RedisObject
  21. from Object.S3Email import S3Email
  22. from Service.CommonService import CommonService
  23. from Service.VivoPushService.push_admin.APIMessage import PushMessage
  24. from Service.VivoPushService.push_admin.APISender import APISender
  25. from AnsjerPush.config import LOGGER
  26. class PushObject:
  27. # 推送对象
  28. @staticmethod
  29. def get_msg_title(nickname):
  30. """
  31. 获取推送消息标题
  32. @param nickname: 设备名
  33. @return: msg_title
  34. """
  35. return nickname
  36. @staticmethod
  37. def get_gateway_msg_text(n_time, tz, lang, alarm):
  38. """
  39. 获取网关推送消息内容
  40. @param n_time: 当前时间
  41. @param tz: 时区
  42. @param lang: 语言
  43. @param alarm: 警报
  44. @return: msg_text
  45. """
  46. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  47. if lang == 'cn':
  48. msg_text = '{} 日期:{}'.format(alarm, n_date)
  49. else:
  50. msg_text = '{} date:{}'.format(alarm, n_date)
  51. return msg_text
  52. @staticmethod
  53. def get_ai_msg_text(channel, n_time, lang, tz, label):
  54. """
  55. 获取AI推送内容
  56. @param channel: 通道
  57. @param n_time: 当前时间
  58. @param lang: 语言
  59. @param tz: 时区
  60. @param label: 识别到的标签
  61. @return: ai_msg_text
  62. """
  63. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  64. if lang == 'cn':
  65. msg = '摄像头AI识别到了{}'.format(label)
  66. ai_msg_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  67. else:
  68. msg = 'Camera AI recognizes {}'.format(label)
  69. ai_msg_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  70. return ai_msg_text
  71. @staticmethod
  72. def get_low_power_msg_text(channel, n_time, lang, tz, electricity, is_sys=0):
  73. """
  74. 获取低电量推送内容
  75. @param channel: 通道
  76. @param n_time: 当前时间
  77. @param lang: 语言
  78. @param tz: 时区
  79. @param electricity: 电量
  80. @param is_sys: 是否为系统消息
  81. @return: low_power_msg_text
  82. """
  83. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  84. if lang == 'cn':
  85. alarm = '剩余电量 ' + electricity
  86. if is_sys:
  87. low_power_msg_text = '{} 通道:{}'.format(alarm, channel)
  88. else:
  89. low_power_msg_text = '{} 通道:{} 日期:{}'.format(alarm, channel, n_date)
  90. else:
  91. alarm = 'Battery remaining ' + electricity
  92. if is_sys:
  93. low_power_msg_text = '{} channel:{}'.format(alarm, channel)
  94. else:
  95. low_power_msg_text = '{} channel:{} date:{}'.format(alarm, channel, n_date)
  96. return low_power_msg_text
  97. @staticmethod
  98. def ios_apns_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  99. uid='', channel='1', launch_image=None):
  100. """
  101. ios apns 推送
  102. @param nickname: 设备昵称
  103. @param app_bundle_id: app包id
  104. @param token_val: 推送token
  105. @param n_time: 当前时间
  106. @param event_type: 事件类型
  107. @param msg_title: 推送标题
  108. @param msg_text: 推送内容
  109. @param uid: uid
  110. @param channel: 通道
  111. @param launch_image: 推送图片链接
  112. @return: None
  113. """
  114. pem_path = os.path.join(BASE_DIR, APNS_CONFIG[app_bundle_id]['pem_path'])
  115. LOGGER.info('IOS推送: app_bundle_id:{}, pem_path:{}'.format(app_bundle_id, pem_path))
  116. try:
  117. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=pem_path)
  118. alert = apns2.PayloadAlert(title=msg_title, body=msg_text, launch_image=launch_image)
  119. push_data = {'alert': 'Motion', 'msg': '', 'sound': '', 'zpush': '1', 'uid': uid, 'channel': channel,
  120. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  121. 'image_url': launch_image
  122. }
  123. payload = apns2.Payload(alert=alert, custom=push_data, sound='default', category='myCategory',
  124. mutable_content=True)
  125. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  126. res = cli.push(n=n, device_token=token_val, topic=app_bundle_id)
  127. LOGGER.info('IOS推送响应状态码{},params,uid:{},{}'.format(res.status_code, uid, json.dumps(push_data)))
  128. assert res.status_code == 200
  129. except Exception as e:
  130. LOGGER.info('IOS推送异常: {}, 证书路径: {}'.format(repr(e), pem_path))
  131. @staticmethod
  132. def android_fcm_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  133. uid='', channel='1', image=''):
  134. """
  135. android fcm 推送
  136. @param nickname: 设备昵称
  137. @param app_bundle_id: app包id
  138. @param token_val: 推送token
  139. @param n_time: 当前时间
  140. @param event_type: 事件类型
  141. @param msg_title: 推送标题
  142. @param msg_text: 推送内容
  143. @param uid: uid
  144. @param channel: 通道
  145. @param image: 推送图片链接
  146. @return: None
  147. """
  148. logger = logging.getLogger('info')
  149. try:
  150. serverKey = FCM_CONFIG[app_bundle_id]
  151. push_service = FCMNotification(api_key=serverKey)
  152. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  153. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  154. 'uid': uid, 'channel': channel
  155. }
  156. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  157. message_body=msg_text, data_message=push_data,
  158. extra_kwargs={'default_sound': True,
  159. 'default_vibrate_timings': True,
  160. 'default_light_settings': True,
  161. }
  162. )
  163. LOGGER.info('fcm推送结果:{}'.format(result))
  164. except Exception as e:
  165. LOGGER.info('fcm推送异常:{}'.format(repr(e)))
  166. @staticmethod
  167. def android_jpush(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text, channel=1):
  168. """
  169. android 极光 推送
  170. @param nickname: 设备昵称
  171. @param app_bundle_id: app包id
  172. @param token_val: 推送token
  173. @param n_time: 当前时间
  174. @param event_type: 事件类型
  175. @param msg_title: 推送标题
  176. @param msg_text: 推送内容
  177. @param channel: 设备通道
  178. @return: None
  179. """
  180. try:
  181. app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  182. master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  183. # 换成各自的app_key和master_secret
  184. _jpush = jpush.JPush(app_key, master_secret)
  185. push = _jpush.create_push()
  186. push.audience = jpush.registration_id(token_val)
  187. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'uid': nickname,
  188. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  189. 'channel': channel
  190. }
  191. android = jpush.android(title=msg_title, big_text=msg_text, alert=msg_text, extras=push_data,
  192. priority=1, style=1, alert_type=7
  193. )
  194. push.notification = jpush.notification(android=android)
  195. push.platform = jpush.all_
  196. res = push.send()
  197. assert res.status_code == 200
  198. except Exception as e:
  199. LOGGER.info('极光推送异常:{}'.format(repr(e)))
  200. @staticmethod
  201. def android_xmpush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  202. uid='', channel='1', image=''):
  203. """
  204. android 小米 推送
  205. @param channel_id: 通知通道
  206. @param nickname: 设备昵称
  207. @param app_bundle_id: app包id
  208. @param token_val: 推送token
  209. @param n_time: 当前时间
  210. @param event_type: 事件类型
  211. @param msg_title: 推送标题
  212. @param msg_text: 推送内容
  213. @param uid: uid
  214. @param channel: 通道
  215. @param image: 推送图片链接
  216. @return: None
  217. """
  218. logger = logging.getLogger('info')
  219. try:
  220. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  221. app_secret = XMPUSH_CONFIG[app_bundle_id]
  222. # payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  223. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  224. # 'uid': uid, 'channel': channel
  225. # }
  226. data = {
  227. 'title': msg_title,
  228. 'description': msg_text,
  229. 'payload': 'payload',
  230. 'restricted_package_name': app_bundle_id,
  231. 'registration_id': token_val,
  232. 'extra.channel_id': channel_id,
  233. 'extra.alert': 'Motion',
  234. 'extra.msg': '',
  235. 'extra.sound': 'sound.aif',
  236. 'extra.zpush': '1',
  237. 'extra.received_at': n_time,
  238. 'extra.event_time': n_time,
  239. 'extra.event_type': event_type,
  240. 'extra.nickname': nickname,
  241. 'extra.uid': uid,
  242. 'extra.channel': channel,
  243. }
  244. # if image:
  245. # data['extra.notification_style_type'] = 2
  246. # data['extra.notification_bigPic_uri'] = image
  247. headers = {
  248. 'Authorization': 'key={}'.format(app_secret)
  249. }
  250. response = requests.post(url, data=data, headers=headers)
  251. logger.info("小米推送返回值:{}".format(response.json()))
  252. assert response.status_code == 200
  253. except Exception as e:
  254. return repr(e)
  255. @staticmethod
  256. def android_vivopush(token_val, n_time, event_type, msg_title, msg_text, app_bundle_id='', uid='', channel='1',
  257. image='', nickname='', appBundleId='', jg_token_val=''):
  258. """
  259. vivo 推送(不支持图片)
  260. @param app_bundle_id: app包名
  261. @param appBundleId: app包名
  262. @param token_val: 推送token
  263. @param jg_token_val: 极光推送token
  264. @param event_type: 事件类型
  265. @param msg_title: 推送标题
  266. @param msg_text: 推送内容
  267. @param n_time: 当前时间
  268. @param nickname: 设备昵称
  269. @param uid: uid
  270. @param image: 推送图片链接
  271. @param channel: 通道
  272. @return: None
  273. """
  274. logger = logging.getLogger('info')
  275. try:
  276. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  277. # 获取redis里面的authToken
  278. if msg_title == '':
  279. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  280. app_id = VIVOPUSH_CONFIG[app_bundle_id]['ID']
  281. app_key = VIVOPUSH_CONFIG[app_bundle_id]['Key']
  282. app_secret = VIVOPUSH_CONFIG[app_bundle_id]['Secret']
  283. sender = APISender(app_secret)
  284. rec = sender.get_token(app_id, app_key)
  285. # 鉴权接口调用获得authToken
  286. sender_send = APISender(app_secret)
  287. sender_send.set_token(rec['authToken'])
  288. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  289. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  290. 'uid': uid, 'channel': channel
  291. }
  292. # 获取唯一标识符
  293. uid_push_qs = UidPushModel.objects.filter(token_val=token_val).values('m_code')
  294. m_code = uid_push_qs[0]['m_code'] if uid_push_qs[0]['m_code'] else ''
  295. # 推送 push_mode: 推送模式 (0:正式推送;1:测试推送,默认为0)
  296. # 推送 event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  297. # 推送 skip_type: 跳转类型(1:打开 APP 首页 2:打开链接 3:自定义 4:打开 app 内指定页面)
  298. activity = 'vpushscheme://com.vivo.pushvideo/detail'
  299. message = PushMessage() \
  300. .reg_id(token_val) \
  301. .title(msg_title) \
  302. .content(msg_text) \
  303. .push_mode(0) \
  304. .notify_type(3) \
  305. .skip_type(4) \
  306. .skip_content(activity) \
  307. .request_id(m_code) \
  308. .classification(1) \
  309. .client_custom_map(**push_data) \
  310. .message_dict()
  311. rec = sender_send.send(message)
  312. logger.info('vivo推送结果:{}, 设备uid:{}'.format(rec, uid))
  313. if rec['result'] == 0 and event_type in [606, 607]:
  314. PushObject.jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, jg_token_val, push_data)
  315. return rec
  316. except Exception as e:
  317. logger.info('vivo推送异常:{}'.format(e))
  318. @staticmethod
  319. def android_oppopush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  320. uid='', channel='1', image='', jg_token_val=''):
  321. """
  322. android oppo 推送
  323. @param channel_id: 通知通道id
  324. @param nickname: 设备昵称
  325. @param app_bundle_id: app包id
  326. @param token_val: 推送token
  327. @param jg_token_val: 推送token
  328. @param n_time: 当前时间
  329. @param event_type: 事件类型
  330. @param msg_title: 推送标题
  331. @param msg_text: 推送内容
  332. @param uid: uid
  333. @param channel: 通道
  334. @param image: 推送图片链接
  335. @return: None
  336. """
  337. logger = logging.getLogger('info')
  338. try:
  339. """
  340. android 国内oppo APP消息提醒推送
  341. """
  342. app_key = OPPOPUSH_CONFIG[app_bundle_id]['Key']
  343. master_secret = OPPOPUSH_CONFIG[app_bundle_id]['Secret']
  344. url = 'https://api.push.oppomobile.com/'
  345. now_time = str(round(time.time() * 1000))
  346. # 1、实例化一个sha256对象
  347. sha256 = hashlib.sha256()
  348. # 2、调用update方法进行加密
  349. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  350. # 3、调用hexdigest方法,获取加密结果
  351. sign = sha256.hexdigest()
  352. # 获取auth_token
  353. get_token_url = url + 'server/v1/auth'
  354. post_data = {
  355. 'app_key': app_key,
  356. 'sign': sign,
  357. 'timestamp': now_time
  358. }
  359. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  360. response = requests.post(get_token_url, data=post_data, headers=headers)
  361. result = response.json()
  362. # 发送推送
  363. push_url = url + 'server/v1/message/notification/unicast'
  364. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  365. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  366. 'uid': uid, 'channel': channel
  367. }
  368. message = {
  369. "target_type": 2,
  370. "target_value": token_val,
  371. "notification": {
  372. "title": msg_title,
  373. "content": msg_text,
  374. 'channel_id': channel_id,
  375. 'action_parameters': extra_data,
  376. 'click_action_type': 1,
  377. 'click_action_activity': 'com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity'
  378. }
  379. }
  380. push_data = {
  381. 'auth_token': result['data']['auth_token'],
  382. 'message': json.dumps(message)
  383. }
  384. response = requests.post(push_url, data=push_data, headers=headers)
  385. logger.info("oppo推送返回值:{}".format(response.json()))
  386. if response.status_code == 200 and event_type in [606, 607]:
  387. PushObject.jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, jg_token_val, extra_data)
  388. except Exception as e:
  389. return repr(e)
  390. @staticmethod
  391. def android_meizupush(token_val, n_time, event_type, msg_title, msg_text, uid='', channel='1',
  392. app_bundle_id='', appBundleId='', nickname='', image=''):
  393. """
  394. android 魅族推送(不支持图片)
  395. @param app_bundle_id: app包名
  396. @param appBundleId: app包名
  397. @param token_val: 推送token
  398. @param event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  399. @param msg_title: 推送标题
  400. @param msg_text: 推送内容
  401. @param n_time: 当前时间
  402. @param nickname: 设备昵称
  403. @param uid: uid
  404. @param image: 推送图片链接
  405. @param channel: 通道
  406. @return: None
  407. """
  408. logger = logging.getLogger('info')
  409. try:
  410. # 获取包和AppSecret
  411. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  412. appId = MEIZUPUSH_CONFIG[app_bundle_id]['ID']
  413. appSecret = MEIZUPUSH_CONFIG[app_bundle_id]['AppSecret']
  414. url = 'https://server-api-push.meizu.com/garcia/api/server/push/varnished/pushByPushId'
  415. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  416. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  417. 'uid': uid, 'channel': channel
  418. }
  419. # 转换为json格式
  420. extra_data = json.dumps(extra_data)
  421. if msg_title == '':
  422. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  423. # 拼接发送内容
  424. activity = "com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity" # 应用页面地址
  425. # clickType点击动作, 0打开应用, 1打开应用页面, 2打开url页面, 3应用客户端自定义
  426. messageJson = '{"clickTypeInfo": {"activity": "%s",' \
  427. '"clickType": 1, "parameters": %s },"extra": {},' % (activity, extra_data)
  428. noticeBarInfo = ('"noticeBarInfo": {"title": "%s", "content": "%s"},' % (msg_title, msg_text))
  429. noticeExpandInfo = '"noticeExpandInfo": {"noticeExpandType": 0}, "pushTimeInfo": {"validTime": 24}}'
  430. messageJson += noticeBarInfo
  431. messageJson += noticeExpandInfo
  432. data_meizu = {
  433. 'appId': appId,
  434. 'pushIds': token_val,
  435. 'messageJson': messageJson
  436. }
  437. # 魅族MD5加密,生成密钥
  438. sign = CommonService.getMD5Sign(data=data_meizu, key=appSecret)
  439. data = {
  440. 'appId': appId,
  441. 'messageJson': messageJson,
  442. 'sign': sign,
  443. 'pushIds': token_val,
  444. }
  445. # 进行推送
  446. response = requests.post(url, data=data)
  447. logger.info("魅族推送结果:{}".format(response.json()))
  448. return response.status_code
  449. except Exception as e:
  450. return repr(e)
  451. @staticmethod
  452. def jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, token_val, extra_data):
  453. """
  454. android 极光透传
  455. @param msg_title: 推送标题
  456. @param msg_text: 推送内容
  457. @param token_val: 推送token
  458. @param app_bundle_id: app包id
  459. @param extra_data: 额外数据
  460. @return: None
  461. """
  462. try:
  463. app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  464. master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  465. # 换成各自的app_key和master_secret
  466. _jpush = jpush.JPush(app_key, master_secret)
  467. push = _jpush.create_push()
  468. push.audience = jpush.registration_id(token_val)
  469. push.message = jpush.message(msg_content=msg_text, title=msg_title, extras=extra_data)
  470. push.platform = jpush.all_
  471. res = push.send()
  472. assert res.status_code == 200
  473. LOGGER.info('token为{}的极光透传返回结果:{}'.format(token_val, res))
  474. except Exception as e:
  475. LOGGER.info('token为{}极光透传返回结果, errLine:{}, errMsg:{}'.format(token_val, e.__traceback__.tb_lineno, repr(e)))
  476. return repr(e)