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