recycle_daily_publish_articles.py 25 KB

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