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