407 lines
15 KiB
Python
407 lines
15 KiB
Python
"""
|
|
本地 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 ..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._heartbeat_started = False
|
|
|
|
def ensure_applicant(self) -> Applicant:
|
|
if self.applicant is None:
|
|
self.applicant = Applicant(self.browser, self.server_api, self.ai)
|
|
return self.applicant
|
|
|
|
# ------------------------------------------------------------------
|
|
# 心跳:登录成功后启动后台线程,周期性向服务端上报存活
|
|
# ------------------------------------------------------------------
|
|
def ensure_heartbeat(self) -> None:
|
|
if self._heartbeat_started or not self.server_api.token:
|
|
return
|
|
self._heartbeat_started = True
|
|
threading.Thread(target=self._heartbeat_loop, daemon=True).start()
|
|
logger.info(f"心跳线程已启动,间隔 {client_settings.HEARTBEAT_INTERVAL}s")
|
|
|
|
def _heartbeat_loop(self) -> None:
|
|
while True:
|
|
if not self.server_api.token:
|
|
# 已退出登录,停止心跳
|
|
self._heartbeat_started = False
|
|
logger.info("已退出登录,心跳停止")
|
|
break
|
|
self.server_api.heartbeat()
|
|
time.sleep(client_settings.HEARTBEAT_INTERVAL)
|
|
|
|
|
|
state = AppState()
|
|
|
|
|
|
# =======================================================
|
|
# 前置校验(收敛:所有需要已登录云端的路由统一走这里)
|
|
# =======================================================
|
|
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_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
|
|
boss_online_only: bool = False
|
|
daily_limit: int = 0
|
|
|
|
|
|
# =======================================================
|
|
# 页面
|
|
# =======================================================
|
|
@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_heartbeat() # 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_heartbeat()
|
|
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_heartbeat()
|
|
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)
|
|
|
|
|
|
# =======================================================
|
|
# Step 3 & 4: 开始 / 结束投递
|
|
# =======================================================
|
|
@app.post("/api/start-apply")
|
|
def start_apply(req: StartApplyReq):
|
|
_require_auth()
|
|
_require_rpa_online() # 在线预检:与服务端 require_online_user 前置校验呼应
|
|
if not state.server_api.get_primary_resume():
|
|
raise HTTPException(status_code=400, detail="请先设置主简历")
|
|
try:
|
|
# 浏览器可能被用户手动关闭,投递前确保已拉起(复用登录态 profile)
|
|
state.browser.ensure_browser_started()
|
|
except RuntimeError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
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),
|
|
boss_online_only=req.boss_online_only,
|
|
daily_limit=req.daily_limit,
|
|
)
|
|
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()
|