DetectControllerV2.py 9.0 KB

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