PushService.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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 jpush
  14. import requests
  15. import jwt
  16. import httpx
  17. from firebase_admin import messaging
  18. from firebase_admin.messaging import UnregisteredError
  19. from pyfcm import FCMNotification
  20. from AnsjerPush.config import APP_BUNDLE_DICT, BASE_DIR, APNS_CONFIG, FCM_CONFIG, JPUSH_CONFIG, XMPUSH_CONFIG, \
  21. VIVOPUSH_CONFIG, OPPOPUSH_CONFIG, MEIZUPUSH_CONFIG, CONFIG_INFO, HONORPUSH_CONFIG, DATA_PUSH_EVENT_TYPE_LIST, \
  22. CONFIG_TEST
  23. from Model.models import UidPushModel
  24. from Object.enums.ConstantEnum import ConstantEnum
  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. apns_url = "https://api.sandbox.push.apple.com" if CONFIG_INFO == CONFIG_TEST else "https://api.push.apple.com"
  123. url = f"{apns_url}/3/device/{token_val}"
  124. jump_type = CommonService.get_jump_type(event_type)
  125. sound = 'call_phone.mp3' if event_type in DATA_PUSH_EVENT_TYPE_LIST else 'default'
  126. # 构造 body —— 把 image_url 等字段放顶层,便于 Notification Service Extension 直接读取
  127. body = {
  128. "alert": msg_text,
  129. "aps": {
  130. "alert": {
  131. "title": msg_title,
  132. "body": msg_text
  133. },
  134. "sound": sound,
  135. "category": "myCategory",
  136. "mutable-content": 1
  137. },
  138. 'jump_type': jump_type,
  139. 'image_url': launch_image,
  140. "channel": channel,
  141. "event_time": n_time,
  142. "event_type": event_type,
  143. "msg": "",
  144. "received_at": n_time,
  145. "sound": "",
  146. "uid": uid,
  147. "zpush": "1"
  148. }
  149. headers = {
  150. "apns-topic": app_bundle_id,
  151. "apns-push-type": "alert"
  152. }
  153. with httpx.Client(http2=True,timeout=10, cert=str(pem_path),) as client:
  154. res = client.post(url, headers=headers, json=body)
  155. if res.status_code == 200:
  156. LOGGER.info(f"{uid} iOS 推送成功, token:{token_val}")
  157. return True
  158. elif res.status_code == 410:
  159. LOGGER.error(
  160. f"{uid} iOS 推送失败, 状态码: {res.status_code}, 原因: {res.text}, 包名: {app_bundle_id}, iOS token过期"
  161. )
  162. # 删除失效token数据
  163. UidPushModel.objects.filter(uid_set__uid=uid, token_val=token_val).delete()
  164. return False
  165. else:
  166. LOGGER.error(f"{uid} iOS 推送失败,状态码: {res.status_code}, 原因: {res.text}")
  167. return False
  168. except Exception as e:
  169. LOGGER.error(f"{uid} iOS 推送异常: {repr(e)}, 行数: {e.__traceback__.tb_lineno}")
  170. return False
  171. @staticmethod
  172. def ios_p8_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  173. uid='', channel='1', launch_image=None):
  174. """
  175. iOS推送 (P8证书模式)
  176. @param nickname: 设备昵称
  177. @param app_bundle_id: app包id
  178. @param token_val: 推送 token
  179. @param n_time: 当前时间
  180. @param event_type: 事件类型
  181. @param msg_title: 推送标题
  182. @param msg_text: 推送内容
  183. @param uid:uid
  184. @param channel: 通道
  185. @param launch_image: 推送图片链接
  186. @return: bool
  187. """
  188. if app_bundle_id not in ConstantEnum.IOS_P8_CONFIG.value:
  189. return PushObject.ios_apns_push(
  190. nickname=nickname,
  191. app_bundle_id=app_bundle_id,
  192. token_val=token_val,
  193. n_time=n_time,
  194. event_type=event_type,
  195. msg_title=msg_title,
  196. msg_text=msg_text,
  197. uid=uid,
  198. channel=channel,
  199. launch_image=launch_image
  200. )
  201. else:
  202. LOGGER.info("进入 ios_p8_push 方法,准备开始推送")
  203. try:
  204. team_id = ConstantEnum.IOS_P8_CONFIG.value[app_bundle_id]['team_id']
  205. key_id = ConstantEnum.IOS_P8_CONFIG.value[app_bundle_id]['key_id']
  206. p8_path = os.path.join(BASE_DIR, ConstantEnum.IOS_P8_CONFIG.value[app_bundle_id]['pem_path'])
  207. with open(p8_path, "r") as f:
  208. private_key = f.read()
  209. now = int(time.time())
  210. token = jwt.encode(
  211. {"iss": team_id, "iat": now},
  212. private_key,
  213. algorithm="ES256",
  214. headers={"kid": key_id}
  215. )
  216. if isinstance(token, bytes):
  217. token = token.decode("utf-8")
  218. apns_url = "https://api.sandbox.push.apple.com" if CONFIG_INFO == CONFIG_TEST else "https://api.push.apple.com"
  219. url = f"{apns_url}/3/device/{token_val}"
  220. sound = 'call_phone.mp3' if event_type in DATA_PUSH_EVENT_TYPE_LIST else 'default'
  221. body = {
  222. "aps": {
  223. "alert": {
  224. "title": msg_title,
  225. "body": msg_text
  226. },
  227. "sound": sound,
  228. "category": "myCategory",
  229. "mutable-content": 1
  230. },
  231. # ---- 把原来的 push_data 展平到顶层(尤其是 image_url) ----
  232. "jump_type": CommonService.get_jump_type(event_type),
  233. "image_url": launch_image,
  234. "channel": channel,
  235. "event_time": n_time,
  236. "event_type": event_type,
  237. "msg":"",
  238. "received_at": n_time,
  239. "sound":"",
  240. "uid": uid,
  241. "zpush": "1",
  242. "nickname": nickname,
  243. }
  244. headers = {
  245. "authorization": f"bearer {token}",
  246. "apns-topic": app_bundle_id,
  247. "apns-push-type": "alert"
  248. }
  249. with httpx.Client(http2=True, timeout=10,) as client:
  250. res = client.post(url, headers=headers, json=body)
  251. if res.status_code == 200:
  252. LOGGER.info(f"{uid} iOS p8 推送成功, token:{token_val}")
  253. return True
  254. elif res.status_code == 410:
  255. LOGGER.error(
  256. f"{uid} iOS p8 推送失败, 状态码: {res.status_code}, "
  257. f"原因: {res.text}, 包名: {app_bundle_id}, iOS token过期")
  258. # 删除失效token数据
  259. UidPushModel.objects.filter(uid_set__uid=uid, token_val=token_val).delete()
  260. return False
  261. else:
  262. LOGGER.error(f"{uid} iOS p8 推送失败,状态码: {res.status_code}, 原因: {res.text}")
  263. return False
  264. except Exception as e:
  265. LOGGER.error(f"{uid} iOS p8 推送异常: {repr(e)}, 行数: {e.__traceback__.tb_lineno}")
  266. return False
  267. @staticmethod
  268. def android_fcm_push(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  269. uid='', channel='1', image=''):
  270. """
  271. android fcm 推送
  272. @param nickname: 设备昵称
  273. @param app_bundle_id: app包id
  274. @param token_val: 推送token
  275. @param n_time: 当前时间
  276. @param event_type: 事件类型
  277. @param msg_title: 推送标题
  278. @param msg_text: 推送内容
  279. @param uid: uid
  280. @param channel: 通道
  281. @param image: 推送图片链接
  282. @return: bool
  283. """
  284. try:
  285. serverKey = FCM_CONFIG[app_bundle_id]
  286. push_service = FCMNotification(api_key=serverKey)
  287. push_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  288. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  289. 'uid': uid, 'channel': channel
  290. }
  291. if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  292. push_data['priority'] = 'high'
  293. push_data['content_available'] = True
  294. push_data['direct_boot_ok'] = True
  295. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  296. message_body=msg_text, data_message=push_data,
  297. click_action='android.intent.action.VIEW',
  298. extra_kwargs={'default_sound': True,
  299. 'default_vibrate_timings': True,
  300. 'default_light_settings': True,
  301. },
  302. )
  303. TIME_LOGGER.info('uid:{}fcm推送结果:{}'.format(uid, result))
  304. return True
  305. except Exception as e:
  306. TIME_LOGGER.error('uid:{}fcm推送异常:{}'.format(uid, repr(e)))
  307. return False
  308. @staticmethod
  309. def android_fcm_push_v1(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  310. uid='', channel='1', image=''):
  311. """
  312. android fcm 推送
  313. @param nickname: 设备昵称
  314. @param app_bundle_id: app包id
  315. @param token_val: 推送token
  316. @param n_time: 当前时间
  317. @param event_type: 事件类型
  318. @param msg_title: 推送标题
  319. @param msg_text: 推送内容
  320. @param uid: uid
  321. @param channel: 通道
  322. @param image: 推送图片链接
  323. @return: bool
  324. """
  325. try:
  326. event_type = str(event_type)
  327. n_time = str(n_time)
  328. # 跳转类型
  329. jump_type = str(CommonService.get_jump_type(event_type))
  330. # 推送数据类型必须为字符串,否则抛ValueError('Message.data must not contain non-string values.')异常
  331. push_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  332. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  333. 'uid': uid, 'channel': channel, 'jump_type': jump_type
  334. }
  335. if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  336. push_data['priority'] = 'high'
  337. push_data['content_available'] = True
  338. push_data['direct_boot_ok'] = True
  339. message = messaging.Message(
  340. notification=messaging.Notification(
  341. title=msg_title,
  342. body=msg_text,
  343. image=image
  344. ),
  345. data=push_data,
  346. token=token_val,
  347. )
  348. # Send a message to the device corresponding to the provided
  349. # registration token.
  350. result = messaging.send(message)
  351. LOGGER.info('uid:{} fcm推送结果:{}'.format(uid, result))
  352. return True
  353. except UnregisteredError as e:
  354. LOGGER.info('uid:{},token:{},fcm推送异常UnregisteredError:{}'.format(uid, token_val, repr(e)))
  355. # 删除失效token数据
  356. UidPushModel.objects.filter(uid_set__uid=uid, token_val=token_val).delete()
  357. except Exception as e:
  358. LOGGER.info('uid:{} fcm推送异常:{}'.format(uid, repr(e)))
  359. return False
  360. @staticmethod
  361. def android_jpush(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text, channel=1):
  362. """
  363. android 极光 推送
  364. @param nickname: 设备昵称
  365. @param app_bundle_id: app包id
  366. @param token_val: 推送token
  367. @param n_time: 当前时间
  368. @param event_type: 事件类型
  369. @param msg_title: 推送标题
  370. @param msg_text: 推送内容
  371. @param channel: 设备通道
  372. @return: bool
  373. """
  374. try:
  375. # app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  376. # master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  377. # # 换成各自的app_key和master_secret
  378. # _jpush = jpush.JPush(app_key, master_secret)
  379. # push = _jpush.create_push()
  380. # push.audience = jpush.registration_id(token_val)
  381. # if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  382. # channel_id = '111934'
  383. # else:
  384. # channel_id = '1'
  385. # push_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'uid': nickname,
  386. # 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  387. # 'channel': channel
  388. # }
  389. # android = jpush.android(title=msg_title, big_text=msg_text, alert=msg_text, extras=push_data,
  390. # priority=1, style=1, alert_type=7, channel_id=channel_id
  391. # )
  392. # push.notification = jpush.notification(android=android)
  393. # push.platform = jpush.all_
  394. # res = push.send()
  395. # assert res.status_code == 200
  396. return True
  397. except Exception as e:
  398. LOGGER.info('极光推送异常:{}'.format(repr(e)))
  399. return False
  400. @staticmethod
  401. def jpush(nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text, channel=1):
  402. """
  403. android 极光 推送
  404. @param nickname: 设备昵称
  405. @param app_bundle_id: app包id
  406. @param token_val: 推送token
  407. @param n_time: 当前时间
  408. @param event_type: 事件类型
  409. @param msg_title: 推送标题
  410. @param msg_text: 推送内容
  411. @param channel: 设备通道
  412. @return: bool
  413. """
  414. try:
  415. app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  416. master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  417. # 换成各自的app_key和master_secret
  418. _jpush = jpush.JPush(app_key, master_secret)
  419. push = _jpush.create_push()
  420. push.audience = jpush.registration_id(token_val)
  421. if event_type in DATA_PUSH_EVENT_TYPE_LIST:
  422. channel_id = '111934'
  423. else:
  424. channel_id = '1'
  425. # 跳转类型
  426. jump_type = CommonService.get_jump_type(event_type)
  427. push_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'uid': nickname,
  428. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  429. 'channel': channel, 'jump_type': jump_type
  430. }
  431. android = jpush.android(title=msg_title, big_text=msg_text, alert=msg_text, extras=push_data,
  432. priority=1, style=1, alert_type=7, channel_id=channel_id
  433. )
  434. push.notification = jpush.notification(android=android)
  435. push.platform = jpush.all_
  436. res = push.send()
  437. assert res.status_code == 200
  438. LOGGER.info('极光推送响应:{}, 参数:{}, 令牌:{}'.format(res, push_data, token_val))
  439. return True
  440. except Exception as e:
  441. LOGGER.info('极光推送异常:{}'.format(repr(e)))
  442. return False
  443. @staticmethod
  444. def android_xmpush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  445. uid='', channel='1', image=''):
  446. """
  447. android 小米 推送
  448. @param channel_id: 通知通道
  449. @param nickname: 设备昵称
  450. @param app_bundle_id: app包id
  451. @param token_val: 推送token
  452. @param n_time: 当前时间
  453. @param event_type: 事件类型
  454. @param msg_title: 推送标题
  455. @param msg_text: 推送内容
  456. @param uid: uid
  457. @param channel: 通道
  458. @param image: 推送图片链接
  459. @return: bool
  460. """
  461. try:
  462. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  463. app_secret = XMPUSH_CONFIG[app_bundle_id]
  464. # 跳转类型
  465. jump_type = CommonService.get_jump_type(event_type)
  466. data = {
  467. 'title': msg_title,
  468. 'description': msg_text,
  469. 'payload': 'payload',
  470. 'restricted_package_name': app_bundle_id,
  471. 'registration_id': token_val,
  472. 'extra.channel_id': channel_id,
  473. 'extra.alert': msg_text,
  474. 'extra.msg': '',
  475. 'extra.sound': 'sound.aif',
  476. 'extra.zpush': '1',
  477. 'extra.received_at': n_time,
  478. 'extra.event_time': n_time,
  479. 'extra.event_type': event_type,
  480. 'extra.nickname': nickname,
  481. 'extra.uid': uid,
  482. 'extra.channel': channel,
  483. 'extra.jump_type': jump_type
  484. }
  485. # if image:
  486. # data['extra.notification_style_type'] = 2
  487. # data['extra.notification_bigPic_uri'] = image
  488. headers = {
  489. 'Authorization': 'key={}'.format(app_secret)
  490. }
  491. response = requests.post(url, data=data, headers=headers)
  492. LOGGER.info("小米推送返回值:{}".format(response.json()))
  493. assert response.status_code == 200
  494. return True
  495. except Exception as e:
  496. LOGGER.info("小米推送异常:{}".format(repr(e)))
  497. return False
  498. @staticmethod
  499. def android_vivopush(token_val, n_time, event_type, msg_title, msg_text, app_bundle_id='', uid='', channel='1',
  500. image='', nickname='', appBundleId='', jg_token_val=''):
  501. """
  502. vivo 推送(不支持图片)
  503. @param app_bundle_id: app包名
  504. @param appBundleId: app包名
  505. @param token_val: 推送token
  506. @param jg_token_val: 极光推送token
  507. @param event_type: 事件类型
  508. @param msg_title: 推送标题
  509. @param msg_text: 推送内容
  510. @param n_time: 当前时间
  511. @param nickname: 设备昵称
  512. @param uid: uid
  513. @param image: 推送图片链接
  514. @param channel: 通道
  515. @return: bool
  516. """
  517. try:
  518. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  519. # 获取redis里面的authToken
  520. if msg_title == '':
  521. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  522. app_id = VIVOPUSH_CONFIG[app_bundle_id]['ID']
  523. app_key = VIVOPUSH_CONFIG[app_bundle_id]['Key']
  524. app_secret = VIVOPUSH_CONFIG[app_bundle_id]['Secret']
  525. sender = APISender(app_secret)
  526. rec = sender.get_token(app_id, app_key)
  527. # 鉴权接口调用获得authToken
  528. sender_send = APISender(app_secret)
  529. sender_send.set_token(rec['authToken'])
  530. # 跳转类型
  531. jump_type = CommonService.get_jump_type(event_type)
  532. push_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1', 'image': image,
  533. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  534. 'uid': uid, 'channel': channel, 'jump_type': jump_type
  535. }
  536. # 获取唯一标识符
  537. uid_push_qs = UidPushModel.objects.filter(token_val=token_val).values('m_code')
  538. m_code = uid_push_qs[0]['m_code'] if uid_push_qs[0]['m_code'] else ''
  539. # 推送 push_mode: 推送模式 (0:正式推送;1:测试推送,默认为0)
  540. # 推送 event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  541. # 推送 skip_type: 跳转类型(1:打开 APP 首页 2:打开链接 3:自定义 4:打开 app 内指定页面)
  542. activity = 'vpushscheme://com.vivo.pushvideo/detail'
  543. message = PushMessage() \
  544. .reg_id(token_val) \
  545. .title(msg_title) \
  546. .content(msg_text) \
  547. .push_mode(0) \
  548. .notify_type(3) \
  549. .skip_type(4) \
  550. .skip_content(activity) \
  551. .request_id(m_code) \
  552. .classification(1) \
  553. .client_custom_map(**push_data) \
  554. .message_dict()
  555. rec = sender_send.send(message)
  556. LOGGER.info('vivo推送结果:{}, 设备uid:{}'.format(rec, uid))
  557. if rec['result'] == 0 and event_type in DATA_PUSH_EVENT_TYPE_LIST:
  558. PushObject.jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, jg_token_val, push_data)
  559. return True
  560. except Exception as e:
  561. LOGGER.error('vivo推送异常,uid:{},error_line:{},error_msg:{}'.
  562. format(uid, e.__traceback__.tb_lineno, repr(e)))
  563. return False
  564. @staticmethod
  565. def android_oppopush(channel_id, nickname, app_bundle_id, token_val, n_time, event_type, msg_title, msg_text,
  566. uid='', channel='1', image='', jg_token_val=''):
  567. """
  568. android oppo 推送
  569. @param channel_id: 通知通道id
  570. @param nickname: 设备昵称
  571. @param app_bundle_id: app包id
  572. @param token_val: 推送token
  573. @param jg_token_val: 推送token
  574. @param n_time: 当前时间
  575. @param event_type: 事件类型
  576. @param msg_title: 推送标题
  577. @param msg_text: 推送内容
  578. @param uid: uid
  579. @param channel: 通道
  580. @param image: 推送图片链接
  581. @return: bool
  582. """
  583. try:
  584. """
  585. android 国内oppo APP消息提醒推送
  586. """
  587. app_key = OPPOPUSH_CONFIG[app_bundle_id]['Key']
  588. master_secret = OPPOPUSH_CONFIG[app_bundle_id]['Secret']
  589. url = 'https://api.push.oppomobile.com/'
  590. now_time = str(round(time.time() * 1000))
  591. # 1、实例化一个sha256对象
  592. sha256 = hashlib.sha256()
  593. # 2、调用update方法进行加密
  594. sha256.update((app_key + now_time + master_secret).encode('utf-8'))
  595. # 3、调用hexdigest方法,获取加密结果
  596. sign = sha256.hexdigest()
  597. # 获取auth_token
  598. get_token_url = url + 'server/v1/auth'
  599. post_data = {
  600. 'app_key': app_key,
  601. 'sign': sign,
  602. 'timestamp': now_time
  603. }
  604. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  605. response = requests.post(get_token_url, data=post_data, headers=headers)
  606. result = response.json()
  607. # 发送推送
  608. push_url = url + 'server/v1/message/notification/unicast'
  609. extra_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  610. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  611. 'uid': uid, 'channel': channel
  612. }
  613. message = {
  614. "target_type": 2,
  615. "target_value": token_val,
  616. "notification": {
  617. "title": msg_title,
  618. "content": msg_text,
  619. 'channel_id': channel_id,
  620. 'action_parameters': extra_data,
  621. 'click_action_type': 1,
  622. 'click_action_activity': OPPOPUSH_CONFIG[app_bundle_id]['click_action_activity']
  623. }
  624. }
  625. push_data = {
  626. 'auth_token': result['data']['auth_token'],
  627. 'message': json.dumps(message)
  628. }
  629. response = requests.post(push_url, data=push_data, headers=headers)
  630. LOGGER.info("oppo推送返回值:{}".format(response.json()))
  631. if response.status_code == 200 and event_type in DATA_PUSH_EVENT_TYPE_LIST:
  632. PushObject.jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, jg_token_val, extra_data)
  633. return True
  634. except Exception as e:
  635. LOGGER.info("oppo推送异常:{}".format(repr(e)))
  636. return False
  637. @staticmethod
  638. def android_meizupush(token_val, n_time, event_type, msg_title, msg_text, uid='', channel='1',
  639. app_bundle_id='', appBundleId='', nickname='', image=''):
  640. """
  641. android 魅族推送(不支持图片)
  642. @param app_bundle_id: app包名
  643. @param appBundleId: app包名
  644. @param token_val: 推送token
  645. @param event_type: 消息类型 (0:运营类消息,1:系统类消息。默认为 0)
  646. @param msg_title: 推送标题
  647. @param msg_text: 推送内容
  648. @param n_time: 当前时间
  649. @param nickname: 设备昵称
  650. @param uid: uid
  651. @param image: 推送图片链接
  652. @param channel: 通道
  653. @return: bool
  654. """
  655. try:
  656. # 获取包和AppSecret
  657. app_bundle_id = app_bundle_id if app_bundle_id != '' else appBundleId
  658. appId = MEIZUPUSH_CONFIG[app_bundle_id]['ID']
  659. appSecret = MEIZUPUSH_CONFIG[app_bundle_id]['AppSecret']
  660. url = 'https://server-api-push.meizu.com/garcia/api/server/push/varnished/pushByPushId'
  661. # 跳转类型
  662. jump_type = CommonService.get_jump_type(event_type)
  663. extra_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  664. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type, 'nickname': nickname,
  665. 'uid': uid, 'channel': channel, 'jump_type': jump_type
  666. }
  667. # 转换为json格式
  668. extra_data = json.dumps(extra_data)
  669. if msg_title == '':
  670. msg_title = APP_BUNDLE_DICT[app_bundle_id]
  671. # 拼接发送内容
  672. activity = MEIZUPUSH_CONFIG[app_bundle_id]['click_action_activity']
  673. # clickType点击动作, 0打开应用, 1打开应用页面, 2打开url页面, 3应用客户端自定义
  674. messageJson = '{"clickTypeInfo": {"activity": "%s",' \
  675. '"clickType": 1, "parameters": %s },"extra": {},' % (activity, extra_data)
  676. noticeBarInfo = ('"noticeBarInfo": {"title": "%s", "content": "%s"},' % (msg_title, msg_text))
  677. noticeExpandInfo = '"noticeExpandInfo": {"noticeExpandType": 0}, "pushTimeInfo": {"validTime": 24}}'
  678. messageJson += noticeBarInfo
  679. messageJson += noticeExpandInfo
  680. data_meizu = {
  681. 'appId': appId,
  682. 'pushIds': token_val,
  683. 'messageJson': messageJson
  684. }
  685. # 魅族MD5加密,生成密钥
  686. sign = CommonService.getMD5Sign(data=data_meizu, key=appSecret)
  687. data = {
  688. 'appId': appId,
  689. 'messageJson': messageJson,
  690. 'sign': sign,
  691. 'pushIds': token_val,
  692. }
  693. # 进行推送
  694. response = requests.post(url, data=data)
  695. LOGGER.info("魅族推送结果:{}".format(response.json()))
  696. return True
  697. except Exception as e:
  698. LOGGER.info("魅族推送异常:{}".format(repr(e)))
  699. return False
  700. @staticmethod
  701. def android_honorpush(token_val, n_time, event_type, msg_title, msg_text,
  702. uid='', channel='1', image='', app_bundle_id='', appBundleId='', channel_id='', nickname=''):
  703. """
  704. android honor 推送
  705. @param channel_id: 通知通道id
  706. @param nickname: 设备昵称
  707. @param app_bundle_id: app包id
  708. @param appBundleId: app包id
  709. @param token_val: 推送token
  710. @param n_time: 当前时间
  711. @param event_type: 事件类型
  712. @param msg_title: 推送标题
  713. @param msg_text: 推送内容
  714. @param uid: uid
  715. @param channel: 通道
  716. @param image: 推送图片链接
  717. @return: bool
  718. """
  719. app_bundle_id = appBundleId if appBundleId else app_bundle_id
  720. try:
  721. client_id = HONORPUSH_CONFIG[app_bundle_id]['client_id']
  722. client_secret = HONORPUSH_CONFIG[app_bundle_id]['client_secret']
  723. app_id = HONORPUSH_CONFIG[app_bundle_id]['app_id']
  724. get_access_token_url = 'https://iam.developer.hihonor.com/auth/token'
  725. post_data = {
  726. 'grant_type': 'client_credentials',
  727. 'client_id': client_id,
  728. 'client_secret': client_secret
  729. }
  730. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  731. access_token_response = requests.post(get_access_token_url, data=post_data, headers=headers)
  732. access_result = access_token_response.json()
  733. authorization_token = 'Bearer ' + access_result['access_token']
  734. # 发送推送
  735. push_url = 'https://push-api.cloud.hihonor.com/api/v1/{}/sendMessage'.format(app_id)
  736. headers = {'Content-Type': 'application/json', 'Authorization': authorization_token,
  737. 'timestamp': str(int(time.time()) * 1000)}
  738. # 跳转类型
  739. jump_type = CommonService.get_jump_type(event_type)
  740. extra_data = {'alert': msg_text, 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  741. 'received_at': n_time, 'event_time': n_time, 'event_type': str(event_type),
  742. 'nickname': nickname, 'uid': uid, 'channel': channel, 'title': msg_title, 'body': msg_text,
  743. 'jump_type': jump_type
  744. }
  745. # 通知推送
  746. push_data = {
  747. "android": {
  748. "notification": {
  749. "body": msg_text,
  750. "title": msg_title,
  751. "importance": "NORMAL",
  752. "clickAction": {
  753. "type": 3,
  754. }
  755. },
  756. "targetUserType": 0,
  757. "data": json.dumps(extra_data)
  758. },
  759. "token": [token_val]
  760. }
  761. LOGGER.info("uid:{},时间:{},荣耀推送发送内容:{}".format(uid, n_time, push_data))
  762. response = requests.post(push_url, json=push_data, headers=headers)
  763. LOGGER.info("uid:{},时间:{},荣耀推送通知返回值:{}".format(uid, n_time, response.json()))
  764. # 一键通话透传推送
  765. if int(event_type) in DATA_PUSH_EVENT_TYPE_LIST:
  766. push_data = {
  767. "data": json.dumps(extra_data),
  768. "token": [token_val]
  769. }
  770. response = requests.post(push_url, json=push_data, headers=headers)
  771. LOGGER.info("uid:{},时间:{},荣耀透传推送返回值:{}".format(uid, n_time, response.json()))
  772. return True
  773. except Exception as e:
  774. LOGGER.info("荣耀推送异常:error_line:{},error_msg:{}".format(e.__traceback__.tb_lineno, repr(e)))
  775. return False
  776. @staticmethod
  777. def jpush_transparent_transmission(msg_title, msg_text, app_bundle_id, token_val, extra_data):
  778. """
  779. android 极光透传
  780. @param msg_title: 推送标题
  781. @param msg_text: 推送内容
  782. @param token_val: 推送token
  783. @param app_bundle_id: app包id
  784. @param extra_data: 额外数据
  785. @return: None
  786. """
  787. try:
  788. app_key = JPUSH_CONFIG[app_bundle_id]['Key']
  789. master_secret = JPUSH_CONFIG[app_bundle_id]['Secret']
  790. # 换成各自的app_key和master_secret
  791. _jpush = jpush.JPush(app_key, master_secret)
  792. push = _jpush.create_push()
  793. push.audience = jpush.registration_id(token_val)
  794. push.message = jpush.message(msg_content=msg_text, title=msg_title, extras=extra_data)
  795. push.platform = jpush.all_
  796. res = push.send()
  797. LOGGER.info('极光透传,结果:{},参数:{}'.format(res, extra_data))
  798. except Exception as e:
  799. LOGGER.info('jpush_transparent_transmission极光透传异常:errLine:{}, errMsg:{}, 参数:{}'.format(
  800. e.__traceback__.tb_lineno, repr(e), extra_data))