recycle_daily_publish_articles.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import asyncio
  2. import json
  3. import time
  4. import datetime
  5. import urllib.parse
  6. import traceback
  7. from tqdm.asyncio import tqdm
  8. from applications.api import feishu_robot
  9. from applications.crawler.wechat import get_article_list_from_account
  10. from applications.crawler.wechat import get_article_detail
  11. from applications.pipeline import insert_article_into_recycle_pool
  12. from applications.utils import str_to_md5
  13. class Const:
  14. # 订阅号
  15. SUBSCRIBE_TYPE_SET = {0, 1}
  16. NEW_ACCOUNT_CRAWL_PERIOD = 60 * 60 * 24 * 30
  17. FORBIDDEN_GH_IDS = [
  18. "gh_4c058673c07e",
  19. "gh_de9f9ebc976b",
  20. "gh_7b4a5f86d68c",
  21. "gh_f902cea89e48",
  22. "gh_789a40fe7935",
  23. "gh_cd041ed721e6",
  24. "gh_62d7f423f382",
  25. "gh_043223059726",
  26. ]
  27. # 文章状态
  28. # 记录默认状态
  29. DEFAULT_STATUS = 0
  30. # 请求接口失败状态
  31. REQUEST_FAIL_STATUS = -1
  32. # 文章被删除状态
  33. DELETE_STATUS = -2
  34. # 未知原因无信息返回状态
  35. UNKNOWN_STATUS = -3
  36. # 文章违规状态
  37. ILLEGAL_STATUS = -4
  38. ARTICLE_ILLEGAL_CODE = 25012
  39. ARTICLE_DELETE_CODE = 25005
  40. ARTICLE_SUCCESS_CODE = 0
  41. ARTICLE_UNKNOWN_CODE = 10000
  42. STAT_PERIOD = 3 * 24 * 3600
  43. INIT_STATUS = 0
  44. PROCESSING_STATUS = 1
  45. SUCCESS_STATUS = 2
  46. FAILED_STATUS = 99
  47. class RecycleDailyPublishArticlesTask(Const):
  48. def __init__(self, pool, log_client, date_string):
  49. self.pool = pool
  50. self.log_client = log_client
  51. self.date_string = date_string
  52. async def get_publish_accounts(self):
  53. """
  54. get all publish accounts
  55. """
  56. query = f"""
  57. select distinct t3.name, t3.gh_id, t3.follower_count, t3.create_timestamp as account_init_timestamp,
  58. t4.service_type_info as account_type, t4.verify_type_info as account_auth, t3.id as account_id,
  59. group_concat(distinct t5.remark) as account_remark
  60. from
  61. publish_plan t1
  62. join publish_plan_account t2 on t1.id = t2.plan_id
  63. join publish_account t3 on t2.account_id = t3.id
  64. left join publish_account_wx_type t4 on t3.id = t4.account_id
  65. left join publish_account_remark t5 on t3.id = t5.publish_account_id
  66. where t1.plan_status = 1 and t1.content_modal = 3 and t3.channel = 5
  67. group by t3.id;
  68. """
  69. account_list = await self.pool.async_fetch(query, db_name="aigc")
  70. return [i for i in account_list if "自动回复" not in str(i["account_remark"])]
  71. async def get_account_status(self):
  72. """get account experiment status"""
  73. sql = f"""
  74. select t1.account_id, t2.status
  75. from wx_statistics_group_source_account t1
  76. join wx_statistics_group_source t2 on t1.group_source_name = t2.account_source_name;
  77. """
  78. account_status_list = await self.pool.async_fetch(sql, db_name="aigc")
  79. account_status_dict = {
  80. account["account_id"]: account["status"] for account in account_status_list
  81. }
  82. return account_status_dict
  83. async def recycle_single_account(self, account):
  84. """recycle single account"""
  85. query = f"""
  86. select max(publish_timestamp) as publish_timestamp from official_articles_v2 where ghId = %s;
  87. """
  88. response = await self.pool.async_fetch(
  89. query, params=(account["gh_id"],), db_name="piaoquan_crawler"
  90. )
  91. if response:
  92. max_publish_timestamp = response[0]["publish_timestamp"]
  93. else:
  94. max_publish_timestamp = int(time.time()) - self.NEW_ACCOUNT_CRAWL_PERIOD
  95. cursor = None
  96. while True:
  97. response = await get_article_list_from_account(
  98. account_id=account["gh_id"], index=cursor
  99. )
  100. response_code = response["code"]
  101. match response_code:
  102. case 25013:
  103. await feishu_robot.bot(
  104. title="发布账号封禁",
  105. detail={
  106. "账号名称": account["name"],
  107. "账号id": account["gh_id"],
  108. },
  109. )
  110. return
  111. case 0:
  112. msg_list = response.get("data", {}).get("data", [])
  113. if not msg_list:
  114. return
  115. await insert_article_into_recycle_pool(
  116. self.pool, self.log_client, msg_list, account
  117. )
  118. # check last article
  119. last_article = msg_list[-1]
  120. last_publish_timestamp = last_article["AppMsg"]["BaseInfo"][
  121. "UpdateTime"
  122. ]
  123. if last_publish_timestamp <= max_publish_timestamp:
  124. return
  125. cursor = response["data"].get("next_cursor")
  126. if not cursor:
  127. return
  128. case _:
  129. return
  130. async def get_task_list(self):
  131. """recycle all publish accounts articles"""
  132. binding_accounts = await self.get_publish_accounts()
  133. # 过滤封禁账号
  134. binding_accounts = [
  135. i for i in binding_accounts if i["gh_id"] not in self.FORBIDDEN_GH_IDS
  136. ]
  137. account_status = await self.get_account_status()
  138. account_list = [
  139. {
  140. **item,
  141. "using_status": (
  142. 0 if account_status.get(item["account_id"]) == "实验" else 1
  143. ),
  144. }
  145. for item in binding_accounts
  146. ]
  147. # 订阅号
  148. subscription_accounts = [
  149. i for i in account_list if i["account_type"] in self.SUBSCRIBE_TYPE_SET
  150. ]
  151. return subscription_accounts
  152. async def deal(self):
  153. subscription_accounts = await self.get_task_list()
  154. for account in tqdm(subscription_accounts, desc="recycle each account"):
  155. try:
  156. await self.recycle_single_account(account)
  157. except Exception as e:
  158. print(
  159. f"{account['name']}\t{account['gh_id']}: recycle account error:", e
  160. )
  161. class CheckDailyPublishArticlesTask(RecycleDailyPublishArticlesTask):
  162. async def check_account(self, account: dict, date_string: str) -> bool:
  163. """check account data"""
  164. query = f"""
  165. select accountName, count(1) as publish_count
  166. from official_articles_v2 where ghId = %s and from_unixtime(publish_timestamp) > %s;
  167. """
  168. response = await self.pool.async_fetch(
  169. query=query,
  170. db_name="piaoquan_crawler",
  171. params=(account["gh_id"], date_string),
  172. )
  173. if response:
  174. today_publish_count = response[0]["publish_count"]
  175. return today_publish_count > 0
  176. else:
  177. return False
  178. async def deal(self):
  179. task_list = await self.get_task_list()
  180. for task in tqdm(task_list, desc="check each account step1: "):
  181. if await self.check_account(task, self.date_string):
  182. continue
  183. else:
  184. await self.recycle_single_account(task)
  185. # check again
  186. fail_list = []
  187. for second_task in tqdm(task_list, desc="check each account step2: "):
  188. if await self.check_account(second_task, self.date_string):
  189. continue
  190. else:
  191. second_task.pop("account_type", None)
  192. second_task.pop("account_auth", None)
  193. second_task.pop("account_id", None)
  194. second_task.pop("account_remark", None)
  195. fail_list.append(second_task)
  196. if fail_list:
  197. now = datetime.datetime.now()
  198. if now.hour < 20:
  199. return
  200. columns = [
  201. feishu_robot.create_feishu_columns_sheet(
  202. sheet_type="plain_text",
  203. sheet_name="name",
  204. display_name="公众号名称",
  205. ),
  206. feishu_robot.create_feishu_columns_sheet(
  207. sheet_type="plain_text", sheet_name="gh_id", display_name="gh_id"
  208. ),
  209. feishu_robot.create_feishu_columns_sheet(
  210. sheet_type="number",
  211. sheet_name="follower_count",
  212. display_name="粉丝数",
  213. ),
  214. feishu_robot.create_feishu_columns_sheet(
  215. sheet_type="date",
  216. sheet_name="account_init_timestamp",
  217. display_name="账号接入系统时间",
  218. ),
  219. feishu_robot.create_feishu_columns_sheet(
  220. sheet_type="plain_text",
  221. sheet_name="using_status",
  222. display_name="利用状态",
  223. ),
  224. ]
  225. await feishu_robot.bot(
  226. title=f"{self.date_string} 发布文章,存在未更新的账号",
  227. detail={"columns": columns, "rows": fail_list},
  228. table=True,
  229. mention=False,
  230. )
  231. else:
  232. await feishu_robot.bot(
  233. title=f"{self.date_string} 发布文章,所有文章更新成功",
  234. detail={
  235. "date_string": self.date_string,
  236. "finish_time": datetime.datetime.now().__str__(),
  237. },
  238. mention=False,
  239. )
  240. class UpdateRootSourceIdAndUpdateTimeTask(Const):
  241. """
  242. update publish_timestamp && root_source_id
  243. """
  244. def __init__(self, pool, log_client):
  245. self.pool = pool
  246. self.log_client = log_client
  247. async def get_article_list(self):
  248. query = f"""select ContentUrl, wx_sn from official_articles_v2 where publish_timestamp in %s;"""
  249. article_list = await self.pool.async_fetch(
  250. query=query, db_name="piaoquan_crawler", params=(tuple([0, -1]),)
  251. )
  252. return article_list
  253. async def check_each_article(self, article: dict):
  254. url = article["ContentUrl"]
  255. wx_sn = article["wx_sn"].decode("utf-8")
  256. try:
  257. response = await get_article_detail(url)
  258. response_code = response["code"]
  259. if response_code == self.ARTICLE_DELETE_CODE:
  260. publish_timestamp_s = self.DELETE_STATUS
  261. root_source_id_list = []
  262. elif response_code == self.ARTICLE_ILLEGAL_CODE:
  263. publish_timestamp_s = self.ILLEGAL_STATUS
  264. root_source_id_list = []
  265. elif response_code == self.ARTICLE_SUCCESS_CODE:
  266. data = response["data"]["data"]
  267. publish_timestamp_ms = data["publish_timestamp"]
  268. publish_timestamp_s = int(publish_timestamp_ms / 1000)
  269. mini_program = data.get("mini_program", [])
  270. if mini_program:
  271. root_source_id_list = [
  272. urllib.parse.parse_qs(urllib.parse.unquote(i["path"]))[
  273. "rootSourceId"
  274. ][0]
  275. for i in mini_program
  276. ]
  277. else:
  278. root_source_id_list = []
  279. else:
  280. publish_timestamp_s = self.UNKNOWN_STATUS
  281. root_source_id_list = []
  282. except Exception as e:
  283. publish_timestamp_s = self.REQUEST_FAIL_STATUS
  284. root_source_id_list = None
  285. error_msg = traceback.format_exc()
  286. await self.log_client.log(
  287. contents={
  288. "task": "get_official_article_detail",
  289. "data": {
  290. "url": url,
  291. "wx_sn": wx_sn,
  292. "error_msg": error_msg,
  293. "error": str(e),
  294. },
  295. "function": "check_each_article",
  296. "status": "fail",
  297. }
  298. )
  299. query = f"""
  300. update official_articles_v2 set publish_timestamp = %s, root_source_id_list = %s
  301. where wx_sn = %s;
  302. """
  303. await self.pool.async_save(
  304. query=query,
  305. db_name="piaoquan_crawler",
  306. params=(
  307. publish_timestamp_s,
  308. json.dumps(root_source_id_list, ensure_ascii=False),
  309. wx_sn,
  310. ),
  311. )
  312. if publish_timestamp_s == self.REQUEST_FAIL_STATUS:
  313. return article
  314. else:
  315. return None
  316. async def fallback_mechanism(self):
  317. # 通过msgId 来修改publish_timestamp
  318. update_sql = f"""
  319. update official_articles_v2 oav
  320. join (
  321. select ghId, appMsgId, max(publish_timestamp) as publish_timestamp
  322. from official_articles_v2
  323. where publish_timestamp > %s
  324. group by ghId, appMsgId
  325. ) vv
  326. on oav.appMsgId = vv.appMsgId and oav.ghId = vv.ghId
  327. set oav.publish_timestamp = vv.publish_timestamp
  328. where oav.publish_timestamp <= %s;
  329. """
  330. affected_rows_1 = await self.pool.async_save(
  331. query=update_sql, params=(0, 0), db_name="piaoquan_crawler"
  332. )
  333. # 若还是无 publish_timestamp,用update_time当作 publish_timestamp
  334. update_sql_2 = f"""
  335. update official_articles_v2
  336. set publish_timestamp = updateTime
  337. where publish_timestamp < %s;
  338. """
  339. affected_rows_2 = await self.pool.async_save(query=update_sql_2, params=0)
  340. if affected_rows_1 or affected_rows_2:
  341. await feishu_robot.bot(
  342. title="执行兜底修改发布时间戳",
  343. detail={
  344. "通过msgId修改": affected_rows_1,
  345. "通过update_timestamp修改": affected_rows_2,
  346. },
  347. mention=False,
  348. )
  349. async def deal(self):
  350. task_list = await self.get_article_list()
  351. for task in tqdm(task_list, desc="get article detail step1: "):
  352. try:
  353. await self.check_each_article(task)
  354. except Exception as e:
  355. try:
  356. await self.log_client.log(
  357. contents={
  358. "task": "get_official_article_detail_step1",
  359. "data": {
  360. "detail": {
  361. "url": task["ContentUrl"],
  362. "wx_sn": task["wx_sn"].decode("utf-8"),
  363. },
  364. "error_msg": traceback.format_exc(),
  365. "error": str(e),
  366. },
  367. "function": "check_each_article",
  368. "status": "fail",
  369. }
  370. )
  371. except Exception as e:
  372. print(e)
  373. print(traceback.format_exc())
  374. # process_failed_task_reproduce
  375. fail_tasks = await self.get_article_list()
  376. fail_list = []
  377. for fail_task in tqdm(fail_tasks, desc="get article detail step2: "):
  378. try:
  379. res = await self.check_each_article(fail_task)
  380. if res:
  381. fail_list.append(res)
  382. except Exception as e:
  383. await self.log_client.log(
  384. contents={
  385. "task": "get_official_article_detail_step2",
  386. "data": {
  387. "detail": {
  388. "url": fail_task["ContentUrl"],
  389. "wx_sn": fail_task["wx_sn"].decode("utf-8"),
  390. },
  391. "error_msg": traceback.format_exc(),
  392. "error": str(e),
  393. },
  394. "function": "check_each_article",
  395. "status": "fail",
  396. }
  397. )
  398. if fail_list:
  399. await feishu_robot.bot(title="更新文章,获取detail失败", detail=fail_list)
  400. current_hour = datetime.datetime.now().hour
  401. if current_hour >= 21:
  402. await self.fallback_mechanism()
  403. class RecycleFwhDailyPublishArticlesTask(Const):
  404. def __init__(self, pool, log_client):
  405. self.pool = pool
  406. self.log_client = log_client
  407. @staticmethod
  408. async def illegal_article_bot(
  409. account_name: str,
  410. gh_id: str,
  411. group_id: str,
  412. illegal_msg: str,
  413. publish_date: str,
  414. ):
  415. await feishu_robot.bot(
  416. title="服务号文章违规告警,请前往微信公众平台处理",
  417. detail={
  418. "account_name": account_name,
  419. "gh_id": gh_id,
  420. "group_id": group_id,
  421. "illegal_msg": illegal_msg,
  422. "publish_date": str(publish_date),
  423. },
  424. env="server_account_publish_monitor",
  425. )
  426. async def save_data_to_database(self, article):
  427. """
  428. save data to db
  429. """
  430. insert_query = f"""
  431. insert into official_articles_v2
  432. (ghId, accountName, appMsgId, title, Type, createTime, updateTime, ItemIndex, ContentUrl, show_view_count,
  433. wx_sn, title_md5, article_group, channel_content_id, root_source_id_list, publish_timestamp)
  434. values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  435. """
  436. return await self.pool.async_save(
  437. query=insert_query, db_name="piaoquan_crawler", params=article
  438. )
  439. async def update_article_read_cnt(self, wx_sn, new_read_cnt):
  440. if new_read_cnt <= 0:
  441. return 0
  442. update_query = """
  443. update official_articles_v2
  444. set show_view_count = %s
  445. where wx_sn = %s;
  446. """
  447. return await self.pool.async_save(
  448. query=update_query, db_name="piaoquan_crawler", params=(new_read_cnt, wx_sn)
  449. )
  450. async def get_group_server_accounts(self):
  451. fetch_query = "select gzh_id from article_gzh_developer;"
  452. fetch_response = await self.pool.async_fetch(
  453. query=fetch_query, db_name="piaoquan_crawler"
  454. )
  455. gh_id_list = [i["gzh_id"] for i in fetch_response]
  456. return gh_id_list
  457. async def get_stat_published_articles(self, gh_id):
  458. earliest_timestamp = int(time.time()) - self.STAT_PERIOD
  459. fetch_query = """
  460. select publish_date, account_name, gh_id, user_group_id, url, publish_timestamp
  461. from long_articles_group_send_result
  462. where gh_id = %s and recycle_status = %s and create_time > %s;
  463. """
  464. earliest_time = datetime.datetime.fromtimestamp(earliest_timestamp).strftime(
  465. "%Y-%m-%d %H:%M:%S"
  466. )
  467. return await self.pool.async_fetch(
  468. query=fetch_query,
  469. params=(gh_id, self.SUCCESS_STATUS, earliest_time),
  470. )
  471. async def process_each_account_data(self, account_published_article_list):
  472. if not account_published_article_list:
  473. return
  474. for article in account_published_article_list:
  475. account_name = article["account_name"]
  476. gh_id = article["gh_id"]
  477. user_group_id = article["user_group_id"]
  478. url = article["url"]
  479. publish_date = article["publish_date"]
  480. # get article detail info with spider
  481. try:
  482. article_detail_info = await get_article_detail(
  483. url, is_count=True, is_cache=False
  484. )
  485. response_code = article_detail_info["code"]
  486. if response_code == self.ARTICLE_ILLEGAL_CODE:
  487. await self.illegal_article_bot(
  488. account_name=account_name,
  489. gh_id=gh_id,
  490. group_id=user_group_id,
  491. illegal_msg=article_detail_info["msg"],
  492. publish_date=publish_date,
  493. )
  494. await asyncio.sleep(1)
  495. content_url = article_detail_info["data"]["data"]["content_link"]
  496. app_msg_id = content_url.split("mid=")[-1].split("&")[0]
  497. wx_sn = content_url.split("sn=")[-1]
  498. publish_timestamp = int(
  499. article_detail_info["data"]["data"]["publish_timestamp"] / 1000
  500. )
  501. create_time = publish_timestamp
  502. update_time = publish_timestamp
  503. item_index = article_detail_info["data"]["data"]["item_index"]
  504. show_view_count = article_detail_info["data"]["data"]["view_count"]
  505. title = article_detail_info["data"]["data"]["title"]
  506. title_md5 = str_to_md5(title)
  507. channel_content_id = article_detail_info["data"]["data"][
  508. "channel_content_id"
  509. ]
  510. mini_program_info = article_detail_info["data"]["data"]["mini_program"]
  511. root_source_id_list = [
  512. urllib.parse.parse_qs(urllib.parse.unquote(i["path"]))[
  513. "rootSourceId"
  514. ][0]
  515. for i in mini_program_info
  516. ]
  517. root_source_id_list = json.dumps(root_source_id_list)
  518. try:
  519. await self.save_data_to_database(
  520. article=(
  521. gh_id,
  522. account_name,
  523. app_msg_id,
  524. title,
  525. "9",
  526. create_time,
  527. update_time,
  528. item_index,
  529. url,
  530. show_view_count,
  531. wx_sn,
  532. title_md5,
  533. user_group_id,
  534. channel_content_id,
  535. root_source_id_list,
  536. publish_timestamp,
  537. )
  538. )
  539. except Exception as e:
  540. await self.update_article_read_cnt(wx_sn, show_view_count)
  541. except Exception as e:
  542. print(f"article {url} is not available, skip it")
  543. print(e)
  544. async def deal(self):
  545. account_id_list = await self.get_group_server_accounts()
  546. for account_id in account_id_list:
  547. publish_articles = tqdm(
  548. await self.get_stat_published_articles(account_id),
  549. desc=f"<crawling> {account_id}",
  550. )
  551. await self.process_each_account_data(publish_articles)