DevicePushService.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : DevicePushService.py
  4. @Time : 2022/11/23 11:40
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import logging
  10. import os
  11. import threading
  12. import time
  13. import apns2
  14. import jpush as jpush
  15. import requests
  16. from pyfcm import FCMNotification
  17. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE, APP_BUNDLE_DICT, \
  18. XMPUSH_CONFIG, VIVOPUSH_CONFIG
  19. from AnsjerPush.config import SERVER_TYPE
  20. from Model.models import UidPushModel, SysMsgModel, DeviceSharePermission, DeviceChannelUserSet, \
  21. DeviceChannelUserPermission
  22. from Object.ETkObject import ETkObject
  23. from Object.RedisObject import RedisObject
  24. from Object.UidTokenObject import UidTokenObject
  25. from Object.utils import LocalDateTimeUtil
  26. from Service.CommonService import CommonService
  27. from Service.EquipmentInfoService import EquipmentInfoService
  28. from Service.HuaweiPushService.HuaweiPushService import HuaweiPushObject
  29. from Service.PushService import PushObject
  30. from Service.VivoPushService.push_admin.APIMessage import PushMessage
  31. from Service.VivoPushService.push_admin.APISender import APISender
  32. LOGGING = logging.getLogger('info')
  33. class DevicePushService:
  34. @staticmethod
  35. def decode_uid(etk, uidToken):
  36. """
  37. 解密UID,优先解密etk 否则判断uidToken
  38. """
  39. # 解密获取uid
  40. if etk:
  41. eto = ETkObject(etk)
  42. uid = eto.uid
  43. else:
  44. uto = UidTokenObject(uidToken)
  45. uid = uto.UID
  46. LOGGING.info('消息推送-当前UID:{}'.format(uid))
  47. return uid
  48. @classmethod
  49. def query_uid_push(cls, uid):
  50. """
  51. 查询uid_set与push数据列表
  52. """
  53. uid_push_qs = UidPushModel.objects.filter(uid_set__uid=uid, uid_set__detect_status=1). \
  54. values('token_val', 'app_type', 'appBundleId', 'm_code', 'push_type', 'userID_id', 'userID__NickName',
  55. 'lang', 'm_code', 'tz', 'uid_set__nickname', 'uid_set__detect_interval', 'uid_set__detect_group',
  56. 'uid_set__channel', 'uid_set__ai_type', 'uid_set__new_detect_interval')
  57. return uid_push_qs
  58. @staticmethod
  59. def cache_uid_push(uid_push_qs):
  60. """
  61. 将uid_push 信息进行缓存
  62. @param uid_push_qs: uid_set & uid_push 列表对象
  63. @return: uid_set_list
  64. """
  65. uid_set_list = []
  66. for qs in uid_push_qs:
  67. uid_set_list.append(qs)
  68. # redis_obj.set_data(key=name, val=str(redis_list), expire=expire)
  69. return uid_set_list
  70. @staticmethod
  71. def cache_push_detect_interval(redis_obj, name, detect_interval, new_detect_interval):
  72. """
  73. 缓存设置推送消息的时间间隔
  74. @param redis_obj: redis对象
  75. @param name: redis key
  76. @param detect_interval: 原推送时间间隔
  77. @param new_detect_interval: 新推送时间间隔
  78. """
  79. if SERVER_TYPE != 'Ansjer.cn_config.cn_formal_settings':
  80. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  81. detect_interval = 60 if detect_interval < 60 else detect_interval
  82. redis_obj.set_data(key=name, val=1, expire=detect_interval - 5)
  83. LOGGING.info('消息推送-缓存设置APP推送间隔:{}s'.format(detect_interval))
  84. @classmethod
  85. def save_msg_push(cls, uid_set_push_list, **params):
  86. """
  87. APP消息推送以及报警消息存库
  88. @nickname 设备名称
  89. @channel 通道
  90. @event_type 事件类型
  91. """
  92. new_device_info_list = []
  93. sys_msg_list = []
  94. userID_ids = []
  95. kwag_args = params['kwag_args']
  96. code_data = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  97. local_date_time = ''
  98. push_permission = True
  99. for up in uid_set_push_list:
  100. appBundleId = up['appBundleId']
  101. token_val = up['token_val']
  102. lang = up['lang']
  103. tz = up['tz']
  104. if tz is None or tz == '':
  105. tz = 0
  106. # 发送标题
  107. msg_title = cls.get_msg_title(appBundleId=appBundleId, nickname=params['nickname'])
  108. # 发送内容
  109. msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  110. tz=tz, event_type=params['event_type'],
  111. electricity=params['electricity'])
  112. kwag_args['appBundleId'] = appBundleId
  113. kwag_args['token_val'] = token_val
  114. kwag_args['msg_title'] = msg_title
  115. kwag_args['msg_text'] = msg_text
  116. LOGGING.info('推送要的数据: {}'.format(kwag_args))
  117. local_date_time = CommonService.get_now_time_str(n_time=params['n_time'], tz=tz, lang='cn')
  118. LOGGING.info('<<<<<根据时区计算后日期={},时区={}'.format(local_date_time, tz))
  119. local_date_time = local_date_time[0:10]
  120. LOGGING.info('<<<<<切片后的日期={}'.format(local_date_time))
  121. # 以下是存库
  122. userID_id = up["userID_id"]
  123. if userID_id not in userID_ids:
  124. now_time = int(time.time())
  125. if params['is_sys_msg']:
  126. sys_msg_text = cls.get_msg_text(channel=params['channel'], n_time=params['n_time'], lang=lang,
  127. tz=tz,
  128. event_type=params['event_type'], electricity=params['electricity'],
  129. is_sys=1)
  130. sys_msg_list.append(SysMsgModel(userID_id=userID_id, msg=sys_msg_text, addTime=now_time,
  131. updTime=now_time, uid=params['uid'],
  132. eventType=params['event_type']))
  133. else:
  134. LOGGING.info('分表存数据start------')
  135. params['userID_id'] = userID_id
  136. push_permission = DevicePushService.check_share_permission(userID_id, params['channel'],
  137. params['uid'])
  138. if push_permission:
  139. new_device_info_list.append(cls.created_device_vo(local_date_time, **params))
  140. userID_ids.append(userID_id)
  141. params['appBundleId'] = appBundleId
  142. params['token_val'] = token_val
  143. params['lang'] = lang
  144. params['tz'] = tz
  145. params['kwag_args'] = kwag_args
  146. code_data = cls.send_app_msg_push(up['push_type'], **params) if push_permission else code_data
  147. return {'code_date': code_data, 'new_device_info_list': new_device_info_list, 'sys_msg_list': sys_msg_list,
  148. 'local_date_time': local_date_time}
  149. @classmethod
  150. def send_app_msg_push(cls, push_type, **param):
  151. """
  152. 发送app消息推送
  153. """
  154. try:
  155. kwag_args = param['kwag_args']
  156. result = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': '', 'do_xmpush_code': '',
  157. 'do_vivopush_code': ''}
  158. # 判断是否进行APP消息推送,如app_push不为空,则不进行推送
  159. if not param['app_push']:
  160. LOGGING.info('APP准备推送:{}, {}'.format(param['uid'], param))
  161. # 推送显示图片
  162. if (param['is_st'] == 1 or param['is_st'] == 3) and \
  163. (push_type == 0 or push_type == 1 or push_type == 3 or push_type == 4):
  164. if param['is_st'] == 1:
  165. key = '{}/{}/{}.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  166. else:
  167. key = '{}/{}/{}_0.jpeg'.format(param['uid'], param['channel'], param['n_time'])
  168. push_thread = threading.Thread(target=cls.async_send_picture_push, args=(
  169. push_type, param['aws_s3_client'], param['bucket'], key, param['uid'], param['appBundleId'],
  170. param['token_val'], param['event_type'], param['n_time'],
  171. param['kwag_args']['msg_title'], param['kwag_args']['msg_text'], param['channel']))
  172. push_thread.start()
  173. else:
  174. if push_type == 0: # ios apns
  175. result['do_apns_code'] = cls.do_apns(**kwag_args)
  176. elif push_type == 1: # android gcm
  177. result['do_fcm_code'] = cls.do_fcm(**kwag_args)
  178. elif push_type == 2: # android jpush
  179. result['do_jpush_code'] = cls.do_jpush(**kwag_args)
  180. elif push_type == 4: # android xmpush
  181. result['do_xmpush_code'] = cls.do_xmpush(**kwag_args)
  182. elif push_type == 5:
  183. result['do_vivopush_code'] = cls.do_vivopush(**kwag_args)
  184. return result
  185. except Exception as e:
  186. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  187. return None
  188. @classmethod
  189. def save_sys_msg(cls, is_sys_msg, local_date_time, sys_msg_list, new_device_info_list):
  190. """
  191. 保存系统消息&设备推送消息存库
  192. """
  193. if is_sys_msg:
  194. SysMsgModel.objects.bulk_create(sys_msg_list)
  195. else:
  196. # new 分表批量存储 设备信息
  197. if new_device_info_list and len(new_device_info_list) > 0:
  198. # 根据日期获得星期几
  199. week = LocalDateTimeUtil.date_to_week(local_date_time)
  200. EquipmentInfoService.equipment_info_bulk_create(week, new_device_info_list)
  201. LOGGING.info('设备信息分表批量保存end------')
  202. return True
  203. @classmethod
  204. def created_device_vo(cls, local_date_time, **params):
  205. """
  206. 获取设备推送表对象
  207. """
  208. return EquipmentInfoService.get_equipment_info_obj(
  209. local_date_time,
  210. device_user_id=params['userID_id'],
  211. event_time=params['n_time'],
  212. event_type=params['event_type'],
  213. device_uid=params['uid'],
  214. device_nick_name=params['nickname'],
  215. channel=params['channel'],
  216. alarm='Motion \tChannel:{channel}'.format(channel=params['channel']),
  217. is_st=params['is_st'],
  218. receive_time=params['n_time'],
  219. add_time=int(time.time()),
  220. storage_location=2,
  221. border_coords='',
  222. )
  223. @staticmethod
  224. def get_msg_title(appBundleId, nickname):
  225. """
  226. 获取消息标题
  227. """""
  228. if appBundleId in APP_BUNDLE_DICT.keys():
  229. return APP_BUNDLE_DICT[appBundleId] + '(' + nickname + ')'
  230. else:
  231. return nickname
  232. @staticmethod
  233. def get_msg_text(channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  234. """
  235. 获取消息文本
  236. """
  237. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  238. etype = int(event_type)
  239. if lang == 'cn':
  240. if etype == 704:
  241. msg_type = '剩余电量:' + electricity
  242. elif etype == 702:
  243. msg_type = '摄像头休眠'
  244. elif etype == 703:
  245. msg_type = '摄像头唤醒'
  246. else:
  247. msg_type = ''
  248. if is_sys:
  249. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  250. else:
  251. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  252. else:
  253. if etype == 704:
  254. msg_type = 'Battery remaining:' + electricity
  255. elif etype == 702:
  256. msg_type = 'Camera sleep'
  257. elif etype == 703:
  258. msg_type = 'Camera wake'
  259. else:
  260. msg_type = ''
  261. if is_sys:
  262. send_text = '{msg_type} channel:{channel}'. \
  263. format(msg_type=msg_type, channel=channel)
  264. else:
  265. send_text = '{msg_type} channel:{channel} date:{date}'. \
  266. format(msg_type=msg_type, channel=channel, date=n_date)
  267. return send_text
  268. @staticmethod
  269. def do_jpush(uid, channel, appBundleId, token_val, event_type, n_time,
  270. msg_title, msg_text):
  271. """
  272. android 国内极光APP消息提醒推送
  273. """
  274. app_key = JPUSH_CONFIG[appBundleId]['Key']
  275. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  276. _jpush = jpush.JPush(app_key, master_secret)
  277. push = _jpush.create_push()
  278. push.audience = jpush.registration_id(token_val)
  279. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  280. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  281. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  282. big_text=msg_text, title=msg_title,
  283. extras=push_data)
  284. push.notification = jpush.notification(android=android)
  285. push.platform = jpush.all_
  286. res = push.send()
  287. print(res)
  288. return res.status_code
  289. @staticmethod
  290. def do_fcm(uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  291. """
  292. android 谷歌APP消息提醒推送
  293. """
  294. try:
  295. serverKey = FCM_CONFIG[appBundleId]
  296. except Exception as e:
  297. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  298. return 'serverKey abnormal'
  299. push_service = FCMNotification(api_key=serverKey)
  300. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  301. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  302. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  303. message_body=msg_text, data_message=data,
  304. extra_kwargs={
  305. 'default_vibrate_timings': True,
  306. 'default_sound': True,
  307. 'default_light_settings': True
  308. })
  309. return result
  310. @staticmethod
  311. def do_apns(uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  312. msg_text):
  313. """
  314. ios 消息提醒推送
  315. """
  316. LOGGING.info("进来do_apns函数了")
  317. LOGGING.info(token_val)
  318. LOGGING.info(APNS_MODE)
  319. LOGGING.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  320. try:
  321. cli = apns2.APNSClient(
  322. mode=APNS_MODE, client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  323. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  324. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  325. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  326. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  327. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  328. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  329. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  330. print(res.status_code)
  331. LOGGING.info("apns_推送状态:")
  332. LOGGING.info(res.status_code)
  333. if res.status_code == 200:
  334. return res.status_code
  335. else:
  336. print('apns push fail')
  337. print(res.reason)
  338. LOGGING.info('apns push fail')
  339. LOGGING.info(res.reason)
  340. return res.status_code
  341. except (ValueError, ArithmeticError):
  342. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  343. except Exception as e:
  344. print(repr(e))
  345. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  346. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  347. return repr(e)
  348. @staticmethod
  349. def do_xmpush(uid, channel, appBundleId, token_val, event_type, n_time,
  350. msg_title, msg_text):
  351. """
  352. android 国内小米APP消息提醒推送
  353. """
  354. url = 'https://api.xmpush.xiaomi.com/v3/message/regid'
  355. app_secret = XMPUSH_CONFIG[appBundleId]
  356. payload = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  357. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  358. 'uid': uid, 'channel': channel
  359. }
  360. data = {
  361. 'title': msg_title,
  362. 'description': msg_text,
  363. 'payload': 'payload',
  364. 'restricted_package_name': appBundleId,
  365. 'registration_id': token_val,
  366. }
  367. headers = {
  368. 'Authorization': 'key={}'.format(app_secret)
  369. }
  370. response = requests.post(url, data=data, headers=headers)
  371. if response.status_code == 200:
  372. return response.json()
  373. @classmethod
  374. def async_send_picture_push(cls, push_type, aws_s3_client, bucket, key, uid, appBundleId,
  375. token_val, event_type, n_time, msg_title, msg_text, channel):
  376. """
  377. 异步APP图片推送
  378. """
  379. try:
  380. image_url = aws_s3_client.generate_presigned_url('get_object',
  381. Params={'Bucket': bucket, 'Key': key},
  382. ExpiresIn=300)
  383. LOGGING.info('推送图片url:{}'.format(image_url))
  384. if push_type == 0:
  385. PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  386. uid, channel, image_url)
  387. elif push_type == 1:
  388. PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  389. msg_text, uid, channel, image_url)
  390. elif push_type == 3:
  391. huawei_push_object = HuaweiPushObject()
  392. huawei_push_object.send_push_android_notify_message(title=msg_title, body=msg_text, image=image_url,
  393. token=token_val)
  394. elif push_type == 4:
  395. PushObject.android_xmpush(uid, appBundleId, token_val, n_time, event_type, msg_title,
  396. msg_text, uid, channel, image_url)
  397. except Exception as e:
  398. LOGGING.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  399. @staticmethod
  400. def get_push_url(**params):
  401. """
  402. 获取推送URL,设备根本当前返回结果进行数据上传
  403. @return: re_data
  404. """
  405. re_data = {'code': 0, 'msg': 'success'}
  406. if params['is_st'] == 0 or params['is_st'] == 2:
  407. re_data['msg'] = 'success 0 or 2'
  408. for up in params['uid_set_push_list']:
  409. if up['push_type'] == 0: # ios apns
  410. up['do_apns_code'] = params['code_dict']['code_date']['do_apns_code']
  411. elif up['push_type'] == 1: # android gcm
  412. up['do_fcm_code'] = params['code_dict']['code_date']['do_fcm_code']
  413. elif up['push_type'] == 2: # android jpush
  414. up['do_jpush_code'] = params['code_dict']['code_date']['do_jpush_code']
  415. elif up['push_type'] == 4: # android jpush
  416. up['do_xmpush_code'] = params['code_dict']['code_date']['do_xmpush_code']
  417. elif up['push_type'] == 5: # android jpush
  418. up['do_vivopush_code'] = params['code_dict']['code_date']['do_xmpush_code']
  419. del up['push_type']
  420. del up['userID_id']
  421. del up['userID__NickName']
  422. del up['lang']
  423. del up['tz']
  424. del up['uid_set__nickname']
  425. del up['uid_set__detect_interval']
  426. del up['uid_set__detect_group']
  427. re_data['re_list'] = params['uid_set_push_list']
  428. elif params['is_st'] == 1:
  429. key_name = '{uid}/{channel}/{filename}.jpeg' \
  430. .format(uid=params['uid'], channel=params['channel'], filename=params['n_time'])
  431. re_args = {'Key': key_name}
  432. if params['region'] == 2: # 2:国内
  433. re_args['Bucket'] = 'push'
  434. else: # 1:国外
  435. re_args['Bucket'] = 'foreignpush'
  436. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  437. re_data['img_push'] = response_url
  438. elif params['is_st'] == 3:
  439. img_url_list = []
  440. if params['region'] == 2: # 2:国内
  441. re_args = {'Bucket': 'push'}
  442. else: # 1:国外
  443. re_args = {'Bucket': 'foreignpush'}
  444. for i in range(params['is_st']):
  445. key_name = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  446. format(uid=params['uid'], channel=params['channel'], filename=params['n_time'], st=i)
  447. re_args['Key'] = key_name
  448. response_url = DevicePushService.generate_s3_url(params['aws_s3_client'], re_args)
  449. img_url_list.append(response_url)
  450. re_data['img_url_list'] = img_url_list
  451. re_data['msg'] = 'success 3'
  452. return re_data
  453. @staticmethod
  454. def generate_s3_url(aws_s3_client, params):
  455. """
  456. 获取S3对象URL
  457. """
  458. response_url = aws_s3_client.generate_presigned_url(
  459. ClientMethod='put_object',
  460. Params=params,
  461. ExpiresIn=3600
  462. )
  463. return response_url
  464. @staticmethod
  465. def check_share_permission(user_id, channel, uid):
  466. """
  467. 检查用户是否有权限接收设备报警推送
  468. """
  469. user_permission_qs = DeviceChannelUserSet.objects.filter(user_id=user_id, uid=uid) \
  470. .values('id', 'channels')
  471. # 根据当前用户与uid查询是否设置过通道权限,不存在则不是分享设备
  472. if not user_permission_qs.exists():
  473. return True
  474. up_id = user_permission_qs[0]['id']
  475. channels = user_permission_qs[0]['channels']
  476. channels_list = [int(val) for val in channels.split(',')]
  477. # 当前uid是属于分享设备并且设置了权限
  478. # 判断通道是否设置了权限,不存在则当前通道没有权限接受消息推送
  479. if int(channel) not in channels_list:
  480. return False
  481. permission_qs = DeviceSharePermission.objects.filter(code='AlarmMessages').values('id')
  482. p_id = permission_qs[0]['id']
  483. # 当前通道存在设置则查看是否有 消息推送权限
  484. channel_permission_qs = DeviceChannelUserPermission.objects \
  485. .filter(channel_user_id=up_id, permission_id=p_id) \
  486. .values('permission_id', 'channel_user_id')
  487. if not channel_permission_qs.exists():
  488. return False
  489. return True
  490. @classmethod
  491. def do_vivopush(cls, uid, channel, appBundleId, token_val, event_type, n_time,
  492. msg_title, msg_text):
  493. logger = logging.getLogger('info')
  494. try:
  495. authToken = 'authToken_' + appBundleId
  496. redisObj = RedisObject()
  497. # 获取redis里面的authToken
  498. redis_authToken = redisObj.get_data(key=authToken)
  499. if msg_title == '':
  500. msg_title = '周视'
  501. if redis_authToken is not False:
  502. app_secret = VIVOPUSH_CONFIG[appBundleId]['Secret']
  503. sender_send = APISender(app_secret)
  504. sender_send.set_token(redis_authToken)
  505. else:
  506. app_id = VIVOPUSH_CONFIG[appBundleId]['ID']
  507. app_key = VIVOPUSH_CONFIG[appBundleId]['Key']
  508. app_secret = VIVOPUSH_CONFIG[appBundleId]['Secret']
  509. sender = APISender(app_secret)
  510. rec = sender.get_token(app_id, app_key)
  511. # 存放authToken,有效期3个小时
  512. redisObj = RedisObject()
  513. redisObj.set_data(key=authToken, val=rec['authToken'], expire=10800)
  514. sender_send = APISender(app_secret)
  515. sender_send.set_token(rec['authToken'])
  516. push_data = {'alert': 'Motion', 'msg': '', 'sound': 'sound.aif', 'zpush': '1',
  517. 'received_at': n_time, 'event_time': n_time, 'event_type': event_type,
  518. 'uid': uid, 'channel': channel
  519. }
  520. # 推送
  521. message = PushMessage() \
  522. .reg_id(token_val) \
  523. .title(msg_title) \
  524. .content(msg_text) \
  525. .push_mode(1) \
  526. .notify_type(1) \
  527. .skip_type('1') \
  528. .request_id('123456') \
  529. .classification(1) \
  530. .client_custom_map(**push_data) \
  531. .message_dict()
  532. rec2 = sender_send.send(message)
  533. logger.info('vivo推送结果:{}'.format(rec2))
  534. except Exception as e:
  535. logger.info('vivo推送异常:{}'.format(e))