PushService.py 35 KB

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