DevicePushService.py 21 KB

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