PushService.py 35 KB

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