This commit is contained in:
mzl
2026-01-12 14:59:27 +08:00
parent c32cda9704
commit e64adfe628
4 changed files with 1167 additions and 31 deletions
+188
View File
@@ -257,6 +257,194 @@ async def get_users():
return {"users": users}
@app.post("/api/users")
async def add_user(request: dict):
"""添加用户"""
user_id = request.get("user_id", "").strip()
if not user_id:
raise HTTPException(status_code=400, detail="用户ID不能为空")
# 验证用户ID格式
if not user_id or len(user_id) < 10:
raise HTTPException(status_code=400, detail="用户ID格式不正确")
users_file = os.path.join(config.DATA_DIR, "users.txt")
# 检查是否已存在
if os.path.exists(users_file):
with open(users_file, 'r', encoding='utf-8') as f:
existing_users = [line.strip() for line in f if line.strip()]
if user_id in existing_users:
raise HTTPException(status_code=400, detail="用户ID已存在")
# 添加到文件
with open(users_file, 'a', encoding='utf-8') as f:
f.write(f"{user_id}\n")
return {
"success": True,
"message": f"用户 {user_id} 已添加",
"user_id": user_id
}
@app.delete("/api/users/{user_id}")
async def remove_user(user_id: str):
"""删除用户"""
users_file = os.path.join(config.DATA_DIR, "users.txt")
if not os.path.exists(users_file):
raise HTTPException(status_code=404, detail="用户文件不存在")
# 读取所有用户
with open(users_file, 'r', encoding='utf-8') as f:
users = [line.strip() for line in f if line.strip()]
# 检查用户是否存在
if user_id not in users:
raise HTTPException(status_code=404, detail="用户不存在")
# 删除用户
users.remove(user_id)
# 写回文件
with open(users_file, 'w', encoding='utf-8') as f:
for user in users:
f.write(f"{user}\n")
# 删除采集数据文件
data_file = os.path.join(config.DATA_DIR, f"{user_id}.json")
if os.path.exists(data_file):
os.remove(data_file)
return {
"success": True,
"message": f"用户 {user_id} 已删除"
}
@app.delete("/api/users")
async def clear_all_users():
"""清空所有用户"""
users_file = os.path.join(config.DATA_DIR, "users.txt")
if not os.path.exists(users_file):
raise HTTPException(status_code=404, detail="用户文件不存在")
# 清空文件
with open(users_file, 'w', encoding='utf-8') as f:
f.write("")
# 删除所有采集数据
data_dir = config.DATA_DIR
for filename in os.listdir(data_dir):
if filename.endswith('.json') and filename != 'auth_state.json':
file_path = os.path.join(data_dir, filename)
os.remove(file_path)
# 重置状态
app_state.users_status = {}
return {
"success": True,
"message": "所有用户已清空"
}
@app.post("/api/users/import/txt")
async def import_users_from_txt():
"""从users.txt导入用户(模拟)"""
users_file = os.path.join(config.DATA_DIR, "users.txt")
if not os.path.exists(users_file):
raise HTTPException(status_code=404, detail="users.txt文件不存在")
with open(users_file, 'r', encoding='utf-8') as f:
user_ids = [line.strip() for line in f if line.strip()]
return {
"success": True,
"count": len(user_ids),
"users": user_ids
}
@app.get("/api/users/export/txt")
async def export_users_to_txt():
"""导出用户列表到txt文件"""
users_file = os.path.join(config.DATA_DIR, "users.txt")
if not os.path.exists(users_file):
raise HTTPException(status_code=404, detail="用户文件不存在")
with open(users_file, 'r', encoding='utf-8') as f:
content = f.read()
return StreamingResponse(
iter([content]),
media_type="text/plain",
headers={
"Content-Disposition": f"attachment; filename=users_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
}
)
# ========== 登录相关 API ==========
class LoginStatusResponse(BaseModel):
logged_in: bool
login_time: Optional[str] = None
@app.get("/api/login/status", response_model=LoginStatusResponse)
async def get_login_status():
"""获取登录状态"""
auth_file = os.path.join(config.DATA_DIR, "auth_state.json")
if not os.path.exists(auth_file):
return LoginStatusResponse(logged_in=False)
try:
with open(auth_file, 'r', encoding='utf-8') as f:
auth_data = json.load(f)
return LoginStatusResponse(
logged_in=auth_data.get("logged_in", False),
login_time=auth_data.get("login_time")
)
except Exception:
return LoginStatusResponse(logged_in=False)
@app.post("/api/login/qrcode")
async def generate_qrcode():
"""生成登录二维码"""
# 这里应该调用实际的小红书登录API
# 暂时返回模拟数据
return {
"qr_url": "https://example.com/login/qrcode",
"qr_id": "123456"
}
@app.post("/api/logout")
async def logout():
"""退出登录"""
auth_file = os.path.join(config.DATA_DIR, "auth_state.json")
try:
if os.path.exists(auth_file):
os.remove(auth_file)
return {
"success": True,
"message": "已退出登录"
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"退出登录失败: {str(e)}")
@app.get("/api/data/{user_id}")
async def get_user_data(user_id: str):
"""获取用户采集数据"""