DetectControllerV2.py 9.5 KB

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