PushService.py 36 KB

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