PushService.py 31 KB

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