crawler_gzh_fans.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import asyncio
  2. import json
  3. import time
  4. from datetime import datetime
  5. from applications.crawler.wechat import (
  6. get_gzh_fans,
  7. get_access_token,
  8. get_union_id_batch,
  9. )
  10. from applications.api import feishu_robot
  11. from applications.utils import run_tasks_with_asyncio_task_group
  12. class CrawlerGzhFansConst:
  13. INIT_STATUS = 0
  14. PROCESSING_STATUS = 1
  15. FINISHED_STATUS = 2
  16. FAILED_STATUS = 99
  17. AVAILABLE_STATUS = 1
  18. INVALID_STATUS = 0
  19. MAX_SIZE = 100
  20. MAX_CONCURRENCY = 5
  21. GAP_DURATION = 300
  22. class CrawlerGzhFansBase(CrawlerGzhFansConst):
  23. def __init__(self, pool, log_client):
  24. self.pool = pool
  25. self.log_client = log_client
  26. # 从数据库获取 access_token
  27. async def get_access_token_from_database(self, gh_id):
  28. query = """
  29. SELECT access_token, expire_timestamp FROM gzh_cookie_info where gh_id = %s;
  30. """
  31. return await self.pool.async_fetch(query=query, params=(gh_id, ))
  32. # 从数据库获取粉丝 && token
  33. async def get_cookie_token_from_database(self, gh_id):
  34. query = """
  35. SELECT token, cookie FROM gzh_cookie_info WHERE gh_id = %s and token_status = %s;
  36. """
  37. return await self.pool.async_fetch(
  38. query=query, params=(gh_id, self.AVAILABLE_STATUS)
  39. )
  40. # 设置access_token状态为无效
  41. async def set_access_token_as_invalid(self, gh_id):
  42. query = """
  43. UPDATE gzh_cookie_info SET access_token_status = %s WHERE gh_id = %s;
  44. """
  45. return await self.pool.async_save(
  46. query=query, params=(self.INVALID_STATUS, gh_id)
  47. )
  48. # 设置 cookie 状态为无效
  49. async def set_cookie_token_as_invalid(self, gh_id):
  50. query = """
  51. UPDATE gzh_cookie_info SET token_status = %s WHERE gh_id = %s;
  52. """
  53. return await self.pool.async_save(
  54. query=query, params=(self.INVALID_STATUS, gh_id)
  55. )
  56. # 修改抓取账号状态
  57. async def update_account_crawl_history_status(self, gh_id, status):
  58. query = """
  59. UPDATE gzh_account_info SET crawl_history_status = %s WHERE gh_id = %s;
  60. """
  61. return await self.pool.async_save(query=query, params=(status, gh_id))
  62. # 获取账号列表
  63. async def get_account_list_from_database(self):
  64. query = """
  65. SELECT gh_id, account_name, app_id, app_secret, cursor_openid, cursor_timestamp, crawl_history_status
  66. FROM gzh_account_info WHERE status = %s;
  67. """
  68. return await self.pool.async_fetch(query=query, params=(self.AVAILABLE_STATUS,))
  69. # 获取 open_id 列表
  70. async def get_open_id_list_from_database(self, gh_id):
  71. query = """
  72. SELECT user_openid as openid, 'zh_CN' as lang FROM gzh_fans_info
  73. WHERE status = %s and gh_id = %s LIMIT %s;
  74. """
  75. return await self.pool.async_fetch(
  76. query=query, params=(self.INIT_STATUS, gh_id, self.MAX_SIZE)
  77. )
  78. # 批量插入粉丝信息
  79. async def insert_gzh_fans_batch(self, account_info, user_list):
  80. for user in user_list:
  81. query = """
  82. INSERT IGNORE INTO gzh_fans_info
  83. (gh_id, account_name, user_openid, user_name, user_create_time, user_head_img, user_remark, identity_type, identity_open_id)
  84. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);
  85. """
  86. params = (
  87. account_info["gh_id"],
  88. account_info["account_name"],
  89. user["user_openid"],
  90. user["user_name"],
  91. user["user_create_time"],
  92. user["user_head_img"],
  93. user["user_remark"],
  94. user["identity_type"],
  95. user["identity_open_id"],
  96. )
  97. await self.pool.async_save(query=query, params=params)
  98. # 插入失败详情
  99. async def insert_fail_detail(self, gh_id, fail_info):
  100. query = """
  101. UPDATE gzh_account_info SET fail_detail = %s WHERE gh_id = %s;
  102. """
  103. return await self.pool.async_save(
  104. query=query, params=(gh_id, json.dumps(fail_info, ensure_ascii=False))
  105. )
  106. # 获取失败详情
  107. async def fetch_fail_index(self, gh_id):
  108. query = """
  109. SELECT fail_detail FROM gzh_account_info WHERE gh_id = %s;
  110. """
  111. return await self.pool.async_fetch(query=query, params=(gh_id,))
  112. # 更新抓取union_id任务的状态码
  113. async def update_task_status(self, gh_id, user_openid, ori_status, new_status):
  114. query = """
  115. UPDATE gzh_fans_info SET status = %s WHERE gh_id = %s and user_openid = %s and status = %s;
  116. """
  117. return await self.pool.async_save(
  118. query=query, params=(new_status, gh_id, user_openid, ori_status)
  119. )
  120. # 更新 union_id
  121. async def save_single_union_user(self, gh_id, user_info, semaphore):
  122. async with semaphore:
  123. openid = user_info.get("openid")
  124. if not openid:
  125. return 0
  126. try:
  127. locked = await self.update_task_status(
  128. gh_id=gh_id,
  129. user_openid=openid,
  130. ori_status=self.INIT_STATUS,
  131. new_status=self.PROCESSING_STATUS,
  132. )
  133. if not locked:
  134. return 0
  135. update_sql = """
  136. UPDATE gzh_fans_info
  137. SET union_id = %s, sex = %s, city = %s, province = %s, subscribe_scene = %s, status = %s
  138. WHERE
  139. gh_id = %s AND user_openid = %s AND status = %s;
  140. """
  141. affected_rows = await self.pool.async_save(
  142. query=update_sql,
  143. params=(
  144. user_info.get("unionid"),
  145. user_info.get("sex"),
  146. user_info.get("city"),
  147. user_info.get("province"),
  148. user_info.get("subscribe_scene"),
  149. self.FINISHED_STATUS,
  150. gh_id,
  151. openid,
  152. self.PROCESSING_STATUS,
  153. ),
  154. )
  155. return affected_rows or 0
  156. except Exception:
  157. # ❗防止任务卡死,可选:回滚状态
  158. try:
  159. await self.update_task_status(
  160. gh_id=gh_id,
  161. user_openid=openid,
  162. ori_status=self.PROCESSING_STATUS,
  163. new_status=self.INIT_STATUS,
  164. )
  165. except Exception:
  166. pass
  167. return 0
  168. # 更新公众号的 cursor 位置
  169. async def update_gzh_cursor_info(self, gh_id, cursor_id, cursor_timestamp):
  170. query = """
  171. UPDATE gzh_account_info SET cursor_openid = %s, cursor_timestamp = %s WHERE gh_id = %s;
  172. """
  173. return await self.pool.async_save(
  174. query=query, params=(cursor_id, cursor_timestamp, gh_id)
  175. )
  176. # 更新公众号的 cookie
  177. async def set_cookie_token_for_each_account(self, gh_id, cookie, token):
  178. query = """
  179. UPDATE gzh_cookie_info SET cookie = %s, token = %s, token_status = %s
  180. WHERE gh_id = %s;
  181. """
  182. return await self.pool.async_save(
  183. query=query, params=(cookie, token, self.AVAILABLE_STATUS, gh_id)
  184. )
  185. async def set_access_token_for_each_account(self, gh_id, access_token, expire_timestamp):
  186. query = """
  187. UPDATE gzh_cookie_info
  188. SET access_token = %s, access_token_status = %s, expire_timestamp = %s
  189. WHERE gh_id = %s;
  190. """
  191. return await self.pool.async_save(
  192. query=query,
  193. params=(access_token, self.AVAILABLE_STATUS, expire_timestamp, gh_id)
  194. )
  195. async def get_max_cursor_id(self, gh_id):
  196. query = """
  197. SELECT user_openid, user_create_time
  198. FROM gzh_fans_info WHERE gh_id = %s
  199. ORDER BY user_create_time DESC LIMIT 1;
  200. """
  201. return await self.pool.async_fetch(query=query, params=(gh_id,))
  202. class CrawlerGzhFans(CrawlerGzhFansBase):
  203. def __init__(self, pool, log_client):
  204. super().__init__(pool, log_client)
  205. # 抓取账号新增粉丝
  206. async def crawl_new_fans_for_each_account(self, account_info: dict):
  207. cookie_obj = await self.get_cookie_token_from_database(account_info["gh_id"])
  208. if not cookie_obj:
  209. return
  210. # 获取失败详情
  211. fetch_response = await self.fetch_fail_index(account_info["gh_id"])
  212. fail_detail = json.loads(fetch_response[0]["fail_detail"] or "{}")
  213. cursor_openid = fail_detail.get("cursor_openid") or ""
  214. cursor_timestamp = fail_detail.get("cursor_timestamp") or ""
  215. newest_timestamp = fail_detail.get("newest_timestamp") or None
  216. if not newest_timestamp:
  217. newest_fans = await self.get_max_cursor_id(account_info["gh_id"])
  218. newest_timestamp = newest_fans[0]["user_create_time"]
  219. while True:
  220. try:
  221. response = await get_gzh_fans(
  222. token=cookie_obj[0]["token"],
  223. cookie=cookie_obj[0]["cookie"],
  224. cursor_id=cursor_openid,
  225. cursor_timestamp=cursor_timestamp,
  226. )
  227. print(response)
  228. base_resp = response.get("base_resp", {})
  229. code = base_resp.get("ret")
  230. error_msg = base_resp.get("err_msg")
  231. match code:
  232. case 0:
  233. user_list = response.get("user_list", {}).get("user_info_list")
  234. next_cursor_id = user_list[-1].get("user_openid")
  235. next_cursor_timestamp = user_list[-1].get("user_create_time")
  236. await self.insert_gzh_fans_batch(account_info, user_list)
  237. if next_cursor_timestamp <= newest_timestamp:
  238. await feishu_robot.bot(
  239. title=f"{account_info['account_name']}本月新增粉丝抓取完毕",
  240. detail=account_info,
  241. env="cookie_monitor",
  242. mention=False,
  243. )
  244. break
  245. else:
  246. cursor_openid = next_cursor_id
  247. cursor_timestamp = next_cursor_timestamp
  248. print(datetime.fromtimestamp(cursor_timestamp).strftime("%Y-%m-%d %H:%M:%S"))
  249. case "00040":
  250. print(f"token 非法: {error_msg}")
  251. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  252. await feishu_robot.bot(
  253. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  254. detail=account_info,
  255. env="cookie_monitor",
  256. mention=False,
  257. )
  258. break
  259. case _:
  260. print("token 异常, 请及时刷新")
  261. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  262. await feishu_robot.bot(
  263. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  264. detail=account_info,
  265. env="cookie_monitor",
  266. mention=False,
  267. )
  268. break
  269. except Exception as e:
  270. fail_obj = {
  271. "cursor_openid": cursor_openid,
  272. "cursor_timestamp": cursor_timestamp,
  273. "newest_timestamp": newest_timestamp,
  274. "fail_reason": str(e),
  275. }
  276. await self.insert_fail_detail(account_info["gh_id"], fail_obj)
  277. await feishu_robot.bot(
  278. title=f"{account_info['account_name']}本月新增粉丝抓取异常,请查看",
  279. detail=fail_obj,
  280. env="cookie_monitor",
  281. mention=False,
  282. )
  283. break
  284. # 抓取单个账号存量的粉丝
  285. async def crawl_history_fans_for_each_account(self, account_info: dict):
  286. cookie_obj = await self.get_cookie_token_from_database(account_info["gh_id"])
  287. if not cookie_obj:
  288. return
  289. if not account_info.get("cursor_openid"):
  290. cursor_openid = ""
  291. else:
  292. cursor_openid = account_info["cursor_openid"]
  293. if not account_info.get("cursor_timestamp"):
  294. cursor_timestamp = ""
  295. else:
  296. cursor_timestamp = account_info["cursor_timestamp"]
  297. response = await get_gzh_fans(
  298. token=cookie_obj[0]["token"],
  299. cookie=cookie_obj[0]["cookie"],
  300. cursor_id=cursor_openid,
  301. cursor_timestamp=cursor_timestamp,
  302. )
  303. base_resp = response.get("base_resp", {})
  304. code = base_resp.get("ret")
  305. error_msg = base_resp.get("err_msg")
  306. match code:
  307. case 0:
  308. user_list = response.get("user_list", {}).get("user_info_list")
  309. if not user_list:
  310. await feishu_robot.bot(
  311. title=f"{account_info['account_name']}的粉丝已经抓取完毕,请检查",
  312. detail=account_info,
  313. env="cookie_monitor",
  314. mention=False,
  315. )
  316. await self.update_account_crawl_history_status(account_info["gh_id"], self.INVALID_STATUS)
  317. next_cursor_id = user_list[-1].get("user_openid")
  318. next_cursor_timestamp = user_list[-1].get("user_create_time")
  319. await self.insert_gzh_fans_batch(account_info, user_list)
  320. await self.update_gzh_cursor_info(
  321. account_info["gh_id"], next_cursor_id, next_cursor_timestamp
  322. )
  323. case "00040":
  324. print(f"token 非法: {error_msg}")
  325. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  326. await feishu_robot.bot(
  327. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  328. detail=account_info,
  329. env="cookie_monitor",
  330. mention=False,
  331. )
  332. case _:
  333. print("token 异常, 请及时刷新")
  334. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  335. await feishu_robot.bot(
  336. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  337. detail=account_info,
  338. env="cookie_monitor",
  339. mention=False,
  340. )
  341. # 通过 access_token && open_id 抓取 union_id
  342. async def get_union_ids_for_each_account(self, account_info: dict):
  343. # 通过 access_token 获取 union_id
  344. user_list = await self.get_open_id_list_from_database(
  345. gh_id=account_info["gh_id"]
  346. )
  347. if not user_list:
  348. return
  349. access_token_info = await self.get_access_token_from_database(
  350. account_info["gh_id"]
  351. )
  352. if not access_token_info:
  353. return
  354. # 更新 token
  355. async def update_token(_new_token_info):
  356. _access_token = _new_token_info["access_token"]
  357. _expires_in = _new_token_info["expires_in"]
  358. await self.set_access_token_for_each_account(
  359. gh_id=account_info["gh_id"],
  360. access_token=_access_token,
  361. expire_timestamp=_expires_in + int(time.time()) - self.GAP_DURATION,
  362. )
  363. print(f"{account_info['account_name']} access_token updated to database")
  364. expire_timestamp = access_token_info[0]["expire_timestamp"] or 0
  365. if int(time.time()) >= expire_timestamp:
  366. new_token_info = await get_access_token(
  367. account_info["app_id"], account_info["app_secret"]
  368. )
  369. access_token = new_token_info["access_token"]
  370. await update_token(_new_token_info=new_token_info)
  371. else:
  372. access_token = access_token_info[0]["access_token"]
  373. union_info = await get_union_id_batch(
  374. access_token=access_token, user_list=user_list
  375. )
  376. if union_info.get("errcode"):
  377. await self.set_access_token_as_invalid(gh_id=account_info["gh_id"])
  378. return
  379. # 将查询到的 union_id存储到数据库中
  380. user_info_list = union_info.get("user_info_list") or []
  381. if not user_info_list:
  382. return
  383. semaphore = asyncio.Semaphore(10)
  384. tasks = [
  385. self.save_single_union_user(account_info["gh_id"], user_info, semaphore)
  386. for user_info in user_info_list
  387. ]
  388. await asyncio.gather(*tasks, return_exceptions=True)
  389. # main function
  390. async def deal(self, task_name):
  391. account_list = await self.get_account_list_from_database()
  392. match task_name:
  393. case "get_history_fans":
  394. crawl_history_accounts = [i for i in account_list if i['crawl_history_status'] == self.AVAILABLE_STATUS]
  395. return await run_tasks_with_asyncio_task_group(
  396. task_list=crawl_history_accounts,
  397. handler=self.crawl_history_fans_for_each_account,
  398. max_concurrency=self.MAX_CONCURRENCY,
  399. fail_fast=False,
  400. description="抓取公众号账号粉丝",
  401. unit="page",
  402. )
  403. case "get_union_ids":
  404. return await run_tasks_with_asyncio_task_group(
  405. task_list=account_list,
  406. handler=self.get_union_ids_for_each_account,
  407. max_concurrency=self.MAX_CONCURRENCY,
  408. fail_fast=False,
  409. description="获取粉丝 union_id",
  410. unit="per100",
  411. )
  412. case "get_new_fans":
  413. for account in account_list:
  414. print(f"处理: {account['account_name']}")
  415. await self.crawl_new_fans_for_each_account(account)
  416. # return await run_tasks_with_asyncio_task_group()
  417. return {}
  418. case _:
  419. return {"err_msg": "invalid task_name"}