DetectController.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. import json
  2. import logging
  3. import threading
  4. import oss2
  5. from django.http import JsonResponse
  6. from django.views.generic.base import View
  7. from AnsjerPush.config import CONFIG_INFO, CONFIG_CN
  8. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
  9. from Object.RedisObject import RedisObject
  10. from Service.DevicePushService import DevicePushService
  11. V1_PUSH_LOGGER = logging.getLogger('v1_push')
  12. # 旧移动侦测接口
  13. class NotificationView(View):
  14. def get(self, request, *args, **kwargs):
  15. request.encoding = 'utf-8'
  16. return self.validation(request.GET)
  17. def post(self, request, *args, **kwargs):
  18. request.encoding = 'utf-8'
  19. return self.validation(request.POST)
  20. @staticmethod
  21. def validation(request_dict):
  22. """
  23. 设备触发报警消息推送
  24. @param request_dict:uidToken 加密uid
  25. @param request_dict:etk 加密uid
  26. @param request_dict:channel 设备通道号
  27. @param request_dict:n_time 设备触发报警时间
  28. @param request_dict:event_type 设备事件类型
  29. @param request_dict:is_st 文件类型(0:无,1:图片,2:视频)
  30. """
  31. uidToken = request_dict.get('uidToken', None)
  32. etk = request_dict.get('etk', None)
  33. channel = request_dict.get('channel', '1')
  34. n_time = request_dict.get('n_time', None)
  35. event_type = request_dict.get('event_type', None)
  36. is_st = request_dict.get('is_st', None)
  37. if not all([channel, n_time]):
  38. return JsonResponse(status=200, data={'code': 444, 'msg': 'error channel or n_time'})
  39. redisObj = RedisObject(db=6)
  40. try:
  41. uid = DevicePushService.decode_uid(etk, uidToken) # 解密uid
  42. if len(uid) != 20 and len(uid) != 14:
  43. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  44. V1_PUSH_LOGGER.info('旧移动侦测接口uid:{},时间戳:{},事件类型:{}'.format(uid, n_time, event_type))
  45. event_type = int(event_type)
  46. pkey = '{}_{}_{}_ptl'.format(uid, event_type, channel)
  47. ykey = '{}_redis_qs'.format(uid)
  48. is_sys_msg = DevicePushService.judge_sys_msg(event_type)
  49. if is_sys_msg:
  50. dkey = '{}_{}_{}_flag'.format(uid, event_type, channel)
  51. else:
  52. dkey = '{}_{}_flag'.format(uid, channel)
  53. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  54. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  55. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  56. # 一分钟外,推送开启状态
  57. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  58. if event_type not in [606, 607]:
  59. if have_pkey:
  60. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  61. return JsonResponse(status=200, data=res_data)
  62. # 数据库读取数据
  63. if have_ykey:
  64. uid_push_list = eval(redisObj.get_data(key=ykey))
  65. else:
  66. # 从数据库查询出来
  67. uid_push_qs = DevicePushService.query_uid_push(uid, event_type)
  68. if not uid_push_qs.exists():
  69. V1_PUSH_LOGGER.info('消息推送-uid_push 数据不存在')
  70. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  71. # 修改redis数据,并设置过期时间为10分钟
  72. uid_push_list = DevicePushService.qs_to_list(uid_push_qs)
  73. redisObj.set_data(key=ykey, val=str(uid_push_list), expire=600)
  74. if not uid_push_list:
  75. res_data = {'code': 404, 'msg': 'error !'}
  76. return JsonResponse(status=200, data=res_data)
  77. if not uid_push_list:
  78. res_data = {'code': 0, 'msg': 'uid_push_list not exist'}
  79. return JsonResponse(status=200, data=res_data)
  80. nickname = uid_push_list[0]['uid_set__nickname']
  81. detect_interval = uid_push_list[0]['uid_set__detect_interval']
  82. detect_group = uid_push_list[0]['uid_set__detect_group']
  83. if not nickname:
  84. nickname = uid
  85. if detect_group is not None:
  86. if have_dkey:
  87. detect_med_type = 1 # 1为存库不推送
  88. else:
  89. detect_med_type = 2 # 为2的话,既推送,又存库
  90. if CONFIG_INFO != CONFIG_CN:
  91. new_detect_interval = uid_push_list[0]['uid_set__new_detect_interval']
  92. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  93. detect_interval = 60 if detect_interval < 60 else detect_interval
  94. redisObj.set_data(key=dkey, val=1, expire=detect_interval - 5)
  95. redisObj.set_data(key=pkey, val=1, expire=60)
  96. # 旧模式并且没有pkey,重新创建一个
  97. if not detect_group and not have_pkey:
  98. redisObj.set_data(key=pkey, val=1, expire=60)
  99. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  100. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  101. # 推送相关参数
  102. push_kwargs = {
  103. 'uid': uid,
  104. 'channel': channel,
  105. 'event_type': event_type,
  106. 'n_time': n_time,
  107. }
  108. params = {'nickname': nickname, 'uid': uid, 'push_kwargs': push_kwargs, 'is_st': is_st,
  109. 'is_sys_msg': is_sys_msg, 'channel': channel, 'event_type': event_type, 'n_time': n_time,
  110. 'electricity': '', 'bucket': bucket, 'app_push': have_dkey, 'storage_location': 1, 'ai_type': 0,
  111. 'dealings_type': 0, 'detection': 0, 'device_type': 1, 'app_push_config': '',
  112. 'uid_set_push_list': uid_push_list}
  113. # 异步推送消息和保存数据
  114. push_thread = threading.Thread(
  115. target=push_and_save_data,
  116. kwargs=params)
  117. push_thread.start()
  118. res_data = {}
  119. if is_st == '0' or is_st == '2':
  120. res_data = {'code': 0, 'msg': 'success 0 or 2'}
  121. return JsonResponse(status=200, data=res_data)
  122. elif is_st == '1':
  123. obj = '{}/{}/{}.jpeg'.format(uid, channel, n_time)
  124. url = bucket.sign_url('PUT', obj, 3600)
  125. res_data = {'code': 0, 'img_push': url, 'msg': 'success 1'}
  126. elif is_st == '3':
  127. img_url_list = []
  128. for i in range(int(is_st)):
  129. obj = '{}/{}/{}_{}.jpeg'.format(uid, channel, n_time, i)
  130. url = bucket.sign_url('PUT', obj, 3600)
  131. img_url_list.append(url)
  132. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  133. V1_PUSH_LOGGER.info('旧推送接口响应,uid:{},n_time:{},事件类型:{},响应:{}'.
  134. format(uid, n_time, event_type, json.dumps(res_data)))
  135. return JsonResponse(status=200, data=res_data)
  136. except Exception as e:
  137. V1_PUSH_LOGGER.info('旧推送接口异常,error_line:{},error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  138. data = {
  139. 'error_line': e.__traceback__.tb_lineno,
  140. 'error_msg': repr(e)
  141. }
  142. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  143. def push_and_save_data(**params):
  144. uid = params['uid']
  145. V1_PUSH_LOGGER.info('{}开始异步存表和推送'.format(uid))
  146. # 保存推送数据和推送消息
  147. result = DevicePushService.save_msg_push(**params)
  148. V1_PUSH_LOGGER.info('{}存表和推送结果:{}'.format(uid, result))