PushService.py 21 KB

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