crawler_gzh_fans.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import asyncio
  2. from applications.crawler.wechat import (
  3. get_gzh_fans,
  4. get_access_token,
  5. get_union_id_batch,
  6. )
  7. from applications.api import feishu_robot
  8. from applications.utils import run_tasks_with_asyncio_task_group
  9. class CrawlerGzhFansConst:
  10. INIT_STATUS = 0
  11. PROCESSING_STATUS = 1
  12. FINISHED_STATUS = 2
  13. FAILED_STATUS = 99
  14. AVAILABLE_STATUS = 1
  15. INVALID_STATUS = 0
  16. MAX_SIZE = 100
  17. MAX_CONCURRENCY = 5
  18. class CrawlerGzhFansBase(CrawlerGzhFansConst):
  19. def __init__(self, pool, log_client):
  20. self.pool = pool
  21. self.log_client = log_client
  22. # 从数据库获取 access_token
  23. async def get_access_token_from_database(self, gh_id):
  24. query = """
  25. SELECT access_token FROM gzh_cookie_info where gh_id = %s and access_token_status = %s;
  26. """
  27. return await self.pool.async_fetch(
  28. query=query, params=(gh_id, self.AVAILABLE_STATUS)
  29. )
  30. # 从数据库获取粉丝 && token
  31. async def get_cookie_token_from_database(self, gh_id):
  32. query = """
  33. SELECT token, cookie FROM gzh_cookie_info WHERE gh_id = %s and token_status = %s;
  34. """
  35. return await self.pool.async_fetch(
  36. query=query, params=(gh_id, self.AVAILABLE_STATUS)
  37. )
  38. # 设置access_token状态为无效
  39. async def set_access_token_as_invalid(self, gh_id):
  40. query = """
  41. UPDATE gzh_cookie_info SET access_token_status = %s WHERE gh_id = %s;
  42. """
  43. return await self.pool.async_save(
  44. query=query, params=(self.INVALID_STATUS, gh_id)
  45. )
  46. # 设置 cookie 状态为无效
  47. async def set_cookie_token_as_invalid(self, gh_id):
  48. query = """
  49. UPDATE gzh_cookie_info SET token_status = %s WHERE gh_id = %s;
  50. """
  51. return await self.pool.async_save(
  52. query=query, params=(self.INVALID_STATUS, gh_id)
  53. )
  54. # 获取账号列表
  55. async def get_account_list_from_database(self):
  56. query = """
  57. SELECT gh_id, account_name, app_id, app_secret, cursor_openid, cursor_timestamp
  58. FROM gzh_account_info WHERE status = %s and gh_id != 'gh_77f36c109fb1';
  59. """
  60. return await self.pool.async_fetch(query=query, params=(self.AVAILABLE_STATUS,))
  61. # 获取 open_id 列表
  62. async def get_open_id_list_from_database(self, gh_id):
  63. query = """
  64. SELECT user_openid as openid, 'zh_CN' as lang FROM gzh_fans_info
  65. WHERE status = %s and gh_id = %s LIMIT %s;
  66. """
  67. return await self.pool.async_fetch(
  68. query=query, params=(self.INIT_STATUS, gh_id, self.MAX_SIZE)
  69. )
  70. # 批量插入粉丝信息
  71. async def insert_gzh_fans_batch(self, account_info, user_list):
  72. for user in user_list:
  73. query = """
  74. INSERT IGNORE INTO gzh_fans_info
  75. (gh_id, account_name, user_openid, user_name, user_create_time, user_head_img, user_remark, identity_type, identity_open_id)
  76. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);
  77. """
  78. params = (
  79. account_info["gh_id"],
  80. account_info["account_name"],
  81. user["user_openid"],
  82. user["user_name"],
  83. user["user_create_time"],
  84. user["user_head_img"],
  85. user["user_remark"],
  86. user["identity_type"],
  87. user["identity_open_id"],
  88. )
  89. await self.pool.async_save(query=query, params=params)
  90. # 更新抓取union_id任务的状态码
  91. async def update_task_status(self, gh_id, user_openid, ori_status, new_status):
  92. query = """
  93. UPDATE gzh_fans_info SET status = %s WHERE gh_id = %s and user_openid = %s and status = %s;
  94. """
  95. return await self.pool.async_save(
  96. query=query, params=(new_status, gh_id, user_openid, ori_status)
  97. )
  98. # 更新 union_id
  99. async def save_single_union_user(self, gh_id, user_info, semaphore):
  100. async with semaphore:
  101. openid = user_info.get("openid")
  102. if not openid:
  103. return 0
  104. try:
  105. locked = await self.update_task_status(
  106. gh_id=gh_id,
  107. user_openid=openid,
  108. ori_status=self.INIT_STATUS,
  109. new_status=self.PROCESSING_STATUS,
  110. )
  111. if not locked:
  112. return 0
  113. update_sql = """
  114. UPDATE gzh_fans_info
  115. SET union_id = %s, sex = %s, city = %s, province = %s, subscribe_scene = %s, status = %s
  116. WHERE
  117. gh_id = %s AND user_openid = %s AND status = %s;
  118. """
  119. affected_rows = await self.pool.async_save(
  120. query=update_sql,
  121. params=(
  122. user_info.get("unionid"),
  123. user_info.get("sex"),
  124. user_info.get("city"),
  125. user_info.get("province"),
  126. user_info.get("subscribe_scene"),
  127. self.FINISHED_STATUS,
  128. gh_id,
  129. openid,
  130. self.PROCESSING_STATUS,
  131. ),
  132. )
  133. return affected_rows or 0
  134. except Exception:
  135. # ❗防止任务卡死,可选:回滚状态
  136. try:
  137. await self.update_task_status(
  138. gh_id=gh_id,
  139. user_openid=openid,
  140. ori_status=self.PROCESSING_STATUS,
  141. new_status=self.INIT_STATUS,
  142. )
  143. except Exception:
  144. pass
  145. return 0
  146. # 更新公众号的 cursor 位置
  147. async def update_gzh_cursor_info(self, gh_id, cursor_id, cursor_timestamp):
  148. query = """
  149. UPDATE gzh_account_info SET cursor_openid = %s, cursor_timestamp = %s WHERE gh_id = %s;
  150. """
  151. return await self.pool.async_save(
  152. query=query, params=(cursor_id, cursor_timestamp, gh_id)
  153. )
  154. # 更新公众号的 cookie
  155. async def set_cookie_token_for_each_account(self, gh_id, cookie, token):
  156. query = """
  157. UPDATE gzh_cookie_info SET cookie = %s, token = %s, token_status = %s
  158. WHERE gh_id = %s;
  159. """
  160. return await self.pool.async_save(
  161. query=query, params=(cookie, token, self.AVAILABLE_STATUS, gh_id)
  162. )
  163. async def set_access_token_for_each_account(self, gh_id, access_token):
  164. query = """
  165. UPDATE gzh_cookie_info SET access_token = %s, access_token_status = %s WHERE gh_id = %s;
  166. """
  167. return await self.pool.async_save(
  168. query=query, params=(access_token, self.AVAILABLE_STATUS, gh_id)
  169. )
  170. class CrawlerGzhFans(CrawlerGzhFansBase):
  171. def __init__(self, pool, log_client):
  172. super().__init__(pool, log_client)
  173. # 抓取单个账号存量的粉丝
  174. async def crawl_history_fans_for_each_account(self, account_info):
  175. cookie_obj = await self.get_cookie_token_from_database(account_info["gh_id"])
  176. if not cookie_obj:
  177. return
  178. if not account_info.get("cursor_openid"):
  179. cursor_openid = ""
  180. else:
  181. cursor_openid = account_info["cursor_openid"]
  182. if not account_info.get("cursor_timestamp"):
  183. cursor_timestamp = ""
  184. else:
  185. cursor_timestamp = account_info["cursor_timestamp"]
  186. response = await get_gzh_fans(
  187. token=cookie_obj[0]["token"],
  188. cookie=cookie_obj[0]["cookie"],
  189. cursor_id=cursor_openid,
  190. cursor_timestamp=cursor_timestamp,
  191. )
  192. base_resp = response.get("base_resp", {})
  193. code = base_resp.get("ret")
  194. error_msg = base_resp.get("err_msg")
  195. match code:
  196. case 0:
  197. user_list = response.get("user_list", {}).get("user_info_list")
  198. if not user_list:
  199. await feishu_robot.bot(
  200. title=f"{account_info['account_name']}的粉丝已经抓取完毕,请检查",
  201. detail=account_info,
  202. env="cookie_monitor_bot",
  203. mention=False,
  204. )
  205. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  206. next_cursor_id = user_list[-1].get("user_openid")
  207. next_cursor_timestamp = user_list[-1].get("user_create_time")
  208. await self.insert_gzh_fans_batch(account_info, user_list)
  209. await self.update_gzh_cursor_info(
  210. account_info["gh_id"], next_cursor_id, next_cursor_timestamp
  211. )
  212. case "00040":
  213. print(f"token 非法: {error_msg}")
  214. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  215. await feishu_robot.bot(
  216. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  217. detail=account_info,
  218. env="cookie_monitor_bot",
  219. mention=False,
  220. )
  221. case _:
  222. print("token 异常, 请及时刷新")
  223. await self.set_cookie_token_as_invalid(account_info["gh_id"])
  224. await feishu_robot.bot(
  225. title=f"{account_info['account_name']}的 token && cookie 失效,请及时更新",
  226. detail=account_info,
  227. env="cookie_monitor",
  228. mention=False,
  229. )
  230. # 通过 access_token && open_id 抓取 union_id
  231. async def get_union_ids_for_each_account(self, account_info: dict):
  232. access_token_info = await self.get_access_token_from_database(
  233. account_info["gh_id"]
  234. )
  235. if not access_token_info:
  236. print(f"{account_info['account_name']}: access_token is not available")
  237. response = await get_access_token(
  238. account_info["app_id"], account_info["app_secret"]
  239. )
  240. access_token = response.get("access_token")
  241. await self.set_access_token_for_each_account(
  242. account_info["gh_id"], access_token
  243. )
  244. return
  245. # 通过 access_token 获取 union_id
  246. user_list = await self.get_open_id_list_from_database(
  247. gh_id=account_info["gh_id"]
  248. )
  249. access_token = access_token_info[0]["access_token"]
  250. union_info = await get_union_id_batch(
  251. access_token=access_token, user_list=user_list
  252. )
  253. if union_info.get("errcode"):
  254. await self.set_access_token_as_invalid(gh_id=account_info["gh_id"])
  255. return
  256. # 将查询到的 union_id存储到数据库中
  257. user_info_list = union_info.get("user_info_list") or []
  258. if not user_info_list:
  259. return
  260. semaphore = asyncio.Semaphore(10)
  261. tasks = [
  262. self.save_single_union_user(account_info["gh_id"], user_info, semaphore)
  263. for user_info in user_info_list
  264. ]
  265. await asyncio.gather(*tasks, return_exceptions=True)
  266. # main function
  267. async def deal(self, task_name):
  268. account_list = await self.get_account_list_from_database()
  269. match task_name:
  270. case "get_fans":
  271. return await run_tasks_with_asyncio_task_group(
  272. task_list=account_list,
  273. handler=self.crawl_history_fans_for_each_account,
  274. max_concurrency=self.MAX_CONCURRENCY,
  275. fail_fast=False,
  276. description="抓取公众号账号粉丝",
  277. unit="page",
  278. )
  279. case "get_union_ids":
  280. return await run_tasks_with_asyncio_task_group(
  281. task_list=account_list,
  282. handler=self.get_union_ids_for_each_account,
  283. max_concurrency=self.MAX_CONCURRENCY,
  284. fail_fast=False,
  285. description="获取粉丝 union_id",
  286. unit="per100",
  287. )
  288. case _:
  289. return {"err_msg": "invalid task_name"}