DevicePushService.py 21 KB

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