""" 本地 Web 控制面板 FastAPI 应用:提供操作界面 + 编排浏览器自动化流程 """ import threading 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 ..server_api import ServerAPI from ..ai import AIClient from ..fingerprint import generate_client_code, 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 def ensure_applicant(self) -> Applicant: if self.applicant is None: self.applicant = Applicant(self.browser, self.server_api, self.ai) return self.applicant state = AppState() # ======================================================= # 请求模型 # ======================================================= class ConnectReq(BaseModel): nickname: str | None = None class StartApplyReq(BaseModel): keywords: list[str] city_code: str salary_min: int | None = None salary_max: int | None = None greeting: str = "" min_score: int = 65 delay_min: int = 3 delay_max: int = 8 # ======================================================= # 页面 # ======================================================= @app.get("/", response_class=HTMLResponse) def index(request: Request): return templates.TemplateResponse("index.html", {"request": request}) # ======================================================= # 基础状态 # ======================================================= @app.get("/api/status") def get_status(): """返回整体状态,供前端轮询""" result = { "client_code": generate_client_code()[:16] + "...", "machine": get_machine_summary(), "server_connected": state.connected, "server_reachable": state.server_api.ping(), "adspower_running": state.browser.is_adspower_running(), "ai_configured": state.ai.available(), "login_status": "unknown", "resume_count": 0, "has_primary": False, "applying": False, "apply_stats": None, } if state.connected: try: me = state.server_api.get_me() result["login_status"] = me.get("login_status", "unknown") result["boss_account"] = me.get("boss_account") 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: 连接云端服务端 # ======================================================= @app.post("/api/connect") def connect(req: ConnectReq): try: data = state.server_api.register(req.nickname) state.connected = True return {"ok": True, "user_id": data["user_id"], "is_new": data["is_new"]} except Exception as e: raise HTTPException(status_code=500, detail=f"连接服务端失败:{e}") # ======================================================= # Step 1: 引导登录 Boss直聘 # ======================================================= @app.post("/api/start-login") def start_login(): """打开 AdsPower 浏览器并跳转到 Boss直聘,等待用户手动登录""" if not state.connected: raise HTTPException(status_code=400, detail="请先连接服务端") try: state.server_api.update_login_status("logging_in") page = state.browser.connect() page.goto("https://www.zhipin.com/", wait_until="domcontentloaded", timeout=30000) # 启动后台轮询检测登录 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 分钟""" state.login_polling = True import time 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}") state.login_polling = 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 抓取账号内所有简历并上传到云端""" if not state.connected: raise HTTPException(status_code=400, detail="请先连接服务端") try: 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) # ======================================================= # Step 3 & 4: 开始 / 结束投递 # ======================================================= @app.post("/api/start-apply") def start_apply(req: StartApplyReq): if not state.connected: raise HTTPException(status_code=400, detail="请先连接服务端") if not state.server_api.get_primary_resume(): raise HTTPException(status_code=400, detail="请先设置主简历") if not state.browser.is_adspower_running(): raise HTTPException(status_code=400, detail="AdsPower 未运行") applicant = state.ensure_applicant() if applicant.is_running: raise HTTPException(status_code=400, detail="已有投递任务在运行") applicant.start( keywords=req.keywords, city_code=req.city_code, salary_min=req.salary_min, salary_max=req.salary_max, greeting=req.greeting, min_score=req.min_score, delay_range=(req.delay_min, req.delay_max), ) return {"ok": True, "session_id": applicant.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/stats") def stats(): if not state.connected: return {} return state.server_api.get_stats()