DetectControllerV2.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import json
  2. import logging
  3. import threading
  4. from django.http import JsonResponse
  5. from django.views.generic.base import View
  6. from AnsjerPush.config import CONFIG_EUR, CONFIG_INFO, CONFIG_CN
  7. from Object.RedisObject import RedisObject
  8. from Service.DevicePushService import DevicePushService
  9. TIME_LOGGER = logging.getLogger('time')
  10. # 移动侦测V2接口
  11. class NotificationV2View(View):
  12. def get(self, request, *args, **kwargs):
  13. request.encoding = 'utf-8'
  14. return self.validation(request.GET)
  15. def post(self, request, *args, **kwargs):
  16. request.encoding = 'utf-8'
  17. return self.validation(request.POST)
  18. @staticmethod
  19. def validation(request_dict):
  20. """
  21. 设备触发报警消息推送
  22. @param request_dict:uidToken 加密uid
  23. @param request_dict:etk 加密uid
  24. @param request_dict:channel 设备通道号
  25. @param request_dict:n_time 设备触发报警时间
  26. @param request_dict:event_type 设备事件类型
  27. @param request_dict:is_st 文件类型(0,2:无图, 1:单张图片, 3:三张图片)
  28. @param request_dict:region 文件存储区域(1:国外, 2:国内)
  29. @param request_dict:electricity 电量值
  30. @param request_dict:time_token 时间戳token
  31. @param request_dict:uid uid
  32. @param request_dict:dealings_type 往来检测 1:来,2:离开
  33. @param request_dict:detection 检测类型 0:普通,1:算法
  34. """
  35. uidToken = request_dict.get('uidToken', None)
  36. etk = request_dict.get('etk', None)
  37. channel = request_dict.get('channel', '1')
  38. n_time = request_dict.get('n_time', None)
  39. event_type = request_dict.get('event_type', None)
  40. is_st = request_dict.get('is_st', None)
  41. region = request_dict.get('region', None)
  42. electricity = request_dict.get('electricity', '')
  43. dealings_type = int(request_dict.get('dealingsType', 0))
  44. detection = int(request_dict.get('detection', 0))
  45. button = request_dict.get('button', '1')
  46. # 参数校验
  47. if not all([channel, n_time]):
  48. return JsonResponse(status=200, data={'code': 444, 'msg': 'param is wrong'})
  49. if not region or not is_st:
  50. return JsonResponse(status=200, data={'code': 404, 'msg': 'no region or is_st'})
  51. is_st = int(is_st)
  52. region = int(region)
  53. event_type = int(event_type)
  54. redis_obj = RedisObject()
  55. try:
  56. uid = DevicePushService.decode_uid(etk, uidToken)
  57. if len(uid) != 20 and len(uid) != 14:
  58. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  59. TIME_LOGGER.info('开始推送,uid:{},参数:{}'.format(uid, request_dict))
  60. # 判断是否为系统消息
  61. is_sys_msg = DevicePushService.judge_sys_msg(event_type)
  62. if is_sys_msg:
  63. push_interval = '{}_{}_{}_flag'.format(uid, channel, event_type)
  64. else:
  65. push_interval = '{}_{}_flag'.format(uid, channel)
  66. req_limiting = '{}_{}_{}_ptl'.format(uid, channel, event_type)
  67. cache_req_limiting = redis_obj.get_data(key=req_limiting) # 获取请求限流缓存数据
  68. cache_app_push = redis_obj.get_data(key=push_interval) # 获取APP推送消息时间间隔缓存数据
  69. if event_type not in [606, 607]:
  70. if cache_req_limiting: # 限流存在则直接返回
  71. return JsonResponse(status=200, data={'code': 0, 'msg': 'Push again in one minute'})
  72. redis_obj.set_data(key=req_limiting, val=1, expire=60) # 当缓存不存在限流数据 重新设置一分钟请求一次
  73. # 查询uid_push和uid_set数据
  74. uid_push_qs = DevicePushService.query_uid_push(uid, event_type, button)
  75. if not uid_push_qs.exists():
  76. TIME_LOGGER.info('推送响应,uid:{},uid_push数据不存在!'.format(uid))
  77. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  78. ai_type = uid_push_qs.first()['uid_set__ai_type']
  79. device_type = uid_push_qs.first()['uid_set__device_type']
  80. # uid_push_qs转存列表
  81. uid_set_push_list = DevicePushService.qs_to_list(uid_push_qs)
  82. nickname = uid_set_push_list[0]['uid_set__nickname']
  83. nickname = uid if not nickname else nickname
  84. # APP消息提醒推送间隔
  85. detect_interval = uid_set_push_list[0]['uid_set__detect_interval']
  86. if event_type not in [606, 607]:
  87. if not cache_app_push:
  88. # 缓存APP提醒推送间隔 默认1分钟提醒一次
  89. DevicePushService.cache_push_detect_interval(redis_obj, push_interval, detect_interval,
  90. uid_set_push_list[0]['uid_set__new_detect_interval'])
  91. else:
  92. cache_app_push = ''
  93. bucket = ''
  94. aws_s3_client = ''
  95. # 推图,初始化s3 client
  96. if is_st == 1 or is_st == 3:
  97. aws_s3_client = DevicePushService.get_s3_client(region=region)
  98. bucket = 'foreignpush' if region == 1 else 'push'
  99. # 推送相关参数
  100. push_kwargs = {
  101. 'uid': uid,
  102. 'channel': channel,
  103. 'event_type': event_type,
  104. 'n_time': n_time,
  105. }
  106. # 对象存储区域 2:AWS,3:oci美国凤凰城,4:oci英国伦敦
  107. storage_location = 2 if CONFIG_INFO == CONFIG_CN else 4 if CONFIG_INFO == CONFIG_EUR else 3
  108. params = {'nickname': nickname, 'uid': uid, 'push_kwargs': push_kwargs, 'is_st': is_st, 'region': region,
  109. 'is_sys_msg': is_sys_msg, 'channel': channel, 'event_type': event_type, 'n_time': n_time,
  110. 'electricity': electricity, 'bucket': bucket, 'aws_s3_client': aws_s3_client,
  111. 'app_push': cache_app_push, 'storage_location': storage_location, 'ai_type': ai_type, 'device_type': device_type,
  112. 'dealings_type': dealings_type, 'detection': detection,
  113. 'app_push_config': uid_set_push_list[0]['uid_set__msg_notify'],
  114. 'uid_set_push_list': uid_set_push_list}
  115. # 异步推送消息和保存数据
  116. push_thread = threading.Thread(
  117. target=push_and_save_data,
  118. kwargs=params)
  119. push_thread.start()
  120. # 视频通话不返回图片链接
  121. if event_type == 607:
  122. TIME_LOGGER.info('推送响应,uid:{},n_time:{},事件类型:{}'.format(uid, n_time, event_type))
  123. return JsonResponse(status=200, data={'code': 0, 'msg': 'success'})
  124. # 获取S3对象上传链接
  125. kwargs = {
  126. 'is_st': is_st,
  127. 'uid': uid,
  128. 'channel': channel,
  129. 'n_time': n_time,
  130. 'region': region,
  131. 'aws_s3_client': aws_s3_client,
  132. 'storage_location': storage_location
  133. }
  134. res_data = DevicePushService.get_res_data(**kwargs)
  135. TIME_LOGGER.info('推送响应,uid:{},n_time:{},事件类型:{},响应:{}'.format(
  136. uid, n_time, event_type, json.dumps(res_data)))
  137. return JsonResponse(status=200, data=res_data)
  138. except Exception as e:
  139. TIME_LOGGER.info('V2推送接口异常,error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  140. data = {
  141. 'error_line': e.__traceback__.tb_lineno,
  142. 'error_msg': repr(e)
  143. }
  144. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  145. def push_and_save_data(**params):
  146. uid = params['uid']
  147. TIME_LOGGER.info('{}开始异步存表和推送'.format(uid))
  148. # 异步推送消息
  149. push_thread = threading.Thread(
  150. target=DevicePushService.push_msg,
  151. kwargs=params)
  152. push_thread.start()
  153. # 保存推送数据
  154. result = DevicePushService.save_msg_push(**params)
  155. TIME_LOGGER.info('{}存表结果:{}'.format(uid, result))