PushService.py 37 KB

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