MessageMangementController.py 12 KB

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