init
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# 敏感配置
|
||||||
|
.env
|
||||||
|
*.env.local
|
||||||
|
client/.token
|
||||||
|
|
||||||
|
# 日志与数据
|
||||||
|
logs/
|
||||||
|
client/logs/
|
||||||
|
data/
|
||||||
|
*.db
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,166 @@
|
|||||||
|
# Boss直聘 AI 智能投递系统
|
||||||
|
|
||||||
|
基于 **AdsPower 指纹浏览器 + Playwright + AI 大模型** 的客户端-服务端架构自动求职投递系统。
|
||||||
|
支持多用户数据隔离,每个客户端以机器硬件指纹作为唯一编码注册。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 系统架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────────┐
|
||||||
|
│ Python 客户端(本地 Windows) │
|
||||||
|
│ · 本地 Web 控制面板(浏览器打开操作) │
|
||||||
|
│ · AdsPower 指纹浏览器 + Playwright 自动化 │
|
||||||
|
│ · 机器硬件指纹 → 唯一编码 │
|
||||||
|
└────────────────────┬─────────────────────────┘
|
||||||
|
│ HTTP + JWT Token
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────────────────┐
|
||||||
|
│ FastAPI 服务端(云服务器) │
|
||||||
|
│ · 用户注册 / JWT 认证 │
|
||||||
|
│ · 简历管理(主简历标记) │
|
||||||
|
│ · 投递会话 + 投递记录(按 user_id 隔离) │
|
||||||
|
└────────────────────┬─────────────────────────┘
|
||||||
|
▼
|
||||||
|
MySQL 数据库
|
||||||
|
```
|
||||||
|
|
||||||
|
## 业务流程
|
||||||
|
|
||||||
|
1. **连接**:客户端用机器指纹注册云端,获取 Token
|
||||||
|
2. **登录**:面板引导,通过 AdsPower 打开 Boss直聘,用户手动登录
|
||||||
|
3. **简历**:AI 自动抓取账号内所有简历 → 用户勾选主简历
|
||||||
|
4. **投递**:设置城市/薪资/关键词 → 点击开始,AI 按主简历匹配 JD 自动投递
|
||||||
|
5. **记录**:实时查看进度、历史与统计,随时结束
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
jianli-boss/
|
||||||
|
├── server/ # 云端服务端(FastAPI + MySQL)
|
||||||
|
│ ├── main.py # 服务入口
|
||||||
|
│ ├── config.py # 配置(读 .env)
|
||||||
|
│ ├── database.py # MySQL 连接
|
||||||
|
│ ├── models.py # ORM 模型
|
||||||
|
│ ├── schemas.py # Pydantic 模式
|
||||||
|
│ ├── auth.py # JWT 认证
|
||||||
|
│ ├── routers/ # API 路由
|
||||||
|
│ │ ├── register.py # 注册 / 登录状态
|
||||||
|
│ │ ├── resumes.py # 简历管理
|
||||||
|
│ │ ├── sessions.py # 投递会话
|
||||||
|
│ │ └── jobs.py # 投递记录
|
||||||
|
│ ├── requirements.txt
|
||||||
|
│ └── .env.example
|
||||||
|
│
|
||||||
|
└── client/ # 本地客户端
|
||||||
|
├── main.py # 客户端入口(启动 Web 面板)
|
||||||
|
├── config.py # 配置(读 .env)
|
||||||
|
├── fingerprint.py # 机器硬件指纹
|
||||||
|
├── server_api.py # 调用云端 API
|
||||||
|
├── ai.py # AI 评分 / 简历整理
|
||||||
|
├── browser/
|
||||||
|
│ ├── manager.py # AdsPower + Playwright 管理
|
||||||
|
│ ├── resume_scraper.py # 抓取简历
|
||||||
|
│ └── applicant.py # 投递自动化(可启停)
|
||||||
|
├── web/
|
||||||
|
│ ├── app.py # 本地控制面板后端
|
||||||
|
│ ├── templates/index.html
|
||||||
|
│ └── static/ # style.css / app.js
|
||||||
|
├── requirements.txt
|
||||||
|
└── .env.example
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、部署服务端(云服务器)
|
||||||
|
|
||||||
|
### 1. 准备 MySQL
|
||||||
|
```sql
|
||||||
|
CREATE DATABASE jianli_boss DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 安装依赖
|
||||||
|
```bash
|
||||||
|
cd server
|
||||||
|
pip install -r requirements.txt
|
||||||
|
cp .env.example .env # 编辑 .env 填写数据库密码和 SECRET_KEY
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 启动
|
||||||
|
```bash
|
||||||
|
# 开发模式
|
||||||
|
uvicorn server.main:app --host 0.0.0.0 --port 8000 --reload
|
||||||
|
|
||||||
|
# 生产模式(建议用 gunicorn + uvicorn worker,或配 Nginx 反代 + HTTPS)
|
||||||
|
uvicorn server.main:app --host 0.0.0.0 --port 8000 --workers 4
|
||||||
|
```
|
||||||
|
|
||||||
|
启动后访问 `http://服务器IP:8000/docs` 可查看自动生成的 API 文档(Swagger)。
|
||||||
|
|
||||||
|
> ⚠️ 生产环境务必修改 `.env` 中的 `SECRET_KEY`,并建议通过 Nginx 配置 HTTPS。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、运行客户端(本地 Windows)
|
||||||
|
|
||||||
|
### 1. 安装 AdsPower
|
||||||
|
- 前往 [adspower.net](https://www.adspower.net) 下载安装
|
||||||
|
- 创建一个浏览器 Profile,记住它的 **用户 ID**
|
||||||
|
|
||||||
|
### 2. 安装依赖
|
||||||
|
```powershell
|
||||||
|
cd client
|
||||||
|
pip install -r requirements.txt
|
||||||
|
playwright install chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 配置环境变量
|
||||||
|
复制 `.env.example` 为 `.env` 并填写:
|
||||||
|
```ini
|
||||||
|
SERVER_URL=http://你的服务器IP:8000 # 云端服务端地址
|
||||||
|
ADSPOWER_USER_ID=你的ProfileID # AdsPower 用户 ID(必填)
|
||||||
|
AI_API_KEY=你的大模型Key # AI 评分用
|
||||||
|
AI_BASE_URL=https://api.deepseek.com # OpenAI 兼容接口
|
||||||
|
AI_MODEL=deepseek-chat
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 启动
|
||||||
|
```powershell
|
||||||
|
# 确保 AdsPower 软件已打开
|
||||||
|
python -m client.main
|
||||||
|
```
|
||||||
|
浏览器会自动打开控制面板 `http://127.0.0.1:8088`,按 5 个步骤操作即可。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、关于中文乱码
|
||||||
|
|
||||||
|
所有文件读写均已指定 `encoding="utf-8"`。若 PowerShell 控制台仍乱码,运行:
|
||||||
|
```powershell
|
||||||
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
chcp 65001
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
| 问题 | 解决方案 |
|
||||||
|
|------|---------|
|
||||||
|
| 客户端连不上服务端 | 检查 `SERVER_URL` 是否正确、云服务器安全组是否放行端口 |
|
||||||
|
| 注册一直失败 | 确认服务端已启动且 MySQL 可连接 |
|
||||||
|
| 无法打开浏览器 | 确认 AdsPower 已运行且 `ADSPOWER_USER_ID` 正确 |
|
||||||
|
| 抓不到简历 | 确认已登录 Boss直聘;页面结构变化时需调整 `resume_scraper.py` 选择器 |
|
||||||
|
| AI 评分不生效 | 检查 `AI_API_KEY` 是否配置,`AI_BASE_URL`/`AI_MODEL` 是否匹配 |
|
||||||
|
| 投递按钮找不到 | Boss直聘 前端改版,需更新 `applicant.py` 中的选择器 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 安全与合规提示
|
||||||
|
|
||||||
|
- 请遵守 Boss直聘 的用户协议,控制投递频率(建议每天 ≤30 个),避免账号风险
|
||||||
|
- `SECRET_KEY`、数据库密码、AI Key 等敏感信息请勿提交到代码仓库
|
||||||
|
- 建议将 `.env`、`.token`、`logs/` 加入 `.gitignore`
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# ============ 客户端环境变量示例 ============
|
||||||
|
# 复制本文件为 .env 并填写真实值:.env
|
||||||
|
|
||||||
|
# 云端服务端地址(部署后改成你的服务器地址)
|
||||||
|
SERVER_URL=http://127.0.0.1:8000
|
||||||
|
|
||||||
|
# 本地控制面板端口
|
||||||
|
WEB_PORT=8088
|
||||||
|
|
||||||
|
# AdsPower 本地 API(一般不用改)
|
||||||
|
ADSPOWER_API_URL=http://local.adspower.net:50325
|
||||||
|
# 你的 AdsPower Profile ID(在 AdsPower 界面查看,必填)
|
||||||
|
ADSPOWER_USER_ID=
|
||||||
|
|
||||||
|
# AI 大模型(OpenAI 兼容接口)
|
||||||
|
AI_BASE_URL=https://api.deepseek.com
|
||||||
|
AI_MODEL=deepseek-chat
|
||||||
|
AI_API_KEY=
|
||||||
|
# 低于该分数的职位自动跳过
|
||||||
|
AI_MIN_SCORE=65
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""客户端包"""
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
"""
|
||||||
|
客户端 AI 大模型封装(OpenAI 兼容接口)
|
||||||
|
功能:
|
||||||
|
1. 职位匹配度评分
|
||||||
|
2. 简历内容整理
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from openai import OpenAI
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from .config import client_settings
|
||||||
|
|
||||||
|
|
||||||
|
class MatchResult:
|
||||||
|
def __init__(self, score: int, reason: str):
|
||||||
|
self.score = score
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
def is_worth_applying(self, threshold: int = 60) -> bool:
|
||||||
|
return self.score >= threshold
|
||||||
|
|
||||||
|
|
||||||
|
class AIClient:
|
||||||
|
"""OpenAI 兼容大模型客户端"""
|
||||||
|
|
||||||
|
def __init__(self, api_key: str | None = None, base_url: str | None = None,
|
||||||
|
model: str | None = None):
|
||||||
|
self.api_key = api_key or client_settings.AI_API_KEY or os.environ.get("AI_API_KEY", "")
|
||||||
|
self.base_url = base_url or client_settings.AI_BASE_URL
|
||||||
|
self.model = model or client_settings.AI_MODEL
|
||||||
|
self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
|
||||||
|
|
||||||
|
def available(self) -> bool:
|
||||||
|
return bool(self.api_key)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 职位匹配度评分
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def score_job(self, jd_text: str, resume_content: str) -> MatchResult:
|
||||||
|
"""根据 JD 与主简历内容评估匹配度"""
|
||||||
|
if not self.available():
|
||||||
|
return MatchResult(50, "AI 未配置,默认放行")
|
||||||
|
|
||||||
|
system_prompt = (
|
||||||
|
"你是专业招聘顾问。根据职位描述(JD)和候选人简历,输出 JSON 评估结果,"
|
||||||
|
"不要输出 JSON 以外的内容。\n"
|
||||||
|
'格式:{"score": <0-100整数>, "reason": "<一句话评价>"}\n'
|
||||||
|
"评分标准:80-100 高度匹配;60-79 基本匹配;40-59 部分匹配;0-39 不匹配。"
|
||||||
|
)
|
||||||
|
user_prompt = f"【职位描述】\n{jd_text}\n\n【候选人简历】\n{resume_content}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": user_prompt},
|
||||||
|
],
|
||||||
|
temperature=0.2,
|
||||||
|
max_tokens=256,
|
||||||
|
)
|
||||||
|
raw = resp.choices[0].message.content.strip()
|
||||||
|
if raw.startswith("```"):
|
||||||
|
raw = raw.split("```")[1]
|
||||||
|
if raw.startswith("json"):
|
||||||
|
raw = raw[4:]
|
||||||
|
data = json.loads(raw)
|
||||||
|
return MatchResult(int(data.get("score", 50)), data.get("reason", ""))
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"AI 评分失败,默认放行:{e}")
|
||||||
|
return MatchResult(50, f"AI 异常:{e}")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 简历内容整理
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def clean_resume(self, raw_text: str) -> str:
|
||||||
|
"""用 AI 将抓取的杂乱简历文本整理为清晰的结构化文本"""
|
||||||
|
if not self.available():
|
||||||
|
return raw_text
|
||||||
|
|
||||||
|
system_prompt = (
|
||||||
|
"你是简历整理助手。将下面抓取的杂乱简历文本整理为清晰、结构化的纯文本简历,"
|
||||||
|
"保留所有关键信息(姓名可省略,联系方式可保留),去除广告和无关内容。"
|
||||||
|
"直接输出整理后的文本,不要加任何解释。"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
resp = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": system_prompt},
|
||||||
|
{"role": "user", "content": raw_text},
|
||||||
|
],
|
||||||
|
temperature=0.3,
|
||||||
|
max_tokens=2048,
|
||||||
|
)
|
||||||
|
return resp.choices[0].message.content.strip()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"AI 整理简历失败,返回原文:{e}")
|
||||||
|
return raw_text
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 连通测试
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def ping(self) -> bool:
|
||||||
|
try:
|
||||||
|
resp = self.client.chat.completions.create(
|
||||||
|
model=self.model,
|
||||||
|
messages=[{"role": "user", "content": "回复1"}],
|
||||||
|
max_tokens=5,
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"AI 接口连通失败:{e}")
|
||||||
|
return False
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""浏览器自动化包"""
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
"""
|
||||||
|
投递自动化模块
|
||||||
|
在后台线程运行,支持用户随时开始/结束。
|
||||||
|
向云端服务端上报投递记录与统计。
|
||||||
|
"""
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import threading
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from .manager import BrowserManager
|
||||||
|
from ..ai import AIClient
|
||||||
|
from ..server_api import ServerAPI
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class JobCard:
|
||||||
|
job_id: str
|
||||||
|
title: str
|
||||||
|
company: str
|
||||||
|
salary: str
|
||||||
|
location: str
|
||||||
|
hr_active: str
|
||||||
|
can_chat: bool
|
||||||
|
can_deliver: bool
|
||||||
|
jd_text: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class Applicant:
|
||||||
|
"""投递执行器(可启停)"""
|
||||||
|
|
||||||
|
BASE_URL = "https://www.zhipin.com"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
manager: BrowserManager,
|
||||||
|
server_api: ServerAPI,
|
||||||
|
ai_client: AIClient | None,
|
||||||
|
):
|
||||||
|
self.manager = manager
|
||||||
|
self.server = server_api
|
||||||
|
self.ai = ai_client
|
||||||
|
|
||||||
|
# 运行控制
|
||||||
|
self._stop_event = threading.Event()
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self.is_running = False
|
||||||
|
|
||||||
|
# 运行时状态(供 Web 面板查询)
|
||||||
|
self.session_id: int | None = None
|
||||||
|
self.primary_resume_content: str = ""
|
||||||
|
self.stats = {"applied": 0, "skipped": 0, "current": ""}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 启停控制
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def start(self, keywords: list[str], city_code: str,
|
||||||
|
salary_min: int | None, salary_max: int | None,
|
||||||
|
greeting: str, min_score: int, delay_range: tuple[int, int]) -> None:
|
||||||
|
"""在新线程中启动投递任务"""
|
||||||
|
if self.is_running:
|
||||||
|
logger.warning("已有投递任务在运行")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 创建服务端会话
|
||||||
|
session = self.server.start_session(
|
||||||
|
keywords=",".join(keywords),
|
||||||
|
city_code=city_code,
|
||||||
|
salary_min=salary_min,
|
||||||
|
salary_max=salary_max,
|
||||||
|
)
|
||||||
|
self.session_id = session["id"]
|
||||||
|
|
||||||
|
# 获取主简历内容
|
||||||
|
primary = self.server.get_primary_resume()
|
||||||
|
self.primary_resume_content = primary["content"] if primary else ""
|
||||||
|
|
||||||
|
self._stop_event.clear()
|
||||||
|
self.is_running = True
|
||||||
|
self.stats = {"applied": 0, "skipped": 0, "current": "初始化..."}
|
||||||
|
|
||||||
|
self._thread = threading.Thread(
|
||||||
|
target=self._run,
|
||||||
|
args=(keywords, city_code, salary_min, salary_max,
|
||||||
|
greeting, min_score, delay_range),
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
self._thread.start()
|
||||||
|
logger.success(f"投递任务已启动,会话 ID:{self.session_id}")
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""请求停止投递任务"""
|
||||||
|
logger.info("收到停止投递请求...")
|
||||||
|
self._stop_event.set()
|
||||||
|
|
||||||
|
def _finish(self) -> None:
|
||||||
|
"""任务结束后的收尾工作"""
|
||||||
|
self.is_running = False
|
||||||
|
if self.session_id:
|
||||||
|
try:
|
||||||
|
self.server.stop_session(self.session_id)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"结束会话失败:{e}")
|
||||||
|
self.stats["current"] = "已停止"
|
||||||
|
logger.info(
|
||||||
|
f"投递任务结束。本次投递 {self.stats['applied']} 个,"
|
||||||
|
f"跳过 {self.stats['skipped']} 个"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _should_stop(self) -> bool:
|
||||||
|
return self._stop_event.is_set()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 主循环
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _run(self, keywords, city_code, salary_min, salary_max,
|
||||||
|
greeting, min_score, delay_range):
|
||||||
|
try:
|
||||||
|
for keyword in keywords:
|
||||||
|
if self._should_stop():
|
||||||
|
break
|
||||||
|
self.stats["current"] = f"搜索关键词:{keyword}"
|
||||||
|
self._process_keyword(
|
||||||
|
keyword, city_code, salary_min, salary_max,
|
||||||
|
greeting, min_score, delay_range,
|
||||||
|
)
|
||||||
|
if not self._should_stop():
|
||||||
|
self._sleep(5, 9)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"投递任务异常:{e}")
|
||||||
|
finally:
|
||||||
|
self._finish()
|
||||||
|
|
||||||
|
def _process_keyword(self, keyword, city_code, salary_min, salary_max,
|
||||||
|
greeting, min_score, delay_range, max_per_keyword: int = 15):
|
||||||
|
page = 1
|
||||||
|
applied_in_kw = 0
|
||||||
|
while applied_in_kw < max_per_keyword and not self._should_stop():
|
||||||
|
cards = self._fetch_job_list(keyword, city_code, salary_min, salary_max, page)
|
||||||
|
if not cards:
|
||||||
|
break
|
||||||
|
for card in cards:
|
||||||
|
if self._should_stop():
|
||||||
|
return
|
||||||
|
if applied_in_kw >= max_per_keyword:
|
||||||
|
break
|
||||||
|
applied_in_kw += self._handle_card(card, greeting, min_score, delay_range)
|
||||||
|
page += 1
|
||||||
|
|
||||||
|
def _handle_card(self, card: JobCard, greeting: str, min_score: int,
|
||||||
|
delay_range: tuple[int, int]) -> int:
|
||||||
|
"""处理单个职位卡片,返回是否投递成功(1/0)"""
|
||||||
|
# 1. 去重(服务端查询)
|
||||||
|
try:
|
||||||
|
if self.server.check_applied(card.job_id):
|
||||||
|
return 0
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
self.stats["current"] = f"评估:{card.company} - {card.title}"
|
||||||
|
|
||||||
|
# 2. AI 匹配度评分
|
||||||
|
ai_score, ai_reason = -1, ""
|
||||||
|
if self.ai and self.ai.available() and self.primary_resume_content:
|
||||||
|
jd = card.jd_text or self._fetch_jd_detail(card)
|
||||||
|
result = self.ai.score_job(jd, self.primary_resume_content)
|
||||||
|
ai_score, ai_reason = result.score, result.reason
|
||||||
|
if not result.is_worth_applying(min_score):
|
||||||
|
self._report_skip(card, f"AI 评分低({ai_score})", ai_score, ai_reason)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 3. 执行投递
|
||||||
|
success, apply_type = self._apply(card, greeting)
|
||||||
|
if success:
|
||||||
|
self._report_apply(card, apply_type, ai_score, ai_reason)
|
||||||
|
self._sleep(*delay_range)
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 服务端上报
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _report_apply(self, card: JobCard, apply_type: str, ai_score: int, ai_reason: str):
|
||||||
|
try:
|
||||||
|
self.server.report_application(self.session_id, {
|
||||||
|
"job_id": card.job_id,
|
||||||
|
"job_title": card.title,
|
||||||
|
"company": card.company,
|
||||||
|
"salary": card.salary,
|
||||||
|
"location": card.location,
|
||||||
|
"apply_type": apply_type,
|
||||||
|
"ai_score": ai_score,
|
||||||
|
"ai_reason": ai_reason[:255] if ai_reason else None,
|
||||||
|
})
|
||||||
|
self.server.update_session_stats(self.session_id, applied_delta=1, skipped_delta=0)
|
||||||
|
self.stats["applied"] += 1
|
||||||
|
logger.success(f"[{self.stats['applied']}] 投递成功({apply_type}):{card.company} - {card.title}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"上报投递记录失败:{e}")
|
||||||
|
|
||||||
|
def _report_skip(self, card: JobCard, reason: str, ai_score: int = -1, ai_reason: str = ""):
|
||||||
|
try:
|
||||||
|
self.server.report_application(self.session_id, {
|
||||||
|
"job_id": card.job_id,
|
||||||
|
"job_title": card.title,
|
||||||
|
"company": card.company,
|
||||||
|
"salary": card.salary,
|
||||||
|
"apply_type": "skipped",
|
||||||
|
"ai_score": ai_score,
|
||||||
|
"ai_reason": ai_reason[:255] if ai_reason else None,
|
||||||
|
"skip_reason": reason,
|
||||||
|
})
|
||||||
|
self.server.update_session_stats(self.session_id, applied_delta=0, skipped_delta=1)
|
||||||
|
self.stats["skipped"] += 1
|
||||||
|
logger.info(f"跳过({reason}):{card.company} - {card.title}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"上报跳过记录失败:{e}")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 页面操作
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _fetch_job_list(self, keyword, city_code, salary_min, salary_max, page) -> list[JobCard]:
|
||||||
|
page_obj = self.manager.ensure_connected()
|
||||||
|
url = f"{self.BASE_URL}/web/geek/job?query={keyword}&city={city_code}&page={page}"
|
||||||
|
if salary_min or salary_max:
|
||||||
|
url += f"&salary={(salary_min or 0) * 1000},{(salary_max or 0) * 1000}"
|
||||||
|
|
||||||
|
self.stats["current"] = f"加载职位列表 第{page}页"
|
||||||
|
try:
|
||||||
|
page_obj.goto(url, wait_until="domcontentloaded", timeout=30000)
|
||||||
|
page_obj.wait_for_timeout(2500)
|
||||||
|
page_obj.wait_for_selector(".job-card-wrapper", timeout=10000)
|
||||||
|
except Exception:
|
||||||
|
logger.warning(f"第 {page} 页无职位列表")
|
||||||
|
return []
|
||||||
|
|
||||||
|
cards = []
|
||||||
|
for el in page_obj.query_selector_all(".job-card-wrapper"):
|
||||||
|
try:
|
||||||
|
card = self._parse_card(el)
|
||||||
|
if card:
|
||||||
|
cards.append(card)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
logger.info(f"第 {page} 页解析到 {len(cards)} 个职位")
|
||||||
|
return cards
|
||||||
|
|
||||||
|
def _parse_card(self, el) -> JobCard | None:
|
||||||
|
def text(sel: str) -> str:
|
||||||
|
node = el.query_selector(sel)
|
||||||
|
return node.inner_text().strip() if node else ""
|
||||||
|
|
||||||
|
link = el.query_selector("a.job-card-left")
|
||||||
|
href = link.get_attribute("href") if link else ""
|
||||||
|
m = re.search(r"/job_detail/(\w+)\.html", href or "")
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
return JobCard(
|
||||||
|
job_id=m.group(1),
|
||||||
|
title=text(".job-name"),
|
||||||
|
company=text(".company-name"),
|
||||||
|
salary=text(".salary"),
|
||||||
|
location=text(".job-area"),
|
||||||
|
hr_active=text(".info-public"),
|
||||||
|
can_chat=bool(el.query_selector(".start-chat-btn:not([disabled])")),
|
||||||
|
can_deliver=bool(el.query_selector(".btn-deliver")),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _fetch_jd_detail(self, card: JobCard) -> str:
|
||||||
|
page_obj = self.manager.page
|
||||||
|
try:
|
||||||
|
page_obj.goto(f"{self.BASE_URL}/job_detail/{card.job_id}.html",
|
||||||
|
wait_until="domcontentloaded", timeout=20000)
|
||||||
|
page_obj.wait_for_timeout(1500)
|
||||||
|
el = page_obj.query_selector(".job-detail-section")
|
||||||
|
jd = el.inner_text().strip() if el else f"{card.title} {card.company}"
|
||||||
|
page_obj.go_back()
|
||||||
|
page_obj.wait_for_timeout(1500)
|
||||||
|
return jd
|
||||||
|
except Exception:
|
||||||
|
return f"{card.title} {card.company}"
|
||||||
|
|
||||||
|
def _apply(self, card: JobCard, greeting: str) -> tuple[bool, str]:
|
||||||
|
if card.can_chat and self._do_chat(card, greeting):
|
||||||
|
return True, "chat"
|
||||||
|
if card.can_deliver and self._do_deliver(card):
|
||||||
|
return True, "deliver"
|
||||||
|
return False, ""
|
||||||
|
|
||||||
|
def _do_chat(self, card: JobCard, greeting: str) -> bool:
|
||||||
|
page_obj = self.manager.page
|
||||||
|
try:
|
||||||
|
btn = page_obj.query_selector(f"[data-job-id='{card.job_id}'] .start-chat-btn")
|
||||||
|
if not btn:
|
||||||
|
return False
|
||||||
|
btn.click()
|
||||||
|
page_obj.wait_for_timeout(2000)
|
||||||
|
if greeting:
|
||||||
|
inp = page_obj.query_selector(".chat-input textarea")
|
||||||
|
if inp:
|
||||||
|
inp.fill(greeting)
|
||||||
|
page_obj.wait_for_timeout(500)
|
||||||
|
send = page_obj.query_selector(".chat-input .btn-send")
|
||||||
|
if send:
|
||||||
|
send.click()
|
||||||
|
page_obj.wait_for_timeout(1500)
|
||||||
|
close = page_obj.query_selector(".dialog-container .close-btn")
|
||||||
|
if close:
|
||||||
|
close.click()
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"立即沟通失败:{e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _do_deliver(self, card: JobCard) -> bool:
|
||||||
|
page_obj = self.manager.page
|
||||||
|
try:
|
||||||
|
btn = page_obj.query_selector(f"[data-job-id='{card.job_id}'] .btn-deliver")
|
||||||
|
if not btn:
|
||||||
|
return False
|
||||||
|
btn.click()
|
||||||
|
page_obj.wait_for_timeout(2000)
|
||||||
|
confirm = page_obj.query_selector(".dialog-confirm .btn-sure")
|
||||||
|
if confirm:
|
||||||
|
confirm.click()
|
||||||
|
page_obj.wait_for_timeout(1500)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"投递简历失败:{e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _sleep(self, min_s: float, max_s: float) -> None:
|
||||||
|
# 分段睡眠以便及时响应停止信号
|
||||||
|
total = random.uniform(min_s, max_s)
|
||||||
|
elapsed = 0.0
|
||||||
|
while elapsed < total and not self._should_stop():
|
||||||
|
time.sleep(0.5)
|
||||||
|
elapsed += 0.5
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
"""
|
||||||
|
浏览器管理器
|
||||||
|
统一管理 AdsPower 浏览器启动与 Playwright CDP 连接。
|
||||||
|
登录、抓取简历、投递共用同一个浏览器会话(复用登录态)。
|
||||||
|
"""
|
||||||
|
import requests
|
||||||
|
from loguru import logger
|
||||||
|
from playwright.sync_api import sync_playwright, Playwright, Browser, BrowserContext, Page
|
||||||
|
|
||||||
|
from ..config import client_settings
|
||||||
|
|
||||||
|
BOSS_HOME = "https://www.zhipin.com/web/geek/job"
|
||||||
|
BOSS_RESUME_PAGE = "https://www.zhipin.com/web/geek/resume"
|
||||||
|
|
||||||
|
|
||||||
|
class BrowserManager:
|
||||||
|
"""管理 AdsPower 浏览器 + Playwright 连接"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.api_url = client_settings.ADSPOWER_API_URL.rstrip("/")
|
||||||
|
self.user_id = client_settings.ADSPOWER_USER_ID
|
||||||
|
self._playwright: Playwright | None = None
|
||||||
|
self._browser: Browser | None = None
|
||||||
|
self._context: BrowserContext | None = None
|
||||||
|
self.page: Page | None = None
|
||||||
|
self.cdp_url: str | None = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# AdsPower 本地 API
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def is_adspower_running(self) -> bool:
|
||||||
|
try:
|
||||||
|
resp = requests.get(f"{self.api_url}/status", timeout=5)
|
||||||
|
return resp.status_code == 200
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def start_adspower_browser(self) -> str:
|
||||||
|
"""启动 AdsPower 浏览器,返回 CDP 地址"""
|
||||||
|
url = f"{self.api_url}/api/v1/browser/start"
|
||||||
|
resp = requests.get(url, params={"user_id": self.user_id, "open_tabs": 1}, timeout=30)
|
||||||
|
data = resp.json()
|
||||||
|
if data.get("code") != 0:
|
||||||
|
raise RuntimeError(f"启动 AdsPower 浏览器失败:{data.get('msg')}")
|
||||||
|
ws = data["data"]["ws"]
|
||||||
|
self.cdp_url = ws.get("puppeteer") or ws.get("selenium")
|
||||||
|
logger.success(f"AdsPower 浏览器已启动,CDP: {self.cdp_url}")
|
||||||
|
return self.cdp_url
|
||||||
|
|
||||||
|
def stop_adspower_browser(self) -> None:
|
||||||
|
try:
|
||||||
|
requests.get(
|
||||||
|
f"{self.api_url}/api/v1/browser/stop",
|
||||||
|
params={"user_id": self.user_id}, timeout=10,
|
||||||
|
)
|
||||||
|
logger.info("AdsPower 浏览器已关闭")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"关闭 AdsPower 浏览器失败:{e}")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Playwright 连接
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def connect(self) -> Page:
|
||||||
|
"""启动浏览器并通过 CDP 连接,返回可操作的 page"""
|
||||||
|
if self.page is not None:
|
||||||
|
return self.page
|
||||||
|
|
||||||
|
if not self.user_id:
|
||||||
|
raise RuntimeError("未配置 AdsPower Profile ID(ADSPOWER_USER_ID)")
|
||||||
|
|
||||||
|
if not self.is_adspower_running():
|
||||||
|
raise RuntimeError("AdsPower 软件未运行,请先打开 AdsPower")
|
||||||
|
|
||||||
|
self.start_adspower_browser()
|
||||||
|
self._playwright = sync_playwright().start()
|
||||||
|
self._browser = self._playwright.chromium.connect_over_cdp(self.cdp_url)
|
||||||
|
contexts = self._browser.contexts
|
||||||
|
self._context = contexts[0] if contexts else self._browser.new_context()
|
||||||
|
pages = self._context.pages
|
||||||
|
self.page = pages[0] if pages else self._context.new_page()
|
||||||
|
logger.info("Playwright 已连接到 AdsPower 浏览器")
|
||||||
|
return self.page
|
||||||
|
|
||||||
|
def ensure_connected(self) -> Page:
|
||||||
|
"""确保已连接,返回 page"""
|
||||||
|
if self.page is None:
|
||||||
|
return self.connect()
|
||||||
|
return self.page
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 登录状态检测
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def check_boss_login(self) -> bool:
|
||||||
|
"""
|
||||||
|
检测 Boss直聘 是否已登录。
|
||||||
|
通过访问首页并检查是否存在登录后才有的元素判断。
|
||||||
|
"""
|
||||||
|
page = self.ensure_connected()
|
||||||
|
try:
|
||||||
|
page.goto(BOSS_HOME, wait_until="domcontentloaded", timeout=30000)
|
||||||
|
page.wait_for_timeout(2000)
|
||||||
|
# 已登录:页面上会显示用户头像/用户名;未登录:会显示"登录/注册"
|
||||||
|
logged_in_indicators = [
|
||||||
|
".user-nav .user-info",
|
||||||
|
".nav-figure .user",
|
||||||
|
"[class*='avatar']",
|
||||||
|
".header-login .name",
|
||||||
|
]
|
||||||
|
for sel in logged_in_indicators:
|
||||||
|
if page.query_selector(sel):
|
||||||
|
logger.success("检测到已登录 Boss直聘")
|
||||||
|
return True
|
||||||
|
# 检查是否出现登录弹窗/登录按钮
|
||||||
|
if page.query_selector(".btn-sign-up, .login-register, [class*='login-btn']"):
|
||||||
|
return False
|
||||||
|
# 兜底:检查 cookie 中是否有登录凭证
|
||||||
|
cookies = page.context.cookies()
|
||||||
|
cookie_names = {c["name"] for c in cookies}
|
||||||
|
return "__zp_stoken__" in cookie_names or "wt2" in cookie_names
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"登录状态检测异常:{e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_boss_account_name(self) -> str | None:
|
||||||
|
"""尝试获取登录用户名"""
|
||||||
|
page = self.ensure_connected()
|
||||||
|
try:
|
||||||
|
for sel in [".user-nav .name", ".header-login .name", ".user-info .name"]:
|
||||||
|
el = page.query_selector(sel)
|
||||||
|
if el:
|
||||||
|
return el.inner_text().strip()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 关闭
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def close(self) -> None:
|
||||||
|
"""关闭 Playwright 连接(不关闭 AdsPower 浏览器,保留登录态)"""
|
||||||
|
try:
|
||||||
|
if self._playwright:
|
||||||
|
self._playwright.stop()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._playwright = None
|
||||||
|
self._browser = None
|
||||||
|
self._context = None
|
||||||
|
self.page = None
|
||||||
|
|
||||||
|
def close_all(self) -> None:
|
||||||
|
"""关闭连接并停止 AdsPower 浏览器"""
|
||||||
|
self.close()
|
||||||
|
self.stop_adspower_browser()
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""
|
||||||
|
AI 简历抓取模块
|
||||||
|
从已登录的 Boss直聘 账号中抓取所有简历,
|
||||||
|
并用 AI 整理成结构化文本后返回。
|
||||||
|
"""
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from .manager import BrowserManager, BOSS_RESUME_PAGE
|
||||||
|
|
||||||
|
|
||||||
|
class ResumeScraper:
|
||||||
|
"""抓取 Boss直聘 账号内的所有简历"""
|
||||||
|
|
||||||
|
def __init__(self, manager: BrowserManager, ai_client=None):
|
||||||
|
self.manager = manager
|
||||||
|
self.ai = ai_client
|
||||||
|
|
||||||
|
def scrape_all(self) -> list[dict]:
|
||||||
|
"""
|
||||||
|
抓取所有简历。
|
||||||
|
返回格式:[{boss_resume_id, title, position, content}, ...]
|
||||||
|
"""
|
||||||
|
page = self.manager.ensure_connected()
|
||||||
|
logger.info("正在打开 Boss直聘 简历页...")
|
||||||
|
page.goto(BOSS_RESUME_PAGE, wait_until="domcontentloaded", timeout=30000)
|
||||||
|
page.wait_for_timeout(3000)
|
||||||
|
|
||||||
|
resumes: list[dict] = []
|
||||||
|
|
||||||
|
# 尝试多种可能的简历卡片选择器(Boss直聘 页面结构可能变化)
|
||||||
|
card_selectors = [
|
||||||
|
".resume-item",
|
||||||
|
".resume-card",
|
||||||
|
"[class*='resume-list'] li",
|
||||||
|
".geek-resume-item",
|
||||||
|
]
|
||||||
|
card_els = []
|
||||||
|
for sel in card_selectors:
|
||||||
|
card_els = page.query_selector_all(sel)
|
||||||
|
if card_els:
|
||||||
|
logger.info(f"使用选择器 {sel} 找到 {len(card_els)} 份简历")
|
||||||
|
break
|
||||||
|
|
||||||
|
if not card_els:
|
||||||
|
logger.warning("未通过卡片选择器找到简历,尝试整页抓取")
|
||||||
|
return self._scrape_whole_page(page)
|
||||||
|
|
||||||
|
for i, card in enumerate(card_els):
|
||||||
|
try:
|
||||||
|
resume = self._parse_resume_card(card, i)
|
||||||
|
if resume:
|
||||||
|
resumes.append(resume)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"解析第 {i} 份简历失败:{e}")
|
||||||
|
|
||||||
|
logger.success(f"共抓取到 {len(resumes)} 份简历")
|
||||||
|
return resumes
|
||||||
|
|
||||||
|
def _parse_resume_card(self, card, index: int) -> dict | None:
|
||||||
|
"""解析单个简历卡片"""
|
||||||
|
def text(sel: str) -> str:
|
||||||
|
el = card.query_selector(sel)
|
||||||
|
return el.inner_text().strip() if el else ""
|
||||||
|
|
||||||
|
title = (
|
||||||
|
text(".resume-title") or text(".title") or
|
||||||
|
text(".name") or f"简历 {index + 1}"
|
||||||
|
)
|
||||||
|
position = text(".position") or text(".job-name") or text(".expect-position")
|
||||||
|
|
||||||
|
# 尝试点开详情获取完整内容
|
||||||
|
content = self._extract_detail_content(card) or text(".resume-content") or text("p")
|
||||||
|
|
||||||
|
# 用 AI 整理内容
|
||||||
|
if content and self.ai:
|
||||||
|
content = self.ai.clean_resume(content)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"boss_resume_id": None, # Boss直聘 前端通常不暴露,后续可从 URL 提取
|
||||||
|
"title": title,
|
||||||
|
"position": position or None,
|
||||||
|
"content": content or None,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _extract_detail_content(self, card) -> str | None:
|
||||||
|
"""尝试点击简历卡片进入详情页抓取完整内容"""
|
||||||
|
page = self.manager.page
|
||||||
|
try:
|
||||||
|
clickable = card.query_selector("a") or card
|
||||||
|
clickable.click()
|
||||||
|
page.wait_for_timeout(2000)
|
||||||
|
detail_selectors = [
|
||||||
|
".resume-detail",
|
||||||
|
".geek-resume-detail",
|
||||||
|
"[class*='resume-content']",
|
||||||
|
".resume-preview",
|
||||||
|
]
|
||||||
|
for sel in detail_selectors:
|
||||||
|
el = page.query_selector(sel)
|
||||||
|
if el:
|
||||||
|
content = el.inner_text().strip()
|
||||||
|
page.go_back()
|
||||||
|
page.wait_for_timeout(1500)
|
||||||
|
return content
|
||||||
|
page.go_back()
|
||||||
|
page.wait_for_timeout(1500)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"提取简历详情失败:{e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _scrape_whole_page(self, page) -> list[dict]:
|
||||||
|
"""兜底方案:抓取整个简历页主体文本作为一份简历"""
|
||||||
|
body_selectors = [".main-wrap", ".geek-wrap", "main", "#main"]
|
||||||
|
for sel in body_selectors:
|
||||||
|
el = page.query_selector(sel)
|
||||||
|
if el:
|
||||||
|
content = el.inner_text().strip()
|
||||||
|
if content:
|
||||||
|
content = self.ai.clean_resume(content) if self.ai else content
|
||||||
|
return [{
|
||||||
|
"boss_resume_id": None,
|
||||||
|
"title": "我的在线简历",
|
||||||
|
"position": None,
|
||||||
|
"content": content,
|
||||||
|
}]
|
||||||
|
return []
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""
|
||||||
|
客户端配置
|
||||||
|
"""
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class ClientSettings(BaseSettings):
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# 云端服务端地址
|
||||||
|
# -------------------------------------------------------
|
||||||
|
SERVER_URL: str = "http://127.0.0.1:8000"
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# 本地 Web 控制面板
|
||||||
|
# -------------------------------------------------------
|
||||||
|
WEB_HOST: str = "127.0.0.1"
|
||||||
|
WEB_PORT: int = 8088
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# AdsPower 本地 API
|
||||||
|
# -------------------------------------------------------
|
||||||
|
ADSPOWER_API_URL: str = "http://local.adspower.net:50325"
|
||||||
|
# 要使用的 AdsPower Profile ID(在 config.env 或面板中配置)
|
||||||
|
ADSPOWER_USER_ID: str = ""
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# AI 大模型(OpenAI 兼容接口)
|
||||||
|
# -------------------------------------------------------
|
||||||
|
AI_BASE_URL: str = "https://api.deepseek.com"
|
||||||
|
AI_MODEL: str = "deepseek-chat"
|
||||||
|
AI_API_KEY: str = "" # 建议通过环境变量 AI_API_KEY 注入
|
||||||
|
AI_MIN_SCORE: int = 65
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# Token 持久化路径
|
||||||
|
# -------------------------------------------------------
|
||||||
|
TOKEN_FILE: str = "client/.token"
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
env_file = "client/.env"
|
||||||
|
env_file_encoding = "utf-8"
|
||||||
|
|
||||||
|
|
||||||
|
client_settings = ClientSettings()
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""
|
||||||
|
机器硬件指纹生成
|
||||||
|
通过 MAC 地址 + 磁盘序列号 + CPU ID 生成稳定的唯一编码,
|
||||||
|
使用 SHA256 哈希,保证同一台机器每次生成结果一致。
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import platform
|
||||||
|
import subprocess
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
def _run_wmic(args: list[str]) -> str:
|
||||||
|
"""执行 wmic 命令并返回输出(仅 Windows)"""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["wmic"] + args,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=10,
|
||||||
|
encoding="utf-8",
|
||||||
|
errors="ignore",
|
||||||
|
)
|
||||||
|
return result.stdout.strip()
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def get_mac_address() -> str:
|
||||||
|
"""获取网卡 MAC 地址"""
|
||||||
|
mac = uuid.getnode()
|
||||||
|
return ":".join(
|
||||||
|
"%02x" % ((mac >> (8 * i)) & 0xFF) for i in range(5, -1, -1)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_disk_serial() -> str:
|
||||||
|
"""获取主磁盘序列号(Windows)"""
|
||||||
|
output = _run_wmic(["diskdrive", "get", "serialnumber"])
|
||||||
|
lines = [l.strip() for l in output.splitlines() if l.strip() and l.strip().lower() != "serialnumber"]
|
||||||
|
return lines[0] if lines else ""
|
||||||
|
|
||||||
|
|
||||||
|
def get_cpu_id() -> str:
|
||||||
|
"""获取 CPU ProcessorId(Windows)"""
|
||||||
|
output = _run_wmic(["cpu", "get", "processorid"])
|
||||||
|
lines = [l.strip() for l in output.splitlines() if l.strip() and l.strip().lower() != "processorid"]
|
||||||
|
return lines[0] if lines else ""
|
||||||
|
|
||||||
|
|
||||||
|
def generate_client_code() -> str:
|
||||||
|
"""
|
||||||
|
生成机器唯一编码。
|
||||||
|
组合多个硬件特征,避免单一特征缺失导致不稳定。
|
||||||
|
"""
|
||||||
|
parts = [
|
||||||
|
get_mac_address(),
|
||||||
|
get_disk_serial(),
|
||||||
|
get_cpu_id(),
|
||||||
|
platform.node(), # 计算机名作为兜底
|
||||||
|
]
|
||||||
|
raw = "|".join(parts)
|
||||||
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def get_machine_summary() -> dict:
|
||||||
|
"""返回机器基本信息(用于展示)"""
|
||||||
|
return {
|
||||||
|
"hostname": platform.node(),
|
||||||
|
"system": f"{platform.system()} {platform.release()}",
|
||||||
|
"mac": get_mac_address(),
|
||||||
|
"client_code": generate_client_code(),
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""
|
||||||
|
客户端主入口
|
||||||
|
启动本地 Web 控制面板,并在浏览器中自动打开。
|
||||||
|
运行方式:python -m client.main
|
||||||
|
"""
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import webbrowser
|
||||||
|
import uvicorn
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from .config import client_settings
|
||||||
|
from .fingerprint import get_machine_summary
|
||||||
|
|
||||||
|
|
||||||
|
def setup_logger() -> None:
|
||||||
|
logger.remove()
|
||||||
|
logger.add(
|
||||||
|
sys.stderr,
|
||||||
|
level="INFO",
|
||||||
|
format="<green>{time:HH:mm:ss}</green> | <level>{level:<7}</level> | {message}",
|
||||||
|
colorize=True,
|
||||||
|
)
|
||||||
|
logger.add(
|
||||||
|
"client/logs/client.log",
|
||||||
|
level="DEBUG",
|
||||||
|
format="{time:YYYY-MM-DD HH:mm:ss} | {level:<7} | {message}",
|
||||||
|
encoding="utf-8",
|
||||||
|
rotation="10 MB",
|
||||||
|
retention="7 days",
|
||||||
|
enqueue=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def open_browser_later(url: str, delay: float = 1.5) -> None:
|
||||||
|
def _open():
|
||||||
|
import time
|
||||||
|
time.sleep(delay)
|
||||||
|
webbrowser.open(url)
|
||||||
|
threading.Thread(target=_open, daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
setup_logger()
|
||||||
|
|
||||||
|
machine = get_machine_summary()
|
||||||
|
logger.info(f"本机:{machine['hostname']} ({machine['system']})")
|
||||||
|
logger.info(f"机器指纹:{machine['client_code']}")
|
||||||
|
logger.info(f"云端服务端地址:{client_settings.SERVER_URL}")
|
||||||
|
|
||||||
|
if not client_settings.ADSPOWER_USER_ID:
|
||||||
|
logger.warning("尚未配置 AdsPower Profile ID(ADSPOWER_USER_ID),请在 client/.env 中填写")
|
||||||
|
if not client_settings.AI_API_KEY:
|
||||||
|
logger.warning("尚未配置 AI_API_KEY,AI 评分功能将不可用")
|
||||||
|
|
||||||
|
host = client_settings.WEB_HOST
|
||||||
|
port = client_settings.WEB_PORT
|
||||||
|
url = f"http://{host}:{port}"
|
||||||
|
|
||||||
|
logger.success(f"控制面板地址:{url}")
|
||||||
|
open_browser_later(url)
|
||||||
|
|
||||||
|
# 启动本地 Web 服务
|
||||||
|
uvicorn.run(
|
||||||
|
"client.web.app:app",
|
||||||
|
host=host,
|
||||||
|
port=port,
|
||||||
|
log_level="warning",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# 客户端依赖
|
||||||
|
fastapi>=0.111.0
|
||||||
|
uvicorn[standard]>=0.30.0
|
||||||
|
jinja2>=3.1.0
|
||||||
|
requests>=2.31.0
|
||||||
|
playwright>=1.44.0
|
||||||
|
openai>=1.30.0
|
||||||
|
pydantic>=2.7.0
|
||||||
|
pydantic-settings>=2.3.0
|
||||||
|
loguru>=0.7.2
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
"""
|
||||||
|
客户端 → 云端服务端 API 封装
|
||||||
|
统一管理 token 持久化与请求头
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import requests
|
||||||
|
from loguru import logger
|
||||||
|
|
||||||
|
from .config import client_settings
|
||||||
|
from .fingerprint import generate_client_code
|
||||||
|
|
||||||
|
|
||||||
|
class ServerAPI:
|
||||||
|
"""调用云端 FastAPI 服务端"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.base_url = client_settings.SERVER_URL.rstrip("/")
|
||||||
|
self.token: str | None = None
|
||||||
|
self.user_id: int | None = None
|
||||||
|
self._load_token()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Token 持久化
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _token_path(self) -> str:
|
||||||
|
path = client_settings.TOKEN_FILE
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def _load_token(self) -> None:
|
||||||
|
path = self._token_path()
|
||||||
|
if os.path.exists(path):
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
|
lines = f.read().strip().splitlines()
|
||||||
|
if lines:
|
||||||
|
self.token = lines[0]
|
||||||
|
self.user_id = int(lines[1]) if len(lines) > 1 else None
|
||||||
|
logger.info("已加载本地 token")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"读取 token 失败:{e}")
|
||||||
|
|
||||||
|
def _save_token(self) -> None:
|
||||||
|
with open(self._token_path(), "w", encoding="utf-8") as f:
|
||||||
|
f.write(f"{self.token}\n{self.user_id}")
|
||||||
|
|
||||||
|
def _headers(self) -> dict:
|
||||||
|
return {"Authorization": f"Bearer {self.token}"} if self.token else {}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 认证
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def register(self, nickname: str | None = None) -> dict:
|
||||||
|
"""用机器指纹注册/登录,返回 token"""
|
||||||
|
client_code = generate_client_code()
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/auth/register",
|
||||||
|
json={"client_code": client_code, "nickname": nickname},
|
||||||
|
timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
self.token = data["token"]
|
||||||
|
self.user_id = data["user_id"]
|
||||||
|
self._save_token()
|
||||||
|
logger.info(f"注册/登录成功,user_id={self.user_id},新用户={data.get('is_new')}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
def get_me(self) -> dict:
|
||||||
|
resp = requests.get(f"{self.base_url}/api/auth/me", headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def update_login_status(self, status: str, boss_account: str | None = None) -> dict:
|
||||||
|
payload = {"login_status": status}
|
||||||
|
if boss_account:
|
||||||
|
payload["boss_account"] = boss_account
|
||||||
|
resp = requests.put(
|
||||||
|
f"{self.base_url}/api/auth/login-status",
|
||||||
|
json=payload, headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 简历
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def upload_resumes(self, resumes: list[dict]) -> list[dict]:
|
||||||
|
"""批量上传简历"""
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/resumes/batch",
|
||||||
|
json={"resumes": resumes}, headers=self._headers(), timeout=30,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def list_resumes(self) -> list[dict]:
|
||||||
|
resp = requests.get(f"{self.base_url}/api/resumes", headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def get_primary_resume(self) -> dict | None:
|
||||||
|
resp = requests.get(f"{self.base_url}/api/resumes/primary", headers=self._headers(), timeout=15)
|
||||||
|
if resp.status_code == 404:
|
||||||
|
return None
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def set_primary_resume(self, resume_id: int) -> dict:
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/resumes/{resume_id}/set-primary",
|
||||||
|
headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 投递会话
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def start_session(self, keywords: str, city_code: str,
|
||||||
|
salary_min: int | None, salary_max: int | None) -> dict:
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/sessions/start",
|
||||||
|
json={
|
||||||
|
"keywords": keywords,
|
||||||
|
"city_code": city_code,
|
||||||
|
"salary_min": salary_min,
|
||||||
|
"salary_max": salary_max,
|
||||||
|
},
|
||||||
|
headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def stop_session(self, session_id: int) -> dict:
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/sessions/{session_id}/stop",
|
||||||
|
headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def update_session_stats(self, session_id: int, applied_delta: int, skipped_delta: int) -> dict:
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/sessions/{session_id}/stats",
|
||||||
|
json={"applied_delta": applied_delta, "skipped_delta": skipped_delta},
|
||||||
|
headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 投递记录
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def report_application(self, session_id: int | None, data: dict) -> dict:
|
||||||
|
params = {"session_id": session_id} if session_id else {}
|
||||||
|
resp = requests.post(
|
||||||
|
f"{self.base_url}/api/jobs/report",
|
||||||
|
json=data, params=params, headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def check_applied(self, job_id: str) -> bool:
|
||||||
|
resp = requests.get(
|
||||||
|
f"{self.base_url}/api/jobs/check/{job_id}",
|
||||||
|
headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json().get("applied", False)
|
||||||
|
|
||||||
|
def get_stats(self) -> dict:
|
||||||
|
resp = requests.get(f"{self.base_url}/api/jobs/stats", headers=self._headers(), timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
def get_history(self, limit: int = 50, apply_type: str | None = None) -> list[dict]:
|
||||||
|
params = {"limit": limit}
|
||||||
|
if apply_type:
|
||||||
|
params["apply_type"] = apply_type
|
||||||
|
resp = requests.get(
|
||||||
|
f"{self.base_url}/api/jobs/history",
|
||||||
|
params=params, headers=self._headers(), timeout=15,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# 连通性
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def ping(self) -> bool:
|
||||||
|
try:
|
||||||
|
resp = requests.get(f"{self.base_url}/", timeout=5)
|
||||||
|
return resp.status_code == 200
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Web 控制面板包"""
|
||||||
@@ -0,0 +1,273 @@
|
|||||||
|
"""
|
||||||
|
本地 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()
|
||||||
@@ -0,0 +1,310 @@
|
|||||||
|
// ==========================================================
|
||||||
|
// Boss直聘 AI 投递 - 控制面板前端逻辑
|
||||||
|
// ==========================================================
|
||||||
|
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
let currentStep = 1;
|
||||||
|
let loginPollTimer = null;
|
||||||
|
let applyPollTimer = null;
|
||||||
|
|
||||||
|
// ---------- Toast ----------
|
||||||
|
function toast(msg, ms = 3000) {
|
||||||
|
const t = $('toast');
|
||||||
|
t.textContent = msg;
|
||||||
|
t.classList.add('show');
|
||||||
|
setTimeout(() => t.classList.remove('show'), ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 步骤切换 ----------
|
||||||
|
function goToStep(step) {
|
||||||
|
currentStep = step;
|
||||||
|
document.querySelectorAll('.step').forEach(el => {
|
||||||
|
el.classList.toggle('active', parseInt(el.dataset.step) === step);
|
||||||
|
});
|
||||||
|
for (let i = 1; i <= 5; i++) {
|
||||||
|
$(`panel-${i}`).classList.toggle('hidden', i !== step);
|
||||||
|
}
|
||||||
|
if (step === 5) loadHistory();
|
||||||
|
if (step === 3) loadResumes();
|
||||||
|
}
|
||||||
|
document.querySelectorAll('.step').forEach(el => {
|
||||||
|
el.addEventListener('click', () => goToStep(parseInt(el.dataset.step)));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- 通用请求 ----------
|
||||||
|
async function api(path, options = {}) {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(err.detail || `请求失败 ${res.status}`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 徽章工具 ----------
|
||||||
|
function badge(text, cls) {
|
||||||
|
return `<span class="badge ${cls || ''}">${text}</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 初始化状态 ----------
|
||||||
|
async function refreshStatus() {
|
||||||
|
try {
|
||||||
|
const s = await api('/api/status');
|
||||||
|
$('clientCode').textContent = s.client_code;
|
||||||
|
$('serverReachable').innerHTML = badge(
|
||||||
|
s.server_reachable ? '可连接' : '无法连接',
|
||||||
|
s.server_reachable ? 'ok' : 'err'
|
||||||
|
);
|
||||||
|
$('adspowerStatus').innerHTML = badge(
|
||||||
|
s.adspower_running ? '运行中' : '未运行',
|
||||||
|
s.adspower_running ? 'ok' : 'warn'
|
||||||
|
);
|
||||||
|
// 顶部徽章
|
||||||
|
$('statusBadges').innerHTML =
|
||||||
|
badge(s.server_connected ? '已连接' : '未连接', s.server_connected ? 'ok' : '') +
|
||||||
|
badge(s.ai_configured ? 'AI已配置' : 'AI未配置', s.ai_configured ? 'ok' : 'warn');
|
||||||
|
|
||||||
|
if (s.server_connected) {
|
||||||
|
updateLoginBadge(s.login_status, s.boss_account);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLoginBadge(status, account) {
|
||||||
|
const el = $('loginStatus');
|
||||||
|
if (status === 'logged_in') {
|
||||||
|
el.innerHTML = badge(`已登录 ${escapeHtml(account || '')}`, 'ok');
|
||||||
|
} else if (status === 'logging_in') {
|
||||||
|
el.innerHTML = badge('登录中...', 'warn');
|
||||||
|
} else {
|
||||||
|
el.innerHTML = badge('未登录', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================
|
||||||
|
// Step 1: 连接服务端
|
||||||
|
// ==========================================================
|
||||||
|
$('btnConnect').addEventListener('click', async () => {
|
||||||
|
const btn = $('btnConnect');
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const data = await api('/api/connect', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ nickname: $('nickname').value || null }),
|
||||||
|
});
|
||||||
|
toast(data.is_new ? '注册成功!' : '登录成功!');
|
||||||
|
await refreshStatus();
|
||||||
|
goToStep(2);
|
||||||
|
} catch (e) {
|
||||||
|
toast('连接失败:' + e.message, 5000);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ==========================================================
|
||||||
|
// Step 2: 登录 Boss直聘
|
||||||
|
// ==========================================================
|
||||||
|
$('btnStartLogin').addEventListener('click', async () => {
|
||||||
|
const btn = $('btnStartLogin');
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
await api('/api/start-login', { method: 'POST' });
|
||||||
|
toast('浏览器已打开,请在 AdsPower 浏览器中完成登录');
|
||||||
|
$('loginSpinner').classList.remove('hidden');
|
||||||
|
startLoginPoll();
|
||||||
|
} catch (e) {
|
||||||
|
toast('打开浏览器失败:' + e.message, 5000);
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
function startLoginPoll() {
|
||||||
|
if (loginPollTimer) clearInterval(loginPollTimer);
|
||||||
|
loginPollTimer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const r = await api('/api/login-status');
|
||||||
|
updateLoginBadge(r.status, r.boss_account);
|
||||||
|
if (r.status === 'logged_in') {
|
||||||
|
clearInterval(loginPollTimer);
|
||||||
|
$('loginSpinner').classList.add('hidden');
|
||||||
|
$('btnStartLogin').disabled = false;
|
||||||
|
toast('登录成功!即将进入简历步骤');
|
||||||
|
setTimeout(() => goToStep(3), 1200);
|
||||||
|
}
|
||||||
|
} catch (e) { /* 忽略 */ }
|
||||||
|
}, 2500);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================
|
||||||
|
// Step 3: 抓取简历
|
||||||
|
// ==========================================================
|
||||||
|
$('btnScrape').addEventListener('click', async () => {
|
||||||
|
const btn = $('btnScrape');
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = '正在抓取...';
|
||||||
|
try {
|
||||||
|
const data = await api('/api/scrape-resumes', { method: 'POST' });
|
||||||
|
toast(`抓取到 ${data.count} 份简历`);
|
||||||
|
loadResumes();
|
||||||
|
} catch (e) {
|
||||||
|
toast('抓取失败:' + e.message, 5000);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '开始抓取简历';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function loadResumes() {
|
||||||
|
try {
|
||||||
|
const resumes = await api('/api/resumes');
|
||||||
|
const list = $('resumeList');
|
||||||
|
if (!resumes.length) {
|
||||||
|
list.innerHTML = '<p class="hint">暂无简历,请先抓取。</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
list.innerHTML = resumes.map(r => `
|
||||||
|
<div class="resume-item ${r.is_primary ? 'primary' : ''}" data-id="${r.id}">
|
||||||
|
<div class="radio"></div>
|
||||||
|
<div>
|
||||||
|
<div class="r-title">${escapeHtml(r.title)}</div>
|
||||||
|
<div class="r-pos">${escapeHtml(r.position || '未设置求职意向')}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
list.querySelectorAll('.resume-item').forEach(el => {
|
||||||
|
el.addEventListener('click', () => setPrimary(parseInt(el.dataset.id)));
|
||||||
|
});
|
||||||
|
} catch (e) { console.error(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setPrimary(id) {
|
||||||
|
try {
|
||||||
|
await api(`/api/resumes/${id}/primary`, { method: 'POST' });
|
||||||
|
toast('已设为主简历');
|
||||||
|
loadResumes();
|
||||||
|
// 允许进入下一步
|
||||||
|
setTimeout(() => { if (currentStep === 3) goToStep(4); }, 600);
|
||||||
|
} catch (e) {
|
||||||
|
toast('设置失败:' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================
|
||||||
|
// Step 4: 开始 / 结束投递
|
||||||
|
// ==========================================================
|
||||||
|
$('btnStartApply').addEventListener('click', async () => {
|
||||||
|
const keywords = $('keywords').value.split(',').map(k => k.trim()).filter(Boolean);
|
||||||
|
if (!keywords.length) { toast('请填写搜索关键词'); return; }
|
||||||
|
|
||||||
|
const btn = $('btnStartApply');
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
await api('/api/start-apply', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({
|
||||||
|
keywords,
|
||||||
|
city_code: $('cityCode').value,
|
||||||
|
salary_min: parseInt($('salaryMin').value) || null,
|
||||||
|
salary_max: parseInt($('salaryMax').value) || null,
|
||||||
|
greeting: $('greeting').value,
|
||||||
|
min_score: parseInt($('minScore').value) || 65,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
toast('投递任务已启动');
|
||||||
|
toggleApplyUI(true);
|
||||||
|
startApplyPoll();
|
||||||
|
} catch (e) {
|
||||||
|
toast('启动失败:' + e.message, 5000);
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('btnStopApply').addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
const r = await api('/api/stop-apply', { method: 'POST' });
|
||||||
|
toast(r.msg);
|
||||||
|
} catch (e) { toast('停止失败:' + e.message); }
|
||||||
|
});
|
||||||
|
|
||||||
|
function toggleApplyUI(running) {
|
||||||
|
$('btnStartApply').classList.toggle('hidden', running);
|
||||||
|
$('btnStopApply').classList.toggle('hidden', !running);
|
||||||
|
$('progressBox').classList.toggle('hidden', !running);
|
||||||
|
$('btnStartApply').disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startApplyPoll() {
|
||||||
|
if (applyPollTimer) clearInterval(applyPollTimer);
|
||||||
|
applyPollTimer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const r = await api('/api/apply-status');
|
||||||
|
if (r.stats) {
|
||||||
|
$('progressCurrent').textContent = r.stats.current || '';
|
||||||
|
$('statApplied').textContent = r.stats.applied || 0;
|
||||||
|
$('statSkipped').textContent = r.stats.skipped || 0;
|
||||||
|
}
|
||||||
|
if (!r.running) {
|
||||||
|
clearInterval(applyPollTimer);
|
||||||
|
toggleApplyUI(false);
|
||||||
|
toast('投递任务已结束');
|
||||||
|
}
|
||||||
|
} catch (e) { /* 忽略 */ }
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==========================================================
|
||||||
|
// Step 5: 历史与统计
|
||||||
|
// ==========================================================
|
||||||
|
async function loadHistory() {
|
||||||
|
try {
|
||||||
|
const [stats, history] = await Promise.all([
|
||||||
|
api('/api/stats'),
|
||||||
|
api('/api/history?limit=50'),
|
||||||
|
]);
|
||||||
|
$('statsGrid').innerHTML = `
|
||||||
|
<div class="stat-card"><div class="num">${stats.total_applied || 0}</div><div class="label">累计投递</div></div>
|
||||||
|
<div class="stat-card"><div class="num">${stats.total_chat || 0}</div><div class="label">立即沟通</div></div>
|
||||||
|
<div class="stat-card"><div class="num">${stats.total_deliver || 0}</div><div class="label">投递简历</div></div>
|
||||||
|
<div class="stat-card"><div class="num">${stats.today_applied || 0}</div><div class="label">今日投递</div></div>
|
||||||
|
`;
|
||||||
|
$('historyBody').innerHTML = history.map(h => `
|
||||||
|
<tr>
|
||||||
|
<td>${escapeHtml(h.job_title || '-')}</td>
|
||||||
|
<td>${escapeHtml(h.company || '-')}</td>
|
||||||
|
<td>${escapeHtml(h.salary || '-')}</td>
|
||||||
|
<td><span class="tag ${safeType(h.apply_type)}">${typeLabel(h.apply_type)}</span></td>
|
||||||
|
<td>${h.ai_score >= 0 ? h.ai_score : '-'}</td>
|
||||||
|
<td>${formatTime(h.applied_at)}</td>
|
||||||
|
</tr>
|
||||||
|
`).join('') || '<tr><td colspan="6" style="text-align:center;color:#999">暂无记录</td></tr>';
|
||||||
|
} catch (e) { console.error(e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function typeLabel(t) {
|
||||||
|
return { chat: '沟通', deliver: '投递', skipped: '跳过' }[t] || t;
|
||||||
|
}
|
||||||
|
// apply_type 仅允许白名单值用作 CSS class,防止注入
|
||||||
|
function safeType(t) {
|
||||||
|
return ['chat', 'deliver', 'skipped'].includes(t) ? t : 'skipped';
|
||||||
|
}
|
||||||
|
function formatTime(s) {
|
||||||
|
if (!s) return '-';
|
||||||
|
return s.replace('T', ' ').substring(0, 16);
|
||||||
|
}
|
||||||
|
function escapeHtml(s) {
|
||||||
|
if (!s) return '';
|
||||||
|
return s.replace(/[&<>"']/g, c => ({
|
||||||
|
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
|
||||||
|
}[c]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 启动 ----------
|
||||||
|
refreshStatus();
|
||||||
|
setInterval(refreshStatus, 8000);
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--primary: #2f6fed;
|
||||||
|
--primary-dark: #1e56c8;
|
||||||
|
--success: #16a34a;
|
||||||
|
--danger: #dc2626;
|
||||||
|
--warning: #d97706;
|
||||||
|
--bg: #f4f6fa;
|
||||||
|
--card: #ffffff;
|
||||||
|
--text: #1f2937;
|
||||||
|
--text-light: #6b7280;
|
||||||
|
--border: #e5e7eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
max-width: 860px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 24px 16px 60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 顶部 ===== */
|
||||||
|
.header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.header h1 { font-size: 22px; }
|
||||||
|
.status-badges { display: flex; gap: 8px; }
|
||||||
|
|
||||||
|
/* ===== 步骤导航 ===== */
|
||||||
|
.steps {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.step {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 100px;
|
||||||
|
text-align: center;
|
||||||
|
padding: 10px 8px;
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
color: var(--text-light);
|
||||||
|
transition: all .2s;
|
||||||
|
}
|
||||||
|
.step.active {
|
||||||
|
background: var(--primary);
|
||||||
|
color: #fff;
|
||||||
|
border-color: var(--primary);
|
||||||
|
}
|
||||||
|
.step-num {
|
||||||
|
display: inline-block;
|
||||||
|
width: 20px; height: 20px;
|
||||||
|
line-height: 20px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: rgba(0,0,0,.08);
|
||||||
|
margin-right: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.step.active .step-num { background: rgba(255,255,255,.25); }
|
||||||
|
|
||||||
|
/* ===== 面板 ===== */
|
||||||
|
.panel {
|
||||||
|
background: var(--card);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 28px;
|
||||||
|
box-shadow: 0 1px 4px rgba(0,0,0,.06);
|
||||||
|
}
|
||||||
|
.panel h2 { font-size: 19px; margin-bottom: 8px; }
|
||||||
|
.panel .hint { color: var(--text-light); font-size: 14px; margin-bottom: 18px; }
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
|
||||||
|
.info-box {
|
||||||
|
background: var(--bg);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 2;
|
||||||
|
}
|
||||||
|
.info-box code {
|
||||||
|
background: #eef2ff;
|
||||||
|
padding: 2px 6px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 徽章 ===== */
|
||||||
|
.badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border-radius: 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
background: var(--border);
|
||||||
|
color: var(--text-light);
|
||||||
|
}
|
||||||
|
.badge.ok { background: #dcfce7; color: var(--success); }
|
||||||
|
.badge.warn { background: #fef3c7; color: var(--warning); }
|
||||||
|
.badge.err { background: #fee2e2; color: var(--danger); }
|
||||||
|
|
||||||
|
/* ===== 表单 ===== */
|
||||||
|
.form-group { margin-bottom: 16px; }
|
||||||
|
.form-row { display: flex; gap: 14px; }
|
||||||
|
.form-row .form-group { flex: 1; }
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-light);
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
.form-group input,
|
||||||
|
.form-group select,
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-family: inherit;
|
||||||
|
}
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group select:focus,
|
||||||
|
.form-group textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ===== 按钮 ===== */
|
||||||
|
.btn {
|
||||||
|
padding: 11px 22px;
|
||||||
|
border: none;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 15px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all .2s;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.btn-primary { background: var(--primary); color: #fff; }
|
||||||
|
.btn-primary:hover { background: var(--primary-dark); }
|
||||||
|
.btn-success { background: var(--success); color: #fff; }
|
||||||
|
.btn-success:hover { filter: brightness(1.1); }
|
||||||
|
.btn-danger { background: var(--danger); color: #fff; }
|
||||||
|
.btn-danger:hover { filter: brightness(1.1); }
|
||||||
|
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
|
.action-buttons { display: flex; gap: 12px; margin-top: 10px; }
|
||||||
|
|
||||||
|
/* ===== 加载 ===== */
|
||||||
|
.spinner {
|
||||||
|
margin-top: 16px;
|
||||||
|
color: var(--primary);
|
||||||
|
font-size: 14px;
|
||||||
|
animation: pulse 1.5s infinite;
|
||||||
|
}
|
||||||
|
@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.5} }
|
||||||
|
|
||||||
|
/* ===== 简历列表 ===== */
|
||||||
|
.resume-list { margin-top: 18px; }
|
||||||
|
.resume-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 14px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all .2s;
|
||||||
|
}
|
||||||
|
.resume-item:hover { border-color: var(--primary); }
|
||||||
|
.resume-item.primary {
|
||||||
|
border-color: var(--success);
|
||||||
|
background: #f0fdf4;
|
||||||
|
}
|
||||||
|
.resume-item .radio {
|
||||||
|
width: 18px; height: 18px;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--border);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.resume-item.primary .radio {
|
||||||
|
border-color: var(--success);
|
||||||
|
background: var(--success);
|
||||||
|
}
|
||||||
|
.resume-item .r-title { font-weight: 600; }
|
||||||
|
.resume-item .r-pos { font-size: 13px; color: var(--text-light); }
|
||||||
|
|
||||||
|
/* ===== 进度 ===== */
|
||||||
|
.progress-box {
|
||||||
|
margin-top: 18px;
|
||||||
|
padding: 16px;
|
||||||
|
background: var(--bg);
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
.progress-current { font-size: 14px; margin-bottom: 10px; color: var(--primary); }
|
||||||
|
.progress-stats { display: flex; gap: 24px; font-size: 14px; }
|
||||||
|
|
||||||
|
/* ===== 统计网格 ===== */
|
||||||
|
.stats-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.stat-card {
|
||||||
|
background: var(--bg);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.stat-card .num { font-size: 26px; font-weight: 700; color: var(--primary); }
|
||||||
|
.stat-card .label { font-size: 13px; color: var(--text-light); margin-top: 4px; }
|
||||||
|
|
||||||
|
/* ===== 历史表格 ===== */
|
||||||
|
.history-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||||
|
.history-table th, .history-table td {
|
||||||
|
padding: 10px 8px;
|
||||||
|
text-align: left;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.history-table th { color: var(--text-light); font-weight: 600; }
|
||||||
|
.history-table td .tag {
|
||||||
|
padding: 2px 8px; border-radius: 10px; font-size: 12px;
|
||||||
|
}
|
||||||
|
.tag.chat { background: #dcfce7; color: var(--success); }
|
||||||
|
.tag.deliver { background: #dbeafe; color: var(--primary); }
|
||||||
|
.tag.skipped { background: #f3f4f6; color: var(--text-light); }
|
||||||
|
|
||||||
|
/* ===== Toast ===== */
|
||||||
|
.toast {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 24px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%) translateY(80px);
|
||||||
|
background: #1f2937;
|
||||||
|
color: #fff;
|
||||||
|
padding: 12px 22px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
opacity: 0;
|
||||||
|
transition: all .3s;
|
||||||
|
z-index: 999;
|
||||||
|
max-width: 80%;
|
||||||
|
}
|
||||||
|
.toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Boss直聘 AI 智能投递</title>
|
||||||
|
<link rel="stylesheet" href="/static/style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="container">
|
||||||
|
<!-- 顶部标题栏 -->
|
||||||
|
<header class="header">
|
||||||
|
<h1>🎯 Boss直聘 AI 智能投递</h1>
|
||||||
|
<div class="status-badges" id="statusBadges"></div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- 步骤导航 -->
|
||||||
|
<nav class="steps">
|
||||||
|
<div class="step active" data-step="1"><span class="step-num">1</span> 连接</div>
|
||||||
|
<div class="step" data-step="2"><span class="step-num">2</span> 登录</div>
|
||||||
|
<div class="step" data-step="3"><span class="step-num">3</span> 简历</div>
|
||||||
|
<div class="step" data-step="4"><span class="step-num">4</span> 投递</div>
|
||||||
|
<div class="step" data-step="5"><span class="step-num">5</span> 记录</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<!-- Step 1: 连接服务端 -->
|
||||||
|
<section class="panel" id="panel-1">
|
||||||
|
<h2>连接云端服务端</h2>
|
||||||
|
<p class="hint">使用本机硬件指纹作为唯一编码注册,数据将隔离存储在你的账号下。</p>
|
||||||
|
<div class="info-box">
|
||||||
|
<div><strong>机器指纹:</strong><code id="clientCode">加载中...</code></div>
|
||||||
|
<div><strong>服务端状态:</strong><span id="serverReachable" class="badge">检测中</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>昵称(可选)</label>
|
||||||
|
<input type="text" id="nickname" placeholder="给自己起个名字">
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary" id="btnConnect">连接并注册</button>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Step 2: 登录 Boss直聘 -->
|
||||||
|
<section class="panel hidden" id="panel-2">
|
||||||
|
<h2>登录 Boss直聘</h2>
|
||||||
|
<p class="hint">点击下方按钮,将通过 AdsPower 指纹浏览器打开 Boss直聘,请在弹出的浏览器窗口中手动完成登录(扫码或账号密码)。</p>
|
||||||
|
<div class="info-box">
|
||||||
|
<div><strong>AdsPower 状态:</strong><span id="adspowerStatus" class="badge">检测中</span></div>
|
||||||
|
<div><strong>登录状态:</strong><span id="loginStatus" class="badge">未登录</span></div>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary" id="btnStartLogin">打开浏览器登录</button>
|
||||||
|
<div class="spinner hidden" id="loginSpinner">正在等待登录,请在浏览器中完成操作...</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Step 3: 简历管理 -->
|
||||||
|
<section class="panel hidden" id="panel-3">
|
||||||
|
<h2>抓取并选择主简历</h2>
|
||||||
|
<p class="hint">AI 将自动抓取你 Boss直聘 账号内的所有简历,请勾选一份作为主简历用于 JD 匹配。</p>
|
||||||
|
<button class="btn btn-primary" id="btnScrape">开始抓取简历</button>
|
||||||
|
<div class="resume-list" id="resumeList"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Step 4: 配置投递 -->
|
||||||
|
<section class="panel hidden" id="panel-4">
|
||||||
|
<h2>配置并开始投递</h2>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>搜索关键词(多个用逗号分隔)</label>
|
||||||
|
<input type="text" id="keywords" placeholder="如:Python开发,后端工程师" value="Python开发">
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>城市</label>
|
||||||
|
<select id="cityCode">
|
||||||
|
<option value="101010100">北京</option>
|
||||||
|
<option value="101020100">上海</option>
|
||||||
|
<option value="101280100">广州</option>
|
||||||
|
<option value="101280600">深圳</option>
|
||||||
|
<option value="101210100">杭州</option>
|
||||||
|
<option value="101190100">成都</option>
|
||||||
|
<option value="101110100">西安</option>
|
||||||
|
<option value="101120100">济南</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>AI 最低匹配分</label>
|
||||||
|
<input type="number" id="minScore" value="65" min="0" max="100">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<div class="form-group">
|
||||||
|
<label>最低薪资 (K)</label>
|
||||||
|
<input type="number" id="salaryMin" value="15" min="0">
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>最高薪资 (K)</label>
|
||||||
|
<input type="number" id="salaryMax" value="40" min="0">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="form-group">
|
||||||
|
<label>打招呼语(留空使用默认)</label>
|
||||||
|
<textarea id="greeting" rows="2" placeholder="您好,我对贵司岗位很感兴趣..."></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="action-buttons">
|
||||||
|
<button class="btn btn-success" id="btnStartApply">▶ 开始投递</button>
|
||||||
|
<button class="btn btn-danger hidden" id="btnStopApply">■ 结束投递</button>
|
||||||
|
</div>
|
||||||
|
<div class="progress-box hidden" id="progressBox">
|
||||||
|
<div class="progress-current" id="progressCurrent">准备中...</div>
|
||||||
|
<div class="progress-stats">
|
||||||
|
<span>已投递:<strong id="statApplied">0</strong></span>
|
||||||
|
<span>已跳过:<strong id="statSkipped">0</strong></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Step 5: 投递记录 -->
|
||||||
|
<section class="panel hidden" id="panel-5">
|
||||||
|
<h2>投递记录与统计</h2>
|
||||||
|
<div class="stats-grid" id="statsGrid"></div>
|
||||||
|
<table class="history-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>职位</th><th>公司</th><th>薪资</th><th>方式</th><th>AI评分</th><th>时间</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="historyBody"></tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Toast 提示 -->
|
||||||
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
<script src="/static/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# ============ 服务端环境变量示例 ============
|
||||||
|
# 复制本文件为 .env 并填写真实值:.env
|
||||||
|
|
||||||
|
# MySQL 数据库配置
|
||||||
|
DB_HOST=127.0.0.1
|
||||||
|
DB_PORT=3306
|
||||||
|
DB_USER=root
|
||||||
|
DB_PASSWORD=
|
||||||
|
DB_NAME=jianli_boss
|
||||||
|
|
||||||
|
# JWT 密钥(生产环境务必改成随机长字符串)
|
||||||
|
SECRET_KEY=please-change-this-to-a-long-random-string
|
||||||
|
|
||||||
|
# Token 有效期(天)
|
||||||
|
ACCESS_TOKEN_EXPIRE_DAYS=30
|
||||||
|
|
||||||
|
# 调试模式
|
||||||
|
DEBUG=false
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""服务端包"""
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""
|
||||||
|
JWT 认证工具
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
from .database import get_db
|
||||||
|
from .models import User
|
||||||
|
|
||||||
|
# 使用 HTTP Bearer Token 认证
|
||||||
|
bearer_scheme = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(user_id: int, client_code: str) -> str:
|
||||||
|
"""生成 JWT token"""
|
||||||
|
expire = datetime.utcnow() + timedelta(days=settings.ACCESS_TOKEN_EXPIRE_DAYS)
|
||||||
|
payload = {
|
||||||
|
"sub": str(user_id),
|
||||||
|
"client_code": client_code,
|
||||||
|
"exp": expire,
|
||||||
|
}
|
||||||
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_token(token: str) -> Optional[dict]:
|
||||||
|
"""解码 token,失败返回 None"""
|
||||||
|
try:
|
||||||
|
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
||||||
|
except JWTError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user(
|
||||||
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
) -> User:
|
||||||
|
"""
|
||||||
|
FastAPI 依赖:从请求头解析 token 并返回当前用户。
|
||||||
|
未认证时抛出 401。
|
||||||
|
"""
|
||||||
|
if credentials is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="缺少认证 token",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
payload = decode_token(credentials.credentials)
|
||||||
|
if payload is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="token 无效或已过期",
|
||||||
|
)
|
||||||
|
user_id = int(payload.get("sub", 0))
|
||||||
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if user is None or not user.is_active:
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在或已禁用")
|
||||||
|
return user
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""
|
||||||
|
服务端配置文件
|
||||||
|
使用环境变量或 .env 文件加载敏感配置
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# 应用
|
||||||
|
# -------------------------------------------------------
|
||||||
|
APP_NAME: str = "Boss直聘投递服务端"
|
||||||
|
APP_VERSION: str = "1.0.0"
|
||||||
|
DEBUG: bool = False
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# 数据库(MySQL)
|
||||||
|
# -------------------------------------------------------
|
||||||
|
DB_HOST: str = "127.0.0.1"
|
||||||
|
DB_PORT: int = 3306
|
||||||
|
DB_USER: str = "root"
|
||||||
|
DB_PASSWORD: str = ""
|
||||||
|
DB_NAME: str = "jianli_boss"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def DATABASE_URL(self) -> str:
|
||||||
|
return (
|
||||||
|
f"mysql+pymysql://{self.DB_USER}:{self.DB_PASSWORD}"
|
||||||
|
f"@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
|
||||||
|
f"?charset=utf8mb4"
|
||||||
|
)
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# JWT 认证
|
||||||
|
# -------------------------------------------------------
|
||||||
|
SECRET_KEY: str = "change-this-to-a-random-secret-key-in-production"
|
||||||
|
JWT_ALGORITHM: str = "HS256"
|
||||||
|
# Token 有效期(天)
|
||||||
|
ACCESS_TOKEN_EXPIRE_DAYS: int = 30
|
||||||
|
|
||||||
|
# -------------------------------------------------------
|
||||||
|
# CORS(允许客户端 Web 面板访问)
|
||||||
|
# -------------------------------------------------------
|
||||||
|
CORS_ORIGINS: list[str] = ["*"]
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
env_file = ".env"
|
||||||
|
env_file_encoding = "utf-8"
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""
|
||||||
|
MySQL 数据库连接与 SQLAlchemy 引擎初始化
|
||||||
|
"""
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
|
||||||
|
# 连接池配置:避免频繁创建连接
|
||||||
|
engine = create_engine(
|
||||||
|
settings.DATABASE_URL,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
pool_recycle=3600,
|
||||||
|
pool_size=10,
|
||||||
|
max_overflow=20,
|
||||||
|
echo=settings.DEBUG,
|
||||||
|
connect_args={"charset": "utf8mb4"},
|
||||||
|
)
|
||||||
|
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
# 所有 ORM 模型的基类
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
"""FastAPI 依赖注入:获取数据库会话"""
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def init_db() -> None:
|
||||||
|
"""创建所有表(生产环境建议改用 Alembic 迁移)"""
|
||||||
|
from . import models # noqa: F401 确保模型被导入
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""
|
||||||
|
服务端主入口
|
||||||
|
运行方式:uvicorn server.main:app --host 0.0.0.0 --port 8000 --reload
|
||||||
|
"""
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from .config import settings
|
||||||
|
from .database import init_db
|
||||||
|
from .routers import register, resumes, sessions, jobs
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app: FastAPI):
|
||||||
|
# 启动时建表
|
||||||
|
init_db()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.APP_NAME,
|
||||||
|
version=settings.APP_VERSION,
|
||||||
|
lifespan=lifespan,
|
||||||
|
)
|
||||||
|
|
||||||
|
# CORS:允许客户端 Web 面板跨域访问
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.CORS_ORIGINS,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 注册路由
|
||||||
|
app.include_router(register.router)
|
||||||
|
app.include_router(resumes.router)
|
||||||
|
app.include_router(sessions.router)
|
||||||
|
app.include_router(jobs.router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/", tags=["健康检查"])
|
||||||
|
def health_check():
|
||||||
|
return {
|
||||||
|
"name": settings.APP_NAME,
|
||||||
|
"version": settings.APP_VERSION,
|
||||||
|
"status": "ok",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
uvicorn.run("server.main:app", host="0.0.0.0", port=8000, reload=True)
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""
|
||||||
|
SQLAlchemy ORM 模型定义
|
||||||
|
所有业务表均带 user_id 外键,实现用户数据隔离
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import (
|
||||||
|
Column, Integer, BigInteger, String, Text, Boolean,
|
||||||
|
DateTime, Float, ForeignKey, Index, UniqueConstraint,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from .database import Base
|
||||||
|
|
||||||
|
|
||||||
|
def utcnow() -> datetime:
|
||||||
|
return datetime.utcnow()
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
"""
|
||||||
|
客户端用户
|
||||||
|
以机器硬件指纹(client_code)作为唯一标识
|
||||||
|
"""
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
# 机器硬件指纹哈希(唯一)
|
||||||
|
client_code = Column(String(128), unique=True, nullable=False, index=True)
|
||||||
|
# 客户端显示昵称(可选)
|
||||||
|
nickname = Column(String(64), nullable=True)
|
||||||
|
# JWT token 存储(服务端无状态校验,这里仅做记录)
|
||||||
|
is_active = Column(Boolean, default=True, nullable=False)
|
||||||
|
# Boss直聘 账号标识(登录成功后回填,用于区分同一 Boss 账号)
|
||||||
|
boss_account = Column(String(128), nullable=True)
|
||||||
|
# 登录状态:not_login / logging_in / logged_in
|
||||||
|
login_status = Column(String(20), default="not_login", nullable=False)
|
||||||
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
last_seen_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||||
|
|
||||||
|
# 关联
|
||||||
|
resumes = relationship("Resume", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
applications = relationship("JobApplication", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
sessions = relationship("ApplySession", back_populates="user", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class Resume(Base):
|
||||||
|
"""
|
||||||
|
简历
|
||||||
|
一个用户可有多份简历,其中一份标记为主简历
|
||||||
|
"""
|
||||||
|
__tablename__ = "resumes"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
# Boss直聘 简历 ID
|
||||||
|
boss_resume_id = Column(String(64), nullable=True)
|
||||||
|
# 简历标题
|
||||||
|
title = Column(String(128), nullable=False)
|
||||||
|
# 求职意向岗位
|
||||||
|
position = Column(String(128), nullable=True)
|
||||||
|
# 简历全文(结构化或纯文本)
|
||||||
|
content = Column(Text, nullable=True)
|
||||||
|
# 是否为主简历
|
||||||
|
is_primary = Column(Boolean, default=False, nullable=False)
|
||||||
|
created_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
updated_at = Column(DateTime, default=utcnow, onupdate=utcnow)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="resumes")
|
||||||
|
|
||||||
|
|
||||||
|
class ApplySession(Base):
|
||||||
|
"""
|
||||||
|
投递会话
|
||||||
|
记录一次"开始投递 → 结束投递"的完整过程
|
||||||
|
"""
|
||||||
|
__tablename__ = "apply_sessions"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
# 会话状态:running / stopped / finished
|
||||||
|
status = Column(String(20), default="running", nullable=False)
|
||||||
|
# 搜索关键词(逗号分隔)
|
||||||
|
keywords = Column(String(512), nullable=True)
|
||||||
|
# 城市代码
|
||||||
|
city_code = Column(String(20), nullable=True)
|
||||||
|
# 薪资范围
|
||||||
|
salary_min = Column(Integer, nullable=True)
|
||||||
|
salary_max = Column(Integer, nullable=True)
|
||||||
|
# 本次会话投递数量统计
|
||||||
|
applied_count = Column(Integer, default=0)
|
||||||
|
skipped_count = Column(Integer, default=0)
|
||||||
|
started_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
ended_at = Column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="sessions")
|
||||||
|
applications = relationship("JobApplication", back_populates="session", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
class JobApplication(Base):
|
||||||
|
"""
|
||||||
|
投递记录
|
||||||
|
"""
|
||||||
|
__tablename__ = "job_applications"
|
||||||
|
__table_args__ = (
|
||||||
|
# 同一用户不重复投递同一职位
|
||||||
|
UniqueConstraint("user_id", "job_id", name="uq_user_job"),
|
||||||
|
Index("idx_user_session", "user_id", "session_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
session_id = Column(Integer, ForeignKey("apply_sessions.id", ondelete="SET NULL"), nullable=True)
|
||||||
|
# Boss直聘 职位 ID
|
||||||
|
job_id = Column(String(64), nullable=False, index=True)
|
||||||
|
job_title = Column(String(128), nullable=True)
|
||||||
|
company = Column(String(128), nullable=True)
|
||||||
|
salary = Column(String(32), nullable=True)
|
||||||
|
location = Column(String(64), nullable=True)
|
||||||
|
# 投递方式:chat=立即沟通 / deliver=投递简历 / skipped=跳过
|
||||||
|
apply_type = Column(String(20), nullable=False)
|
||||||
|
# AI 匹配评分(-1 表示未评分)
|
||||||
|
ai_score = Column(Integer, default=-1)
|
||||||
|
ai_reason = Column(String(255), nullable=True)
|
||||||
|
# 跳过原因
|
||||||
|
skip_reason = Column(String(255), nullable=True)
|
||||||
|
applied_at = Column(DateTime, default=utcnow, nullable=False)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="applications")
|
||||||
|
session = relationship("ApplySession", back_populates="applications")
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# 服务端依赖
|
||||||
|
fastapi>=0.111.0
|
||||||
|
uvicorn[standard]>=0.30.0
|
||||||
|
sqlalchemy>=2.0.30
|
||||||
|
pymysql>=1.1.0
|
||||||
|
cryptography>=42.0.0
|
||||||
|
pydantic>=2.7.0
|
||||||
|
pydantic-settings>=2.3.0
|
||||||
|
python-jose[cryptography]>=3.3.0
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""路由包"""
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""
|
||||||
|
投递记录路由:上报投递结果、查询历史、统计
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
from ..auth import get_current_user
|
||||||
|
from ..database import get_db
|
||||||
|
from ..models import User, JobApplication
|
||||||
|
from ..schemas import ApplicationIn, ApplicationOut, Message, StatsOut
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/jobs", tags=["投递记录"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/report", response_model=ApplicationOut)
|
||||||
|
def report_application(
|
||||||
|
req: ApplicationIn,
|
||||||
|
session_id: Optional[int] = Query(None, description="所属会话 ID"),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
客户端上报一条投递/跳过记录。
|
||||||
|
同一用户 + 同一职位 ID 去重,已存在则更新。
|
||||||
|
"""
|
||||||
|
existing = db.query(JobApplication).filter(
|
||||||
|
JobApplication.user_id == current_user.id,
|
||||||
|
JobApplication.job_id == req.job_id,
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
existing.apply_type = req.apply_type
|
||||||
|
existing.ai_score = req.ai_score
|
||||||
|
existing.ai_reason = req.ai_reason
|
||||||
|
existing.skip_reason = req.skip_reason
|
||||||
|
if session_id:
|
||||||
|
existing.session_id = session_id
|
||||||
|
record = existing
|
||||||
|
else:
|
||||||
|
record = JobApplication(
|
||||||
|
user_id=current_user.id,
|
||||||
|
session_id=session_id,
|
||||||
|
job_id=req.job_id,
|
||||||
|
job_title=req.job_title,
|
||||||
|
company=req.company,
|
||||||
|
salary=req.salary,
|
||||||
|
location=req.location,
|
||||||
|
apply_type=req.apply_type,
|
||||||
|
ai_score=req.ai_score,
|
||||||
|
ai_reason=req.ai_reason,
|
||||||
|
skip_reason=req.skip_reason,
|
||||||
|
)
|
||||||
|
db.add(record)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(record)
|
||||||
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/check/{job_id}", response_model=dict)
|
||||||
|
def check_applied(
|
||||||
|
job_id: str,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""检查某职位是否已投递过(用于客户端去重)"""
|
||||||
|
record = db.query(JobApplication).filter(
|
||||||
|
JobApplication.user_id == current_user.id,
|
||||||
|
JobApplication.job_id == job_id,
|
||||||
|
JobApplication.apply_type.in_(["chat", "deliver"]),
|
||||||
|
).first()
|
||||||
|
return {"job_id": job_id, "applied": record is not None}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/history", response_model=list[ApplicationOut])
|
||||||
|
def list_applications(
|
||||||
|
apply_type: Optional[str] = Query(None, description="过滤投递类型"),
|
||||||
|
limit: int = Query(50, le=500),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取投递历史(按时间倒序)"""
|
||||||
|
query = db.query(JobApplication).filter(JobApplication.user_id == current_user.id)
|
||||||
|
if apply_type:
|
||||||
|
query = query.filter(JobApplication.apply_type == apply_type)
|
||||||
|
return query.order_by(JobApplication.applied_at.desc()).limit(limit).all()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/stats", response_model=StatsOut)
|
||||||
|
def get_stats(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取投递统计"""
|
||||||
|
base = db.query(JobApplication).filter(JobApplication.user_id == current_user.id)
|
||||||
|
|
||||||
|
def count(**filters):
|
||||||
|
q = base
|
||||||
|
for k, v in filters.items():
|
||||||
|
q = q.filter(getattr(JobApplication, k) == v)
|
||||||
|
return q.count()
|
||||||
|
|
||||||
|
today_str = datetime.utcnow().strftime("%Y-%m-%d")
|
||||||
|
total_applied = base.filter(JobApplication.apply_type.in_(["chat", "deliver"])).count()
|
||||||
|
today_applied = base.filter(
|
||||||
|
JobApplication.apply_type.in_(["chat", "deliver"]),
|
||||||
|
func.date(JobApplication.applied_at) == today_str,
|
||||||
|
).count()
|
||||||
|
|
||||||
|
return StatsOut(
|
||||||
|
total_applied=total_applied,
|
||||||
|
total_chat=count(apply_type="chat"),
|
||||||
|
total_deliver=count(apply_type="deliver"),
|
||||||
|
total_skipped=count(apply_type="skipped"),
|
||||||
|
today_applied=today_applied,
|
||||||
|
)
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
客户端注册 / 登录状态 / 用户信息路由
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import create_access_token, get_current_user
|
||||||
|
from ..database import get_db
|
||||||
|
from ..models import User
|
||||||
|
from ..schemas import (
|
||||||
|
RegisterRequest, RegisterResponse, UserInfo, LoginStatusUpdate, Message,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth", tags=["认证与用户"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register", response_model=RegisterResponse)
|
||||||
|
def register(req: RegisterRequest, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
客户端注册/登录。
|
||||||
|
以机器硬件指纹 client_code 作为唯一标识:
|
||||||
|
- 已存在 → 直接返回 token(视为登录)
|
||||||
|
- 不存在 → 创建新用户
|
||||||
|
"""
|
||||||
|
user = db.query(User).filter(User.client_code == req.client_code).first()
|
||||||
|
is_new = user is None
|
||||||
|
|
||||||
|
if is_new:
|
||||||
|
user = User(client_code=req.client_code, nickname=req.nickname)
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(user)
|
||||||
|
|
||||||
|
# 更新最后活跃时间
|
||||||
|
user.last_seen_at = datetime.utcnow()
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
token = create_access_token(user.id, user.client_code)
|
||||||
|
return RegisterResponse(
|
||||||
|
user_id=user.id,
|
||||||
|
token=token,
|
||||||
|
client_code=user.client_code,
|
||||||
|
is_new=is_new,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserInfo)
|
||||||
|
def get_me(current_user: User = Depends(get_current_user)):
|
||||||
|
"""获取当前用户信息"""
|
||||||
|
return UserInfo(
|
||||||
|
id=current_user.id,
|
||||||
|
client_code=current_user.client_code,
|
||||||
|
nickname=current_user.nickname,
|
||||||
|
boss_account=current_user.boss_account,
|
||||||
|
login_status=current_user.login_status,
|
||||||
|
created_at=current_user.created_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/login-status", response_model=Message)
|
||||||
|
def update_login_status(
|
||||||
|
req: LoginStatusUpdate,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""更新 Boss直聘 登录状态"""
|
||||||
|
valid_status = {"not_login", "logging_in", "logged_in"}
|
||||||
|
if req.login_status not in valid_status:
|
||||||
|
raise HTTPException(status_code=400, detail=f"登录状态必须是 {valid_status} 之一")
|
||||||
|
current_user.login_status = req.login_status
|
||||||
|
if req.boss_account:
|
||||||
|
current_user.boss_account = req.boss_account
|
||||||
|
db.commit()
|
||||||
|
return Message(msg=f"登录状态已更新为 {req.login_status}")
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""
|
||||||
|
简历管理路由
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import get_current_user
|
||||||
|
from ..database import get_db
|
||||||
|
from ..models import User, Resume
|
||||||
|
from ..schemas import ResumeIn, ResumeOut, ResumeBatchIn, Message
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/resumes", tags=["简历管理"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[ResumeOut])
|
||||||
|
def list_resumes(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取当前用户的所有简历"""
|
||||||
|
resumes = db.query(Resume).filter(Resume.user_id == current_user.id).all()
|
||||||
|
return resumes
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/primary", response_model=ResumeOut)
|
||||||
|
def get_primary_resume(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取当前用户的主简历"""
|
||||||
|
resume = db.query(Resume).filter(
|
||||||
|
Resume.user_id == current_user.id,
|
||||||
|
Resume.is_primary == True,
|
||||||
|
).first()
|
||||||
|
if resume is None:
|
||||||
|
raise HTTPException(status_code=404, detail="尚未设置主简历")
|
||||||
|
return resume
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/batch", response_model=list[ResumeOut])
|
||||||
|
def upload_resumes_batch(
|
||||||
|
req: ResumeBatchIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
批量上传抓取到的简历。
|
||||||
|
以 boss_resume_id 去重:存在则更新,不存在则新增。
|
||||||
|
第一份简历自动设为主简历(若当前没有主简历)。
|
||||||
|
"""
|
||||||
|
results = []
|
||||||
|
has_primary = db.query(Resume).filter(
|
||||||
|
Resume.user_id == current_user.id, Resume.is_primary == True
|
||||||
|
).first() is not None
|
||||||
|
|
||||||
|
for i, item in enumerate(req.resumes):
|
||||||
|
existing = None
|
||||||
|
if item.boss_resume_id:
|
||||||
|
existing = db.query(Resume).filter(
|
||||||
|
Resume.user_id == current_user.id,
|
||||||
|
Resume.boss_resume_id == item.boss_resume_id,
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if existing:
|
||||||
|
existing.title = item.title
|
||||||
|
existing.position = item.position
|
||||||
|
existing.content = item.content
|
||||||
|
results.append(existing)
|
||||||
|
else:
|
||||||
|
resume = Resume(
|
||||||
|
user_id=current_user.id,
|
||||||
|
boss_resume_id=item.boss_resume_id,
|
||||||
|
title=item.title,
|
||||||
|
position=item.position,
|
||||||
|
content=item.content,
|
||||||
|
)
|
||||||
|
# 若尚无主简历,将第一份设为主简历
|
||||||
|
if not has_primary and i == 0:
|
||||||
|
resume.is_primary = True
|
||||||
|
has_primary = True
|
||||||
|
db.add(resume)
|
||||||
|
results.append(resume)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
for r in results:
|
||||||
|
db.refresh(r)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{resume_id}/set-primary", response_model=Message)
|
||||||
|
def set_primary(
|
||||||
|
resume_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""将指定简历设为主简历(同时取消其他主简历标记)"""
|
||||||
|
target = db.query(Resume).filter(
|
||||||
|
Resume.id == resume_id,
|
||||||
|
Resume.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if target is None:
|
||||||
|
raise HTTPException(status_code=404, detail="简历不存在")
|
||||||
|
|
||||||
|
# 取消当前主简历标记
|
||||||
|
db.query(Resume).filter(
|
||||||
|
Resume.user_id == current_user.id, Resume.is_primary == True
|
||||||
|
).update({"is_primary": False})
|
||||||
|
target.is_primary = True
|
||||||
|
db.commit()
|
||||||
|
return Message(msg=f"已将《{target.title}》设为主简历")
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{resume_id}", response_model=Message)
|
||||||
|
def delete_resume(
|
||||||
|
resume_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""删除指定简历"""
|
||||||
|
resume = db.query(Resume).filter(
|
||||||
|
Resume.id == resume_id,
|
||||||
|
Resume.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if resume is None:
|
||||||
|
raise HTTPException(status_code=404, detail="简历不存在")
|
||||||
|
db.delete(resume)
|
||||||
|
db.commit()
|
||||||
|
return Message(msg="简历已删除")
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
"""
|
||||||
|
投递会话路由:开始 / 结束投递、上报统计
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..auth import get_current_user
|
||||||
|
from ..database import get_db
|
||||||
|
from ..models import User, ApplySession
|
||||||
|
from ..schemas import SessionStartIn, SessionOut, SessionStatsIn, Message
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/sessions", tags=["投递会话"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/start", response_model=SessionOut)
|
||||||
|
def start_session(
|
||||||
|
req: SessionStartIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""开始一次投递会话"""
|
||||||
|
# 若已有进行中的会话,先结束它
|
||||||
|
running = db.query(ApplySession).filter(
|
||||||
|
ApplySession.user_id == current_user.id,
|
||||||
|
ApplySession.status == "running",
|
||||||
|
).first()
|
||||||
|
if running:
|
||||||
|
running.status = "stopped"
|
||||||
|
running.ended_at = datetime.utcnow()
|
||||||
|
|
||||||
|
session = ApplySession(
|
||||||
|
user_id=current_user.id,
|
||||||
|
status="running",
|
||||||
|
keywords=req.keywords,
|
||||||
|
city_code=req.city_code,
|
||||||
|
salary_min=req.salary_min,
|
||||||
|
salary_max=req.salary_max,
|
||||||
|
)
|
||||||
|
db.add(session)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(session)
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/current", response_model=SessionOut)
|
||||||
|
def get_current_session(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取当前进行中的会话"""
|
||||||
|
session = db.query(ApplySession).filter(
|
||||||
|
ApplySession.user_id == current_user.id,
|
||||||
|
ApplySession.status == "running",
|
||||||
|
).order_by(ApplySession.started_at.desc()).first()
|
||||||
|
if session is None:
|
||||||
|
raise HTTPException(status_code=404, detail="当前没有进行中的会话")
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{session_id}/stop", response_model=SessionOut)
|
||||||
|
def stop_session(
|
||||||
|
session_id: int,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""结束指定会话"""
|
||||||
|
session = db.query(ApplySession).filter(
|
||||||
|
ApplySession.id == session_id,
|
||||||
|
ApplySession.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if session is None:
|
||||||
|
raise HTTPException(status_code=404, detail="会话不存在")
|
||||||
|
session.status = "stopped"
|
||||||
|
session.ended_at = datetime.utcnow()
|
||||||
|
db.commit()
|
||||||
|
db.refresh(session)
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{session_id}/stats", response_model=SessionOut)
|
||||||
|
def update_session_stats(
|
||||||
|
session_id: int,
|
||||||
|
req: SessionStatsIn,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""增量上报投递/跳过数量"""
|
||||||
|
session = db.query(ApplySession).filter(
|
||||||
|
ApplySession.id == session_id,
|
||||||
|
ApplySession.user_id == current_user.id,
|
||||||
|
).first()
|
||||||
|
if session is None:
|
||||||
|
raise HTTPException(status_code=404, detail="会话不存在")
|
||||||
|
session.applied_count += req.applied_delta
|
||||||
|
session.skipped_count += req.skipped_delta
|
||||||
|
db.commit()
|
||||||
|
db.refresh(session)
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/history", response_model=list[SessionOut])
|
||||||
|
def list_sessions(
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""获取历史会话列表"""
|
||||||
|
return db.query(ApplySession).filter(
|
||||||
|
ApplySession.user_id == current_user.id
|
||||||
|
).order_by(ApplySession.started_at.desc()).limit(50).all()
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""
|
||||||
|
Pydantic 请求/响应数据模式
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 认证相关
|
||||||
|
# =======================================================
|
||||||
|
class RegisterRequest(BaseModel):
|
||||||
|
client_code: str = Field(..., min_length=8, max_length=128, description="机器硬件指纹哈希")
|
||||||
|
nickname: Optional[str] = Field(None, max_length=64)
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterResponse(BaseModel):
|
||||||
|
user_id: int
|
||||||
|
token: str
|
||||||
|
client_code: str
|
||||||
|
is_new: bool # 是否为新注册用户
|
||||||
|
|
||||||
|
|
||||||
|
class TokenPayload(BaseModel):
|
||||||
|
sub: int # user_id
|
||||||
|
client_code: str
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 用户状态
|
||||||
|
# =======================================================
|
||||||
|
class UserInfo(BaseModel):
|
||||||
|
id: int
|
||||||
|
client_code: str
|
||||||
|
nickname: Optional[str]
|
||||||
|
boss_account: Optional[str]
|
||||||
|
login_status: str
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class LoginStatusUpdate(BaseModel):
|
||||||
|
login_status: str = Field(..., description="not_login / logging_in / logged_in")
|
||||||
|
boss_account: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 简历相关
|
||||||
|
# =======================================================
|
||||||
|
class ResumeIn(BaseModel):
|
||||||
|
boss_resume_id: Optional[str] = None
|
||||||
|
title: str = Field(..., min_length=1, max_length=128)
|
||||||
|
position: Optional[str] = None
|
||||||
|
content: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ResumeOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
boss_resume_id: Optional[str]
|
||||||
|
title: str
|
||||||
|
position: Optional[str]
|
||||||
|
content: Optional[str]
|
||||||
|
is_primary: bool
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class ResumeBatchIn(BaseModel):
|
||||||
|
"""批量上传抓取到的所有简历"""
|
||||||
|
resumes: list[ResumeIn]
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 投递会话
|
||||||
|
# =======================================================
|
||||||
|
class SessionStartIn(BaseModel):
|
||||||
|
keywords: str
|
||||||
|
city_code: str
|
||||||
|
salary_min: Optional[int] = None
|
||||||
|
salary_max: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class SessionOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
status: str
|
||||||
|
keywords: Optional[str]
|
||||||
|
city_code: Optional[str]
|
||||||
|
salary_min: Optional[int]
|
||||||
|
salary_max: Optional[int]
|
||||||
|
applied_count: int
|
||||||
|
skipped_count: int
|
||||||
|
started_at: datetime
|
||||||
|
ended_at: Optional[datetime]
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class SessionStatsIn(BaseModel):
|
||||||
|
applied_delta: int = 0
|
||||||
|
skipped_delta: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 投递记录
|
||||||
|
# =======================================================
|
||||||
|
class ApplicationIn(BaseModel):
|
||||||
|
job_id: str
|
||||||
|
job_title: Optional[str] = None
|
||||||
|
company: Optional[str] = None
|
||||||
|
salary: Optional[str] = None
|
||||||
|
location: Optional[str] = None
|
||||||
|
apply_type: str # chat / deliver / skipped
|
||||||
|
ai_score: int = -1
|
||||||
|
ai_reason: Optional[str] = None
|
||||||
|
skip_reason: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ApplicationOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
job_id: str
|
||||||
|
job_title: Optional[str]
|
||||||
|
company: Optional[str]
|
||||||
|
salary: Optional[str]
|
||||||
|
location: Optional[str]
|
||||||
|
apply_type: str
|
||||||
|
ai_score: int
|
||||||
|
ai_reason: Optional[str]
|
||||||
|
skip_reason: Optional[str]
|
||||||
|
applied_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# =======================================================
|
||||||
|
# 通用
|
||||||
|
# =======================================================
|
||||||
|
class Message(BaseModel):
|
||||||
|
msg: str
|
||||||
|
|
||||||
|
|
||||||
|
class StatsOut(BaseModel):
|
||||||
|
total_applied: int
|
||||||
|
total_chat: int
|
||||||
|
total_deliver: int
|
||||||
|
total_skipped: int
|
||||||
|
today_applied: int
|
||||||
Reference in New Issue
Block a user