recycle_daily_publish_articles.py 24 KB

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