Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

150 lignes
7.6KB

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