PushService.py 20 KB

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