PushService.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 firebase_admin
  15. import jpush
  16. import requests
  17. from firebase_admin import messaging, credentials
  18. from pyfcm import FCMNotification
  19. from AnsjerPush.config import APP_BUNDLE_DICT, APNS_MODE, BASE_DIR, APNS_CONFIG, FCM_CONFIG, JPUSH_CONFIG, XMPUSH_CONFIG \
  20. , VIVOPUSH_CONFIG, OPPOPUSH_CONFIG, MEIZUPUSH_CONFIG, CONFIG_INFO, HONORPUSH_CONFIG
  21. from Model.models import UidPushModel
  22. from Object.RedisObject import RedisObject
  23. from Object.S3Email import S3Email
  24. from Service.CommonService import CommonService
  25. from Service.VivoPushService.push_admin.APIMessage import PushMessage
  26. from Service.VivoPushService.push_admin.APISender import APISender
  27. from AnsjerPush.config import LOGGER
  28. class PushObject:
  29. # 推送对象
  30. @staticmethod
  31. def get_msg_title(nickname):
  32. """
  33. 获取推送消息标题
  34. @param nickname: 设备名
  35. @return: msg_title
  36. """
  37. return nickname
  38. @staticmethod
  39. def get_gateway_msg_text(n_time, tz, lang, alarm):
  40. """
  41. 获取网关推送消息内容
  42. @param n_time: 当前时间
  43. @param tz: 时区
  44. @param lang: 语言
  45. @param alarm: 警报
  46. @return: msg_text
  47. """
  48. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  49. if lang == 'cn':
  50. msg_text = '{} 日期:{}'.format(alarm, n_date)
  51. else:
  52. msg_text = '{} date:{}'.format(alarm, n_date)
  53. return msg_text
  54. @staticmethod
  55. def get_ai_msg_text(channel, n_time, lang, tz, label):
  56. """
  57. 获取AI推送内容
  58. @param channel: 通道
  59. @param n_time: 当前时间
  60. @param lang: 语言
  61. @param tz: 时区
  62. @param label: 识别到的标签
  63. @return: ai_msg_text
  64. """
  65. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  66. if lang == 'cn':
  67. msg = '摄像头AI识别到了{}'.format(label)
  68. ai_msg_text = '{msg} 通道:{channel} 日期:{date}'.format(msg=msg, channel=channel, date=n_date)
  69. else:
  70. msg = 'Camera AI recognizes {}'.format(label)
  71. ai_msg_text = '{msg} channel:{channel} date:{date}'.format(msg=msg, channel=channel, date=n_date)
  72. return ai_msg_text
  73. @staticmethod
  74. def get_low_power_msg_text(channel, n_time, lang, tz, electricity, is_sys=0):
  75. """
  76. 获取低电量推送内容
  77. @param channel: 通道
  78. @param n_time: 当前时间
  79. @param lang: 语言
  80. @param tz: 时区
  81. @param electricity: 电量
  82. @param is_sys: 是否为系统消息
  83. @return: low_power_msg_text
  84. """
  85. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  86. if lang == 'cn':
  87. alarm = '剩余电量 ' + electricity
  88. if is_sys:
  89. low_power_msg_text = '{} 通道:{}'.format(alarm, channel)
  90. else:
  91. low_power_msg_text = '{} 通道:{} 日期:{}'.format(alarm, channel, n_date)
  92. else:
  93. alarm = 'Battery remaining ' + electricity
  94. if is_sys:
  95. low_power_msg_text = '{} channel:{}'.format(alarm, channel)
  96. else:
  97. low_power_msg_text = '{} channel:{} date:{}'.format(alarm, channel, n_date)
  98. return low_power_msg_text
  99. @staticmethod
  100. def ios_apns_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  101. uid='', channel='1', launch_image=None):
  102. """
  103. ios apns 推送
  104. @param nickname: 设备昵称
  105. @param app_bundle_id: app包id
  106. @param token_val: 推送token
  107. @param n_time: 当前时间
  108. @param event_type: 事件类型
  109. @param msg_title: 推送标题
  110. @param msg_text: 推送内容
  111. @param uid: uid
  112. @param channel: 通道
  113. @param launch_image: 推送图片链接
  114. @return: bool
  115. """
  116. pem_path = os.path.join(BASE_DIR, APNS_CONFIG[app_bundle_id]['pem_path'])
  117. LOGGER.info('IOS推送: app_bundle_id:{}, pem_path:{}'.format(app_bundle_id, pem_path))
  118. try:
  119. cli = apns2.APNSClient(mode=APNS_MODE, client_cert=pem_path)
  120. alert = apns2.PayloadAlert(title=msg_title, body=msg_text, launch_image=launch_image)
  121. push_data = {'alert': 'Motion', 'msg': '', 'sound': '', 'zpush': '1', 'uid': uid, 'channel': channel,
  122. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  123. 'image_url': launch_image
  124. }
  125. payload = apns2.Payload(alert=alert, custom=push_data, sound='default', category='myCategory',
  126. mutable_content=True)
  127. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  128. res = cli.push(n=n, device_token=token_val, topic=app_bundle_id)
  129. LOGGER.info('IOS推送响应状态码{},params,uid:{},{}'.format(res.status_code, uid, json.dumps(push_data)))
  130. assert res.status_code == 200
  131. return True
  132. except Exception as e:
  133. LOGGER.info('IOS推送异常: {}, 证书路径: {}'.format(repr(e), pem_path))
  134. return False
  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: bool
  151. """
  152. try:
  153. serverKey = FCM_CONFIG[app_bundle_id]
  154. push_service = FCMNotification(api_key=serverKey)
  155. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  156. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  157. 'uid': uid, 'channel': channel
  158. }
  159. if event_type in [606, 607]:
  160. push_data['priority'] = 'high'
  161. push_data['content_available'] = True
  162. push_data['direct_boot_ok'] = True
  163. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  164. message_body=msg_text, data_message=push_data,
  165. click_action='android.intent.action.VIEW',
  166. extra_kwargs={'default_sound': True,
  167. 'default_vibrate_timings': True,
  168. 'default_light_settings': True,
  169. },
  170. )
  171. LOGGER.info('fcm推送结果:{}'.format(result))
  172. return True
  173. except Exception as e:
  174. LOGGER.info('fcm推送异常:{}'.format(repr(e)))
  175. return False
  176. @staticmethod
  177. def android_fcm_push_v1(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  178. uid='', channel='1', image=''):
  179. """
  180. android fcm 推送
  181. @param nickname: 设备昵称
  182. @param app_bundle_id: app包id
  183. @param token_val: 推送token
  184. @param n_time: 当前时间
  185. @param event_type: 事件类型
  186. @param msg_title: 推送标题
  187. @param msg_text: 推送内容
  188. @param uid: uid
  189. @param channel: 通道
  190. @param image: 推送图片链接
  191. @return: bool
  192. """
  193. try:
  194. # See documentation on defining a message payload.
  195. cred = credentials.Certificate(
  196. BASE_DIR + '/static/fcm/adcloud-fdf9b-firebase-adminsdk-dcvn1-d53e047cc8.json')
  197. firebase_admin.initialize_app(cred)
  198. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  199. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  200. 'uid': uid, 'channel': channel
  201. }
  202. if event_type in [606, 607]:
  203. push_data['priority'] = 'high'
  204. push_data['content_available'] = True
  205. push_data['direct_boot_ok'] = True
  206. message = messaging.Message(
  207. data=push_data,
  208. token=token_val,
  209. )
  210. # Send a message to the device corresponding to the provided
  211. # registration token.
  212. result = messaging.send(message)
  213. LOGGER.info('fcm推送结果:{}'.format(result))
  214. return True
  215. except Exception as e:
  216. LOGGER.info('fcm推送异常:{}'.format(repr(e)))
  217. return False
  218. @staticmethod
  219. def android_jpush(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text, channel=1):
  220. """
  221. android 极光 推送
  222. @param nickname: 设备昵称
  223. @param app_bundle_id: app包id
  224. @param token_val: 推送token
  225. @param n_time: 当前时间
  226. @param event_type: 事件类型
  227. @param msg_title: 推送标题
  228. @param msg_text: 推送内容
  229. @param channel: 设备通道
  230. @return: bool
  231. """
  232. try:
  233. app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  234. master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  235. # 换成各自的app_key和master_secret
  236. _jpush = jpush.JPush(app_key, master_secret)
  237. push = _jpush.create_push()
  238. push.audience = jpush.registration_id(token_val)
  239. if event_type in [606, 607]:
  240. channel_id = '111934'
  241. else:
  242. channel_id = '1'
  243. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'uid': nickname,
  244. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  245. 'channel': channel
  246. }
  247. android = jpush.android(title=msg_title, big_text=msg_text, alert=msg_text, extras=push_data,
  248. priority=1, style=1, alert_type=7, channel_id=channel_id
  249. )
  250. push.notification = jpush.notification(android=android)
  251. push.platform = jpush.all_
  252. res = push.send()
  253. assert res.status_code == 200
  254. return True
  255. except Exception as e:
  256. LOGGER.info('极光推送异常:{}'.format(repr(e)))
  257. return False
  258. @staticmethod
  259. def android_xmpush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  260. uid='', channel='1', image=''):
  261. """
  262. android 小米 推送
  263. @param channel_id: 通知通道
  264. @param nickname: 设备昵称
  265. @param app_bundle_id: app包id
  266. @param token_val: 推送token
  267. @param n_time: 当前时间
  268. @param event_type: 事件类型
  269. @param msg_title: 推送标题
  270. @param msg_text: 推送内容
  271. @param uid: uid
  272. @param channel: 通道
  273. @param image: 推送图片链接
  274. @return: bool
  275. """
  276. try:
  277. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  278. app_secret = XMPUSH_CONFIG[app_bundle_id]
  279. # payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  280. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  281. # 'uid': uid, 'channel': channel
  282. # }
  283. data = {
  284. 'title': msg_title,
  285. 'description': msg_text,
  286. 'payload': 'payload',
  287. 'restricted_package_name': app_bundle_id,
  288. 'registration_id': token_val,
  289. 'extra.channel_id': channel_id,
  290. 'extra.alert': 'Motion',
  291. 'extra.msg': '',
  292. 'extra.sound': 'sound.aif',
  293. 'extra.zpush': '1',
  294. 'extra.received_at': n_time,
  295. 'extra.event_time': n_time,
  296. 'extra.event_type': event_type,
  297. 'extra.nickname': nickname,
  298. 'extra.uid': uid,
  299. 'extra.channel': channel,
  300. }
  301. # if image:
  302. # data['extra.notification_style_type'] = 2
  303. # data['extra.notification_bigPic_uri'] = image
  304. headers = {
  305. 'Authorization': 'key={}'.format(app_secret)
  306. }
  307. response = requests.post(url, data=data, headers=headers)
  308. LOGGER.info("小米推送返回值:{}".format(response.json()))
  309. assert response.status_code == 200
  310. return True
  311. except Exception as e:
  312. LOGGER.info("小米推送异常:{}".format(repr(e)))
  313. return False
  314. @staticmethod
  315. def android_vivopush(token_val, n_time, event_type, msg_title, msg_text, app_bundle_id='', uid='', channel='1',
  316. image='', nickname='', appBundleId='', jg_token_val=''):
  317. """
  318. vivo 推送(不支持图片)
  319. @param app_bundle_id: app包名
  320. @param appBundleId: app包名
  321. @param token_val: 推送token
  322. @param jg_token_val: 极光推送token
  323. @param event_type: 事件类型
  324. @param msg_title: 推送标题
  325. @param msg_text: 推送内容
  326. @param n_time: 当前时间
  327. @param nickname: 设备昵称
  328. @param uid: uid
  329. @param image: 推送图片链接
  330. @param channel: 通道
  331. @return: bool
  332. """
  333. try:
  334. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  335. # 获取redis里面的authToken
  336. if msg_title == '':
  337. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  338. app_id = VIVOPUSH_CONFIG[app_bundle_id]['ID']
  339. app_key = VIVOPUSH_CONFIG[app_bundle_id]['Key']
  340. app_secret = VIVOPUSH_CONFIG[app_bundle_id]['Secret']
  341. sender = APISender(app_secret)
  342. rec = sender.get_token(app_id, app_key)
  343. # 鉴权接口调用获得authToken
  344. sender_send = APISender(app_secret)
  345. sender_send.set_token(rec['authToken'])
  346. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  347. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  348. 'uid': uid, 'channel': channel
  349. }
  350. # 获取唯一标识符
  351. uid_push_qs = UidPushModel.objects.filter(token_val=token_val).values('m_code')
  352. m_code = uid_push_qs[0]['m_code'] if uid_push_qs[0]['m_code'] else ''
  353. # 推送 push_mode: 推送模式 (0:正式推送;1:测试推送,默认为0)
  354. # 推送 event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  355. # 推送 skip_type: 跳转类型(1:打开 APP 首页 2:打开链接 3:自定义 4:打开 app 内指定页面)
  356. activity = 'vpushscheme://com.vivo.pushvideo/detail'
  357. message = PushMessage() \
  358. .reg_id(token_val) \
  359. .title(msg_title) \
  360. .content(msg_text) \
  361. .push_mode(0) \
  362. .notify_type(3) \
  363. .skip_type(4) \
  364. .skip_content(activity) \
  365. .request_id(m_code) \
  366. .classification(1) \
  367. .client_custom_map(**push_data) \
  368. .message_dict()
  369. rec = sender_send.send(message)
  370. LOGGER.info('vivo推送结果:{}, 设备uid:{}'.format(rec, uid))
  371. if rec['result'] == 0 and event_type in [606, 607]:
  372. PushObject.jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, jg_token_val, push_data)
  373. return True
  374. except Exception as e:
  375. LOGGER.info('vivo推送异常:{}'.format(e))
  376. return False
  377. @staticmethod
  378. def android_oppopush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  379. uid='', channel='1', image='', jg_token_val=''):
  380. """
  381. android oppo 推送
  382. @param channel_id: 通知通道id
  383. @param nickname: 设备昵称
  384. @param app_bundle_id: app包id
  385. @param token_val: 推送token
  386. @param jg_token_val: 推送token
  387. @param n_time: 当前时间
  388. @param event_type: 事件类型
  389. @param msg_title: 推送标题
  390. @param msg_text: 推送内容
  391. @param uid: uid
  392. @param channel: 通道
  393. @param image: 推送图片链接
  394. @return: bool
  395. """
  396. try:
  397. """
  398. android 国内oppo APP消息提醒推送
  399. """
  400. app_key = OPPOPUSH_CONFIG[app_bundle_id]['Key']
  401. master_secret = OPPOPUSH_CONFIG[app_bundle_id]['Secret']
  402. url = 'https://api.push.oppomobile.com/'
  403. now_time = str(round(time.time() * 1000))
  404. # 1、实例化一个sha256对象
  405. sha256 = hashlib.sha256()
  406. # 2、调用update方法进行加密
  407. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  408. # 3、调用hexdigest方法,获取加密结果
  409. sign = sha256.hexdigest()
  410. # 获取auth_token
  411. get_token_url = url + 'server/v1/auth'
  412. post_data = {
  413. 'app_key': app_key,
  414. 'sign': sign,
  415. 'timestamp': now_time
  416. }
  417. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  418. response = requests.post(get_token_url, data=post_data, headers=headers)
  419. result = response.json()
  420. # 发送推送
  421. push_url = url + 'server/v1/message/notification/unicast'
  422. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  423. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  424. 'uid': uid, 'channel': channel
  425. }
  426. message = {
  427. "target_type": 2,
  428. "target_value": token_val,
  429. "notification": {
  430. "title": msg_title,
  431. "content": msg_text,
  432. 'channel_id': channel_id,
  433. 'action_parameters': extra_data,
  434. 'click_action_type': 1,
  435. 'click_action_activity': 'com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity'
  436. }
  437. }
  438. push_data = {
  439. 'auth_token': result['data']['auth_token'],
  440. 'message': json.dumps(message)
  441. }
  442. response = requests.post(push_url, data=push_data, headers=headers)
  443. LOGGER.info("oppo推送返回值:{}".format(response.json()))
  444. if response.status_code == 200 and event_type in [606, 607]:
  445. PushObject.jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, jg_token_val, extra_data)
  446. return True
  447. except Exception as e:
  448. LOGGER.info("oppo推送异常:{}".format(repr(e)))
  449. return False
  450. @staticmethod
  451. def android_meizupush(token_val, n_time, event_type, msg_title, msg_text, uid='', channel='1',
  452. app_bundle_id='', appBundleId='', nickname='', image=''):
  453. """
  454. android 魅族推送(不支持图片)
  455. @param app_bundle_id: app包名
  456. @param appBundleId: app包名
  457. @param token_val: 推送token
  458. @param event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  459. @param msg_title: 推送标题
  460. @param msg_text: 推送内容
  461. @param n_time: 当前时间
  462. @param nickname: 设备昵称
  463. @param uid: uid
  464. @param image: 推送图片链接
  465. @param channel: 通道
  466. @return: bool
  467. """
  468. try:
  469. # 获取包和AppSecret
  470. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  471. appId = MEIZUPUSH_CONFIG[app_bundle_id]['ID']
  472. appSecret = MEIZUPUSH_CONFIG[app_bundle_id]['AppSecret']
  473. url = 'https://server-api-push.meizu.com/garcia/api/server/push/varnished/pushByPushId'
  474. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  475. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  476. 'uid': uid, 'channel': channel
  477. }
  478. # 转换为json格式
  479. extra_data = json.dumps(extra_data)
  480. if msg_title == '':
  481. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  482. # 拼接发送内容
  483. activity = "com.ansjer.zccloud_a.AJ_MainView.AJ_Home.AJMainActivity" # 应用页面地址
  484. # clickType点击动作, 0打开应用, 1打开应用页面, 2打开url页面, 3应用客户端自定义
  485. messageJson = '{"clickTypeInfo": {"activity": "%s",' \
  486. '"clickType": 1, "parameters": %s },"extra": {},' % (activity, extra_data)
  487. noticeBarInfo = ('"noticeBarInfo": {"title": "%s", "content": "%s"},' % (msg_title, msg_text))
  488. noticeExpandInfo = '"noticeExpandInfo": {"noticeExpandType": 0}, "pushTimeInfo": {"validTime": 24}}'
  489. messageJson += noticeBarInfo
  490. messageJson += noticeExpandInfo
  491. data_meizu = {
  492. 'appId': appId,
  493. 'pushIds': token_val,
  494. 'messageJson': messageJson
  495. }
  496. # 魅族MD5加密,生成密钥
  497. sign = CommonService.getMD5Sign(data=data_meizu, key=appSecret)
  498. data = {
  499. 'appId': appId,
  500. 'messageJson': messageJson,
  501. 'sign': sign,
  502. 'pushIds': token_val,
  503. }
  504. # 进行推送
  505. response = requests.post(url, data=data)
  506. LOGGER.info("魅族推送结果:{}".format(response.json()))
  507. return True
  508. except Exception as e:
  509. LOGGER.info("魅族推送异常:{}".format(repr(e)))
  510. return False
  511. @staticmethod
  512. def android_honorpush(token_val, n_time, event_type, msg_title, msg_text,
  513. uid='', channel='1', image='', app_bundle_id='', appBundleId='', channel_id='', nickname=''):
  514. """
  515. android honor 推送
  516. @param channel_id: 通知通道id
  517. @param nickname: 设备昵称
  518. @param app_bundle_id: app包id
  519. @param appBundleId: app包id
  520. @param token_val: 推送token
  521. @param n_time: 当前时间
  522. @param event_type: 事件类型
  523. @param msg_title: 推送标题
  524. @param msg_text: 推送内容
  525. @param uid: uid
  526. @param channel: 通道
  527. @param image: 推送图片链接
  528. @return: bool
  529. """
  530. app_bundle_id = appBundleId if appBundleId else app_bundle_id
  531. try:
  532. client_id = HONORPUSH_CONFIG[app_bundle_id]['client_id']
  533. client_secret = HONORPUSH_CONFIG[app_bundle_id]['client_secret']
  534. app_id = HONORPUSH_CONFIG[app_bundle_id]['app_id']
  535. get_access_token_url = 'https://iam.developer.hihonor.com/auth/token'
  536. post_data = {
  537. 'grant_type': 'client_credentials',
  538. 'client_id': client_id,
  539. 'client_secret': client_secret
  540. }
  541. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  542. access_token_response = requests.post(get_access_token_url, data=post_data, headers=headers)
  543. access_result = access_token_response.json()
  544. authorization_token = 'Bearer ' + access_result['access_token']
  545. # 发送推送
  546. push_url = 'https://push-api.cloud.hihonor.com/api/v1/{}/sendMessage'.format(app_id)
  547. headers = {'Content-Type': 'application/json', 'Authorization': authorization_token,
  548. 'timestamp': str(int(time.time()) * 1000)}
  549. extra_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  550. 'received_at': n_time, 'event_time': n_time, 'event_type': str(event_type), 'nickname': nickname,
  551. 'uid': uid, 'channel': channel, 'title': msg_title, 'body': msg_text
  552. }
  553. # 通知推送
  554. push_data = {
  555. "android": {
  556. "notification": {
  557. "body": msg_text,
  558. "title": msg_title,
  559. "importance": "NORMAL",
  560. "clickAction": {
  561. "type": 3
  562. }
  563. },
  564. "targetUserType": 0,
  565. "data": json.dumps(extra_data)
  566. },
  567. "token": [token_val]
  568. }
  569. response = requests.post(push_url, json=push_data, headers=headers)
  570. LOGGER.info("uid:{},时间:{},荣耀推送通知返回值:{}".format(uid, n_time, response.json()))
  571. # 一键通话透传推送
  572. if int(event_type) in [606, 607]:
  573. push_data = {
  574. "data": json.dumps(extra_data),
  575. "token": [token_val]
  576. }
  577. response = requests.post(push_url, json=push_data, headers=headers)
  578. LOGGER.info("uid:{},时间:{},荣耀透传推送返回值:{}".format(uid, n_time, response.json()))
  579. return True
  580. except Exception as e:
  581. LOGGER.info("荣耀推送异常:error_line:{},error_msg:{}".format(e.__traceback__.tb_lineno, repr(e)))
  582. return False
  583. @staticmethod
  584. def jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, token_val, extra_data):
  585. """
  586. android 极光透传
  587. @param msg_title: 推送标题
  588. @param msg_text: 推送内容
  589. @param token_val: 推送token
  590. @param app_bundle_id: app包id
  591. @param extra_data: 额外数据
  592. @return: None
  593. """
  594. try:
  595. app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  596. master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  597. # 换成各自的app_key和master_secret
  598. _jpush = jpush.JPush(app_key, master_secret)
  599. push = _jpush.create_push()
  600. push.audience = jpush.registration_id(token_val)
  601. push.message = jpush.message(msg_content=msg_text, title=msg_title, extras=extra_data)
  602. push.platform = jpush.all_
  603. res = push.send()
  604. assert res.status_code == 200
  605. except Exception as e:
  606. return repr(e)