crawler_gzh_fans.py 19 KB

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