DevicePushService.py 23 KB

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