|
- # -*- coding: utf-8 -*-
- from json import loads
- from traceback import format_exc
-
- import oss2
- import time
-
- from aliyunsdkvod.request.v20170321.GetPlayInfoRequest import GetPlayInfoRequest
- from loguru import logger
-
- from exception.CustomerException import ServiceException
- from enums.ExceptionEnum import ExceptionType
- from aliyunsdkcore.client import AcsClient
- from aliyunsdkvod.request.v20170321 import GetPlayInfoRequest
-
- from util.RWUtils import getConfigs
- from vodsdk.AliyunVodUploader import AliyunVodUploader
- from vodsdk.UploadVideoRequest import UploadVideoRequest
-
-
- class AliyunOssSdk:
-
- __slots__ = ('bucket', '__requestId', '__aliyun_config')
-
- def __init__(self, base_dir, requestId):
- self.bucket = None
- self.__requestId = requestId
- self.__aliyun_config = getConfigs(base_dir, 'config/dsp_aliyun.json')
-
- def get_oss_bucket(self):
- if self.bucket is None:
- logger.info("初始化oss桶, requestId:{}", self.__requestId)
- auth = oss2.Auth(self.__aliyun_config["access_key"], self.__aliyun_config["access_secret"])
- self.bucket = oss2.Bucket(auth, self.__aliyun_config["oss"]["endpoint"],
- self.__aliyun_config["oss"]["bucket"],
- connect_timeout=self.__aliyun_config["oss"]["connect_timeout"])
-
- def sync_upload_file(self, updatePath, fileByte):
- logger.info("开始上传文件到oss, requestId:{}", self.__requestId)
- self.get_oss_bucket()
- MAX_RETRIES = 3
- retry_count = 0
- while True:
- try:
- self.bucket.put_object(updatePath, fileByte)
- logger.info("上传文件到oss成功! requestId:{}", self.__requestId)
- break
- except Exception as e:
- retry_count += 1
- time.sleep(1)
- logger.info("上传文件到oss失败, 重试次数:{}, requestId:{}", retry_count, self.__requestId)
- if retry_count > MAX_RETRIES:
- logger.error("上传文件到oss重试失败:{}, requestId:{}", format_exc(), self.__requestId)
- raise e
-
-
- class ThAliyunVodSdk:
-
- __slots__ = ('__aliyun_config', '__requestId', "__active")
-
- def __init__(self, base_dir, requestId, active):
- self.__requestId = requestId
- self.__active = active
- self.__aliyun_config = getConfigs(base_dir, 'config/dsp_aliyun.json')
-
- def init_vod_client(self, accessKeyId, accessKeySecret):
- regionId = self.__aliyun_config["vod"]["ecsRegionId"]
- return AcsClient(accessKeyId, accessKeySecret, regionId, auto_retry=True, max_retry_time=3, timeout=30)
-
- def get_play_info(self, videoId):
- logger.info("开始获取视频地址,videoId:{}, requestId:{}", videoId, self.__requestId)
- start = time.time()
- while True:
- try:
- clt = self.init_vod_client(self.__aliyun_config["access_key"],
- self.__aliyun_config["access_secret"])
- request: GetPlayInfoRequest = GetPlayInfoRequest.GetPlayInfoRequest()
- request.set_accept_format('JSON')
- request.set_VideoId(videoId)
- request.set_AuthTimeout(3600 * 5)
- response = loads(clt.do_action_with_exception(request))
- play_url = response["PlayInfoList"]["PlayInfo"][0]["PlayURL"]
- logger.info("获取视频地址成功,视频地址: {}, requestId: {}", play_url, self.__requestId)
- return play_url
- except Exception as e:
- logger.info("获取视频地址失败,5秒后重试, requestId: {}", self.__requestId)
- time.sleep(5)
- current_time = time.time()
- if "HTTP Status: 403" not in str(e):
- logger.error("获取视频地址失败: {}, requestId: {}", format_exc(), self.__requestId)
- raise ServiceException(ExceptionType.GET_VIDEO_URL_EXCEPTION.value[0],
- ExceptionType.GET_VIDEO_URL_EXCEPTION.value[1])
- if "HTTP Status: 403" in str(e) and ("UploadFail" in str(e) or "TranscodeFail" in str(e)):
- logger.error("获取视频地址失败: {}, requestId: {}", format_exc(), self.__requestId)
- raise ServiceException(ExceptionType.GET_VIDEO_URL_EXCEPTION.value[0],
- ExceptionType.GET_VIDEO_URL_EXCEPTION.value[1])
- diff_time = current_time - start
- if diff_time > 60 * 60 * 5:
- logger.error("获取视频地址失败超时异常: {},超时时间:{}, requestId: {}", format_exc(),
- diff_time, self.__requestId)
- raise ServiceException(ExceptionType.GET_VIDEO_URL_TIMEOUT_EXCEPTION.value[0],
- ExceptionType.GET_VIDEO_URL_TIMEOUT_EXCEPTION.value[1])
-
- def upload_local_video(self, filePath, file_title):
- logger.info("开始执行vod视频上传, filePath: {}, requestId: {}", filePath, self.__requestId)
- uploader = AliyunVodUploader(self.__aliyun_config["access_key"],
- self.__aliyun_config["access_secret"], self.__requestId)
- uploadVideoRequest: UploadVideoRequest = UploadVideoRequest(filePath, file_title)
- logger.info("视频分类:{}, requestId:{}", self.__aliyun_config["vod"][self.__active]["CateId"], self.__requestId)
- uploadVideoRequest.setCateId(self.__aliyun_config["vod"][self.__active]["CateId"])
- # 可以设置视频封面,如果是本地或网络图片可使用UploadImageRequest上传图片到视频点播,获取到ImageURL
- # ImageURL示例:https://example.com/sample-****.jpg
- # uploadVideoRequest.setCoverURL('<your Image URL>')
- # 标签
- # uploadVideoRequest.setTags('tag1,tag2')
- MAX_RETRIES = 3
- retry_count = 0
- while True:
- try:
- result = uploader.uploadLocalVideo(uploadVideoRequest)
- logger.info("vod视频上传成功, videoId:{}, requestId:{}", result.get("VideoId"), self.__requestId)
- return result.get("VideoId")
- except Exception:
- retry_count += 1
- time.sleep(1)
- logger.error("vod视频上传失败:{},重试次数:{}, requestId:{}", format_exc(), retry_count,
- self.__requestId)
- if retry_count >= MAX_RETRIES:
- raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
- ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
-
- def get_play_url(self, filePath, file_title):
- videoId = self.upload_local_video(filePath, file_title)
- if videoId is None or len(videoId) == 0:
- return None
- return self.get_play_info(videoId)
|