PushService.py 31 KB

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