PushService.py 29 KB

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