xigua_publish.py 12 KB

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