PushService.py 31 KB

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