DetectController.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import json
  2. import logging
  3. import oss2
  4. from django.http import JsonResponse
  5. from django.views.generic.base import View
  6. from AnsjerPush.config import CONFIG_INFO, CONFIG_CN
  7. from AnsjerPush.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
  8. from Model.models import SysMsgModel
  9. from Object.RedisObject import RedisObject
  10. from Object.utils import LocalDateTimeUtil
  11. from Service.DevicePushService import DevicePushService
  12. from Service.EquipmentInfoService import EquipmentInfoService
  13. # 旧移动侦测接口
  14. class NotificationView(View):
  15. def get(self, request, *args, **kwargs):
  16. request.encoding = 'utf-8'
  17. return self.validation(request.GET)
  18. def post(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. return self.validation(request.POST)
  21. def validation(self, 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. logger = logging.getLogger('info')
  32. logger.info("旧移动侦测接口参数:{}".format(request_dict))
  33. uidToken = request_dict.get('uidToken', None)
  34. etk = request_dict.get('etk', None)
  35. channel = request_dict.get('channel', '1')
  36. n_time = request_dict.get('n_time', None)
  37. event_type = request_dict.get('event_type', None)
  38. is_st = request_dict.get('is_st', None)
  39. if not all([channel, n_time]):
  40. return JsonResponse(status=200, data={'code': 444, 'msg': 'error channel or n_time'})
  41. try:
  42. uid = DevicePushService.decode_uid(etk, uidToken) # 解密uid
  43. if len(uid) != 20 and len(uid) != 14:
  44. return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong uid'})
  45. logger.info("旧移动侦测接口的uid:{}".format(uid))
  46. pkey = '{uid}_{channel}_{event_type}_ptl'.format(uid=uid, event_type=event_type, channel=channel)
  47. ykey = '{uid}_redis_qs'.format(uid=uid)
  48. is_sys_msg = self.is_sys_msg(int(event_type))
  49. if is_sys_msg is True:
  50. dkey = '{uid}_{channel}_{event_type}_flag'.format(uid=uid, event_type=event_type, channel=channel)
  51. else:
  52. dkey = '{uid}_{channel}_flag'.format(uid=uid, channel=channel)
  53. redisObj = RedisObject(db=6)
  54. have_ykey = redisObj.get_data(key=ykey) # uid_set 数据库缓存
  55. have_pkey = redisObj.get_data(key=pkey) # 一分钟限制key
  56. have_dkey = redisObj.get_data(key=dkey) # 推送类型限制
  57. # 一分钟外,推送开启状态
  58. detect_med_type = 0 # 0推送旧机制 1存库不推送,2推送存库
  59. # 暂时注销
  60. if have_pkey:
  61. res_data = {'code': 0, 'msg': 'Push it once a minute'}
  62. return JsonResponse(status=200, data=res_data)
  63. # 数据库读取数据
  64. if have_ykey:
  65. uid_push_list = eval(redisObj.get_data(key=ykey))
  66. else:
  67. # 从数据库查询出来
  68. uid_push_qs = DevicePushService.query_uid_push(uid)
  69. if not uid_push_qs.exists():
  70. logger.info('消息推送-uid_push 数据不存在')
  71. return JsonResponse(status=200, data={'code': 176, 'msg': 'no uid_push data'})
  72. # 修改redis数据,并设置过期时间为10分钟
  73. uid_push_list = DevicePushService.cache_uid_push(uid_push_qs)
  74. redisObj.set_data(key=ykey, val=str(uid_push_list), expire=600)
  75. if not uid_push_list:
  76. res_data = {'code': 404, 'msg': 'error !'}
  77. return JsonResponse(status=200, data=res_data)
  78. if not uid_push_list:
  79. res_data = {'code': 0, 'msg': 'uid_push_list not exist'}
  80. return JsonResponse(status=200, data=res_data)
  81. nickname = uid_push_list[0]['uid_set__nickname']
  82. detect_interval = uid_push_list[0]['uid_set__detect_interval']
  83. detect_group = uid_push_list[0]['uid_set__detect_group']
  84. if not nickname:
  85. nickname = uid
  86. if detect_group is not None:
  87. if have_dkey:
  88. detect_med_type = 1 # 1为存库不推送
  89. else:
  90. detect_med_type = 2 # 为2的话,既推送,又存库
  91. if CONFIG_INFO != CONFIG_CN:
  92. new_detect_interval = uid_push_list[0]['uid_set__new_detect_interval']
  93. detect_interval = new_detect_interval if new_detect_interval > 0 else detect_interval
  94. detect_interval = 60 if detect_interval < 60 else detect_interval
  95. redisObj.set_data(key=dkey, val=1, expire=detect_interval - 5)
  96. redisObj.set_data(key=pkey, val=1, expire=60)
  97. logger.info(
  98. 'APP消息推送V1接口,是否进行APP推送:{},1为不推送,间隔:{}'.format(detect_med_type, detect_interval))
  99. # 旧模式并且没有pkey,重新创建一个
  100. if not detect_group and not have_pkey:
  101. redisObj.set_data(key=pkey, val=1, expire=60)
  102. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  103. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  104. kwag_args = {
  105. 'uid': uid,
  106. 'channel': channel,
  107. 'event_type': event_type,
  108. 'n_time': n_time,
  109. }
  110. params = {'nickname': nickname, 'uid': uid, 'kwag_args': kwag_args, 'is_st': is_st,
  111. 'is_sys_msg': is_sys_msg, 'channel': channel, 'event_type': event_type, 'n_time': n_time,
  112. 'electricity': '', 'bucket': bucket, 'app_push': '', 'storage_location': 1}
  113. # 推送以及报警消息存库
  114. result = DevicePushService.save_msg_push(uid_set_push_list=uid_push_list, **params)
  115. if result['code_date'] is None:
  116. result['code_date'] = {'do_apns_code': '', 'do_fcm_code': '', 'do_jpush_code': ''}
  117. if detect_med_type == 1:
  118. result['code_date']['do_apns_code'] = '只存库不推送'
  119. result['code_date']['do_fcm_code'] = '只存库不推送'
  120. result['code_date']['do_jpush_code'] = '只存库不推送'
  121. if is_sys_msg:
  122. SysMsgModel.objects.bulk_create(result['sys_msg_list'])
  123. else:
  124. if result['new_device_info_list'] and len(result['new_device_info_list']) > 0:
  125. # 根据日期获得星期几
  126. week = LocalDateTimeUtil.date_to_week(result['local_date_time'])
  127. EquipmentInfoService.equipment_info_bulk_create(week, result['new_device_info_list'])
  128. logger.info('----《旧接口》设备信息分表批量保存end')
  129. if is_st == '0' or is_st == '2':
  130. print("is_st=0or2")
  131. for up in uid_push_list:
  132. if up['push_type'] == 0: # ios apns
  133. up['do_apns_code'] = result['code_date']['do_apns_code']
  134. elif up['push_type'] == 1: # android gcm
  135. up['do_fcm_code'] = result['code_date']['do_fcm_code']
  136. elif up['push_type'] == 2: # android jpush
  137. up['do_jpush_code'] = result['code_date']['do_jpush_code']
  138. del up['push_type']
  139. del up['userID_id']
  140. del up['userID__NickName']
  141. del up['lang']
  142. del up['tz']
  143. del up['uid_set__nickname']
  144. del up['uid_set__detect_interval']
  145. del up['uid_set__detect_group']
  146. return JsonResponse(status=200, data={'code': 0, 'msg': 'success 0 or 2'})
  147. elif is_st == '1':
  148. print("is_st=1")
  149. # Endpoint以杭州为例,其它Region请按实际情况填写。
  150. obj = '{uid}/{channel}/{filename}.jpeg'.format(uid=uid, channel=channel, filename=n_time)
  151. # 设置此签名URL在60秒内有效。
  152. url = bucket.sign_url('PUT', obj, 7200)
  153. for up in uid_push_list:
  154. up['do_apns_code'] = result['code_date']['do_apns_code']
  155. up['do_fcm_code'] = result['code_date']['do_fcm_code']
  156. up['do_jpush_code'] = result['code_date']['do_jpush_code']
  157. del up['push_type']
  158. del up['userID_id']
  159. del up['userID__NickName']
  160. del up['lang']
  161. del up['tz']
  162. del up['uid_set__nickname']
  163. del up['uid_set__detect_interval']
  164. del up['uid_set__detect_group']
  165. res_data = {'code': 0, 'img_push': url, 'msg': 'success'}
  166. return JsonResponse(status=200, data=res_data)
  167. elif is_st == '3':
  168. print("is_st=3")
  169. # 人形检测带动图
  170. # Endpoint以杭州为例,其它Region请按实际情况填写。
  171. img_url_list = []
  172. for i in range(int(is_st)):
  173. obj = '{uid}/{channel}/{filename}_{st}.jpeg'. \
  174. format(uid=uid, channel=channel, filename=n_time, st=i)
  175. # 设置此签名URL在60秒内有效。
  176. url = bucket.sign_url('PUT', obj, 7200)
  177. img_url_list.append(url)
  178. for up in uid_push_list:
  179. up['do_apns_code'] = result['code_date']['do_apns_code']
  180. up['do_fcm_code'] = result['code_date']['do_fcm_code']
  181. up['do_jpush_code'] = result['code_date']['do_jpush_code']
  182. del up['push_type']
  183. del up['userID_id']
  184. del up['userID__NickName']
  185. del up['lang']
  186. del up['tz']
  187. del up['uid_set__nickname']
  188. del up['uid_set__detect_interval']
  189. del up['uid_set__detect_group']
  190. res_data = {'code': 0, 'img_url_list': img_url_list, 'msg': 'success 3'}
  191. return JsonResponse(status=200, data=res_data)
  192. except Exception as e:
  193. logger.info('消息推送-异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  194. data = {
  195. 'errLine': e.__traceback__.tb_lineno,
  196. 'errMsg': repr(e),
  197. }
  198. return JsonResponse(status=200, data=json.dumps(data), safe=False)
  199. def is_sys_msg(self, event_type):
  200. event_type_list = [702, 703, 704]
  201. if event_type in event_type_list:
  202. return True
  203. return False