recycle_daily_publish_articles.py 23 KB

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