PushService.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.RedisObject import RedisObject
  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推送响应状态码{}'.format(res.status_code))
  127. assert res.status_code == 200
  128. except Exception as e:
  129. logger.info('--->IOS推送异常{}'.format(repr(e)))
  130. return repr(e)
  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. 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(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  200. uid='', channel='1', image=''):
  201. """
  202. android 小米 推送
  203. @param nickname: 设备昵称
  204. @param app_bundle_id: app包id
  205. @param token_val: 推送token
  206. @param n_time: 当前时间
  207. @param event_type: 事件类型
  208. @param msg_title: 推送标题
  209. @param msg_text: 推送内容
  210. @param uid: uid
  211. @param channel: 通道
  212. @param image: 推送图片链接
  213. @return: None
  214. """
  215. logger = logging.getLogger('info')
  216. try:
  217. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  218. app_secret = XMPUSH_CONFIG[app_bundle_id]
  219. payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  220. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  221. 'uid': uid, 'channel': channel
  222. }
  223. data = {
  224. 'title': msg_title,
  225. 'description': msg_text,
  226. 'payload': 'payload',
  227. 'restricted_package_name': app_bundle_id,
  228. 'registration_id': token_val,
  229. }
  230. # if image:
  231. # data['extra.notification_style_type'] = 2
  232. # data['extra.notification_bigPic_uri'] = image
  233. headers = {
  234. 'Authorization': 'key={}'.format(app_secret)
  235. }
  236. response = requests.post(url, data=data, headers=headers)
  237. logger.info("小米推送返回值:{}".format(response.json()))
  238. assert response.status_code == 200
  239. except Exception as e:
  240. return repr(e)
  241. @staticmethod
  242. def android_vivopush(token_val, n_time, event_type, msg_title, msg_text, app_bundle_id='', uid='', channel='1',
  243. image='', nickname='', appBundleId=''):
  244. """
  245. vivo 推送(不支持图片)
  246. @param app_bundle_id: app包名
  247. @param appBundleId: app包名
  248. @param token_val: 推送token
  249. @param event_type: 事件类型
  250. @param msg_title: 推送标题
  251. @param msg_text: 推送内容
  252. @param n_time: 当前时间
  253. @param nickname: 设备昵称
  254. @param uid: uid
  255. @param image: 推送图片链接
  256. @param channel: 通道
  257. @return: None
  258. """
  259. logger = logging.getLogger('info')
  260. try:
  261. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  262. # 获取redis里面的authToken
  263. if msg_title == '':
  264. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  265. app_id = VIVOPUSH_CONFIG[app_bundle_id]['ID']
  266. app_key = VIVOPUSH_CONFIG[app_bundle_id]['Key']
  267. app_secret = VIVOPUSH_CONFIG[app_bundle_id]['Secret']
  268. sender = APISender(app_secret)
  269. rec = sender.get_token(app_id, app_key)
  270. # 鉴权接口调用获得authToken
  271. sender_send = APISender(app_secret)
  272. sender_send.set_token(rec['authToken'])
  273. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  274. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  275. 'uid': uid, 'channel': channel
  276. }
  277. # 获取唯一标识符
  278. uid_push_qs = UidPushModel.objects.filter(token_val=token_val).values('m_code')
  279. m_code = uid_push_qs[0]['m_code'] if uid_push_qs[0]['m_code'] else ''
  280. # 推送 push_mode: 推送模式 (0:正式推送;1:测试推送,默认为0)
  281. # 推送 event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  282. # 推送 skip_type: 跳转类型(1:打开 APP 首页 2:打开链接 3:自定义 4:打开 app 内指定页面)
  283. message = PushMessage() \
  284. .reg_id(token_val) \
  285. .title(msg_title) \
  286. .content(msg_text) \
  287. .push_mode(1) \
  288. .notify_type(3) \
  289. .skip_type(1) \
  290. .request_id(m_code) \
  291. .classification(0) \
  292. .client_custom_map(**push_data) \
  293. .message_dict()
  294. rec = sender_send.send(message)
  295. logger.info('vivo推送结果:{}'.format(rec))
  296. return rec
  297. except Exception as e:
  298. logger.info('vivo推送异常:{}'.format(e))
  299. @staticmethod
  300. def android_oppopush(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  301. uid='', channel='1', image=''):
  302. """
  303. android oppo 推送
  304. @param nickname: 设备昵称
  305. @param app_bundle_id: app包id
  306. @param token_val: 推送token
  307. @param n_time: 当前时间
  308. @param event_type: 事件类型
  309. @param msg_title: 推送标题
  310. @param msg_text: 推送内容
  311. @param uid: uid
  312. @param channel: 通道
  313. @param image: 推送图片链接
  314. @return: None
  315. """
  316. logger = logging.getLogger('info')
  317. try:
  318. """
  319. android 国内oppo APP消息提醒推送
  320. """
  321. app_key = OPPOPUSH_CONFIG[app_bundle_id]['Key']
  322. master_secret = OPPOPUSH_CONFIG[app_bundle_id]['Secret']
  323. url = 'https://api.push.oppomobile.com/'
  324. now_time = str(round(time.time() * 1000))
  325. # 1、实例化一个sha256对象
  326. sha256 = hashlib.sha256()
  327. # 2、调用update方法进行加密
  328. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  329. # 3、调用hexdigest方法,获取加密结果
  330. sign = sha256.hexdigest()
  331. # 获取auth_token
  332. get_token_url = url + 'server/v1/auth'
  333. post_data = {
  334. 'app_key': app_key,
  335. 'sign': sign,
  336. 'timestamp': now_time
  337. }
  338. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  339. response = requests.post(get_token_url, data=post_data, headers=headers)
  340. result = response.json()
  341. # 发送推送
  342. push_url = url + 'server/v1/message/notification/unicast'
  343. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  344. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  345. 'uid': uid, 'channel': channel
  346. }
  347. message = {
  348. "target_type": 2,
  349. "target_value": token_val,
  350. "notification": {
  351. "title": msg_title,
  352. "content": msg_text,
  353. }
  354. }
  355. push_data = {
  356. 'auth_token': result['data']['auth_token'],
  357. 'message': json.dumps(message)
  358. }
  359. response = requests.post(push_url, data=push_data, headers=headers)
  360. logger.info("oppo推送返回值:{}".format(response.json()))
  361. assert response.status_code == 200
  362. except Exception as e:
  363. return repr(e)
  364. @staticmethod
  365. def android_meizupush(token_val, n_time, event_type, msg_title, msg_text, uid='', channel='1',
  366. app_bundle_id='', appBundleId='', nickname='', image=''):
  367. """
  368. android 魅族推送(不支持图片)
  369. @param app_bundle_id: app包名
  370. @param appBundleId: app包名
  371. @param token_val: 推送token
  372. @param event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  373. @param msg_title: 推送标题
  374. @param msg_text: 推送内容
  375. @param n_time: 当前时间
  376. @param nickname: 设备昵称
  377. @param uid: uid
  378. @param image: 推送图片链接
  379. @param channel: 通道
  380. @return: None
  381. """
  382. logger = logging.getLogger('info')
  383. try:
  384. # 获取包和AppSecret
  385. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  386. appId = MEIZUPUSH_CONFIG[app_bundle_id]['ID']
  387. appSecret = MEIZUPUSH_CONFIG[app_bundle_id]['AppSecret']
  388. url = 'https://server-api-push.meizu.com/garcia/api/server/push/varnished/pushByPushId'
  389. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  390. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  391. 'uid': uid, 'channel': channel
  392. }
  393. if msg_title == '':
  394. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  395. # 拼接发送内容
  396. messageJson = '{"clickTypeInfo":{"activity":"","clickType":0,"customAttribute":""},"extra":{},'
  397. noticeBarInfo = ('"noticeBarInfo": {"title": "%s", "content": "%s"},' % (msg_title, msg_text))
  398. noticeExpandInfo = '"noticeExpandInfo":{"noticeExpandType":0},"pushTimeInfo":{"validTime":24}}'
  399. messageJson += noticeBarInfo
  400. messageJson += noticeExpandInfo
  401. data_meizu = {
  402. 'appId': appId,
  403. 'pushIds': token_val,
  404. 'messageJson': messageJson
  405. }
  406. # 魅族MD5加密,生成密钥
  407. sign = CommonService.getMD5Sign(data=data_meizu, key=appSecret)
  408. data = {
  409. 'appId': appId,
  410. 'messageJson': messageJson,
  411. 'sign': sign,
  412. 'pushIds': token_val,
  413. }
  414. # 进行推送
  415. response = requests.post(url, data=data)
  416. logger.info("魅族推送结果:{}".format(response.json()))
  417. return response.status_code
  418. except Exception as e:
  419. return repr(e)