recycle_daily_publish_articles.py 24 KB

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