Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

137 rindas
6.9KB

  1. # -*- coding: utf-8 -*-
  2. from json import loads
  3. from traceback import format_exc
  4. import oss2
  5. import time
  6. from aliyunsdkvod.request.v20170321.GetPlayInfoRequest import GetPlayInfoRequest
  7. from loguru import logger
  8. from exception.CustomerException import ServiceException
  9. from enums.ExceptionEnum import ExceptionType
  10. from aliyunsdkcore.client import AcsClient
  11. from aliyunsdkvod.request.v20170321 import GetPlayInfoRequest
  12. from util.RWUtils import getConfigs
  13. from vodsdk.AliyunVodUploader import AliyunVodUploader
  14. from vodsdk.UploadVideoRequest import UploadVideoRequest
  15. class AliyunOssSdk:
  16. __slots__ = ('bucket', '__requestId', '__aliyun_config')
  17. def __init__(self, base_dir, requestId):
  18. self.bucket = None
  19. self.__requestId = requestId
  20. self.__aliyun_config = getConfigs(base_dir, 'config/dsp_aliyun.json')
  21. def get_oss_bucket(self):
  22. if self.bucket is None:
  23. logger.info("初始化oss桶, requestId:{}", self.__requestId)
  24. auth = oss2.Auth(self.__aliyun_config["access_key"], self.__aliyun_config["access_secret"])
  25. self.bucket = oss2.Bucket(auth, self.__aliyun_config["oss"]["endpoint"],
  26. self.__aliyun_config["oss"]["bucket"],
  27. connect_timeout=self.__aliyun_config["oss"]["connect_timeout"])
  28. def sync_upload_file(self, updatePath, fileByte):
  29. logger.info("开始上传文件到oss, requestId:{}", self.__requestId)
  30. self.get_oss_bucket()
  31. MAX_RETRIES = 3
  32. retry_count = 0
  33. while True:
  34. try:
  35. self.bucket.put_object(updatePath, fileByte)
  36. logger.info("上传文件到oss成功! requestId:{}", self.__requestId)
  37. break
  38. except Exception as e:
  39. retry_count += 1
  40. time.sleep(1)
  41. logger.info("上传文件到oss失败, 重试次数:{}, requestId:{}", retry_count, self.__requestId)
  42. if retry_count > MAX_RETRIES:
  43. logger.error("上传文件到oss重试失败:{}, requestId:{}", format_exc(), self.__requestId)
  44. raise e
  45. class ThAliyunVodSdk:
  46. __slots__ = ('__aliyun_config', '__requestId', "__active")
  47. def __init__(self, base_dir, requestId, active):
  48. self.__requestId = requestId
  49. self.__active = active
  50. self.__aliyun_config = getConfigs(base_dir, 'config/dsp_aliyun.json')
  51. def init_vod_client(self, accessKeyId, accessKeySecret):
  52. regionId = self.__aliyun_config["vod"]["ecsRegionId"]
  53. return AcsClient(accessKeyId, accessKeySecret, regionId, auto_retry=True, max_retry_time=3, timeout=30)
  54. def get_play_info(self, videoId):
  55. logger.info("开始获取视频地址,videoId:{}, requestId:{}", videoId, self.__requestId)
  56. start = time.time()
  57. while True:
  58. try:
  59. clt = self.init_vod_client(self.__aliyun_config["access_key"],
  60. self.__aliyun_config["access_secret"])
  61. request: GetPlayInfoRequest = GetPlayInfoRequest.GetPlayInfoRequest()
  62. request.set_accept_format('JSON')
  63. request.set_VideoId(videoId)
  64. request.set_AuthTimeout(3600 * 5)
  65. response = loads(clt.do_action_with_exception(request))
  66. play_url = response["PlayInfoList"]["PlayInfo"][0]["PlayURL"]
  67. logger.info("获取视频地址成功,视频地址: {}, requestId: {}", play_url, self.__requestId)
  68. return play_url
  69. except Exception as e:
  70. logger.info("获取视频地址失败,5秒后重试, requestId: {}", self.__requestId)
  71. time.sleep(5)
  72. current_time = time.time()
  73. if "HTTP Status: 403" not in str(e):
  74. logger.error("获取视频地址失败: {}, requestId: {}", format_exc(), self.__requestId)
  75. raise ServiceException(ExceptionType.GET_VIDEO_URL_EXCEPTION.value[0],
  76. ExceptionType.GET_VIDEO_URL_EXCEPTION.value[1])
  77. if "HTTP Status: 403" in str(e) and ("UploadFail" in str(e) or "TranscodeFail" in str(e)):
  78. logger.error("获取视频地址失败: {}, requestId: {}", format_exc(), self.__requestId)
  79. raise ServiceException(ExceptionType.GET_VIDEO_URL_EXCEPTION.value[0],
  80. ExceptionType.GET_VIDEO_URL_EXCEPTION.value[1])
  81. diff_time = current_time - start
  82. if diff_time > 60 * 60 * 5:
  83. logger.error("获取视频地址失败超时异常: {},超时时间:{}, requestId: {}", format_exc(),
  84. diff_time, self.__requestId)
  85. raise ServiceException(ExceptionType.GET_VIDEO_URL_TIMEOUT_EXCEPTION.value[0],
  86. ExceptionType.GET_VIDEO_URL_TIMEOUT_EXCEPTION.value[1])
  87. def upload_local_video(self, filePath, file_title):
  88. logger.info("开始执行vod视频上传, filePath: {}, requestId: {}", filePath, self.__requestId)
  89. uploader = AliyunVodUploader(self.__aliyun_config["access_key"],
  90. self.__aliyun_config["access_secret"], self.__requestId)
  91. uploadVideoRequest: UploadVideoRequest = UploadVideoRequest(filePath, file_title)
  92. logger.info("视频分类:{}, requestId:{}", self.__aliyun_config["vod"][self.__active]["CateId"], self.__requestId)
  93. uploadVideoRequest.setCateId(self.__aliyun_config["vod"][self.__active]["CateId"])
  94. # 可以设置视频封面,如果是本地或网络图片可使用UploadImageRequest上传图片到视频点播,获取到ImageURL
  95. # ImageURL示例:https://example.com/sample-****.jpg
  96. # uploadVideoRequest.setCoverURL('<your Image URL>')
  97. # 标签
  98. # uploadVideoRequest.setTags('tag1,tag2')
  99. MAX_RETRIES = 3
  100. retry_count = 0
  101. while True:
  102. try:
  103. result = uploader.uploadLocalVideo(uploadVideoRequest)
  104. logger.info("vod视频上传成功, videoId:{}, requestId:{}", result.get("VideoId"), self.__requestId)
  105. return result.get("VideoId")
  106. except Exception:
  107. retry_count += 1
  108. time.sleep(1)
  109. logger.error("vod视频上传失败:{},重试次数:{}, requestId:{}", format_exc(), retry_count,
  110. self.__requestId)
  111. if retry_count >= MAX_RETRIES:
  112. raise ServiceException(ExceptionType.SERVICE_INNER_EXCEPTION.value[0],
  113. ExceptionType.SERVICE_INNER_EXCEPTION.value[1])
  114. def get_play_url(self, filePath, file_title):
  115. videoId = self.upload_local_video(filePath, file_title)
  116. if videoId is None or len(videoId) == 0:
  117. return None
  118. return self.get_play_info(videoId)