kdjsfq_publish.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/12/22
  4. """
  5. 上传视频到阿里云 OSS
  6. 上传视频到管理后台
  7. """
  8. import json
  9. import os
  10. import random
  11. import shutil
  12. import time
  13. import oss2
  14. import requests
  15. import urllib3
  16. from main.common import Common
  17. proxies = {"http": None, "https": None}
  18. class Publish:
  19. @classmethod
  20. def publish_video_dev(cls, log_type, request_data):
  21. """
  22. loginUid 站内uid (随机)
  23. appType 默认:888888
  24. crawlerSrcId 站外视频ID
  25. crawlerSrcCode 渠道(自定义 KYK)
  26. crawlerSrcPublishTimestamp 视频原发布时间
  27. crawlerTaskTimestamp 爬虫创建时间(可以是当前时间)
  28. videoPath 视频oss地址
  29. coverImgPath 视频封面oss地址
  30. title 标题
  31. totalTime 视频时长
  32. viewStatus 视频的有效状态 默认1
  33. versionCode 版本 默认1
  34. :return:
  35. """
  36. # Common.logger(log_type).info('publish request data: {}'.format(request_data))
  37. result = cls.request_post('https://videotest.yishihui.com/longvideoapi/crawler/video/send', request_data)
  38. # Common.logger(log_type).info('publish result: {}'.format(result))
  39. video_id = result["data"]["id"]
  40. # Common.logger(log_type).info('video_id: {}'.format(video_id))
  41. if result['code'] != 0:
  42. Common.logger(log_type).error('pushlish failure msg = {}'.format(result['msg']))
  43. else:
  44. Common.logger(log_type).info('publish success video_id = : {}'.format(request_data['crawlerSrcId']))
  45. return video_id
  46. @classmethod
  47. def publish_video_prod(cls, log_type, request_data):
  48. """
  49. loginUid 站内uid (随机)
  50. appType 默认:888888
  51. crawlerSrcId 站外视频ID
  52. crawlerSrcCode 渠道(自定义 KYK)
  53. crawlerSrcPublishTimestamp 视频原发布时间
  54. crawlerTaskTimestamp 爬虫创建时间(可以是当前时间)
  55. videoPath 视频oss地址
  56. coverImgPath 视频封面oss地址
  57. title 标题
  58. totalTime 视频时长
  59. viewStatus 视频的有效状态 默认1
  60. versionCode 版本 默认1
  61. :return:
  62. """
  63. Common.logger(log_type).info(f'publish request data: {request_data}')
  64. result = cls.request_post('https://longvideoapi.piaoquantv.com/longvideoapi/crawler/video/send', request_data)
  65. Common.logger(log_type).info(f'publish result: {result}')
  66. video_id = result["data"]["id"]
  67. Common.logger(log_type).info(f'video_id: {video_id}')
  68. if result['code'] != 0:
  69. Common.logger(log_type).error('pushlish failure msg = {}'.format(result['msg']))
  70. else:
  71. Common.logger(log_type).info('publish success video_id = : {}'.format(request_data['crawlerSrcId']))
  72. return video_id
  73. @classmethod
  74. def request_post(cls, request_url, request_data):
  75. """
  76. post 请求 HTTP接口
  77. :param request_url: 接口URL
  78. :param request_data: 请求参数
  79. :return: res_data json格式
  80. """
  81. urllib3.disable_warnings()
  82. response = requests.post(url=request_url, data=request_data, proxies=proxies, verify=False)
  83. if response.status_code == 200:
  84. res_data = json.loads(response.text)
  85. return res_data
  86. # 以下代码展示了基本的文件上传、下载、罗列、删除用法。
  87. # 首先初始化AccessKeyId、AccessKeySecret、Endpoint等信息。
  88. # 通过环境变量获取,或者把诸如“<你的AccessKeyId>”替换成真实的AccessKeyId等。
  89. #
  90. # 以杭州区域为例,Endpoint可以是:
  91. # http://oss-cn-hangzhou.aliyuncs.com
  92. # https://oss-cn-hangzhou.aliyuncs.com
  93. # 分别以HTTP、HTTPS协议访问。
  94. access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LTAIP6x1l3DXfSxm')
  95. access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', 'KbTaM9ars4OX3PMS6Xm7rtxGr1FLon')
  96. bucket_name = os.getenv('OSS_TEST_BUCKET', 'art-pubbucket')
  97. # 阿里云内网
  98. # endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-hangzhou-internal.aliyuncs.com')
  99. # 外网
  100. endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-cn-hangzhou.aliyuncs.com')
  101. # 确认上面的参数都填写正确了
  102. for param in (access_key_id, access_key_secret, bucket_name, endpoint):
  103. assert '<' not in param, '请设置参数:' + param
  104. # 创建Bucket对象,所有Object相关的接口都可以通过Bucket对象来进行
  105. bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
  106. """
  107. 处理流程:
  108. 1. 定时(每天凌晨1点执行一次)循环files文件下的内容 结构:files -> 视频文件夹 -> 视频文件 + 封面图 + 基本信息
  109. 2. 视频文件和封面上传到oss
  110. - 视频文件oss目录 longvideo/crawler_local/video/prod/文件名
  111. - 视频封面oss目录 longvideo/crawler_local/image/prod/文件名
  112. 3. 发布视频
  113. - 读取 基本信息 调用发布接口
  114. """
  115. # env 日期20220225 文件名
  116. oss_file_path_video = 'longvideo/crawler_local/video/{}/{}/{}'
  117. oss_file_path_image = 'longvideo/crawler_local/image/{}/{}/{}'
  118. @classmethod
  119. def put_file(cls, log_type, oss_file, local_file):
  120. cls.bucket.put_object_from_file(oss_file, local_file)
  121. Common.logger(log_type).info("put oss file = {}, local file = {} success".format(oss_file, local_file))
  122. # 清除本地文件
  123. @classmethod
  124. def remove_local_file(cls, log_type, local_file):
  125. os.remove(local_file)
  126. Common.logger(log_type).info("remove local file = {} success".format(local_file))
  127. # 清除本地文件夹
  128. @classmethod
  129. def remove_local_file_dir(cls, log_type, local_file):
  130. os.rmdir(local_file)
  131. Common.logger(log_type).info("remove local file dir = {} success".format(local_file))
  132. local_file_path = './videos'
  133. video_file = 'video'
  134. image_file = 'image'
  135. info_file = 'info'
  136. uids_dev_up = [6267140]
  137. uids_dev_play = [6267141]
  138. uids_prod_up = [26117644, 26117645, 26117646, 26117647, 26117648]
  139. uids_prod_play = [26117644, 26117645, 26117646, 26117647, 26117648]
  140. @classmethod
  141. def upload_and_publish(cls, log_type, env, job):
  142. """
  143. 上传视频到 oss
  144. :param log_type: 选择的 log
  145. :param env: 测试环境:dev,正式环境:prod
  146. # :param job: 上升榜:up,播放量:play
  147. :param job: 站内 UID
  148. """
  149. Common.logger(log_type).info("upload_and_publish starting...")
  150. today = time.strftime("%Y%m%d", time.localtime())
  151. # videos 目录下的所有视频文件夹
  152. files = os.listdir(cls.local_file_path)
  153. for fv in files:
  154. try:
  155. # 单个视频文件夹
  156. fi_d = os.path.join(cls.local_file_path, fv)
  157. # 确认为视频文件夹
  158. if os.path.isdir(fi_d):
  159. Common.logger(log_type).info('dir = {}'.format(fi_d))
  160. # 列出所有视频文件夹
  161. dir_files = os.listdir(fi_d)
  162. data = {'appType': '888888',
  163. 'crawlerSrcCode': 'KANDAOJIUSHIFUQI',
  164. 'viewStatus': '1',
  165. 'versionCode': '1'}
  166. now_timestamp = int(round(time.time() * 1000))
  167. data['crawlerTaskTimestamp'] = str(now_timestamp)
  168. if env == "dev" and job == "up":
  169. uid = str(random.choice(cls.uids_dev_up))
  170. elif env == "dev" and job == "play":
  171. uid = str(random.choice(cls.uids_dev_play))
  172. elif env == "prod" and job == "up":
  173. uid = str(random.choice(cls.uids_prod_up))
  174. elif env == "prod" and job == "play":
  175. uid = str(random.choice(cls.uids_prod_play))
  176. else:
  177. uid = str(random.choice(cls.uids_prod_play))
  178. data['loginUid'] = uid
  179. # 单个视频文件夹下的所有视频文件
  180. for fi in dir_files:
  181. # 视频文件夹下的所有文件路径
  182. fi_path = fi_d + '/' + fi
  183. Common.logger(log_type).info('dir fi_path = {}'.format(fi_path))
  184. # 读取 info.txt,赋值给 data
  185. if cls.info_file in fi:
  186. f = open(fi_path, "r", encoding="UTF-8")
  187. # 读取数据 数据准确性写入的时候保证 读取暂不处理
  188. for i in range(14):
  189. line = f.readline()
  190. line = line.replace('\n', '')
  191. if line is not None and len(line) != 0 and not line.isspace():
  192. # Common.logger(log_type).info("line = {}".format(line))
  193. if i == 0:
  194. data['crawlerSrcId'] = line
  195. elif i == 1:
  196. data['title'] = line
  197. elif i == 2:
  198. data['totalTime'] = line
  199. elif i == 8:
  200. data['crawlerSrcPublishTimestamp'] = line
  201. else:
  202. Common.logger(log_type).warning("{} line is None".format(fi_path))
  203. f.close()
  204. # remove info.txt
  205. cls.remove_local_file(log_type, fi_path)
  206. # 刷新数据
  207. dir_files = os.listdir(fi_d)
  208. for fi in dir_files:
  209. fi_path = fi_d + '/' + fi
  210. # Common.logger(log_type).info('dir fi_path = {}'.format(fi_path))
  211. # 上传oss
  212. if cls.video_file in fi:
  213. global oss_video_file
  214. if env == "dev":
  215. oss_video_file = cls.oss_file_path_video.format("dev", today, data['crawlerSrcId'])
  216. elif env == "prod":
  217. oss_video_file = cls.oss_file_path_video.format("prod", today, data['crawlerSrcId'])
  218. Common.logger(log_type).info("oss_video_file = {}".format(oss_video_file))
  219. cls.put_file(log_type, oss_video_file, fi_path)
  220. data['videoPath'] = oss_video_file
  221. Common.logger(log_type).info("videoPath = {}".format(oss_video_file))
  222. elif cls.image_file in fi:
  223. global oss_image_file
  224. if env == "dev":
  225. oss_image_file = cls.oss_file_path_image.format("env", today, data['crawlerSrcId'])
  226. elif env == "prod":
  227. oss_image_file = cls.oss_file_path_image.format("prod", today, data['crawlerSrcId'])
  228. Common.logger(log_type).info("oss_image_file = {}".format(oss_image_file))
  229. cls.put_file(log_type, oss_image_file, fi_path)
  230. data['coverImgPath'] = oss_image_file
  231. Common.logger(log_type).info("coverImgPath = {}".format(oss_image_file))
  232. # 全部remove
  233. cls.remove_local_file(log_type, fi_path)
  234. # 发布
  235. if env == "dev":
  236. video_id = cls.publish_video_dev(log_type, data)
  237. elif env == "prod":
  238. video_id = cls.publish_video_prod(log_type, data)
  239. else:
  240. video_id = cls.publish_video_dev(log_type, data)
  241. cls.remove_local_file_dir(log_type, fi_d)
  242. Common.logger(log_type).info('video_id:{}', video_id)
  243. return video_id
  244. else:
  245. Common.logger(log_type).error('file not a dir = {}'.format(fi_d))
  246. except Exception as e:
  247. # 删除视频文件夹
  248. shutil.rmtree("./videos/" + fv + "/")
  249. Common.logger(log_type).exception('upload_and_publish error', e)