DetectControllerV2.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import json
  2. import logging
  3. import os
  4. import apns2
  5. import boto3
  6. import botocore
  7. import jpush as jpush
  8. from botocore import client
  9. from django.db import transaction
  10. from django.http import JsonResponse
  11. from django.views.generic.base import View
  12. from pyfcm import FCMNotification
  13. from AnsjerPush.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  14. from AnsjerPush.config import JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, BASE_DIR, APNS_MODE
  15. from Object.RedisObject import RedisObject
  16. from Service.CommonService import CommonService
  17. from Service.DevicePushService import DevicePushService
  18. from Service.PushService import PushObject
  19. # 移动侦测V2接口
  20. class NotificationV2View(View):
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. return self.validation(request.GET)
  24. def post(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. return self.validation(request.POST)
  27. def validation(self, request_dict):
  28. """
  29. 设备触发报警消息推送
  30. @param request_dict:uidToken 加密uid
  31. @param request_dict:etk 加密uid
  32. @param request_dict:channel 设备通道号
  33. @param request_dict:n_time 设备触发报警时间
  34. @param request_dict:event_type 设备事件类型
  35. @param request_dict:is_st 文件类型(0:无,1:图片,2:视频)
  36. @param request_dict:region 文件存储区域(1:国外,2国内)
  37. @param request_dict:electricity 电量值
  38. """
  39. logger = logging.getLogger('info')
  40. logger.info("移动侦测V2接口参数:{}".format(request_dict))
  41. uidToken = request_dict.get('uidToken', None)
  42. etk = request_dict.get('etk', None)
  43. channel = request_dict.get('channel', '1')
  44. n_time = request_dict.get('n_time', None)
  45. event_type = request_dict.get('event_type', None)
  46. is_st = request_dict.get('is_st', None)
  47. region = request_dict.get('region', None)
  48. electricity = request_dict.get('electricity', '')
  49. if not all([channel, n_time]):
  50. return JsonResponse(status=200, data={
  51. 'code': 444,
  52. 'msg': 'param is wrong'})
  53. if not region or not is_st:
  54. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  55. try:
  56. with transaction.atomic():
  57. is_st = int(is_st)
  58. region = int(region)
  59. uid = DevicePushService.decode_uid(etk, uidToken) # 解密uid
  60. if len(uid) != 20 and len(uid) != 14:
  61. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  62. req_limiting = '{uid}_{channel}_{event_type}_ptl' \
  63. .format(uid=uid, channel=channel, event_type=event_type)
  64. is_sys_msg = self.is_sys_msg(int(event_type)) # 判断事件类型是否是系统消息
  65. if is_sys_msg:
  66. push_interval = '{uid}_{channel}_{event_type}_flag' \
  67. .format(uid=uid, channel=channel, event_type=event_type)
  68. else:
  69. push_interval = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  70. redisObj = RedisObject(db=6)
  71. cache_req_limiting = redisObj.get_data(key=req_limiting) # 获取请求限流缓存数据
  72. cache_app_push = redisObj.get_data(key=push_interval) # 获取APP推送消息时间间隔缓存数据
  73. logger.info('消息推送- 限流key: {}, 推送间隔key: {}'.
  74. format(cache_req_limiting, cache_app_push))
  75. if cache_req_limiting: # 限流存在则直接返回
  76. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  77. redisObj.set_data(key=req_limiting, val=1, expire=60) # 当缓存不存在限流数据 重新设置一分钟请求一次
  78. uid_push_qs = DevicePushService.query_uid_push(uid) # 查询uid_set与push数据列表
  79. if not uid_push_qs.exists():
  80. logger.info('消息推送-uid_push 数据不存在')
  81. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  82. ai_type = uid_push_qs.first()['uid_set__ai_type']
  83. event_type = self.get_combo_msg_type(ai_type, int(event_type)) # 解析消息事件类型看是否多类型组合
  84. # 将uid_set以及uid_push 转数组列表
  85. uid_set_push_list = DevicePushService.cache_uid_push(uid_push_qs)
  86. nickname = uid_set_push_list[0]['uid_set__nickname']
  87. nickname = uid if not nickname else nickname
  88. # APP消息提醒推送间隔
  89. detect_interval = uid_set_push_list[0]['uid_set__detect_interval']
  90. if not cache_app_push:
  91. # 缓存APP提醒推送间隔 默认1分钟提醒一次
  92. DevicePushService.cache_push_detect_interval(redisObj, push_interval, detect_interval,
  93. uid_set_push_list[0]['uid_set__new_detect_interval'])
  94. bucket = ''
  95. aws_s3_client = ''
  96. if is_st == 1 or is_st == 3: # 使用aws s3
  97. aws_s3_client = s3_client(region=region)
  98. bucket = 'foreignpush' if region == 1 else 'push'
  99. kwag_args = {
  100. 'uid': uid,
  101. 'channel': channel,
  102. 'event_type': event_type,
  103. 'n_time': n_time,
  104. }
  105. params = {'nickname': nickname, 'uid': uid, 'kwag_args': kwag_args, 'is_st': is_st, 'region': region,
  106. 'is_sys_msg': is_sys_msg, 'channel': channel, 'event_type': event_type, 'n_time': n_time,
  107. 'electricity': electricity, 'bucket': bucket, 'aws_s3_client': aws_s3_client,
  108. 'app_push': cache_app_push}
  109. # APP消息推送与获取报警消息数据列表
  110. result = DevicePushService.save_msg_push(uid_set_push_list, **params)
  111. # 批量系统消息&报警消息数据存库
  112. DevicePushService.save_sys_msg(is_sys_msg, result['local_date_time'],
  113. result['sys_msg_list'], result['new_device_info_list'])
  114. params['aws_s3_client'] = aws_s3_client
  115. params['uid_set_push_list'] = uid_set_push_list
  116. params['code_dict'] = result
  117. result_dict = DevicePushService.get_push_url(**params) # 获取S3对象上传链接
  118. return JsonResponse(status=200, data=result_dict)
  119. except Exception as e:
  120. logger.info('消息推送-异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  121. data = {
  122. 'errLine': e.__traceback__.tb_lineno,
  123. 'errMsg': repr(e),
  124. }
  125. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  126. @classmethod
  127. def get_combo_msg_type(cls, ai_type, event_type):
  128. """
  129. 获取组合类型,ai_type == 47 支持算法小店,需判断组合类型
  130. """
  131. logger = logging.getLogger('info')
  132. try:
  133. if ai_type != 47:
  134. return event_type
  135. logger.info('LOG------算法小店组合类型十进制值:{}'.format(event_type))
  136. # 如触发一个事件,则匹配已用类型 1替换后变成51代表移动侦测 1:移动侦测,2:人形,4:车型,8:人脸
  137. event_dict = {
  138. 1: 51,
  139. 2: 57,
  140. 4: 58,
  141. 16: 59,
  142. 8: 60,
  143. 32: 61
  144. }
  145. event_val = event_dict.get(event_type, 0)
  146. # event_val == 0 没有匹配到单个值则认为组合类型
  147. # 如是3,则转为二进制11,代表(1+2)触发了移动侦测+人形侦测
  148. if event_val == 0:
  149. val = cls.dec_to_bin(event_type)
  150. return int(val)
  151. else:
  152. return int(event_val)
  153. except Exception as e:
  154. logger.info('推送错误异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  155. return event_type
  156. @staticmethod
  157. def dec_to_bin(num):
  158. """
  159. 十进制转二进制
  160. """
  161. result = ""
  162. while num != 0:
  163. ret = num % 2
  164. num //= 2
  165. result = str(ret) + result
  166. return result
  167. def push_thread_test(self, push_type, aws_s3_client, bucket, key, uid, appBundleId, token_val, event_type, n_time,
  168. msg_title, msg_text, channel):
  169. logger = logging.getLogger('info')
  170. logger.info('推送图片测试:{} {} {} {} {} {} {} {}'.format(push_type, uid, appBundleId, token_val, event_type, n_time,
  171. msg_title, msg_text))
  172. try:
  173. image_url = aws_s3_client.generate_presigned_url('get_object', Params={'Bucket': bucket, 'Key': key},
  174. ExpiresIn=300)
  175. logger.info('推送图片url:{}'.format(image_url))
  176. if push_type == 0:
  177. PushObject.ios_apns_push(uid, appBundleId, token_val, n_time, event_type, msg_title, msg_text,
  178. uid, channel, image_url)
  179. elif push_type == 1:
  180. PushObject.android_fcm_push(uid, appBundleId, token_val, n_time, event_type, msg_title,
  181. msg_text, uid, channel, image_url)
  182. except Exception as e:
  183. logger.info('推送图片测试异常:{}'.format(e))
  184. @staticmethod
  185. def is_sys_msg(event_type):
  186. """
  187. 判断是否属于系统消息
  188. @return: True | False
  189. """
  190. event_type_list = [702, 703, 704]
  191. if event_type in event_type_list:
  192. return True
  193. return False
  194. def get_msg_text(self, channel, n_time, lang, tz, event_type, electricity='', is_sys=0):
  195. n_date = CommonService.get_now_time_str(n_time=n_time, tz=tz, lang=lang)
  196. etype = int(event_type)
  197. if lang == 'cn':
  198. if etype == 704:
  199. msg_type = '剩余电量 ' + electricity
  200. elif etype == 702:
  201. msg_type = '摄像头休眠'
  202. elif etype == 703:
  203. msg_type = '摄像头唤醒'
  204. else:
  205. msg_type = ''
  206. if is_sys:
  207. send_text = '{msg_type} 通道:{channel}'.format(msg_type=msg_type, channel=channel)
  208. else:
  209. send_text = '{msg_type} 通道:{channel} 日期:{date}'.format(msg_type=msg_type, channel=channel, date=n_date)
  210. else:
  211. if etype == 704:
  212. msg_type = 'Battery remaining ' + electricity
  213. elif etype == 702:
  214. msg_type = 'Camera sleep'
  215. elif etype == 703:
  216. msg_type = 'Camera wake'
  217. else:
  218. msg_type = ''
  219. if is_sys:
  220. send_text = '{msg_type} channel:{channel}'. \
  221. format(msg_type=msg_type, channel=channel)
  222. else:
  223. send_text = '{msg_type} channel:{channel} date:{date}'. \
  224. format(msg_type=msg_type, channel=channel, date=n_date)
  225. return send_text
  226. def do_jpush(self, uid, channel, appBundleId, token_val, event_type, n_time,
  227. msg_title, msg_text):
  228. app_key = JPUSH_CONFIG[appBundleId]['Key']
  229. master_secret = JPUSH_CONFIG[appBundleId]['Secret']
  230. _jpush = jpush.JPush(app_key, master_secret)
  231. push = _jpush.create_push()
  232. push.audience = jpush.registration_id(token_val)
  233. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  234. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  235. android = jpush.android(alert=msg_text, priority=1, style=1, alert_type=7,
  236. big_text=msg_text, title=msg_title,
  237. extras=push_data)
  238. push.notification = jpush.notification(android=android)
  239. push.platform = jpush.all_
  240. res = push.send()
  241. print(res)
  242. return res.status_code
  243. def do_fcm(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title, msg_text):
  244. logger = logging.getLogger('info')
  245. try:
  246. serverKey = FCM_CONFIG[appBundleId]
  247. except Exception as e:
  248. logger.info('------fcm_error:{}'.format(repr(e)))
  249. return 'serverKey abnormal'
  250. push_service = FCMNotification(api_key=serverKey)
  251. data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  252. "received_at": n_time, "sound": "sound.aif", "uid": uid, "zpush": "1", "channel": channel}
  253. result = push_service.notify_single_device(registration_id=token_val, message_title=msg_title,
  254. message_body=msg_text, data_message=data,
  255. extra_kwargs={
  256. 'default_vibrate_timings': True,
  257. 'default_sound': True,
  258. 'default_light_settings': True
  259. })
  260. return result
  261. def do_apns(self, uid, channel, appBundleId, token_val, event_type, n_time, msg_title,
  262. msg_text):
  263. logger = logging.getLogger('info')
  264. logger.info("进来do_apns函数了")
  265. logger.info(token_val)
  266. logger.info(APNS_MODE)
  267. logger.info(os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  268. try:
  269. cli = apns2.APNSClient(mode=APNS_MODE,
  270. client_cert=os.path.join(BASE_DIR, APNS_CONFIG[appBundleId]['pem_path']))
  271. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  272. "received_at": n_time, "sound": "", "uid": uid, "zpush": "1", "channel": channel}
  273. alert = apns2.PayloadAlert(body=msg_text, title=msg_title)
  274. payload = apns2.Payload(alert=alert, custom=push_data, sound="default")
  275. # return uid, channel, appBundleId, str(token_val), event_type, n_time, msg_title,msg_text
  276. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  277. res = cli.push(n=n, device_token=token_val, topic=appBundleId)
  278. print(res.status_code)
  279. logger.info("apns_推送状态:")
  280. logger.info(res.status_code)
  281. if res.status_code == 200:
  282. return res.status_code
  283. else:
  284. print('apns push fail')
  285. print(res.reason)
  286. logger.info('apns push fail')
  287. logger.info(res.reason)
  288. return res.status_code
  289. except (ValueError, ArithmeticError):
  290. return 'The program has a numeric format exception, one of the arithmetic exceptions'
  291. except Exception as e:
  292. print(repr(e))
  293. print('do_apns函数错误行号', e.__traceback__.tb_lineno)
  294. logger.info('do_apns错误:{}'.format(repr(e)))
  295. return repr(e)
  296. def s3_client(region):
  297. if region == 2: # 国内
  298. aws_s3_client = boto3.client(
  299. 's3',
  300. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  301. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  302. config=botocore.client.Config(signature_version='s3v4'),
  303. region_name='cn-northwest-1'
  304. )
  305. else: # 国外
  306. aws_s3_client = boto3.client(
  307. 's3',
  308. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  309. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  310. config=botocore.client.Config(signature_version='s3v4'),
  311. region_name='us-east-1'
  312. )
  313. return aws_s3_client