PushService.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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=''):
  256. """
  257. vivo 推送(不支持图片)
  258. @param app_bundle_id: app包名
  259. @param appBundleId: app包名
  260. @param token_val: 推送token
  261. @param event_type: 事件类型
  262. @param msg_title: 推送标题
  263. @param msg_text: 推送内容
  264. @param n_time: 当前时间
  265. @param nickname: 设备昵称
  266. @param uid: uid
  267. @param image: 推送图片链接
  268. @param channel: 通道
  269. @return: None
  270. """
  271. logger = logging.getLogger('info')
  272. try:
  273. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  274. # 获取redis里面的authToken
  275. if msg_title == '':
  276. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  277. app_id = VIVOPUSH_CONFIG[app_bundle_id]['ID']
  278. app_key = VIVOPUSH_CONFIG[app_bundle_id]['Key']
  279. app_secret = VIVOPUSH_CONFIG[app_bundle_id]['Secret']
  280. sender = APISender(app_secret)
  281. rec = sender.get_token(app_id, app_key)
  282. # 鉴权接口调用获得authToken
  283. sender_send = APISender(app_secret)
  284. sender_send.set_token(rec['authToken'])
  285. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  286. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  287. 'uid': uid, 'channel': channel
  288. }
  289. # 获取唯一标识符
  290. uid_push_qs = UidPushModel.objects.filter(token_val=token_val).values('m_code')
  291. m_code = uid_push_qs[0]['m_code'] if uid_push_qs[0]['m_code'] else ''
  292. # 推送 push_mode: 推送模式 (0:正式推送;1:测试推送,默认为0)
  293. # 推送 event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  294. # 推送 skip_type: 跳转类型(1:打开 APP 首页 2:打开链接 3:自定义 4:打开 app 内指定页面)
  295. activity = 'vpushscheme://com.vivo.pushvideo/detail'
  296. message = PushMessage() \
  297. .reg_id(token_val) \
  298. .title(msg_title) \
  299. .content(msg_text) \
  300. .push_mode(0) \
  301. .notify_type(3) \
  302. .skip_type(4) \
  303. .skip_content(activity) \
  304. .request_id(m_code) \
  305. .classification(1) \
  306. .client_custom_map(**push_data) \
  307. .message_dict()
  308. rec = sender_send.send(message)
  309. logger.info('vivo推送结果:{}, 设备uid:{}'.format(rec, uid))
  310. return rec
  311. except Exception as e:
  312. logger.info('vivo推送异常:{}'.format(e))
  313. @staticmethod
  314. def android_oppopush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  315. uid='', channel='1', image=''):
  316. """
  317. android oppo 推送
  318. @param channel_id: 通知通道id
  319. @param nickname: 设备昵称
  320. @param app_bundle_id: app包id
  321. @param token_val: 推送token
  322. @param n_time: 当前时间
  323. @param event_type: 事件类型
  324. @param msg_title: 推送标题
  325. @param msg_text: 推送内容
  326. @param uid: uid
  327. @param channel: 通道
  328. @param image: 推送图片链接
  329. @return: None
  330. """
  331. logger = logging.getLogger('info')
  332. try:
  333. """
  334. android 国内oppo APP消息提醒推送
  335. """
  336. app_key = OPPOPUSH_CONFIG[app_bundle_id]['Key']
  337. master_secret = OPPOPUSH_CONFIG[app_bundle_id]['Secret']
  338. url = 'https://api.push.oppomobile.com/'
  339. now_time = str(round(time.time() * 1000))
  340. # 1、实例化一个sha256对象
  341. sha256 = hashlib.sha256()
  342. # 2、调用update方法进行加密
  343. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  344. # 3、调用hexdigest方法,获取加密结果
  345. sign = sha256.hexdigest()
  346. # 获取auth_token
  347. get_token_url = url + 'server/v1/auth'
  348. post_data = {
  349. 'app_key': app_key,
  350. 'sign': sign,
  351. 'timestamp': now_time
  352. }
  353. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  354. response = requests.post(get_token_url, data=post_data, headers=headers)
  355. result = response.json()
  356. # 发送推送
  357. push_url = url + 'server/v1/message/notification/unicast'
  358. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  359. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  360. 'uid': uid, 'channel': channel
  361. }
  362. message = {
  363. "target_type": 2,
  364. "target_value": token_val,
  365. "notification": {
  366. "title": msg_title,
  367. "content": msg_text,
  368. 'channel_id': channel_id,
  369. 'action_parameters': extra_data,
  370. 'click_action_type': 1,
  371. 'click_action_activity': 'com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity'
  372. }
  373. }
  374. push_data = {
  375. 'auth_token': result['data']['auth_token'],
  376. 'message': json.dumps(message)
  377. }
  378. response = requests.post(push_url, data=push_data, headers=headers)
  379. logger.info("oppo推送返回值:{}".format(response.json()))
  380. assert response.status_code == 200
  381. except Exception as e:
  382. return repr(e)
  383. @staticmethod
  384. def android_meizupush(token_val, n_time, event_type, msg_title, msg_text, uid='', channel='1',
  385. app_bundle_id='', appBundleId='', nickname='', image=''):
  386. """
  387. android 魅族推送(不支持图片)
  388. @param app_bundle_id: app包名
  389. @param appBundleId: app包名
  390. @param token_val: 推送token
  391. @param event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  392. @param msg_title: 推送标题
  393. @param msg_text: 推送内容
  394. @param n_time: 当前时间
  395. @param nickname: 设备昵称
  396. @param uid: uid
  397. @param image: 推送图片链接
  398. @param channel: 通道
  399. @return: None
  400. """
  401. logger = logging.getLogger('info')
  402. try:
  403. # 获取包和AppSecret
  404. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  405. appId = MEIZUPUSH_CONFIG[app_bundle_id]['ID']
  406. appSecret = MEIZUPUSH_CONFIG[app_bundle_id]['AppSecret']
  407. url = 'https://server-api-push.meizu.com/garcia/api/server/push/varnished/pushByPushId'
  408. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  409. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  410. 'uid': uid, 'channel': channel
  411. }
  412. # 转换为json格式
  413. extra_data = json.dumps(extra_data)
  414. if msg_title == '':
  415. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  416. # 拼接发送内容
  417. activity = "com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity" # 应用页面地址
  418. # clickType点击动作, 0打开应用, 1打开应用页面, 2打开url页面, 3应用客户端自定义
  419. messageJson = '{"clickTypeInfo": {"activity": "%s",' \
  420. '"clickType": 1, "parameters": %s },"extra": {},' % (activity, extra_data)
  421. noticeBarInfo = ('"noticeBarInfo": {"title": "%s", "content": "%s"},' % (msg_title, msg_text))
  422. noticeExpandInfo = '"noticeExpandInfo": {"noticeExpandType": 0}, "pushTimeInfo": {"validTime": 24}}'
  423. messageJson += noticeBarInfo
  424. messageJson += noticeExpandInfo
  425. data_meizu = {
  426. 'appId': appId,
  427. 'pushIds': token_val,
  428. 'messageJson': messageJson
  429. }
  430. # 魅族MD5加密,生成密钥
  431. sign = CommonService.getMD5Sign(data=data_meizu, key=appSecret)
  432. data = {
  433. 'appId': appId,
  434. 'messageJson': messageJson,
  435. 'sign': sign,
  436. 'pushIds': token_val,
  437. }
  438. # 进行推送
  439. response = requests.post(url, data=data)
  440. logger.info("魅族推送结果:{}".format(response.json()))
  441. return response.status_code
  442. except Exception as e:
  443. return repr(e)