PushService.py 36 KB

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