history_task.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. """
  2. @author: luojunhui
  3. """
  4. import json
  5. import time
  6. import asyncio
  7. from applications.config import Config
  8. from applications.log import logging
  9. from applications.functions.pqFunctions import publish_to_pq, get_pq_video_detail
  10. from applications.functions.common import shuffle_list
  11. class historyContentIdTask(object):
  12. """
  13. 处理已经匹配过小程序的文章
  14. """
  15. TASK_PROCESSING_STATUS = 101
  16. EXIT_STATUS = 97
  17. TASK_INIT_STATUS = 0
  18. TASK_PUBLISHED_STATUS = 4
  19. def __init__(self, mysql_client):
  20. """
  21. :param mysql_client:
  22. """
  23. self.mysql_client = mysql_client
  24. self.config = Config()
  25. self.article_match_video_table = self.config.article_match_video_table
  26. self.article_text_table = self.config.article_text_table
  27. self.article_crawler_video_table = self.config.article_crawler_video_table
  28. self.gh_id_dict = json.loads(self.config.get_config_value("testAccountLevel2"))
  29. self.history_coroutines = self.config.get_config_value("historyArticleCoroutines")
  30. async def get_tasks(self):
  31. """
  32. 获取任务
  33. :return:
  34. """
  35. select_sql1 = f"""
  36. SELECT
  37. ART.trace_id,
  38. ART.content_id,
  39. ART.flow_pool_level,
  40. ART.gh_id,
  41. ART.process_times
  42. FROM {self.article_match_video_table} ART
  43. JOIN (
  44. select content_id, count(1) as cnt
  45. from {self.article_crawler_video_table}
  46. where download_status = 2
  47. group by content_id
  48. ) VID on ART.content_id = VID.content_id and VID.cnt >= 3
  49. WHERE ART.content_status = 0 and ART.process_times <= 3
  50. ORDER BY request_timestamp
  51. LIMIT {self.history_coroutines};
  52. """
  53. tasks = await self.mysql_client.async_select(sql=select_sql1)
  54. task_obj_list = [
  55. {
  56. "trace_id": item[0],
  57. "content_id": item[1],
  58. "flow_pool_level": item[2],
  59. "gh_id": item[3],
  60. "process_times": item[4]
  61. } for item in tasks
  62. ]
  63. logging(
  64. code="9001",
  65. info="本次任务获取到 {} 条视频".format(len(task_obj_list)),
  66. data=task_obj_list
  67. )
  68. return task_obj_list
  69. async def get_video_list(self, content_id):
  70. """
  71. content_id
  72. :return:
  73. """
  74. sql = f"""
  75. SELECT platform, play_count, like_count, video_oss_path, cover_oss_path, user_id
  76. FROM {self.article_crawler_video_table}
  77. WHERE content_id = '{content_id}' and download_status = 2
  78. ORDER BY score DESC;
  79. """
  80. res_tuple = await self.mysql_client.async_select(sql)
  81. if len(res_tuple) >= 3:
  82. return [
  83. {
  84. "platform": i[0],
  85. "play_count": i[1],
  86. "like_count": i[2],
  87. "video_oss_path": i[3],
  88. "cover_oss_path": i[4],
  89. "uid": i[5]
  90. }
  91. for i in res_tuple
  92. ]
  93. else:
  94. return []
  95. async def get_kimi_title(self, content_id):
  96. """
  97. 获取 kimiTitle
  98. :param content_id:
  99. :return:
  100. """
  101. select_sql = f"""
  102. select kimi_title from {self.article_text_table} where content_id = '{content_id}';
  103. """
  104. res_tuple = await self.mysql_client.async_select(select_sql)
  105. if res_tuple:
  106. return res_tuple[0][0]
  107. else:
  108. return False
  109. async def update_content_status(self, new_content_status, trace_id, ori_content_status):
  110. """
  111. :param new_content_status:
  112. :param trace_id:
  113. :param ori_content_status:
  114. :return:
  115. """
  116. update_sql = f"""
  117. UPDATE {self.article_match_video_table}
  118. SET content_status = %s, content_status_update_time = %s
  119. WHERE trace_id = %s and content_status = %s;
  120. """
  121. row_counts = await self.mysql_client.async_insert(
  122. sql=update_sql,
  123. params=(
  124. new_content_status,
  125. int(time.time()),
  126. trace_id,
  127. ori_content_status
  128. )
  129. )
  130. return row_counts
  131. async def publish_videos_to_pq(self, trace_id, flow_pool_level, kimi_title, gh_id, download_videos, process_times):
  132. """
  133. 发布至 pq
  134. :param process_times:
  135. :param trace_id:
  136. :param download_videos: 已下载的视频---> list [{}, {}, {}.... ]
  137. :param gh_id: 公众号 id ---> str
  138. :param kimi_title: kimi 标题 ---> str
  139. :param flow_pool_level: 流量池层级 ---> str
  140. :return:
  141. """
  142. match flow_pool_level:
  143. case "autoArticlePoolLevel4":
  144. # 冷启层, 全量做
  145. video_list = shuffle_list(download_videos)[:3]
  146. case "autoArticlePoolLevel3":
  147. # 次条,只针对具体账号做
  148. if self.gh_id_dict.get(gh_id):
  149. video_list = shuffle_list(download_videos)[:3]
  150. else:
  151. video_list = download_videos[:3]
  152. case "autoArticlePoolLevel2":
  153. video_list = []
  154. case "autoArticlePoolLevel1":
  155. # 头条,先不做
  156. video_list = download_videos[:3]
  157. case _:
  158. print("未传流量池信息")
  159. video_list = download_videos[:3]
  160. L = []
  161. for video_obj in video_list:
  162. params = {
  163. "videoPath": video_obj['video_oss_path'],
  164. "uid": video_obj['uid'],
  165. "title": kimi_title
  166. }
  167. publish_response = await publish_to_pq(params)
  168. video_id = publish_response['data']['id']
  169. response = await get_pq_video_detail(video_id)
  170. # time.sleep(2)
  171. obj = {
  172. "uid": video_obj['uid'],
  173. "source": video_obj['platform'],
  174. "kimiTitle": kimi_title,
  175. "videoId": response['data'][0]['id'],
  176. "videoCover": response['data'][0]['shareImgPath'],
  177. "videoPath": response['data'][0]['videoPath'],
  178. "videoOss": video_obj['video_oss_path']
  179. }
  180. L.append(obj)
  181. update_sql = f"""
  182. UPDATE {self.article_match_video_table}
  183. SET content_status = %s, response = %s, process_times = %s
  184. WHERE trace_id = %s and content_status = %s;
  185. """
  186. await self.mysql_client.async_insert(
  187. sql=update_sql,
  188. params=(
  189. self.TASK_PUBLISHED_STATUS,
  190. json.dumps(L, ensure_ascii=False),
  191. process_times + 1,
  192. trace_id,
  193. self.TASK_PROCESSING_STATUS
  194. )
  195. )
  196. logging(
  197. code="9002",
  198. info="已经从历史文章更新",
  199. trace_id=trace_id
  200. )
  201. async def roll_back_content_status_when_fails(self, process_times, trace_id):
  202. """
  203. 处理失败,回滚至初始状态,处理次数加 1
  204. :param process_times:
  205. :param trace_id:
  206. :return:
  207. """
  208. update_article_sql = f"""
  209. UPDATE {self.article_match_video_table}
  210. SET
  211. content_status = %s,
  212. content_status_update_time = %s,
  213. process_times = %s
  214. WHERE trace_id = %s and content_status = %s;
  215. """
  216. await self.mysql_client.async_insert(
  217. sql=update_article_sql,
  218. params=(
  219. self.TASK_INIT_STATUS,
  220. int(time.time()),
  221. process_times + 1,
  222. trace_id,
  223. self.TASK_PROCESSING_STATUS
  224. )
  225. )
  226. async def check_title_whether_exit(self, content_id):
  227. """
  228. 校验文章是标题是否晋升 or 退场
  229. :return:
  230. """
  231. sql = f"""
  232. SELECT lat.article_title, cstp.status
  233. FROM long_articles_text lat
  234. JOIN cold_start_title_pool cstp ON lat.article_title = cstp.title
  235. WHERE lat.content_id = '{content_id}';
  236. """
  237. result = await self.mysql_client.async_select(sql)
  238. if result:
  239. return True
  240. else:
  241. return False
  242. async def process_task(self, params):
  243. """
  244. 异步执行
  245. :param params:
  246. :return:
  247. """
  248. content_id = params['content_id']
  249. trace_id = params['trace_id']
  250. flow_pool_level = params['flow_pool_level']
  251. if flow_pool_level == "autoArticlePoolLevel4":
  252. exit_status = await self.check_title_whether_exit(content_id)
  253. if exit_status:
  254. # 修改状态为执行状态
  255. affected_rows = await self.update_content_status(
  256. trace_id=trace_id,
  257. new_content_status=self.EXIT_STATUS,
  258. ori_content_status=self.TASK_INIT_STATUS
  259. )
  260. if affected_rows == 0:
  261. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  262. return
  263. gh_id = params['gh_id']
  264. process_times = params['process_times']
  265. download_videos = await self.get_video_list(content_id=content_id)
  266. # time.sleep(3)
  267. if download_videos:
  268. # 修改状态为执行状态,获取该任务的锁
  269. affected_rows = await self.update_content_status(
  270. trace_id=trace_id,
  271. new_content_status=self.TASK_PROCESSING_STATUS,
  272. ori_content_status=self.TASK_INIT_STATUS
  273. )
  274. if affected_rows == 0:
  275. print("修改行数为 0,多个进程抢占同一个 task, 抢占失败,进程退出")
  276. return
  277. try:
  278. kimi_title = await self.get_kimi_title(content_id)
  279. await self.publish_videos_to_pq(
  280. flow_pool_level=flow_pool_level,
  281. kimi_title=kimi_title,
  282. gh_id=gh_id,
  283. trace_id=trace_id,
  284. download_videos=download_videos,
  285. process_times=process_times
  286. )
  287. except Exception as e:
  288. logging(
  289. code="5003",
  290. info="history task 在发布的时候出现异常, error = {}".format(e),
  291. trace_id=trace_id
  292. )
  293. await self.roll_back_content_status_when_fails(
  294. trace_id=trace_id,
  295. process_times=process_times
  296. )
  297. else:
  298. return
  299. async def deal(self):
  300. """
  301. 处理
  302. :return:
  303. """
  304. task_list = await self.get_tasks()
  305. logging(
  306. code="5002",
  307. info="History content_task Task Got {} this time".format(len(task_list)),
  308. function="History Contents Task"
  309. )
  310. if task_list:
  311. a = time.time()
  312. tasks = [self.process_task(params) for params in task_list]
  313. await asyncio.gather(*tasks)
  314. b = time.time()
  315. print("{} s 内处理了{}个任务".format(b - a, len(task_list)))
  316. else:
  317. print("暂时未获得历史已存在文章")