recycle_daily_publish_articles.py 24 KB

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