""" 本地 Web 控制面板 FastAPI 应用:提供操作界面 + 编排浏览器自动化流程 """ import threading import time import requests from pathlib import Path from fastapi import FastAPI, HTTPException, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from loguru import logger from ..config import client_settings from .. import outbox from ..server_api import ServerAPI from ..ai import AIClient from ..fingerprint import get_machine_summary from ..browser.manager import BrowserManager from ..browser.resume_scraper import ResumeScraper from ..browser.applicant import Applicant WEB_DIR = Path(__file__).parent app = FastAPI(title="Boss直聘投递控制面板") app.mount("/static", StaticFiles(directory=WEB_DIR / "static"), name="static") templates = Jinja2Templates(directory=str(WEB_DIR / "templates")) # ======================================================= # 全局共享状态(整个客户端生命周期复用) # ======================================================= class AppState: def __init__(self): self.server_api = ServerAPI() self.browser = BrowserManager() self.ai = AIClient() self.applicant: Applicant | None = None self.connected = False # 是否已注册/登录云端 self.login_polling = False self._control_started = False self._boss_login = "unknown" # Boss 登录状态缓存(控制线程周期刷新) def ensure_applicant(self) -> Applicant: if self.applicant is None: self.applicant = Applicant(self.browser, self.server_api, self.ai) return self.applicant # ------------------------------------------------------------------ # 控制线程:登录成功后启动,5s 一轮 = 心跳带全量状态 + outbox 补发 + 远程任务轮询 # ------------------------------------------------------------------ def ensure_control(self) -> None: if self._control_started or not self.server_api.token: return self._control_started = True threading.Thread(target=self._control_loop, daemon=True).start() logger.info("控制线程已启动(状态上报/outbox 补发/远程任务轮询,间隔 5s)") def _control_loop(self) -> None: rounds = 0 while True: if not self.server_api.token: # 已退出登录,停止控制线程 self._control_started = False logger.info("已退出登录,控制线程停止") break try: self.server_api.heartbeat(self._collect_status(rounds)) except Exception as e: logger.debug(f"状态上报失败:{e}") try: outbox.flush(self.server_api) except Exception as e: logger.debug(f"outbox 补发轮异常:{e}") try: self._poll_remote_task() except Exception as e: logger.debug(f"远程任务轮询异常:{e}") rounds += 1 time.sleep(5) def _collect_status(self, rounds: int) -> dict: """采集 RPA 全量状态,随心跳上报(每用户单设备,服务端一行快照)""" # 每 6 轮(约 30s)活体刷新 Boss 登录状态,其余轮次用缓存 if rounds % 6 == 0: try: if self.browser.is_browser_running(): new = "logged_in" if self.browser.check_boss_login() else "not_login" else: new = "not_login" if new != self._boss_login: self._boss_login = new # 与云端 User.login_status 保持一致 try: if new == "logged_in": self.server_api.update_login_status("logged_in", self.browser.get_boss_account_name()) else: self.server_api.update_login_status("not_login") except Exception: pass except Exception as e: logger.debug(f"Boss 登录状态刷新失败:{e}") applying = bool(self.applicant and self.applicant.is_running) stats = self.applicant.stats if self.applicant else {} return { "boss_login": self._boss_login, "browser": "running" if self.browser.is_browser_running() else "stopped", "apply_status": "running" if applying else "idle", "current": (stats.get("current") or "") if applying else "", "applied": stats.get("applied", 0), "skipped": stats.get("skipped", 0), } def _poll_remote_task(self) -> None: """拉取并执行云端下发的远程控制任务,执行完回调终态""" task = self.server_api.fetch_pending_task() if not task: return tid, ttype = task["id"], task["task_type"] logger.info(f"收到远程任务 #{tid}:{ttype}") try: if ttype == "start_apply": res = start_apply_shared(task.get("params") or {}) status, result = ("done", res["msg"]) if res["ok"] else ("failed", res["msg"]) elif ttype == "stop_apply": applicant = self.ensure_applicant() if applicant.is_running: applicant.stop() status, result = "done", "停止指令已下达" else: status, result = "done", "当前没有运行中的投递任务" else: status, result = "failed", f"未知任务类型:{ttype}" except Exception as e: status, result = "failed", f"执行异常:{e}" logger.info(f"远程任务 #{tid} 执行结果:{status} - {result}") try: self.server_api.finish_task(tid, status, result) except Exception as e: logger.warning(f"远程任务回调失败 #{tid}:{e}") state = AppState() def start_apply_shared(params: dict) -> dict: """面板 / 远程任务共用的启动入口(返回 ok+msg,不抛业务异常)""" if not state.server_api.get_primary_resume(): return {"ok": False, "msg": "请先设置主简历"} try: # 浏览器可能被用户手动关闭,投递前确保已拉起(复用登录态 profile) state.browser.ensure_browser_started() except RuntimeError as e: return {"ok": False, "msg": str(e)} applicant = state.ensure_applicant() if applicant.is_running: return {"ok": False, "msg": "已有投递任务在运行"} applicant.start( keywords=list(params.get("keywords") or []), city=str(params.get("city") or ""), salary_min=params.get("salary_min"), salary_max=params.get("salary_max"), min_score=int(params.get("min_score") or 65), delay_range=(int(params.get("delay_min") or 3), int(params.get("delay_max") or 8)), boss_online_only=bool(params.get("boss_online_only")), daily_limit=int(params.get("daily_limit") or 0), allow_headhunter=bool(params.get("allow_headhunter")), ) return {"ok": True, "msg": "投递任务已启动", "session_id": applicant.session_id} # ======================================================= # 前置校验(收敛:所有需要已登录云端的路由统一走这里) # ======================================================= def _require_auth() -> None: """未登录云端时统一抛 400,禁止各路由自行散落判断""" if not state.connected: raise HTTPException(status_code=400, detail="请先登录系统账号") def _require_rpa_online() -> None: """ 关键操作(开始投递)前的在线预检: 先发一次心跳刷新在线状态,再确认服务端判定为在线, 避免心跳链路异常时启动必然失败的操作。 """ state.server_api.heartbeat() try: me = state.server_api.get_me() if not me.get("is_online"): raise HTTPException(status_code=409, detail="RPA 在线状态未确认,请检查网络后重试") except requests.RequestException as e: raise HTTPException(status_code=503, detail=f"无法确认在线状态:{e}") # ======================================================= # 请求模型 # ======================================================= class AuthReq(BaseModel): username: str password: str nickname: str | None = None class StartApplyReq(BaseModel): keywords: list[str] city: str salary_min: int | None = None salary_max: int | None = None min_score: int = 65 delay_min: int = 3 delay_max: int = 8 boss_online_only: bool = False daily_limit: int = 0 allow_headhunter: bool = False class ResumeUpdateReq(BaseModel): title: str | None = None position: str | None = None content: str | None = None # ======================================================= # 页面 # ======================================================= @app.get("/", response_class=HTMLResponse) def index(request: Request): return templates.TemplateResponse("index.html", {"request": request}) # ======================================================= # 基础状态 # ======================================================= @app.get("/api/status") def get_status(): """返回整体状态,供前端轮询(含本地 token 免登录校验)""" # 若本地存有 token,尝试校验并获取用户信息(实现二次启动免登录) me = None if state.server_api.token: try: me = state.server_api.get_me() state.connected = True state.ensure_control() # token 有效时确保控制线程在跑 except Exception: state.connected = False state.server_api.logout() # token 失效,清除本地缓存 else: state.connected = False result = { "machine": get_machine_summary(), "username": state.server_api.username, "server_connected": state.connected, "server_reachable": state.server_api.ping(), "rpa_online": me.get("is_online", False) if me else False, "browser_running": state.browser.is_browser_running(), "ai_configured": state.ai.available(), "login_status": me.get("login_status", "unknown") if me else "unknown", "boss_account": me.get("boss_account") if me else None, "resume_count": 0, "has_primary": False, "applying": False, "apply_stats": None, } if state.connected: try: resumes = state.server_api.list_resumes() result["resume_count"] = len(resumes) result["has_primary"] = any(r.get("is_primary") for r in resumes) except Exception as e: logger.debug(f"获取简历状态失败:{e}") if state.applicant and state.applicant.is_running: result["applying"] = True result["apply_stats"] = state.applicant.stats return result # ======================================================= # Step 0: 登录 / 注册云端账号(账号密码体系) # ======================================================= def _extract_error(e: requests.HTTPError) -> str: """从服务端错误响应中提取 detail 信息""" try: return e.response.json().get("detail", str(e)) except Exception: return str(e) @app.post("/api/register") def register(req: AuthReq): """注册新账号""" try: data = state.server_api.register(req.username, req.password, req.nickname) state.connected = True state.ensure_control() return {"ok": True, "user_id": data["user_id"], "username": data["username"]} except requests.HTTPError as e: raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"注册失败:{e}") @app.post("/api/login") def login(req: AuthReq): """账号密码登录""" try: data = state.server_api.login(req.username, req.password) state.connected = True state.ensure_control() return {"ok": True, "user_id": data["user_id"], "username": data["username"]} except requests.HTTPError as e: raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e)) except Exception as e: raise HTTPException(status_code=500, detail=f"登录失败:{e}") @app.post("/api/logout") def logout(): """退出登录,清除本地 token""" state.server_api.logout() state.connected = False return {"ok": True} # ======================================================= # Step 1: 引导登录 Boss直聘 # ======================================================= @app.post("/api/start-login") def start_login(): """拉起浏览器引导登录 Boss直聘,等待用户手动登录。 首次启动时浏览器自带 Boss直聘 首启标签页(由 Chrome 自己创建,程序不碰); 浏览器已在运行但首启页被关掉了,才补开一个用户标签页。""" _require_auth() try: state.server_api.update_login_status("logging_in") already_running = state.browser.is_browser_running() if not already_running: # 首次启动:拉起浏览器(启动参数自带目标网址,由 Chrome 自己打开) state.browser.ensure_browser_started() else: # 浏览器已在运行:无法确定用户是否还留着登录页,补开一个 # (原生 DevTools 协议开页,无自动化痕迹,风控不拦截) state.browser.open_user_tab("https://www.zhipin.com/") # 启动后台轮询检测登录(防止重复点击叠加多个轮询线程) if not state.login_polling: threading.Thread(target=_poll_login, daemon=True).start() return {"ok": True, "msg": "浏览器已打开,请在浏览器中完成登录"} except Exception as e: state.server_api.update_login_status("not_login") raise HTTPException(status_code=500, detail=f"打开浏览器失败:{e}") def _poll_login(): """后台轮询检测登录状态,最长等待 5 分钟。 检测仅读 Cookie(低痕迹通道,零刷新零开页),不打扰用户标签页。""" state.login_polling = True import time try: for _ in range(150): # 150 * 2s = 5 分钟 time.sleep(2) try: if state.browser.check_boss_login(): account = state.browser.get_boss_account_name() state.server_api.update_login_status("logged_in", account) logger.success(f"登录成功:{account}") break except Exception as e: logger.debug(f"登录轮询异常:{e}") finally: state.login_polling = False @app.post("/api/detect-login") def detect_login(): """活体检测 Boss直聘 登录状态(进入登录步骤时自动调用;仅读 Cookie + 一次性后台复核)""" _require_auth() # 浏览器未运行时直接判未登录,检测行为不应负责拉起浏览器 if not state.browser.is_browser_running(): state.server_api.update_login_status("not_login") return {"logged_in": False} try: logged_in = state.browser.check_boss_login() except Exception as e: raise HTTPException(status_code=500, detail=f"检测失败:{e}") if logged_in: account = state.browser.get_boss_account_name() state.server_api.update_login_status("logged_in", account) return {"logged_in": True, "account": account} state.server_api.update_login_status("not_login") return {"logged_in": False} @app.get("/api/login-status") def login_status(): """前端轮询登录状态""" if not state.connected: return {"status": "not_connected", "polling": False} try: me = state.server_api.get_me() return { "status": me.get("login_status", "not_login"), "boss_account": me.get("boss_account"), "polling": state.login_polling, } except Exception: return {"status": "unknown", "polling": state.login_polling} # ======================================================= # Step 2: 抓取简历 + 选择主简历 # ======================================================= @app.post("/api/scrape-resumes") def scrape_resumes(): """AI 抓取账号内所有简历并上传到云端""" _require_auth() try: # 抓取走低痕迹 CDP 通道(无 Playwright attach,风控不拦截) scraper = ResumeScraper(state.browser, state.ai) resumes = scraper.scrape_all() if not resumes: raise HTTPException(status_code=404, detail="未抓取到任何简历,请确认已登录") uploaded = state.server_api.upload_resumes(resumes) return {"ok": True, "count": len(uploaded), "resumes": uploaded} except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"抓取简历失败:{e}") @app.get("/api/resumes") def list_resumes(): if not state.connected: return [] return state.server_api.list_resumes() @app.post("/api/resumes/{resume_id}/primary") def set_primary(resume_id: int): return state.server_api.set_primary_resume(resume_id) @app.put("/api/resumes/{resume_id}") def update_resume(resume_id: int, req: ResumeUpdateReq): """编辑简历(标题/求职意向/正文)""" _require_auth() data = {k: v for k, v in req.model_dump().items() if v is not None} if not data: raise HTTPException(status_code=400, detail="没有需要更新的字段") try: return state.server_api.update_resume(resume_id, data) except requests.HTTPError as e: raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e)) @app.delete("/api/resumes/{resume_id}") def delete_resume(resume_id: int): """删除简历""" _require_auth() try: return state.server_api.delete_resume(resume_id) except requests.HTTPError as e: raise HTTPException(status_code=e.response.status_code, detail=_extract_error(e)) # ======================================================= # Step 3 & 4: 开始 / 结束投递 # ======================================================= @app.post("/api/start-apply") def start_apply(req: StartApplyReq): _require_auth() _require_rpa_online() # 在线预检:与服务端 require_online_user 前置校验呼应 res = start_apply_shared(req.model_dump()) if not res["ok"]: raise HTTPException(status_code=400, detail=res["msg"]) return {"ok": True, "session_id": res.get("session_id")} @app.post("/api/stop-apply") def stop_apply(): applicant = state.ensure_applicant() if not applicant.is_running: return {"ok": False, "msg": "当前没有运行中的投递任务"} applicant.stop() return {"ok": True, "msg": "正在停止投递任务..."} @app.get("/api/apply-status") def apply_status(): applicant = state.applicant if applicant is None: return {"running": False, "stats": None} return { "running": applicant.is_running, "stats": applicant.stats, "session_id": applicant.session_id, } # ======================================================= # 历史与统计 # ======================================================= @app.get("/api/history") def history(limit: int = 50, apply_type: str | None = None): if not state.connected: return [] return state.server_api.get_history(limit=limit, apply_type=apply_type) @app.get("/api/history-page") def history_page(page: int = 1, page_size: int = 20, apply_type: str | None = None, start: str | None = None, end: str | None = None): """投递记录分页筛选(时间范围 + 投递结果,时间倒序)""" if not state.connected: return {"items": [], "total": 0, "applied": 0, "skipped": 0, "page": page, "page_size": page_size, "pages": 0} return state.server_api.get_history_page( page=page, page_size=page_size, apply_type=apply_type, start=start, end=end) @app.get("/api/stats") def stats(): if not state.connected: return {} return state.server_api.get_stats()