PushService.py 30 KB

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