PushService.py 36 KB

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