MessageMangementController.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import time
  2. import boto3
  3. import botocore
  4. import oss2
  5. from botocore import client
  6. from django.core.paginator import Paginator
  7. from django.db.models import Q
  8. from django.views.generic.base import View
  9. from Ansjer.config import CONFIG_EUR, CONFIG_US
  10. from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
  11. SERVER_TYPE
  12. from Controller.DetectControllerV2 import DetectControllerViewV2
  13. from Model import models
  14. from Model.models import Device_Info, VodBucketModel, DeviceTypeModel
  15. from Object.OCIObjectStorage import OCIObjectStorage
  16. from Object.RedisObject import RedisObject
  17. from Object.ResponseObject import ResponseObject
  18. from Object.TokenObject import TokenObject
  19. from Object.utils import LocalDateTimeUtil
  20. from Service.EquipmentInfoService import EquipmentInfoService
  21. from Service.VodHlsService import SplitVodHlsObject
  22. class MassageView(View):
  23. def get(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request, request.GET, operation)
  27. def post(self, request, *args, **kwargs):
  28. request.encoding = 'utf-8'
  29. operation = kwargs.get('operation')
  30. return self.validation(request, request.POST, operation)
  31. def validation(self, request, request_dict, operation):
  32. language = request_dict.get('language', 'en')
  33. response = ResponseObject(language, 'pc')
  34. if operation == 'XXX':
  35. return 0
  36. else:
  37. tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'), returntpye='pc')
  38. if tko.code != 0:
  39. return response.json(tko.code)
  40. if operation == 'queryInfoList':
  41. return self.query_info_list(request_dict, response)
  42. else:
  43. return response.json(414)
  44. def query_info_list(self, request_dict, response):
  45. """
  46. 查询推送数据
  47. @param request_dict: 请求参数
  48. @request_dict uids: 设备id
  49. @request_dict eventType: 事件类型
  50. @request_dict eventType: userID
  51. @request_dict startTime: 开始时间戳
  52. @request_dict endTime: 结束时间戳
  53. @request_dict pageNo: 开始时间戳
  54. @request_dict pageSize: 结束时间戳
  55. @param response:
  56. @return:
  57. """
  58. try:
  59. uids = request_dict.get('uids', None)
  60. event_type = request_dict.get('eventType', None)
  61. user_id = request_dict.get('userID', None)
  62. # 时间
  63. start_time = request_dict.get('startTime', None)
  64. end_time = request_dict.get('endTime', None)
  65. # 分页
  66. page = int(request_dict.get('pageNo', None))
  67. size = int(request_dict.get('pageSize', None))
  68. # 区域
  69. if SERVER_TYPE == 'Ansjer.cn_config.formal_settings' or SERVER_TYPE == 'Ansjer.cn_config.test_settings':
  70. region = 2
  71. else:
  72. region = 1
  73. query = Q()
  74. if not start_time and not end_time:
  75. # 默认查询近七天内数据
  76. end_time = int(time.time())
  77. start_time = LocalDateTimeUtil.get_before_days_timestamp(end_time, 7)
  78. query &= Q(event_time__range=(start_time, end_time))
  79. elif start_time and end_time:
  80. query &= Q(event_time__range=(start_time, end_time))
  81. else:
  82. response.json(10, "需要给出一个时间段")
  83. if user_id is None and uids is None:
  84. return response.json(0, {"list": [], "total": 0})
  85. # 过滤条件
  86. if user_id is not None and user_id != "":
  87. query &= Q(device_user_id=user_id)
  88. if uids is not None and uids != "":
  89. uid_list = uids.split(',')
  90. query &= Q(device_uid__in=uid_list)
  91. if event_type is not None:
  92. event_type_list = EquipmentInfoService.get_comb_event_type(event_type)
  93. event_type_list = list(set(event_type_list))
  94. tags = EquipmentInfoService.get_event_tag(event_type)
  95. if event_type_list:
  96. query &= Q(event_type__in=event_type_list)
  97. tags = ''
  98. query &= Q(event_tag__regex=tags)
  99. elif tags:
  100. query &= Q(event_tag__regex=tags)
  101. # 联表查询
  102. querysets = []
  103. for i in range(1, 21):
  104. table_name = f'EquipmentInfo{i}'
  105. model_class = getattr(models, table_name)
  106. annotated_queryset = model_class.objects.filter(query)
  107. querysets.append(annotated_queryset)
  108. equipment_info_combined_qs = querysets[0].union(*querysets[1:], all=True)
  109. # 创建分页对象
  110. equipment_info_combined_qs = equipment_info_combined_qs.order_by("-event_time")
  111. paginator = Paginator(equipment_info_combined_qs, size)
  112. # 获取请求页的数据
  113. packages_page = paginator.page(page)
  114. # 连接存储桶
  115. auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
  116. oss_img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  117. aws_s3 = boto3.client(
  118. 's3',
  119. aws_access_key_id=AWS_ACCESS_KEY_ID[1],
  120. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1],
  121. config=botocore.client.Config(signature_version='s3v4'),
  122. region_name='us-east-1'
  123. )
  124. aws_s3_cn = boto3.client(
  125. 's3',
  126. aws_access_key_id=AWS_ACCESS_KEY_ID[0],
  127. aws_secret_access_key=AWS_SECRET_ACCESS_KEY[0],
  128. config=botocore.client.Config(signature_version='s3v4'),
  129. region_name='cn-northwest-1'
  130. )
  131. # 国内生产环境默认不实例OCI对象
  132. oci_eur = OCIObjectStorage(CONFIG_EUR)
  133. oci_us = OCIObjectStorage(CONFIG_US)
  134. redis_obj = RedisObject(3)
  135. # ai消息标识所有组合标签
  136. ai_all_event_type = EquipmentInfoService.get_all_comb_event_type()
  137. # 遍历调整返回数据
  138. equipment_info_list = []
  139. for equipment_info in packages_page:
  140. uid = equipment_info.device_uid
  141. channel = equipment_info.channel
  142. event_time = equipment_info.event_time
  143. storage_location = equipment_info.storage_location
  144. border_coords = equipment_info.border_coords
  145. event_tag = equipment_info.event_tag
  146. img_url = ""
  147. if equipment_info.is_st == 1:
  148. thumbspng = '{}/{}/{}.jpeg'.format(uid, channel, event_time)
  149. if storage_location == 1: # 阿里云oss
  150. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  151. elif storage_location in [3, 4]:
  152. prefix_name = f'{uid}/'
  153. oci = oci_eur if storage_location == 4 else oci_us
  154. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  155. if img_url:
  156. img_url = img_url + thumbspng
  157. else:
  158. params = {'Key': thumbspng}
  159. if region == 1: # AWS国外
  160. params['Bucket'] = 'foreignpush'
  161. img_url = aws_s3.generate_presigned_url(
  162. 'get_object', Params=params, ExpiresIn=300)
  163. else: # AWS国内
  164. params['Bucket'] = 'push'
  165. img_url = aws_s3_cn.generate_presigned_url(
  166. 'get_object', Params=params, ExpiresIn=300)
  167. img_url = img_url
  168. img_list = [img_url]
  169. elif equipment_info.is_st == 2:
  170. # 列表装载回放时间戳标记
  171. split_vod_hls_obj = SplitVodHlsObject()
  172. vodqs = split_vod_hls_obj.get_vod_hls_data(
  173. uid=uid, channel=channel, start_time=int(event_time)).values('bucket_id')
  174. if not vodqs.exists():
  175. return response.json(173)
  176. vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
  177. if not vod_bucket_qs.exists():
  178. return response.json(173)
  179. bucket_name = vod_bucket_qs[0]['bucket']
  180. endpoint = vod_bucket_qs[0]['endpoint']
  181. bucket = oss2.Bucket(auth, endpoint, bucket_name)
  182. ts = '{}/vod{}/{}/ts0.ts'.format(uid, channel, event_time)
  183. if storage_location == 1: # 阿里云oss
  184. thumb0 = bucket.sign_url('GET', ts, 3600,
  185. params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
  186. thumb1 = bucket.sign_url('GET', ts, 3600,
  187. params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
  188. thumb2 = bucket.sign_url('GET', ts, 3600,
  189. params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
  190. img_url = ""
  191. img_list = [thumb0, thumb1, thumb2]
  192. else:
  193. params = {'Key': ts}
  194. if region == 1: # AWS国外
  195. params['Bucket'] = 'foreignpush'
  196. img_url = aws_s3.generate_presigned_url(
  197. 'get_object', Params=params, ExpiresIn=300)
  198. else: # AWS国内
  199. params['Bucket'] = 'push'
  200. img_url = aws_s3_cn.generate_presigned_url(
  201. 'get_object', Params=params, ExpiresIn=300)
  202. img_list = [img_url]
  203. elif equipment_info.is_st == 3 or equipment_info.is_st == 4:
  204. # 列表装载回放时间戳标记
  205. img_list = []
  206. for i in range(equipment_info.is_st):
  207. thumbspng = '{}/{}/{}_{}.jpeg'.format(uid, channel, event_time, i)
  208. if storage_location == 1: # 阿里云oss
  209. img_url = oss_img_bucket.sign_url('GET', thumbspng, 300)
  210. elif storage_location in [3, 4]: # 国外OCI云
  211. prefix_name = f'{uid}/'
  212. oci = oci_eur if storage_location == 4 else oci_us
  213. img_url = DetectControllerViewV2.oci_object_url(oci, redis_obj, uid, prefix_name)
  214. if img_url:
  215. img_url = img_url + thumbspng
  216. else:
  217. params = {'Key': thumbspng}
  218. if region == 1: # 国外AWS
  219. params['Bucket'] = 'foreignpush'
  220. img_url = aws_s3.generate_presigned_url(
  221. 'get_object', Params=params, ExpiresIn=300)
  222. else: # 国内AWS
  223. params['Bucket'] = 'push'
  224. img_url = aws_s3_cn.generate_presigned_url(
  225. 'get_object', Params=params, ExpiresIn=300)
  226. img_list.append(img_url)
  227. else:
  228. img_list = []
  229. uid_type = Device_Info.objects.filter(UID=uid).values('Type').first()
  230. device_type = DeviceTypeModel.objects.filter(type=uid_type['Type']).values('name').first()
  231. if device_type is None:
  232. device_type = {"name": uid_type['Type']}
  233. border_coords = '' if border_coords == '' else eval(border_coords)
  234. ai_event_type_list = []
  235. # 如果是ai消息类型,则分解eventType, 如:123 -> [1,2,3]
  236. if border_coords and event_type in ai_all_event_type:
  237. ai_event_type_list = list(map(int, str(event_type)))
  238. if EquipmentInfoService.is_combo_tag(event_type, event_tag):
  239. ai_event_type_list += EquipmentInfoService.get_combo_types(event_type, event_tag)
  240. equipment_info_data = {
  241. "uid": uid,
  242. "status": equipment_info.status,
  243. "answerStatus": equipment_info.answer_status,
  244. "alarm": equipment_info.alarm,
  245. "isSt": equipment_info.is_st,
  246. "storageLocation": storage_location,
  247. "devNickName": equipment_info.device_nick_name,
  248. "channel": channel,
  249. "eventType": equipment_info.event_type,
  250. "eventTime": int(event_time),
  251. "addTime": equipment_info.add_time,
  252. "borderCoords": border_coords,
  253. "eventTag": event_tag,
  254. "img": img_url,
  255. "imgList": img_list,
  256. "uidType": device_type["name"],
  257. "aiEventTypeList": str(ai_event_type_list),
  258. }
  259. equipment_info_list.append(equipment_info_data)
  260. data = {
  261. "list": equipment_info_list,
  262. "total": paginator.count
  263. }
  264. return response.json(0, data)
  265. except Exception as e:
  266. print(e)
  267. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))