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