Browse Source

新增云相册代码

zhangdongming 2 năm trước cách đây
mục cha
commit
5e73010708
3 tập tin đã thay đổi với 132 bổ sung3 xóa
  1. 78 0
      Controller/Cron/CloudPhotoController.py
  2. 39 1
      Controller/TestApi.py
  3. 15 2
      Object/AWS/AmazonS3Util.py

+ 78 - 0
Controller/Cron/CloudPhotoController.py

@@ -0,0 +1,78 @@
+# -*- encoding: utf-8 -*-
+"""
+@File    : CloudPhotoController.py
+@Time    : 2022/10/24 15:48
+@Author  : stephen
+@Email   : zhangdongming@asj6.wecom.work
+@Software: PyCharm
+"""
+import datetime
+import logging
+import time
+import traceback
+
+from django.views import View
+
+from Ansjer.cn_config.config_formal import PUSH_CLOUD_PHOTO
+from Ansjer.config import ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, PUSH_BUCKET, PUSH_INACCURATE_BUCKET
+from Object.AWS.AmazonS3Util import AmazonS3Util
+from Object.ResponseObject import ResponseObject
+from Service.EquipmentInfoService import EquipmentInfoService
+
+LOGGER = logging.getLogger('info')
+
+
+class CloudPhotoView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.GET, request, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.POST, request, operation)
+
+    def validation(self, request_dict, request, operation):
+        response = ResponseObject()
+        if operation == 'get-photo':
+            return self.get_photo(response)
+        else:
+            return response.json(404)
+
+    @classmethod
+    def get_photo(cls, response):
+        """
+        定时获取云存消息推送图
+        """
+        try:
+            today = datetime.date.today()
+            eq_qs = EquipmentInfoService.get_equipment_info_model(str(today))
+            start_time = "{} 00:00:00".format(str(today))
+            # 先转换为时间数组
+            timeArray = time.strptime(start_time, "%Y-%m-%d %H:%M:%S")
+            # 转换为时间戳
+            timeStamp = int(time.mktime(timeArray))
+            eq_qs = eq_qs.filter(event_time__gt=timeStamp, is_st=1, device_uid='HA154GVEDH41RY8Y111A').values()
+            count = eq_qs.count()
+            page = int(count / 2) if count > 1 else count
+            if page == 0:
+                return response.json(0)
+            eq_qs = eq_qs[(page - 1) * 1:page * 1]
+            eq_vo = eq_qs[0]
+
+            s3 = AmazonS3Util(
+                aws_access_key_id=ACCESS_KEY_ID,
+                secret_access_key=SECRET_ACCESS_KEY,
+                region_name=REGION_NAME
+            )
+            file_path = '{uid}/{channel}/{event_time}.jpeg'.format(uid=eq_vo['device_uid'],
+                                                                   channel=eq_vo['channel'],
+                                                                   event_time=eq_vo['event_time'])
+            s3.copy_obj(PUSH_BUCKET, PUSH_CLOUD_PHOTO, file_path)
+            return response.json(0)
+        except Exception as e:
+            print(e)
+            ex = traceback.format_exc()
+            LOGGER.info('--->抽取推送图片异常:{}'.format(ex))
+            return response.json(177, repr(e))

+ 39 - 1
Controller/TestApi.py

@@ -11,8 +11,14 @@
 @file: Test.py
 @Contact: chanjunkai@163.com
 """
+import os
+from io import BytesIO
+
 import botocore
+import cv2
+from PIL import Image
 from botocore import client
+
 from Controller.DeviceConfirmRegion import Device_Region
 from Object.AWS.AmazonS3Util import AmazonS3Util
 from Object.RedisObject import RedisObject
@@ -148,9 +154,41 @@ class testView(View):
             return self.read_redis_list(response)
         elif operation == 'playM3u8':
             return self.play_m3u8(request_dict, response)
+        elif operation == 'generate_video':
+            return self.generate_video(request_dict, response)
         else:
             return 123
 
+    @classmethod
+    def generate_video(cls, request_dict, response):
+        # 设计抽取图片规则通过消息随机还是时间随机,调试copy S3对象查询是否携带失效时间
+        DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
+        arr_list = ['1666756086.jpeg', '1666831275.jpeg', '1666841492.jpeg']
+        s3 = AmazonS3Util(AWS_ACCESS_KEY_ID[0], AWS_SECRET_ACCESS_KEY[0], 'cn-northwest-1')
+        bucket = 'push-cloud-photo'
+        for item in arr_list:
+            path = DIR + r'\Ansjer\file\{}'.format(item)
+            s3_key = 'HA154GVEDH41RY8Y111A/1/{}'.format(item)
+            s3.download_object(bucket, s3_key, path)
+        video_dir = DIR + r'\Ansjer\file\result.mp4'  # 输出视频的保存路径
+        fps = 0.5  # 帧率
+        img_size = (1920, 1080)  # 图片尺寸
+        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
+        videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)
+        for i in arr_list:
+            img_path = DIR + r'\Ansjer\file\{}'.format(i)
+            frame = cv2.imread(img_path)
+            frame = cv2.resize(frame, img_size)  # 生成视频   图片尺寸和设定尺寸相同
+            videoWriter.write(frame)  # 将图片写进视频里
+            os.remove(img_path)
+        videoWriter.release()  # 释放资源
+        data = open(video_dir, 'rb')
+        key = 'HA154GVEDH41RY8Y111A/1/20221027.mp4'
+        s3.upload_file_obj(bucket, key, data)
+        response_url = s3.generate_file_obj_url(bucket, key)
+        os.remove(video_dir)
+        return response.json(0, response_url)
+
     @classmethod
     def head_bucket(cls, request_dict, response):
         bucket_name = request_dict.get('bucket', None)
@@ -1050,7 +1088,7 @@ class testView(View):
                             'Bucket': bucket_name,
                             'Key': tsFile
                         },
-                        ExpiresIn=24*60*60
+                        ExpiresIn=24 * 60 * 60
                     )
                     playlist_entries.append({
                         'name': response_url,

+ 15 - 2
Object/AWS/AmazonS3Util.py

@@ -72,8 +72,7 @@ class AmazonS3Util:
             Params={
                 'Bucket': bucket,
                 'Key': file_key
-            },
-            ExpiresIn=3600
+            }
         )
         return response_url
 
@@ -124,6 +123,20 @@ class AmazonS3Util:
         except self.client_conn.exceptions.NoSuchKey:
             return False
 
+    def download_object(self, bucket, key, file_name):
+        """
+        下载对象至本地
+        @param file_name: 保存位置以及名称
+        @param bucket: 存储桶
+        @param key: 文件
+        @return : boolean
+        """
+        try:
+            self.client_conn.download_file(bucket, key, file_name)
+            return True
+        except Exception as e:
+            return e.args
+
     def copy_obj(self, source_bucket, to_bucket, file_key):
         """
         复制对象