This commit is contained in:
Ubuntu
2026-07-03 16:58:28 +08:00
commit 32b43f85bd
6240 changed files with 1987678 additions and 0 deletions
@@ -0,0 +1 @@
# routers package
@@ -0,0 +1,210 @@
# app/routers/app_downloads.py
import os
import uuid
from typing import List, Union
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
import qrcode
from app.database import get_db
from app.models.app_download import AppDownload
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
# Schemas
class AppDownloadCreate(BaseModel):
app_name: str
platform: str
download_url: str
description: str = ""
icon: str = ""
sort_order: int = 0
is_enabled: bool = True
class AppDownloadUpdate(BaseModel):
app_name: str = None
platform: str = None
download_url: str = None
description: str = None
icon: str = None
sort_order: int = None
is_enabled: bool = None
class AppDownloadResponse(BaseModel):
code: int = 200
data: Union[dict, list] = None
message: str = "success"
# Helper
def get_qrcode_dir():
routers_dir = os.path.dirname(os.path.abspath(__file__))
app_dir = os.path.dirname(routers_dir)
backend_dir = os.path.dirname(app_dir)
project_root = os.path.dirname(backend_dir)
qrcode_dir = os.path.join(project_root, "storage", "admin", "images", "qrcode")
os.makedirs(qrcode_dir, exist_ok=True)
return qrcode_dir
def generate_qrcode_image(content: str, filename: str) -> str:
"""Generate QR code image and save to storage, return URL path"""
qrcode_dir = get_qrcode_dir()
filepath = os.path.join(qrcode_dir, filename)
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(content)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save(filepath)
return f"/storage/admin/images/qrcode/{filename}"
def delete_qrcode_image(image_path: str):
"""Delete QR code image file if exists"""
if not image_path:
return
filename = os.path.basename(image_path)
filepath = os.path.join(get_qrcode_dir(), filename)
if os.path.exists(filepath):
os.remove(filepath)
def app_download_to_dict(ad: AppDownload) -> dict:
return {
"id": ad.id,
"app_name": ad.app_name,
"platform": ad.platform,
"download_url": ad.download_url,
"description": ad.description,
"icon": ad.icon,
"qr_image_path": ad.qr_image_path,
"sort_order": ad.sort_order,
"is_enabled": ad.is_enabled,
}
# Public routes
@router.get("/app-downloads", response_model=AppDownloadResponse)
def get_public_app_downloads(db: Session = Depends(get_db)):
"""Get enabled app downloads for public display"""
items = db.query(AppDownload).filter(
AppDownload.is_enabled == True
).order_by(AppDownload.sort_order.asc()).all()
return AppDownloadResponse(data=[app_download_to_dict(i) for i in items])
# Admin routes
@router.get("/admin/app-downloads", response_model=AppDownloadResponse)
def get_admin_app_downloads(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get all app downloads for admin"""
items = db.query(AppDownload).order_by(AppDownload.sort_order.asc()).all()
return AppDownloadResponse(data=[app_download_to_dict(i) for i in items])
@router.post("/admin/app-downloads", response_model=AppDownloadResponse)
def create_app_download(
request: AppDownloadCreate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Create new app download, auto-generate QR code"""
if not request.app_name.strip():
raise HTTPException(status_code=400, detail="应用名称不能为空")
if not request.download_url.strip():
raise HTTPException(status_code=400, detail="下载链接不能为空")
if not request.platform.strip():
raise HTTPException(status_code=400, detail="平台不能为空")
# Generate QR code
filename = f"app_download_{uuid.uuid4().hex[:8]}.png"
qr_image_path = generate_qrcode_image(request.download_url.strip(), filename)
item = AppDownload(
app_name=request.app_name.strip(),
platform=request.platform.strip(),
download_url=request.download_url.strip(),
description=request.description.strip() if request.description else "",
icon=request.icon.strip() if request.icon else "",
qr_image_path=qr_image_path,
sort_order=request.sort_order,
is_enabled=request.is_enabled,
)
db.add(item)
db.commit()
db.refresh(item)
return AppDownloadResponse(message="创建成功", data=app_download_to_dict(item))
@router.put("/admin/app-downloads/{item_id}", response_model=AppDownloadResponse)
def update_app_download(
item_id: int,
request: AppDownloadUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Update app download, regenerate QR code if URL changed"""
item = db.query(AppDownload).filter(AppDownload.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="下载链接不存在")
update_data = request.dict(exclude_unset=True)
# If download_url changed, regenerate QR code
new_url = update_data.get("download_url", "").strip()
if new_url and new_url != item.download_url:
delete_qrcode_image(item.qr_image_path)
filename = f"app_download_{uuid.uuid4().hex[:8]}.png"
item.qr_image_path = generate_qrcode_image(new_url, filename)
item.download_url = new_url
update_data.pop("download_url", None)
for field, value in update_data.items():
if field == "app_name" and value:
value = value.strip()
elif field == "platform" and value:
value = value.strip()
elif field == "description" and value is not None:
value = value.strip()
elif field == "icon" and value is not None:
value = value.strip()
setattr(item, field, value)
db.commit()
db.refresh(item)
return AppDownloadResponse(message="更新成功", data=app_download_to_dict(item))
@router.delete("/admin/app-downloads/{item_id}", response_model=AppDownloadResponse)
def delete_app_download(
item_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Delete app download and its QR code image"""
item = db.query(AppDownload).filter(AppDownload.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="下载链接不存在")
delete_qrcode_image(item.qr_image_path)
db.delete(item)
db.commit()
return AppDownloadResponse(message="删除成功")
@@ -0,0 +1,526 @@
"""
内容管理 API 路由
复用新闻资讯模块的核心逻辑,关联到新的栏目(columns)体系
"""
import html
import os
import re
import shutil
import subprocess
from datetime import datetime
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import func
from pydantic import BaseModel, Field
from pypinyin import lazy_pinyin
from app.models.article import Article
from app.models.column import ColumnModel
from app.models.image import Image
from app.routers.auth import get_current_admin
from app.utils.file_utils import cleanup_file_by_path
from app.database import get_db
router = APIRouter(tags=["内容管理"])
# ========== 辅助函数 ==========
def extract_summary(content: str, max_length: int = 100) -> str:
"""从 HTML/Markdown 内容中提取纯文本摘要"""
if not content:
return ""
text = re.sub(r'<[^>]+>', '', content)
text = html.unescape(text)
text = re.sub(r'[#*_`~\[\]\(\)!>-]', '', text)
text = re.sub(r'\s+', ' ', text).strip()
if len(text) > max_length:
return text[:max_length] + "..."
return text
def generate_slug(text: str) -> str:
"""将中文标题转为拼音 slug"""
if not text:
return ""
py = lazy_pinyin(text, style=0)
slug = "-".join(py)
slug = re.sub(r"[^a-zA-Z0-9-]", "", slug).lower()
slug = re.sub(r"-+", "-", slug).strip("-")
return slug or f"article-{int(__import__('time').time())}"
TEMP_STORAGE_PREFIX = "/storage/tmp/crawl"
def get_upload_dir():
"""获取上传目录路径"""
from app.config import get_settings
settings = get_settings()
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
return os.path.join(base_dir, settings.UPLOAD_DIR)
def get_crawl_temp_dir():
"""获取采集临时目录 - 跨平台"""
if os.name == 'nt':
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
return os.path.join(base_dir, 'storage', 'tmp', 'crawl')
return '/tmp/news_crawl'
def migrate_temp_images(content: str, cover_image: Optional[str], db: Session):
"""将内容中的临时图片迁移到正式目录,并写入 images 表"""
upload_dir = get_upload_dir()
temp_dir = get_crawl_temp_dir()
temp_paths = set()
if cover_image and cover_image.startswith(TEMP_STORAGE_PREFIX):
temp_paths.add(cover_image)
pattern = re.escape(TEMP_STORAGE_PREFIX) + r'/[^\\)"\'>\s]+'
for match in re.finditer(pattern, content):
temp_paths.add(match.group())
if not temp_paths:
return content, cover_image
# 按年月分目录存储(与 batch_crawl / wechat_crawl 一致)
year_month = datetime.now().strftime("%Y%m")
dest_dir = os.path.join(upload_dir, year_month)
os.makedirs(dest_dir, exist_ok=True)
path_mapping = {}
for temp_path in temp_paths:
filename = os.path.basename(temp_path)
temp_file = os.path.join(temp_dir, filename)
if not os.path.exists(temp_file):
continue
dest_file = os.path.join(dest_dir, filename)
shutil.move(temp_file, dest_file)
thumb_filename = f"{os.path.splitext(filename)[0]}.jpg"
temp_thumb = os.path.join(temp_dir, "thumbnails", thumb_filename)
dest_thumb = os.path.join(upload_dir, "thumbnails", thumb_filename)
if os.path.exists(temp_thumb):
shutil.move(temp_thumb, dest_thumb)
formal_path = f"/storage/admin/images/{year_month}/{filename}"
formal_thumb = f"/storage/admin/images/thumbnails/{thumb_filename}"
path_mapping[temp_path] = formal_path
try:
file_size = os.path.getsize(dest_file)
except OSError:
file_size = 0
existing = db.query(Image).filter(Image.file_path == formal_path).first()
if not existing:
img_record = Image(
filename=filename,
original_name=filename,
file_path=formal_path,
thumb_path=formal_thumb,
file_size=file_size,
module="articles"
)
db.add(img_record)
new_content = content
for temp_path, formal_path in path_mapping.items():
new_content = new_content.replace(temp_path, formal_path)
new_cover = cover_image
if cover_image and cover_image in path_mapping:
new_cover = path_mapping[cover_image]
return new_content, new_cover
def _validate_column_for_article(column_id: int, db: Session, exclude_article_id: Optional[int] = None):
"""校验栏目是否可关联内容:
- 栏目必须存在
- 顶级栏目若有二级栏目,则禁止直接关联内容
"""
column = db.query(ColumnModel).filter(ColumnModel.id == column_id).first()
if not column:
raise HTTPException(status_code=404, detail="栏目不存在")
# 如果是顶级栏目,检查是否有子栏目
if column.parent_id is None:
child_count = db.query(ColumnModel).filter(ColumnModel.parent_id == column_id).count()
if child_count > 0:
raise HTTPException(status_code=400, detail="该栏目存在子栏目,内容必须关联到子栏目")
return column
# ========== Pydantic 模型 ==========
class ArticleCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
slug: Optional[str] = Field(None, max_length=200)
content: str = Field(..., min_length=1)
content_type: str = Field(default="markdown", pattern="^(markdown|html)$")
summary: Optional[str] = Field(None, max_length=500)
cover_image: Optional[str] = Field(None, max_length=500)
column_id: int
author: Optional[str] = Field(None, max_length=50)
status: str = Field(default="draft", pattern="^(published|draft)$")
sort_order: int = Field(default=0)
class ArticleUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=200)
slug: Optional[str] = Field(None, min_length=1, max_length=200)
content: Optional[str] = Field(None, min_length=1)
content_type: Optional[str] = Field(None, pattern="^(markdown|html)$")
summary: Optional[str] = Field(None, max_length=500)
cover_image: Optional[str] = Field(None, max_length=500)
column_id: Optional[int] = None
author: Optional[str] = Field(None, max_length=50)
status: Optional[str] = Field(None, pattern="^(published|draft)$")
sort_order: Optional[int] = None
class ArticlePublish(BaseModel):
is_published: bool
class BatchDelete(BaseModel):
ids: List[int]
class BatchMove(BaseModel):
ids: List[int]
column_id: int
# ========== API ==========
@router.get("/admin/articles")
def list_articles(
page: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=100),
column_id: Optional[int] = Query(default=None),
keyword: Optional[str] = Query(default=None),
status: Optional[str] = Query(default=None, pattern="^(published|draft|rewriting|all)$"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""获取内容列表(分页 + 筛选)"""
query = db.query(Article).options(joinedload(Article.column))
if column_id:
query = query.filter(Article.column_id == column_id)
if keyword:
query = query.filter(Article.title.contains(keyword))
if status == "published":
query = query.filter(Article.status == "published")
elif status == "draft":
query = query.filter(Article.status == "draft")
query = query.order_by(Article.updated_at.desc())
total = query.count()
articles = query.offset((page - 1) * size).limit(size).all()
return {
"items": [a.to_dict(include_content=False) for a in articles],
"total": total,
"page": page,
"size": size
}
@router.get("/admin/articles/{article_id}")
def get_article(
article_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""获取内容详情"""
article = db.query(Article).options(joinedload(Article.column)).filter(Article.id == article_id).first()
if not article:
raise HTTPException(status_code=404, detail="内容不存在")
return article.to_dict(include_content=True)
@router.post("/admin/articles")
def create_article(
data: ArticleCreate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""创建内容"""
# 校验栏目
_validate_column_for_article(data.column_id, db)
# 自动生成 slug
slug = data.slug or generate_slug(data.title)
if not slug:
raise HTTPException(status_code=400, detail="URL标识生成失败,请手动填写")
existing = db.query(Article).filter(Article.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="内容标识已存在")
# 自动生成摘要
summary = data.summary
if not summary:
summary = extract_summary(data.content, max_length=100)
# 迁移临时图片
migrated_content, migrated_cover = migrate_temp_images(data.content, data.cover_image, db)
article = Article(
title=data.title,
slug=slug,
content=migrated_content,
content_type=data.content_type,
summary=summary,
cover_image=migrated_cover,
column_id=data.column_id,
author=data.author,
status=data.status,
sort_order=data.sort_order,
)
db.add(article)
db.commit()
db.refresh(article)
return article.to_dict(include_content=True)
@router.put("/admin/articles/{article_id}")
def update_article(
article_id: int,
data: ArticleUpdate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""更新内容"""
article = db.query(Article).filter(Article.id == article_id).first()
if not article:
raise HTTPException(status_code=404, detail="内容不存在")
# 检查 slug 冲突
slug = data.slug
if slug is not None:
if not slug.strip():
slug = generate_slug(data.title or article.title)
if slug != article.slug:
existing = db.query(Article).filter(Article.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="内容标识已存在")
# 校验栏目
if data.column_id is not None:
_validate_column_for_article(data.column_id, db, exclude_article_id=article_id)
update_data = data.model_dump(exclude_unset=True)
if slug is not None:
update_data["slug"] = slug
# 摘要被清空时自动提取
if "summary" in update_data and not update_data.get("summary", "").strip():
content_to_extract = update_data.get("content") or article.content
if content_to_extract:
update_data["summary"] = extract_summary(content_to_extract, max_length=100)
# 迁移临时图片(如果内容/封面包含临时路径)
if update_data.get("content"):
migrated_content, migrated_cover = migrate_temp_images(
update_data["content"],
update_data.get("cover_image") or article.cover_image,
db,
)
update_data["content"] = migrated_content
update_data["cover_image"] = migrated_cover
for key, value in update_data.items():
setattr(article, key, value)
db.commit()
db.refresh(article)
return article.to_dict(include_content=True)
@router.delete("/admin/articles/{article_id}")
def delete_article(
article_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""删除内容"""
article = db.query(Article).filter(Article.id == article_id).first()
if not article:
raise HTTPException(status_code=404, detail="内容不存在")
if article.cover_image:
cleanup_file_by_path(article.cover_image)
db.delete(article)
db.commit()
return {"message": "删除成功"}
@router.post("/admin/articles/batch-delete")
def batch_delete_articles(
data: BatchDelete,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""批量删除内容"""
articles = db.query(Article).filter(Article.id.in_(data.ids)).all()
for article in articles:
if article.cover_image:
cleanup_file_by_path(article.cover_image)
db.delete(article)
db.commit()
return {"message": f"成功删除 {len(articles)} 条内容"}
@router.post("/admin/articles/batch-move")
def batch_move_articles(
data: BatchMove,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""批量转移栏目"""
# 校验目标栏目
_validate_column_for_article(data.column_id, db)
articles = db.query(Article).filter(Article.id.in_(data.ids)).all()
for article in articles:
article.column_id = data.column_id
db.commit()
return {"message": f"成功转移 {len(articles)} 条内容"}
@router.post("/admin/articles/{article_id}/publish")
def publish_article(
article_id: int,
data: ArticlePublish,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""发布/取消发布内容"""
article = db.query(Article).filter(Article.id == article_id).first()
if not article:
raise HTTPException(status_code=404, detail="内容不存在")
article.status = "published" if data.is_published else "draft"
db.commit()
db.refresh(article)
return article.to_dict()
# ========== 改写发布 ==========
VENV_PYTHON = "/mnt/datadisk0/www/new-media-platform/website-new/backend/.venv/bin/python3"
PIPELINE_PATH = "/mnt/datadisk0/www/new-media-platform/website-new/rewrite/pipeline.py"
LOG_FILE = "/mnt/datadisk0/www/new-media-platform/website-new/rewrite/logs/pipeline.log"
@router.post("/admin/articles/{article_id}/rewrite-publish")
def rewrite_publish_article(
article_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""一键改写+发布到公众号(异步后台任务)"""
article = db.query(Article).filter(Article.id == article_id).first()
if not article:
raise HTTPException(status_code=404, detail="内容不存在")
if article.status != "draft":
raise HTTPException(status_code=400, detail="只有草稿状态的内容可以改写发布")
# 并发控制:检查是否有正在改写中的文章
rewriting_count = db.query(Article).filter(
Article.status == "rewriting"
).count()
if rewriting_count > 0:
raise HTTPException(status_code=429, detail="已有文章正在改写中,请稍后再试")
# 设置为改写中
article.status = "rewriting"
db.commit()
db.refresh(article)
# 启动后台子进程,stderr 写入日志文件便于排查
stderr_log = open(LOG_FILE, "a")
subprocess.Popen(
[VENV_PYTHON, PIPELINE_PATH, str(article_id)],
stdout=stderr_log,
stderr=stderr_log,
)
return {
"message": "改写任务已启动",
"article_id": article_id,
"status": "rewriting",
}
# ========== 访客端 Public API ==========
@router.get("/public/articles")
def list_public_articles(
page: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=100),
column_slug: Optional[str] = Query(default=None),
db: Session = Depends(get_db),
):
"""访客端:获取已发布的内容列表"""
query = db.query(Article).options(joinedload(Article.column)).filter(
Article.status == "published"
)
# 如果指定了栏目 slug,筛选该栏目及其子栏目的内容
if column_slug:
column = db.query(ColumnModel).filter(
ColumnModel.slug == column_slug,
ColumnModel.is_enabled == True
).first()
if column:
# 获取该栏目及所有子栏目的 ID
column_ids = [column.id]
children = db.query(ColumnModel).filter(
ColumnModel.parent_id == column.id
).all()
column_ids.extend([c.id for c in children])
query = query.filter(Article.column_id.in_(column_ids))
query = query.order_by(Article.sort_order.asc(), Article.updated_at.desc())
total = query.count()
articles = query.offset((page - 1) * size).limit(size).all()
return {
"items": [a.to_dict(include_content=False) for a in articles],
"total": total,
"page": page,
"size": size
}
@router.get("/public/articles/{slug}")
def get_public_article(
slug: str,
db: Session = Depends(get_db),
):
"""访客端:通过 slug 获取内容详情"""
article = db.query(Article).options(joinedload(Article.column)).filter(
Article.slug == slug,
Article.status == "published"
).first()
if not article:
raise HTTPException(status_code=404, detail="内容不存在")
# 增加浏览次数
article.view_count += 1
db.commit()
return article.to_dict(include_content=True)
@@ -0,0 +1,93 @@
# app/routers/auth.py
from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.config import get_settings
from app.database import get_db
from app.models.admin import Admin
from app.auth import verify_password, get_password_hash, create_access_token, get_current_admin
router = APIRouter()
settings = get_settings()
security = HTTPBearer()
# Schemas
class LoginRequest(BaseModel):
username: str
password: str
class LoginResponse(BaseModel):
code: int = 200
message: str
data: dict
class AdminInfoResponse(BaseModel):
code: int = 200
data: dict
class ChangePasswordRequest(BaseModel):
old_password: str
new_password: str
# Routes
@router.post("/login", response_model=LoginResponse)
def login(request: LoginRequest, db: Session = Depends(get_db)):
admin = db.query(Admin).filter(Admin.username == request.username).first()
if not admin or not verify_password(request.password, admin.password_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="用户名或密码错误"
)
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": admin.username}, expires_delta=access_token_expires
)
return LoginResponse(
message="登录成功",
data={
"token": access_token,
"admin": {
"id": admin.id,
"username": admin.username
}
}
)
@router.get("/me", response_model=AdminInfoResponse)
def get_me(current_admin: Admin = Depends(get_current_admin)):
return AdminInfoResponse(
data={
"id": current_admin.id,
"username": current_admin.username
}
)
@router.post("/change-password")
def change_password(
request: ChangePasswordRequest,
current_admin: Admin = Depends(get_current_admin),
db: Session = Depends(get_db)
):
if not verify_password(request.old_password, current_admin.password_hash):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="原密码错误"
)
current_admin.password_hash = get_password_hash(request.new_password)
db.commit()
return {"code": 200, "message": "密码修改成功"}
@@ -0,0 +1,297 @@
"""
栏目管理 API 路由
"""
import re
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import func
from pydantic import BaseModel, Field
from pypinyin import lazy_pinyin
from app.models.column import ColumnModel
from app.routers.auth import get_current_admin
from app.database import get_db
router = APIRouter(tags=["栏目管理"])
def generate_slug(text: str) -> str:
"""将中文标题转为拼音 slug"""
if not text:
return ""
py = lazy_pinyin(text, style=0)
slug = "-".join(py)
slug = re.sub(r"[^a-zA-Z0-9-]", "", slug).lower()
slug = re.sub(r"-+", "-", slug).strip("-")
return slug or f"column-{int(__import__('time').time())}"
# ========== Pydantic 模型 ==========
class ColumnCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=50)
slug: Optional[str] = Field(None, max_length=50)
description: Optional[str] = Field(None, max_length=200)
parent_id: Optional[int] = Field(None)
sort_order: int = Field(default=0)
is_enabled: bool = Field(default=True)
display_mode: str = Field(default="list", pattern="^(list|card)$")
layout_style: str = Field(default="left", pattern="^(left|right|top)$")
icon_name: Optional[str] = Field(None, max_length=50)
class ColumnUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=50)
slug: Optional[str] = Field(None, min_length=1, max_length=50)
description: Optional[str] = Field(None, max_length=200)
parent_id: Optional[int] = Field(None)
sort_order: Optional[int] = None
is_enabled: Optional[bool] = None
display_mode: Optional[str] = Field(None, pattern="^(list|card)$")
layout_style: Optional[str] = Field(None, pattern="^(left|right|top)$")
icon_name: Optional[str] = Field(None, max_length=50)
class ColumnTreeOut(BaseModel):
"""树形栏目输出"""
id: int
name: str
slug: str
description: Optional[str]
parent_id: Optional[int]
sort_order: int
is_enabled: bool
display_mode: str
layout_style: str
children: List["ColumnTreeOut"] = []
class Config:
from_attributes = True
# ========== 辅助函数 ==========
def _build_tree(columns: list, parent_id: Optional[int] = None) -> list:
"""递归构建栏目树"""
tree = []
for col in columns:
if col.parent_id == parent_id:
node = col.to_dict()
node["children"] = _build_tree(columns, col.id)
tree.append(node)
return tree
def _validate_parent(column: ColumnModel, new_parent_id: Optional[int], db: Session):
"""校验 parent_id 是否合法:最多两级"""
if new_parent_id is None:
return
# 不能把自己设为自己的父栏目
if column and new_parent_id == column.id:
raise HTTPException(status_code=400, detail="不能将栏目设为自己的上级栏目")
# 父栏目必须存在
parent = db.query(ColumnModel).filter(ColumnModel.id == new_parent_id).first()
if not parent:
raise HTTPException(status_code=404, detail="上级栏目不存在")
# 父栏目本身不能是二级栏目(最多两级)
if parent.parent_id is not None:
raise HTTPException(status_code=400, detail="最多支持两级栏目,不能将二级栏目设为上级")
def _has_children(column_id: int, db: Session) -> bool:
"""检查栏目是否有子栏目"""
return db.query(ColumnModel).filter(ColumnModel.parent_id == column_id).first() is not None
# ========== API ==========
@router.get("/admin/columns")
def list_columns(
tree: bool = Query(default=False, description="是否返回树形结构"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""获取栏目列表(后台管理)"""
columns = db.query(ColumnModel).order_by(ColumnModel.sort_order.asc()).all()
if tree:
return {"items": _build_tree(columns), "total": len(columns)}
return {"items": [col.to_dict() for col in columns], "total": len(columns)}
@router.get("/admin/columns/tree")
def get_column_tree(
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""获取树形栏目列表(用于下拉选择,后台管理)"""
columns = db.query(ColumnModel).order_by(ColumnModel.sort_order.asc()).all()
return {"items": _build_tree(columns), "total": len(columns)}
@router.get("/admin/columns/{column_id}")
def get_column(
column_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""获取栏目详情(后台管理)"""
column = db.query(ColumnModel).filter(ColumnModel.id == column_id).first()
if not column:
raise HTTPException(status_code=404, detail="栏目不存在")
return column.to_dict()
@router.post("/admin/columns")
def create_column(
data: ColumnCreate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""创建栏目(后台管理)"""
# 校验上级栏目
_validate_parent(None, data.parent_id, db)
# 自动生成 slug
slug = data.slug or generate_slug(data.name)
if not slug:
raise HTTPException(status_code=400, detail="URL标识生成失败,请手动填写")
# 检查 slug 唯一性
existing = db.query(ColumnModel).filter(ColumnModel.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="栏目标识已存在")
column = ColumnModel(
name=data.name,
slug=slug,
description=data.description,
parent_id=data.parent_id,
sort_order=data.sort_order,
is_enabled=data.is_enabled,
display_mode=data.display_mode,
layout_style=data.layout_style,
icon_name=data.icon_name,
)
db.add(column)
db.commit()
db.refresh(column)
return column.to_dict()
@router.put("/admin/columns/{column_id}")
def update_column(
column_id: int,
data: ColumnUpdate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""更新栏目(后台管理)"""
column = db.query(ColumnModel).filter(ColumnModel.id == column_id).first()
if not column:
raise HTTPException(status_code=404, detail="栏目不存在")
# 校验上级栏目
if data.parent_id is not None:
_validate_parent(column, data.parent_id, db)
# 检查 slug 唯一性
slug = data.slug
if slug is not None:
if not slug.strip():
slug = generate_slug(data.name or column.name)
if slug != column.slug:
existing = db.query(ColumnModel).filter(ColumnModel.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="栏目标识已存在")
update_data = data.model_dump(exclude_unset=True)
if slug is not None:
update_data["slug"] = slug
for key, value in update_data.items():
setattr(column, key, value)
db.commit()
db.refresh(column)
return column.to_dict()
@router.delete("/admin/columns/{column_id}")
def delete_column(
column_id: int,
force: bool = Query(default=False, description="强制删除关联内容"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
):
"""删除栏目(后台管理)"""
column = db.query(ColumnModel).filter(ColumnModel.id == column_id).first()
if not column:
raise HTTPException(status_code=404, detail="栏目不存在")
# 检查是否有子栏目
child_count = db.query(ColumnModel).filter(ColumnModel.parent_id == column_id).count()
if child_count > 0:
if not force:
raise HTTPException(
status_code=400,
detail=f"该栏目存在 {child_count} 个子栏目,请先删除子栏目或勾选强制删除"
)
# 强制删除:递归删除所有子栏目
db.query(ColumnModel).filter(ColumnModel.parent_id == column_id).delete(synchronize_session=False)
# TODO: 检查关联的内容数量(等 articles 模型创建后补充)
# content_count = db.query(Article).filter(Article.column_id == column_id).count()
# if content_count > 0:
# if not force:
# raise HTTPException(status_code=400, detail=f"该栏目下还有 {content_count} 条内容,是否强制删除?")
# db.query(Article).filter(Article.column_id == column_id).delete(synchronize_session=False)
db.delete(column)
db.commit()
return {"message": "删除成功"}
# ========== 访客端 Public API ==========
@router.get("/public/columns")
def list_public_columns(
db: Session = Depends(get_db),
):
"""访客端:获取启用的栏目树"""
columns = db.query(ColumnModel).filter(
ColumnModel.is_enabled == True
).order_by(ColumnModel.sort_order.asc()).all()
return {"items": _build_tree(columns), "total": len(columns)}
@router.get("/public/columns/{slug}")
def get_public_column(
slug: str,
db: Session = Depends(get_db),
):
"""访客端:获取栏目详情(包含子栏目)"""
column = db.query(ColumnModel).filter(
ColumnModel.slug == slug,
ColumnModel.is_enabled == True
).first()
if not column:
raise HTTPException(status_code=404, detail="栏目不存在")
result = column.to_dict()
# 加载子栏目
children = db.query(ColumnModel).filter(
ColumnModel.parent_id == column.id,
ColumnModel.is_enabled == True
).order_by(ColumnModel.sort_order.asc()).all()
result["children"] = [c.to_dict() for c in children]
# 加载栏目下的内容数量
from app.models.article import Article
article_count = db.query(Article).filter(
Article.column_id == column.id,
Article.status == "published"
).count()
result["article_count"] = article_count
return result
@@ -0,0 +1,190 @@
# app/routers/contact_qrcodes.py
import os
import uuid
from typing import List, Union
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
import qrcode
from qrcode.image.pil import PilImage
from app.database import get_db
from app.models.contact_qrcode import ContactQRCode
from app.models.admin import Admin
from app.auth import get_current_admin
from app.config import get_settings
router = APIRouter()
settings = get_settings()
# Schemas
class ContactQRCodeCreate(BaseModel):
content: str
description: str = ""
sort_order: int = 0
is_enabled: bool = True
class ContactQRCodeUpdate(BaseModel):
content: str = None
description: str = None
sort_order: int = None
is_enabled: bool = None
class ContactQRCodeResponse(BaseModel):
code: int = 200
data: Union[dict, list] = None
message: str = "success"
# Helper
def get_qrcode_dir():
# __file__ = backend/app/routers/contact_qrcodes.py
# 需要向上3级才能到达项目根目录
routers_dir = os.path.dirname(os.path.abspath(__file__)) # backend/app/routers
app_dir = os.path.dirname(routers_dir) # backend/app
backend_dir = os.path.dirname(app_dir) # backend
project_root = os.path.dirname(backend_dir) # project root
qrcode_dir = os.path.join(project_root, "storage", "admin", "images", "qrcode")
os.makedirs(qrcode_dir, exist_ok=True)
return qrcode_dir
def generate_qrcode_image(content: str, filename: str) -> str:
"""Generate QR code image and save to storage, return URL path"""
qrcode_dir = get_qrcode_dir()
filepath = os.path.join(qrcode_dir, filename)
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(content)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
img.save(filepath)
return f"/storage/admin/images/qrcode/{filename}"
def qrcode_to_dict(qr: ContactQRCode) -> dict:
return {
"id": qr.id,
"content": qr.content,
"description": qr.description,
"image_path": qr.image_path,
"sort_order": qr.sort_order,
"is_enabled": qr.is_enabled,
}
# Public routes
@router.get("/contact-qrcodes", response_model=ContactQRCodeResponse)
def get_public_qrcodes(db: Session = Depends(get_db)):
"""Get enabled QR codes for public display"""
qrcodes = db.query(ContactQRCode).filter(
ContactQRCode.is_enabled == True
).order_by(ContactQRCode.sort_order.asc()).all()
return ContactQRCodeResponse(data=[qrcode_to_dict(q) for q in qrcodes])
# Admin routes
@router.get("/admin/contact-qrcodes", response_model=ContactQRCodeResponse)
def get_admin_qrcodes(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get all QR codes for admin"""
qrcodes = db.query(ContactQRCode).order_by(ContactQRCode.sort_order.asc()).all()
return ContactQRCodeResponse(data=[qrcode_to_dict(q) for q in qrcodes])
@router.post("/admin/contact-qrcodes", response_model=ContactQRCodeResponse)
def create_qrcode(
request: ContactQRCodeCreate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Create new QR code, auto-generate image"""
if not request.content.strip():
raise HTTPException(status_code=400, detail="内容不能为空")
filename = f"qrcode_{uuid.uuid4().hex[:8]}.png"
image_path = generate_qrcode_image(request.content.strip(), filename)
qr = ContactQRCode(
content=request.content.strip(),
description=request.description.strip() if request.description else "",
image_path=image_path,
sort_order=request.sort_order,
is_enabled=request.is_enabled,
)
db.add(qr)
db.commit()
db.refresh(qr)
return ContactQRCodeResponse(message="创建成功", data=qrcode_to_dict(qr))
@router.put("/admin/contact-qrcodes/{qr_id}", response_model=ContactQRCodeResponse)
def update_qrcode(
qr_id: int,
request: ContactQRCodeUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Update QR code, regenerate image if content changed"""
qr = db.query(ContactQRCode).filter(ContactQRCode.id == qr_id).first()
if not qr:
raise HTTPException(status_code=404, detail="QR code not found")
update_data = request.dict(exclude_unset=True)
# If content changed, regenerate QR code image
new_content = update_data.get("content", "").strip()
if new_content and new_content != qr.content:
# Delete old image
if qr.image_path:
old_filename = os.path.basename(qr.image_path)
old_filepath = os.path.join(get_qrcode_dir(), old_filename)
if os.path.exists(old_filepath):
os.remove(old_filepath)
# Generate new image
filename = f"qrcode_{uuid.uuid4().hex[:8]}.png"
qr.image_path = generate_qrcode_image(new_content, filename)
qr.content = new_content
update_data.pop("content", None)
for field, value in update_data.items():
setattr(qr, field, value)
db.commit()
db.refresh(qr)
return ContactQRCodeResponse(message="更新成功", data=qrcode_to_dict(qr))
@router.delete("/admin/contact-qrcodes/{qr_id}", response_model=ContactQRCodeResponse)
def delete_qrcode(
qr_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Delete QR code and its image file"""
qr = db.query(ContactQRCode).filter(ContactQRCode.id == qr_id).first()
if not qr:
raise HTTPException(status_code=404, detail="QR code not found")
# Delete image file
if qr.image_path:
filename = os.path.basename(qr.image_path)
filepath = os.path.join(get_qrcode_dir(), filename)
if os.path.exists(filepath):
os.remove(filepath)
db.delete(qr)
db.commit()
return ContactQRCodeResponse(message="删除成功")
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,184 @@
# app/routers/home_experts.py
# 已迁移到新栏目体系(columns/articles),post_id 语义现在指向 Article.id
from typing import List, Union, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.home_expert import HomeExpert
from app.models.article import Article
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
# Schemas
class HomeExpertCreate(BaseModel):
post_id: int # 语义:article.id
sort_order: int = 0
is_enabled: bool = True
class HomeExpertUpdate(BaseModel):
post_id: Optional[int] = None
sort_order: Optional[int] = None
is_enabled: Optional[bool] = None
class HomeExpertResponse(BaseModel):
code: int = 200
data: Union[dict, list] = None
message: str = "success"
# Helper
def expert_to_dict(expert: HomeExpert, article: Article = None) -> dict:
"""转换为字典。保持对外字段名 `post` 不变,避免破坏前端展示。"""
result = {
"id": expert.id,
"post_id": expert.post_id,
"sort_order": expert.sort_order,
"is_enabled": expert.is_enabled,
}
if article:
result["post"] = {
"id": article.id,
"title": article.title,
"slug": article.slug,
"summary": article.summary,
"cover_image": article.cover_image,
"column_id": article.column_id,
# 兼容老字段名
"category_id": article.column_id,
}
return result
# Public routes
@router.get("/home-experts", response_model=HomeExpertResponse)
def get_public_experts(
limit: int = 6,
db: Session = Depends(get_db)
):
"""访客端:获取启用的专家团队(关联已发布的文章)"""
experts = db.query(HomeExpert).filter(
HomeExpert.is_enabled == True
).order_by(HomeExpert.sort_order.asc()).limit(limit).all()
result = []
for expert in experts:
article = db.query(Article).filter(
Article.id == expert.post_id,
Article.status == "published"
).first()
if article:
result.append(expert_to_dict(expert, article))
return HomeExpertResponse(data=result)
# Admin routes
@router.get("/admin/home-experts", response_model=HomeExpertResponse)
def get_admin_experts(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""后台:获取所有专家团队(含文章信息)"""
experts = db.query(HomeExpert).order_by(HomeExpert.sort_order.asc()).all()
result = []
for expert in experts:
article = db.query(Article).filter(Article.id == expert.post_id).first()
result.append(expert_to_dict(expert, article))
return HomeExpertResponse(data=result)
@router.get("/admin/home-experts/available-posts", response_model=HomeExpertResponse)
def get_available_posts(
keyword: Optional[str] = None,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""后台:获取可选的已发布文章列表(供挑选作为专家)"""
query = db.query(Article).filter(Article.status == "published")
if keyword:
query = query.filter(Article.title.contains(keyword))
articles = query.order_by(Article.created_at.desc()).limit(50).all()
return HomeExpertResponse(data=[
{
"id": a.id,
"title": a.title,
"slug": a.slug,
"summary": a.summary,
"cover_image": a.cover_image,
"column_id": a.column_id,
"created_at": a.created_at.isoformat() if a.created_at else None,
}
for a in articles
])
@router.post("/admin/home-experts", response_model=HomeExpertResponse)
def create_expert(
request: HomeExpertCreate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""添加一篇文章为专家团队成员"""
article = db.query(Article).filter(Article.id == request.post_id).first()
if not article:
raise HTTPException(status_code=404, detail="资讯不存在")
existing = db.query(HomeExpert).filter(HomeExpert.post_id == request.post_id).first()
if existing:
raise HTTPException(status_code=400, detail="该资讯已添加到专家团队")
expert = HomeExpert(
post_id=request.post_id,
sort_order=request.sort_order,
is_enabled=request.is_enabled,
)
db.add(expert)
db.commit()
db.refresh(expert)
return HomeExpertResponse(message="添加成功", data=expert_to_dict(expert, article))
@router.put("/admin/home-experts/{expert_id}", response_model=HomeExpertResponse)
def update_expert(
expert_id: int,
request: HomeExpertUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""更新专家团队条目"""
expert = db.query(HomeExpert).filter(HomeExpert.id == expert_id).first()
if not expert:
raise HTTPException(status_code=404, detail="专家不存在")
for field, value in request.dict(exclude_unset=True).items():
setattr(expert, field, value)
db.commit()
db.refresh(expert)
article = db.query(Article).filter(Article.id == expert.post_id).first()
return HomeExpertResponse(message="更新成功", data=expert_to_dict(expert, article))
@router.delete("/admin/home-experts/{expert_id}", response_model=HomeExpertResponse)
def delete_expert(
expert_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""从首页专家团队移除(不删除原文章)"""
expert = db.query(HomeExpert).filter(HomeExpert.id == expert_id).first()
if not expert:
raise HTTPException(status_code=404, detail="专家不存在")
db.delete(expert)
db.commit()
return HomeExpertResponse(message="移除成功")
@@ -0,0 +1,184 @@
# app/routers/home_modules.py
import json
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.home_module import HomeModule
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
# Schemas
class ModuleContent(BaseModel):
pass
class ModuleStyleConfig(BaseModel):
pass
class ModuleUpdate(BaseModel):
title: Optional[str] = None
subtitle: Optional[str] = None
content: Optional[dict] = None
style_config: Optional[dict] = None
is_enabled: Optional[bool] = None
sort_order: Optional[int] = None
class ModuleSortItem(BaseModel):
id: int
sort_order: int
class ModuleSortRequest(BaseModel):
orders: List[ModuleSortItem]
class ModuleResponse(BaseModel):
code: int = 200
data: dict | list = None
# Helper functions
def module_to_dict(module: HomeModule) -> dict:
return {
"id": module.id,
"name": module.name,
"code": module.code,
"type": module.type,
"sort_order": module.sort_order,
"is_enabled": module.is_enabled,
"is_fixed": module.is_fixed,
"title": module.title,
"subtitle": module.subtitle,
"content": json.loads(module.content) if module.content else {},
"style_config": json.loads(module.style_config) if module.style_config else {}
}
# Public routes
@router.get("/home/modules", response_model=ModuleResponse)
def get_public_modules(db: Session = Depends(get_db)):
"""Get all enabled home modules for public display"""
modules = db.query(HomeModule).filter(
HomeModule.is_enabled == True
).order_by(HomeModule.sort_order.asc()).all()
return ModuleResponse(data=[module_to_dict(m) for m in modules])
# Admin routes
@router.get("/admin/home/modules", response_model=ModuleResponse)
def get_admin_modules(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get all home modules for admin management"""
modules = db.query(HomeModule).order_by(HomeModule.sort_order.asc()).all()
# Auto-create missing default modules
existing_types = {m.type for m in modules}
if 'experts' not in existing_types:
expert_module = HomeModule(
name="专家团队",
code="experts",
type="experts",
sort_order=7,
is_enabled=True,
is_fixed=False,
title="专家团队",
content=json.dumps({"view_more_link": ""}),
style_config=json.dumps({"backgroundColor": "#ffffff"})
)
db.add(expert_module)
db.commit()
db.refresh(expert_module)
modules = db.query(HomeModule).order_by(HomeModule.sort_order.asc()).all()
return ModuleResponse(data=[module_to_dict(m) for m in modules])
@router.get("/admin/home/modules/{module_id}", response_model=ModuleResponse)
def get_module_detail(
module_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get single module detail"""
module = db.query(HomeModule).filter(HomeModule.id == module_id).first()
if not module:
raise HTTPException(status_code=404, detail="Module not found")
return ModuleResponse(data=module_to_dict(module))
@router.put("/admin/home/modules/{module_id}", response_model=ModuleResponse)
def update_module(
module_id: int,
request: ModuleUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Update module content and settings"""
module = db.query(HomeModule).filter(HomeModule.id == module_id).first()
if not module:
raise HTTPException(status_code=404, detail="Module not found")
if request.title is not None:
module.title = request.title
if request.subtitle is not None:
module.subtitle = request.subtitle
if request.content is not None:
module.content = json.dumps(request.content, ensure_ascii=False)
if request.style_config is not None:
module.style_config = json.dumps(request.style_config, ensure_ascii=False)
if request.is_enabled is not None:
module.is_enabled = request.is_enabled
if request.sort_order is not None:
module.sort_order = request.sort_order
db.commit()
db.refresh(module)
return ModuleResponse(message="更新成功", data=module_to_dict(module))
@router.put("/admin/home/modules/sort", response_model=ModuleResponse)
def update_module_sort(
request: ModuleSortRequest,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Batch update module sort order"""
for item in request.orders:
module = db.query(HomeModule).filter(HomeModule.id == item.id).first()
if module:
module.sort_order = item.sort_order
db.commit()
return ModuleResponse(message="排序更新成功")
@router.put("/admin/home/modules/{module_id}/toggle", response_model=ModuleResponse)
def toggle_module(
module_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Toggle module enabled status"""
module = db.query(HomeModule).filter(HomeModule.id == module_id).first()
if not module:
raise HTTPException(status_code=404, detail="Module not found")
module.is_enabled = not module.is_enabled
db.commit()
return ModuleResponse(
message="状态更新成功",
data={"id": module.id, "is_enabled": module.is_enabled}
)
@@ -0,0 +1,136 @@
# app/routers/home_partners.py
from typing import Union, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.home_partner import HomePartner
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
# Schemas
class HomePartnerCreate(BaseModel):
name: str
logo_url: Optional[str] = None
description: Optional[str] = None
website_url: Optional[str] = None
sort_order: int = 0
is_enabled: bool = True
class HomePartnerUpdate(BaseModel):
name: Optional[str] = None
logo_url: Optional[str] = None
description: Optional[str] = None
website_url: Optional[str] = None
sort_order: Optional[int] = None
is_enabled: Optional[bool] = None
class HomePartnerResponse(BaseModel):
code: int = 200
data: Union[dict, list, None] = None
message: str = "success"
# Helper
def partner_to_dict(partner: HomePartner) -> dict:
return {
"id": partner.id,
"name": partner.name,
"logo_url": partner.logo_url,
"description": partner.description,
"website_url": partner.website_url,
"sort_order": partner.sort_order,
"is_enabled": partner.is_enabled,
"created_at": partner.created_at.isoformat() if partner.created_at else None,
"updated_at": partner.updated_at.isoformat() if partner.updated_at else None,
}
# Public routes
@router.get("/home-partners", response_model=HomePartnerResponse)
def get_public_partners(
limit: int = 20,
db: Session = Depends(get_db)
):
"""Get enabled home partners for public display"""
partners = db.query(HomePartner).filter(
HomePartner.is_enabled == True
).order_by(HomePartner.sort_order.asc()).limit(limit).all()
result = [partner_to_dict(p) for p in partners]
return HomePartnerResponse(data=result)
# Admin routes
@router.get("/admin/home-partners", response_model=HomePartnerResponse)
def get_admin_partners(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get all home partners for admin"""
partners = db.query(HomePartner).order_by(HomePartner.sort_order.asc()).all()
result = [partner_to_dict(p) for p in partners]
return HomePartnerResponse(data=result)
@router.post("/admin/home-partners", response_model=HomePartnerResponse)
def create_partner(
request: HomePartnerCreate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Create a new home partner"""
partner = HomePartner(
name=request.name,
logo_url=request.logo_url,
description=request.description,
website_url=request.website_url,
sort_order=request.sort_order,
is_enabled=request.is_enabled,
)
db.add(partner)
db.commit()
db.refresh(partner)
return HomePartnerResponse(message="添加成功", data=partner_to_dict(partner))
@router.put("/admin/home-partners/{partner_id}", response_model=HomePartnerResponse)
def update_partner(
partner_id: int,
request: HomePartnerUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Update home partner"""
partner = db.query(HomePartner).filter(HomePartner.id == partner_id).first()
if not partner:
raise HTTPException(status_code=404, detail="合作伙伴不存在")
for field, value in request.dict(exclude_unset=True).items():
setattr(partner, field, value)
db.commit()
db.refresh(partner)
return HomePartnerResponse(message="更新成功", data=partner_to_dict(partner))
@router.delete("/admin/home-partners/{partner_id}", response_model=HomePartnerResponse)
def delete_partner(
partner_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Delete home partner"""
partner = db.query(HomePartner).filter(HomePartner.id == partner_id).first()
if not partner:
raise HTTPException(status_code=404, detail="合作伙伴不存在")
db.delete(partner)
db.commit()
return HomePartnerResponse(message="删除成功")
@@ -0,0 +1,359 @@
"""
图片资源管理 API 路由
复用自 personal-blog,添加 module 字段支持多模块共用
图片扁平存储在 /uploads 目录下,缩略图在 /uploads/thumbnails/
"""
import os
import re
import uuid
import shutil
from datetime import datetime
from typing import Optional
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile, File, Form
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from sqlalchemy import or_
from PIL import Image as PILImage
from app.database import get_db
from app.models.image import Image
from app.models.article import Article
from app.routers.auth import get_current_admin
from app.config import get_settings
from app.utils.file_utils import cleanup_file_by_path
router = APIRouter(prefix="/images", tags=["images"], redirect_slashes=False)
# 上传配置 - 使用与静态文件服务相同的目录
settings = get_settings()
UPLOAD_DIR = Path(settings.UPLOAD_DIR)
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
# 缩略图目录
THUMBNAIL_DIR = UPLOAD_DIR / "thumbnails"
THUMBNAIL_DIR.mkdir(exist_ok=True)
# 允许的图片格式
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
def generate_filename(original_name: str) -> str:
"""生成唯一文件名"""
ext = Path(original_name).suffix.lower()
if ext not in ALLOWED_EXTENSIONS:
raise HTTPException(status_code=400, detail=f"不支持的文件格式,允许: {', '.join(ALLOWED_EXTENSIONS)}")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
unique_id = uuid.uuid4().hex[:8]
return f"{timestamp}_{unique_id}{ext}"
def create_thumbnail(image_path: Path, thumb_path: Path, max_size: int = 300):
"""创建缩略图"""
try:
with PILImage.open(image_path) as img:
# 转换为 RGB(处理透明图片)
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
# 等比缩放到最大尺寸
img.thumbnail((max_size, max_size), PILImage.Resampling.LANCZOS)
# 保存
img.save(thumb_path, "JPEG", quality=85)
return True
except Exception as e:
print(f"创建缩略图失败: {e}")
return False
@router.get("")
@router.get("/")
def list_images(
page: int = Query(default=1, ge=1),
size: int = Query(default=20, ge=1, le=100),
module: Optional[str] = Query(default=None, description="按模块筛选"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""获取图片列表(同时支持 /api/images 和 /api/images/)"""
query = db.query(Image).order_by(Image.created_at.desc())
if module:
query = query.filter(Image.module == module)
total = query.count()
images = query.offset((page - 1) * size).limit(size).all()
return {
"items": [img.to_dict() for img in images],
"total": total,
"page": page,
"size": size
}
@router.post("/upload")
async def upload_image(
file: UploadFile = File(...),
description: Optional[str] = Form(default=None),
module: str = Form(default="news"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""上传图片 - 扁平存储在 /uploads 目录"""
# 检查文件大小
file_size = 0
content = await file.read()
file_size = len(content)
if file_size > MAX_FILE_SIZE:
raise HTTPException(status_code=400, detail=f"文件大小超过限制 ({MAX_FILE_SIZE / 1024 / 1024}MB)")
# 生成文件名
try:
filename = generate_filename(file.filename)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=400, detail="文件名处理失败")
# 扁平存储 - 直接放在 /uploads 目录下
file_path = UPLOAD_DIR / filename
with open(file_path, "wb") as f:
f.write(content)
# 获取图片尺寸
width, height = None, None
try:
with PILImage.open(file_path) as img:
width, height = img.size
except Exception:
pass
# 创建缩略图 - 统一放在 thumbnails 目录下
# 缩略图与原图同名,但扩展名统一为 .jpg
thumbnail_name = f"{Path(filename).stem}.jpg"
thumb_file_path = THUMBNAIL_DIR / thumbnail_name
thumb_relative_path = None
if create_thumbnail(file_path, thumb_file_path):
thumb_relative_path = f"/storage/admin/images/thumbnails/{thumbnail_name}"
# 保存到数据库 - 使用新的存储路径
relative_file_path = f"/storage/admin/images/{filename}"
image = Image(
filename=filename,
original_name=file.filename,
file_path=relative_file_path,
thumb_path=thumb_relative_path,
description=description,
file_size=file_size,
width=width,
height=height,
module=module
)
db.add(image)
db.commit()
db.refresh(image)
return {
"success": True,
"data": image.to_dict()
}
@router.delete("/{image_id}")
def delete_image(
image_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""删除图片"""
image = db.query(Image).filter(Image.id == image_id).first()
if not image:
raise HTTPException(status_code=404, detail="图片不存在")
# 删除物理文件及其缩略图
cleanup_file_by_path(image.file_path)
db.delete(image)
db.commit()
return {"message": "删除成功"}
@router.put("/{image_id}")
def update_image(
image_id: int,
description: Optional[str] = Form(default=None),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""更新图片描述"""
image = db.query(Image).filter(Image.id == image_id).first()
if not image:
raise HTTPException(status_code=404, detail="图片不存在")
if description is not None:
image.description = description
db.commit()
db.refresh(image)
return image.to_dict()
@router.get("/{image_id}/insert")
def get_image_insert_info(
image_id: int,
size: str = Query(default="original", pattern="^(original|thumb)$"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""获取图片插入信息(用于编辑器插入)"""
image = db.query(Image).filter(Image.id == image_id).first()
if not image:
raise HTTPException(status_code=404, detail="图片不存在")
url = image.file_path if size == "original" else (image.thumb_path or image.file_path)
return {
"id": image.id,
"url": url,
"width": image.width,
"height": image.height,
"original_name": image.original_name
}
@router.post("/batch-delete")
def batch_delete_images(
image_ids: list[int],
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""批量删除图片"""
deleted_count = 0
for image_id in image_ids:
image = db.query(Image).filter(Image.id == image_id).first()
if image:
# 删除物理文件及其缩略图
cleanup_file_by_path(image.file_path)
db.delete(image)
deleted_count += 1
db.commit()
return {"message": f"成功删除 {deleted_count} 张图片"}
def _collect_referenced_paths(db: Session) -> set:
"""收集所有被文章引用的图片路径(封面图 + 内容中的图片)。
优化:仅加载有图片引用的文章,跳过无封面且内容无图片路径的文章。
"""
referenced_paths = set()
# 预过滤:只查有 cover_image 或内容中可能包含图片的文章
articles = db.query(Article).filter(
or_(
Article.cover_image.isnot(None),
Article.cover_image != '',
Article.content.like('%/storage/%'),
Article.content.like('%/uploads/%'),
Article.content.like('%.jpg%'),
Article.content.like('%.png%'),
Article.content.like('%.gif%'),
Article.content.like('%.webp%'),
)
).all()
for post in articles:
if post.cover_image:
referenced_paths.add(post.cover_image)
if post.content:
# Markdown: ![alt](path) 或 <img src="path">
md_images = re.findall(r'!\[.*?\]\((.*?)\)', post.content)
html_images = re.findall(r'<img[^>]+src=["\']([^"\']+)["\']', post.content)
for path in md_images + html_images:
referenced_paths.add(path)
return referenced_paths
@router.get("/unreferenced")
def get_unreferenced_images(
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""扫描未被任何文章引用的图片"""
referenced_paths = _collect_referenced_paths(db)
# 仅获取有 file_path 的图片
all_images = db.query(Image).filter(Image.file_path.isnot(None)).all()
# 找出未引用的图片
unreferenced = []
for img in all_images:
if img.file_path not in referenced_paths:
unreferenced.append(img.to_dict())
return {
"items": unreferenced,
"total": len(unreferenced)
}
@router.post("/cleanup")
def cleanup_unreferenced_images(
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""批量删除未被任何文章引用的图片"""
referenced_paths = _collect_referenced_paths(db)
# 仅获取有 file_path 的图片
all_images = db.query(Image).filter(Image.file_path.isnot(None)).all()
# 删除未引用的图片
deleted_count = 0
deleted_files = []
for img in all_images:
if img.file_path not in referenced_paths:
cleanup_file_by_path(img.file_path)
deleted_files.append(img.to_dict())
db.delete(img)
deleted_count += 1
db.commit()
return {
"message": f"成功清理 {deleted_count} 张未引用图片",
"deleted_count": deleted_count,
"deleted_files": deleted_files
}
# 静态文件服务(开发环境使用,生产环境建议用 Nginx)
@router.get("/file/{path:path}")
def serve_image(path: str):
"""提供图片文件访问"""
file_path = UPLOAD_DIR / path
if not file_path.exists():
raise HTTPException(status_code=404, detail="文件不存在")
# 安全检查,防止目录遍历
try:
file_path.resolve().relative_to(UPLOAD_DIR.resolve())
except ValueError:
raise HTTPException(status_code=403, detail="禁止访问")
return FileResponse(file_path)
@@ -0,0 +1,124 @@
# app/routers/nav_menus.py
from typing import List, Union, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.nav_menu import NavMenu
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
# Schemas
class NavMenuCreate(BaseModel):
name: str
link: str
sort_order: int = 0
is_enabled: bool = True
is_external: bool = False
parent_id: Optional[int] = None
class NavMenuUpdate(BaseModel):
name: str = None
link: str = None
sort_order: int = None
is_enabled: bool = None
is_external: bool = None
parent_id: Optional[int] = None
class NavMenuResponse(BaseModel):
code: int = 200
data: Union[dict, list] = None
message: str = "success"
# Helper
def menu_to_dict(menu: NavMenu) -> dict:
return {
"id": menu.id,
"name": menu.name,
"link": menu.link,
"sort_order": menu.sort_order,
"is_enabled": menu.is_enabled,
"is_external": menu.is_external,
"parent_id": menu.parent_id,
"children": [menu_to_dict(c) for c in menu.children if c.is_enabled] if menu.children else []
}
# Public routes
@router.get("/nav", response_model=NavMenuResponse)
def get_public_menus(db: Session = Depends(get_db)):
"""Get enabled nav menus for public display"""
menus = db.query(NavMenu).filter(
NavMenu.is_enabled == True,
NavMenu.parent_id == None
).order_by(NavMenu.sort_order.asc()).all()
return NavMenuResponse(data=[menu_to_dict(m) for m in menus])
# Admin routes
@router.get("/admin/nav", response_model=NavMenuResponse)
def get_admin_menus(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get all nav menus for admin"""
menus = db.query(NavMenu).order_by(NavMenu.sort_order.asc()).all()
return NavMenuResponse(data=[menu_to_dict(m) for m in menus])
@router.post("/admin/nav", response_model=NavMenuResponse)
def create_menu(
request: NavMenuCreate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Create new nav menu"""
menu = NavMenu(**request.dict())
db.add(menu)
db.commit()
db.refresh(menu)
return NavMenuResponse(message="创建成功", data=menu_to_dict(menu))
@router.put("/admin/nav/{menu_id}", response_model=NavMenuResponse)
def update_menu(
menu_id: int,
request: NavMenuUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Update nav menu"""
menu = db.query(NavMenu).filter(NavMenu.id == menu_id).first()
if not menu:
raise HTTPException(status_code=404, detail="Menu not found")
for field, value in request.dict(exclude_unset=True).items():
setattr(menu, field, value)
db.commit()
db.refresh(menu)
return NavMenuResponse(message="更新成功", data=menu_to_dict(menu))
@router.delete("/admin/nav/{menu_id}", response_model=NavMenuResponse)
def delete_menu(
menu_id: int,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Delete nav menu"""
menu = db.query(NavMenu).filter(NavMenu.id == menu_id).first()
if not menu:
raise HTTPException(status_code=404, detail="Menu not found")
db.delete(menu)
db.commit()
return NavMenuResponse(message="删除成功")
@@ -0,0 +1,574 @@
# ⚠️ 此新闻模块已废弃,不再使用。
# 已被「栏目管理 + 内容管理」(columns.py + articles.py)取代。
# 请勿删除此注释,供后续维护人员参考。
"""
新闻资讯 API 路由(已废弃)
包含栏目管理和资讯管理
"""
import html
import os
import re
import shutil
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import func
from pydantic import BaseModel, Field
from pypinyin import lazy_pinyin
def extract_summary(content: str, max_length: int = 100) -> str:
"""从 HTML/Markdown 内容中提取纯文本摘要"""
if not content:
return ""
# 去除 HTML 标签
text = re.sub(r'<[^>]+>', '', content)
# 解码 HTML 实体(如 &quot; &nbsp; &lt; 等)
text = html.unescape(text)
# 去除 Markdown 标记(简化处理)
text = re.sub(r'[#*_`~\[\]\(\)!>-]', '', text)
# 去除多余空白
text = re.sub(r'\s+', ' ', text).strip()
# 截取摘要
if len(text) > max_length:
return text[:max_length] + "..."
return text
from app.models.news_category import NewsCategory
from app.models.news_post import NewsPost
from app.models.image import Image
from app.routers.auth import get_current_admin
from app.utils.file_utils import cleanup_file_by_path
from app.database import get_db
router = APIRouter(prefix="/news", tags=["news"])
def generate_slug(text: str) -> str:
"""将中文标题转为拼音 slug"""
if not text:
return ''
# 转拼音,无音调
py = lazy_pinyin(text, style=0)
slug = '-'.join(py)
# 清理特殊字符
slug = re.sub(r'[^a-zA-Z0-9-]', '', slug).lower()
# 去重横线
slug = re.sub(r'-+', '-', slug).strip('-')
return slug or f'post-{int(__import__("time").time())}'
# ========== Pydantic 模型 ==========
class CategoryCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=50)
slug: Optional[str] = Field(None, max_length=50)
description: Optional[str] = Field(None, max_length=200)
sort_order: int = Field(default=0)
is_enabled: bool = Field(default=True)
class CategoryUpdate(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=50)
slug: Optional[str] = Field(None, min_length=1, max_length=50)
description: Optional[str] = Field(None, max_length=200)
sort_order: Optional[int] = None
is_enabled: Optional[bool] = None
class PostCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=200)
slug: Optional[str] = Field(None, max_length=200)
content: str = Field(..., min_length=1)
content_type: str = Field(default="markdown", pattern="^(markdown|html)$")
summary: Optional[str] = Field(None, max_length=500)
cover_image: Optional[str] = Field(None, max_length=500)
category_id: int
is_draft: bool = Field(default=True)
class PostUpdate(BaseModel):
title: Optional[str] = Field(None, min_length=1, max_length=200)
slug: Optional[str] = Field(None, min_length=1, max_length=200)
content: Optional[str] = Field(None, min_length=1)
content_type: Optional[str] = Field(None, pattern="^(markdown|html)$")
summary: Optional[str] = Field(None, max_length=500)
cover_image: Optional[str] = Field(None, max_length=500)
category_id: Optional[int] = None
is_draft: Optional[bool] = None
class PostPublish(BaseModel):
is_published: bool
# ========== 临时图片迁移辅助函数 ==========
TEMP_STORAGE_PREFIX = "/storage/tmp/crawl"
def get_upload_dir():
"""获取上传目录路径"""
from app.config import get_settings
settings = get_settings()
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
return os.path.join(base_dir, settings.UPLOAD_DIR)
def get_crawl_temp_dir():
"""获取采集临时目录 - 跨平台"""
if os.name == 'nt': # Windows
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
return os.path.join(base_dir, 'storage', 'tmp', 'crawl')
return '/tmp/news_crawl'
def migrate_temp_images(content: str, cover_image: Optional[str], db: Session):
"""
将内容中的临时图片迁移到正式目录,并写入 images 表。
返回更新后的 (content, cover_image)。
"""
upload_dir = get_upload_dir()
temp_dir = get_crawl_temp_dir()
# 收集所有需要迁移的临时路径
temp_paths = set()
if cover_image and cover_image.startswith(TEMP_STORAGE_PREFIX):
temp_paths.add(cover_image)
# 从 content 中查找所有临时图片路径
pattern = re.escape(TEMP_STORAGE_PREFIX) + r'/[^\\)"\'>\s]+'
for match in re.finditer(pattern, content):
temp_paths.add(match.group())
if not temp_paths:
return content, cover_image
# 路径映射: 临时路径 -> 正式路径
path_mapping = {}
for temp_path in temp_paths:
filename = os.path.basename(temp_path)
temp_file = os.path.join(temp_dir, filename)
if not os.path.exists(temp_file):
continue
# 移动到正式目录
dest_file = os.path.join(upload_dir, filename)
shutil.move(temp_file, dest_file)
# 迁移缩略图
thumb_filename = f"{os.path.splitext(filename)[0]}.jpg"
temp_thumb = os.path.join(temp_dir, "thumbnails", thumb_filename)
dest_thumb = os.path.join(upload_dir, "thumbnails", thumb_filename)
if os.path.exists(temp_thumb):
shutil.move(temp_thumb, dest_thumb)
formal_path = f"/storage/admin/images/{filename}"
formal_thumb = f"/storage/admin/images/thumbnails/{thumb_filename}"
path_mapping[temp_path] = formal_path
# 写入 images 表
try:
file_size = os.path.getsize(dest_file)
except OSError:
file_size = 0
existing = db.query(Image).filter(Image.file_path == formal_path).first()
if not existing:
img_record = Image(
filename=filename,
original_name=filename,
file_path=formal_path,
thumb_path=formal_thumb,
file_size=file_size,
module="news"
)
db.add(img_record)
# 替换 content 中的路径
new_content = content
for temp_path, formal_path in path_mapping.items():
new_content = new_content.replace(temp_path, formal_path)
# 替换 cover_image
new_cover = cover_image
if cover_image and cover_image in path_mapping:
new_cover = path_mapping[cover_image]
return new_content, new_cover
# ========== 栏目管理 API ==========
@router.get("/categories")
def list_categories(
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin),
include_count: bool = Query(default=True, description="是否包含文章数量")
):
"""获取栏目列表"""
query = db.query(NewsCategory).order_by(NewsCategory.sort_order.asc())
categories = query.all()
# 获取每个栏目的文章数量
if include_count:
counts = db.query(
NewsPost.category_id,
func.count(NewsPost.id).label("count")
).group_by(NewsPost.category_id).all()
count_map = {c.category_id: c.count for c in counts}
for cat in categories:
cat.post_count = count_map.get(cat.id, 0)
return {
"items": [cat.to_dict(include_post_count=include_count) for cat in categories],
"total": len(categories)
}
@router.post("/categories")
def create_category(
data: CategoryCreate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""创建栏目"""
# 自动生成 slug(如果未提供)
slug = data.slug or generate_slug(data.name)
# 检查 slug 是否已存在
existing = db.query(NewsCategory).filter(NewsCategory.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="栏目标识已存在")
category = NewsCategory(**{**data.model_dump(), "slug": slug})
db.add(category)
db.commit()
db.refresh(category)
return category.to_dict()
@router.get("/categories/{category_id}")
def get_category(
category_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""获取栏目详情"""
category = db.query(NewsCategory).filter(NewsCategory.id == category_id).first()
if not category:
raise HTTPException(status_code=404, detail="栏目不存在")
return category.to_dict(include_post_count=True)
@router.put("/categories/{category_id}")
def update_category(
category_id: int,
data: CategoryUpdate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""更新栏目"""
category = db.query(NewsCategory).filter(NewsCategory.id == category_id).first()
if not category:
raise HTTPException(status_code=404, detail="栏目不存在")
# 检查 slug 是否冲突
if data.slug and data.slug != category.slug:
existing = db.query(NewsCategory).filter(NewsCategory.slug == data.slug).first()
if existing:
raise HTTPException(status_code=400, detail="栏目标识已存在")
for key, value in data.model_dump(exclude_unset=True).items():
setattr(category, key, value)
db.commit()
db.refresh(category)
return category.to_dict()
@router.delete("/categories/{category_id}")
def delete_category(
category_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""删除栏目"""
category = db.query(NewsCategory).filter(NewsCategory.id == category_id).first()
if not category:
raise HTTPException(status_code=404, detail="栏目不存在")
# 检查是否有文章使用此栏目
post_count = db.query(NewsPost).filter(NewsPost.category_id == category_id).count()
if post_count > 0:
raise HTTPException(status_code=400, detail="该栏目下还有文章,无法删除")
db.delete(category)
db.commit()
return {"message": "删除成功"}
# ========== 资讯管理 API ==========
@router.get("/posts")
def list_posts(
page: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=100),
category_id: Optional[int] = Query(default=None),
keyword: Optional[str] = Query(default=None),
status: Optional[str] = Query(default=None, pattern="^(published|draft|all)$"),
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""获取资讯列表"""
query = db.query(NewsPost).options(joinedload(NewsPost.category))
# 筛选条件
if category_id:
query = query.filter(NewsPost.category_id == category_id)
if keyword:
query = query.filter(NewsPost.title.contains(keyword))
if status == "published":
query = query.filter(NewsPost.is_published == True)
elif status == "draft":
query = query.filter(NewsPost.is_draft == True)
# 排序:先按创建时间倒序
query = query.order_by(NewsPost.created_at.desc())
# 分页
total = query.count()
posts = query.offset((page - 1) * size).limit(size).all()
return {
"items": [post.to_dict(include_content=False) for post in posts],
"total": total,
"page": page,
"size": size
}
@router.post("/posts")
def create_post(
data: PostCreate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""创建资讯"""
# 自动生成 slug(如果未提供)
slug = data.slug or generate_slug(data.title)
# 检查 slug 是否已存在
existing = db.query(NewsPost).filter(NewsPost.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="文章标识已存在")
# 检查栏目是否存在
category = db.query(NewsCategory).filter(NewsCategory.id == data.category_id).first()
if not category:
raise HTTPException(status_code=404, detail="栏目不存在")
# 自动生成摘要(如果未提供)
summary = data.summary
if not summary:
summary = extract_summary(data.content, max_length=100)
# 迁移临时图片到正式目录
migrated_content, migrated_cover = migrate_temp_images(data.content, data.cover_image, db)
post = NewsPost(
title=data.title,
slug=slug,
content=migrated_content,
content_type=data.content_type,
summary=summary,
cover_image=migrated_cover,
category_id=data.category_id,
is_draft=data.is_draft,
is_published=not data.is_draft
)
db.add(post)
db.commit()
db.refresh(post)
return post.to_dict(include_content=True)
@router.get("/posts/{post_id}")
def get_post(
post_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""获取资讯详情"""
post = db.query(NewsPost).options(joinedload(NewsPost.category)).filter(NewsPost.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="文章不存在")
return post.to_dict(include_content=True)
@router.put("/posts/{post_id}")
def update_post(
post_id: int,
data: PostUpdate,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""更新资讯"""
post = db.query(NewsPost).filter(NewsPost.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="文章不存在")
# 检查 slug 是否冲突(如果提供了新的 slug)
slug = data.slug
if slug is not None:
if not slug.strip():
slug = generate_slug(data.title or post.title)
if slug != post.slug:
existing = db.query(NewsPost).filter(NewsPost.slug == slug).first()
if existing:
raise HTTPException(status_code=400, detail="文章标识已存在")
# 检查栏目是否存在
if data.category_id:
category = db.query(NewsCategory).filter(NewsCategory.id == data.category_id).first()
if not category:
raise HTTPException(status_code=404, detail="栏目不存在")
update_data = data.model_dump(exclude_unset=True)
if slug is not None:
update_data['slug'] = slug
# 如果摘要被清空,自动从内容重新提取
if "summary" in update_data and not update_data["summary"].strip():
content_to_extract = update_data.get("content") or post.content
if content_to_extract:
update_data["summary"] = extract_summary(content_to_extract, max_length=100)
# 处理草稿/发布状态联动
if "is_draft" in update_data:
update_data["is_published"] = not update_data["is_draft"]
for key, value in update_data.items():
setattr(post, key, value)
db.commit()
db.refresh(post)
return post.to_dict(include_content=True)
@router.delete("/posts/{post_id}")
def delete_post(
post_id: int,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""删除资讯"""
post = db.query(NewsPost).filter(NewsPost.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="文章不存在")
# 删除封面图及其缩略图
if post.cover_image:
cleanup_file_by_path(post.cover_image)
db.delete(post)
db.commit()
return {"message": "删除成功"}
@router.post("/posts/{post_id}/publish")
def publish_post(
post_id: int,
data: PostPublish,
db: Session = Depends(get_db),
current_admin=Depends(get_current_admin)
):
"""发布/取消发布资讯"""
post = db.query(NewsPost).filter(NewsPost.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="文章不存在")
post.is_published = data.is_published
post.is_draft = not data.is_published
db.commit()
db.refresh(post)
return post.to_dict()
# ========== 访客端 API(无需认证)==========
@router.get("/public/posts")
def list_public_posts(
page: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=50),
category_slug: Optional[str] = Query(default=None),
db: Session = Depends(get_db)
):
"""访客端:获取已发布的资讯列表(仅显示 is_enabled=True 栏目下的文章)"""
query = db.query(NewsPost).options(joinedload(NewsPost.category)).join(
NewsCategory, NewsPost.category_id == NewsCategory.id
).filter(
NewsPost.is_published == True,
NewsCategory.is_enabled == True
)
# 按栏目筛选
if category_slug:
category = db.query(NewsCategory).filter(NewsCategory.slug == category_slug).first()
if category:
query = query.filter(NewsPost.category_id == category.id)
query = query.order_by(NewsPost.created_at.desc())
total = query.count()
posts = query.offset((page - 1) * size).limit(size).all()
return {
"items": [post.to_dict(include_content=False) for post in posts],
"total": total,
"page": page,
"size": size
}
@router.get("/public/posts/{slug}")
def get_public_post(
slug: str,
db: Session = Depends(get_db)
):
"""访客端:通过 slug 获取文章详情"""
post = db.query(NewsPost).options(joinedload(NewsPost.category)).filter(
NewsPost.slug == slug,
NewsPost.is_published == True
).first()
if not post:
raise HTTPException(status_code=404, detail="文章不存在")
# 增加浏览次数
post.view_count += 1
db.commit()
return post.to_dict(include_content=True)
@router.get("/public/categories")
def list_public_categories(
db: Session = Depends(get_db)
):
"""访客端:获取启用的栏目列表"""
categories = db.query(NewsCategory).filter(
NewsCategory.is_enabled == True
).order_by(NewsCategory.sort_order.asc()).all()
return {
"data": {
"items": [cat.to_dict() for cat in categories],
"total": len(categories)
}
}
@@ -0,0 +1,93 @@
# app/routers/settings.py
from typing import Dict
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.setting import Setting
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
# Public settings keys that can be accessed without auth
PUBLIC_SETTINGS = [
"site_name", "site_logo", "site_favicon", "site_description",
"contact_phones", "contact_emails", "contact_address",
"social_links", "friend_links",
"copyright", "bottom_links",
"privacy_url", "terms_url", "sitemap_url",
"seo_title", "seo_description", "seo_keywords"
]
# Schemas
class SettingsUpdate(BaseModel):
settings: Dict[str, str]
class SettingsResponse(BaseModel):
code: int = 200
data: dict = None
message: str = "success"
# Helper
def get_setting_value(db: Session, key: str) -> str:
setting = db.query(Setting).filter(Setting.key == key).first()
return setting.value if setting else None
def set_setting_value(db: Session, key: str, value: str):
setting = db.query(Setting).filter(Setting.key == key).first()
if setting:
setting.value = value
else:
setting = Setting(key=key, value=value)
db.add(setting)
# Public routes
@router.get("/settings", response_model=SettingsResponse)
def get_public_settings(db: Session = Depends(get_db)):
"""Get public settings"""
result = {}
for key in PUBLIC_SETTINGS:
value = get_setting_value(db, key)
if value:
result[key] = value
return SettingsResponse(data=result)
# Admin routes
@router.get("/admin/settings", response_model=SettingsResponse)
def get_all_settings(
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Get all settings"""
settings = db.query(Setting).all()
result = {}
for s in settings:
result[s.key] = {
"value": s.value,
"group": s.group,
"description": s.description
}
return SettingsResponse(data=result)
@router.put("/admin/settings", response_model=SettingsResponse)
def update_settings(
request: SettingsUpdate,
db: Session = Depends(get_db),
current_admin: Admin = Depends(get_current_admin)
):
"""Batch update settings"""
for key, value in request.settings.items():
set_setting_value(db, key, value)
db.commit()
return SettingsResponse(message="设置更新成功")
@@ -0,0 +1,122 @@
# app/routers/upload.py
import os
import uuid
from datetime import datetime
from pathlib import Path
from PIL import Image as PILImage
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException, Form
from pydantic import BaseModel
from app.config import get_settings
from app.models.admin import Admin
from app.auth import get_current_admin
router = APIRouter()
settings = get_settings()
# Allowed file types (MIME)
ALLOWED_IMAGE_TYPES = {
"image/jpeg", "image/png", "image/gif", "image/webp",
"image/x-icon", "image/vnd.microsoft.icon", # .ico favicon
"image/svg+xml", # .svg
}
# Allowed extensions (fallback when browser reports wrong MIME)
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".ico", ".svg"}
MAX_FILE_SIZE = settings.MAX_UPLOAD_SIZE # 5MB
# Schemas
class UploadResponse(BaseModel):
code: int = 200
data: dict = None
message: str = "success"
def create_thumbnail(image_path: Path, thumb_path: Path, max_size: int = 300):
"""创建缩略图"""
try:
with PILImage.open(image_path) as img:
# 转换为 RGB(处理透明图片)
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
# 等比缩放到最大尺寸
img.thumbnail((max_size, max_size), PILImage.Resampling.LANCZOS)
# 保存
img.save(thumb_path, "JPEG", quality=85)
return True
except Exception as e:
print(f"创建缩略图失败: {e}")
return False
@router.post("/upload/image", response_model=UploadResponse)
async def upload_image(
file: UploadFile = File(...),
subdir: str = Form(default=""),
current_admin = Depends(get_current_admin)
):
"""Upload image file - 支持按子目录存储"""
# Check file type - allow by MIME or by extension (browsers may report wrong MIME for .ico)
file_ext = os.path.splitext(file.filename or "")[1].lower()
if file.content_type not in ALLOWED_IMAGE_TYPES and file_ext not in ALLOWED_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"不支持的文件类型: {file.content_type} ({file_ext})"
)
# Check file size
content = await file.read()
if len(content) > MAX_FILE_SIZE:
raise HTTPException(
status_code=400,
detail=f"文件大小超过限制: {MAX_FILE_SIZE / 1024 / 1024}MB"
)
# Generate unique filename with timestamp
ext = os.path.splitext(file.filename)[1].lower()
if not ext:
ext = ".jpg" if file.content_type == "image/jpeg" else ".png"
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{timestamp}_{uuid.uuid4().hex[:8]}{ext}"
# 根据子目录存储
upload_path = Path(settings.UPLOAD_DIR)
if subdir:
upload_path = upload_path / subdir
upload_path.mkdir(parents=True, exist_ok=True)
# 缩略图目录(始终放在 thumbnails 下)
thumbnail_dir = Path(settings.UPLOAD_DIR) / "thumbnails"
thumbnail_dir.mkdir(exist_ok=True)
# Save file
file_path = upload_path / filename
with open(file_path, "wb") as f:
f.write(content)
# 创建缩略图(.ico 和 .svg 跳过缩略图生成)
thumbnail_name = f"{Path(filename).stem}.jpg"
thumb_path = thumbnail_dir / thumbnail_name
thumb_relative_path = None
if ext not in ('.ico', '.svg') and create_thumbnail(file_path, thumb_path):
thumb_relative_path = f"/storage/admin/images/thumbnails/{thumbnail_name}"
# Return URL
if subdir:
url = f"/storage/admin/images/{subdir}/{filename}"
else:
url = f"/storage/admin/images/{filename}"
return UploadResponse(
message="上传成功",
data={
"url": url,
"filename": filename,
"size": len(content),
"thumb_url": thumb_relative_path
}
)
@@ -0,0 +1,530 @@
"""
微信公众号文章采集路由
使用 Playwright + Stealth 采集微信公众号文章内容
"""
import os
import re
import uuid
import json
import asyncio
import requests
from datetime import datetime
from typing import Optional, List
from urllib.parse import urljoin, urlparse
from fastapi import APIRouter, Depends, HTTPException, Body
from pydantic import BaseModel, Field
from sqlalchemy.orm import Session
from bs4 import BeautifulSoup, NavigableString
# 异步 Playwright 支持
try:
import nest_asyncio
nest_asyncio.apply()
except ImportError:
pass
try:
from playwright.async_api import async_playwright
PLAYWRIGHT_AVAILABLE = True
except ImportError:
PLAYWRIGHT_AVAILABLE = False
try:
import markdownify
MARKDOWNIFY_AVAILABLE = True
except ImportError:
MARKDOWNIFY_AVAILABLE = False
# 尝试导入 Stealth 插件
try:
from playwright_stealth import stealth_async
STEALTH_AVAILABLE = True
except ImportError:
STEALTH_AVAILABLE = False
from app.database import SessionLocal, get_db
from app.models.article import Article
from app.models.column import ColumnModel
from app.models.image import Image
from app.routers.auth import get_current_admin
from app.config import get_settings
settings = get_settings()
router = APIRouter(tags=["公众号采集"])
# ========== Pydantic 模型 ==========
class WechatPreviewRequest(BaseModel):
url: str = Field(..., min_length=1, description="微信公众号文章URL(支持 mp.weixin.qq.com 和 weixin.sogou.com)")
class WechatPreviewResponse(BaseModel):
code: int = 200
message: str = "success"
data: Optional[dict] = None
class WechatSaveRequest(BaseModel):
url: str = Field(..., description="原始URL")
title: str = Field(..., min_length=1, max_length=200, description="标题")
author: Optional[str] = Field(None, max_length=50, description="作者")
summary: Optional[str] = Field(None, max_length=500, description="摘要")
cover_image: Optional[str] = Field(None, description="封面图片URL")
content: str = Field(..., description="Markdown内容")
images: List[str] = Field(default=[], description="文章中的图片URL列表")
column_id: int = Field(..., description="所属栏目ID")
source_url: Optional[str] = Field(None, description="来源URL(用于去重)")
class WechatSaveResponse(BaseModel):
code: int = 200
message: str = "success"
data: Optional[dict] = None
# ========== 核心工具函数 ==========
def fix_wechat_html(html: str) -> str:
"""修复微信公众号文章的HTML"""
soup = BeautifulSoup(html, 'html.parser')
# 修复图片:微信用 data-src 存真实URL,src 常为占位图
for img in soup.find_all('img'):
data_src = img.get('data-src', '')
src = img.get('src', '')
# 只要 data-src 是真实http图片URL,且 src 不是有效http图片,就替换
if data_src and data_src.startswith('http') and (
not src or src.startswith('data:image') or not src.startswith('http')
):
img['src'] = data_src
if 'data-src' in img.attrs:
del img['data-src']
# 修复微信代码块:<pre class="code-snippet__js"> 内多个 span 行
for pre in soup.find_all('pre', class_=re.compile('code-snippet')):
code_tag = pre.find('code')
if code_tag:
lines = []
for span in code_tag.find_all('span', class_='code-snippet__line'):
line_text = span.get_text(separator='', strip=False)
if line_text:
lines.append(line_text)
if lines:
code_tag.clear()
for line in lines:
code_tag.append(NavigableString(line + '\n'))
# 移除空标签(保留包含图片的标签)
for tag in soup.find_all(['p', 'div', 'section']):
if tag.get_text(strip=True) == '' and not tag.find_all('img'):
tag.decompose()
return str(soup)
def html_to_markdown(html: str) -> str:
"""将微信HTML转换为Markdown"""
if not MARKDOWNIFY_AVAILABLE:
return html
try:
md = markdownify.markdownify(
html,
heading_style="ATX",
bullets="-",
strip=["script", "style"],
code_language="",
)
# 清理多余空行
md = re.sub(r'\n{3,}', '\n\n', md)
return md.strip()
except Exception:
return html
async def crawl_wechat_article(url: str) -> dict:
"""使用 Playwright 采集微信公众号文章"""
if not PLAYWRIGHT_AVAILABLE:
raise HTTPException(status_code=400, detail="Playwright 未安装,无法采集公众号文章")
result = {"title": "", "content": "", "author": "", "summary": ""}
result["images"] = []
result["cover_image"] = ""
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-blink-features=AutomationControlled",
"--disable-web-security",
"--disable-features=IsolateOrigins,site-per-process",
],
)
context = await browser.new_context(
viewport={"width": 1920, "height": 1080},
user_agent=(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
locale="zh-CN",
)
# 尝试应用 Stealth
try:
page = await context.new_page()
if STEALTH_AVAILABLE:
await stealth_async(page)
except Exception:
page = await context.new_page()
try:
# 搜狗链接需要先激活会话(搜索一次获取 cookies),否则会被反爬拦截
is_sogou = "weixin.sogou.com" in url
if is_sogou:
await page.goto(
"https://weixin.sogou.com/weixin?type=2&query=test",
wait_until="networkidle", timeout=30000,
)
await asyncio.sleep(2)
await page.goto(url, wait_until="networkidle", timeout=30000)
await asyncio.sleep(3)
# 微信文章常有的弹窗
try:
await page.wait_for_selector("#js_pc_qr_code_img", timeout=5000)
# 有二维码,尝试取消
close_btn = await page.query_selector(".js_pc_qr_code_close_btn, .weui-desktop-media__tips-close")
if close_btn:
await close_btn.click()
await asyncio.sleep(2)
except Exception:
pass
# 获取页面标题
title = await page.title()
if title:
title = title.strip()
# 处理微信的 "页面标题 - 文章" 格式
if " - " in title:
title = title.split(" - ")[0]
result["title"] = title
# 尝试获取 HTML 内容
html = await page.content()
# 提取微信公众号的正文
content_html = ""
# 新版微信文章
content_elem = await page.query_selector("#js_content")
if not content_elem:
content_elem = await page.query_selector(".rich_media_content")
if not content_elem:
content_elem = await page.query_selector("#js_article")
if not content_elem:
# 通用:取 body 内容
body = await page.query_selector("body")
if body:
content_html = await body.inner_html()
else:
content_html = await content_elem.inner_html()
if content_html:
content_html = fix_wechat_html(content_html)
result["content"] = html_to_markdown(content_html)
result["raw_html"] = content_html
# 提取作者
try:
author_elem = await page.query_selector(
"#js_name, .rich_media_meta_nickname, .profile_nickname, .rich_media_meta_text"
)
if not author_elem:
author_elem = await page.query_selector(
# 备用选择器
"[id$='_name'], [class*='_name'], .wx_article_author"
)
if author_elem:
author = await author_elem.inner_text()
result["author"] = author.strip()
except Exception:
pass
# 提取摘要/描述
try:
desc_elem = await page.query_selector(
"#js_description, .rich_media_meta_desc, [class*='_desc'], meta[name='description']"
)
if desc_elem:
desc = await desc_elem.inner_text()
result["summary"] = desc.strip()
except Exception:
pass
# 提取封面图片
try:
# 尝试从 meta 标签获取
cover_meta = await page.query_selector('meta[property="og:image"]')
if cover_meta:
cover_url = await cover_meta.get_attribute("content")
if cover_url:
result["cover_image"] = cover_url
if not result["cover_image"]:
cover_img = await page.query_selector(
"#js_cover, .rich_media_cover img, .cover_img, img.cover"
)
if cover_img:
cover_url = await cover_img.get_attribute("src") or await cover_img.get_attribute("data-src")
if cover_url:
result["cover_image"] = cover_url
except Exception:
pass
# 提取文章中所有图片
try:
img_tags = await page.query_selector_all("#js_content img, .rich_media_content img")
img_urls = set()
for img in img_tags:
src = await img.get_attribute("src") or await img.get_attribute("data-src")
if src and ("mmbiz.qpic.cn" in src or src.startswith("http")):
img_urls.add(src)
result["images"] = list(img_urls)
except Exception:
pass
await browser.close()
return result
except Exception as e:
await browser.close()
raise HTTPException(
status_code=500,
detail=f"微信文章采集失败: {str(e)}"
)
def download_image(url: str, save_dir: str) -> Optional[str]:
"""下载图片到本地"""
try:
if not url or not url.startswith("http"):
return url
# 生成唯一文件名
ext = ".jpg"
url_lower = url.lower()
if ".png" in url_lower:
ext = ".png"
elif ".gif" in url_lower:
ext = ".gif"
elif ".webp" in url_lower:
ext = ".webp"
elif ".jpeg" in url_lower or ".jpg" in url_lower:
ext = ".jpg"
filename = f"{uuid.uuid4().hex}{ext}"
filepath = os.path.join(save_dir, filename)
# 创建目录
os.makedirs(save_dir, exist_ok=True)
# 下载
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
"Referer": "https://mp.weixin.qq.com/",
}
resp = requests.get(url, headers=headers, timeout=30, stream=True)
if resp.status_code == 200:
with open(filepath, "wb") as f:
for chunk in resp.iter_content(chunk_size=8192):
f.write(chunk)
return filename
return None
except Exception as e:
print(f"下载图片失败 {url}: {e}")
return None
# ========== API 端点 ==========
@router.post("/wechat-crawl/preview", response_model=WechatPreviewResponse)
async def wechat_preview(
request: WechatPreviewRequest,
admin: dict = Depends(get_current_admin),
db: Session = Depends(get_db),
):
"""预览微信公众号文章(支持 mp.weixin.qq.com 和 weixin.sogou.com 链接)"""
if not (request.url.startswith("https://mp.weixin.qq.com/") or
request.url.startswith("https://weixin.sogou.com/")):
raise HTTPException(status_code=400, detail="请输入正确的微信公众号文章链接")
result = await crawl_wechat_article(request.url)
# 生成摘要(取内容前200个字符)
if not result.get("summary") and result.get("content"):
content_text = re.sub(r'[#*`\[\]()>\-\n]', '', result["content"])
result["summary"] = content_text[:200].strip()
# 获取栏目列表供前端选择
columns = db.query(ColumnModel).filter(
ColumnModel.is_enabled == True
).order_by(ColumnModel.sort_order).all()
return WechatPreviewResponse(
code=200,
message="success",
data={
"title": result.get("title", ""),
"author": result.get("author", ""),
"summary": result.get("summary", ""),
"cover_image": result.get("cover_image", ""),
"content": result.get("content", ""),
"images": result.get("images", []),
"columns": [c.to_dict() for c in columns],
}
)
@router.post("/wechat-crawl/save", response_model=WechatSaveResponse)
async def wechat_save(
request: WechatSaveRequest,
admin: dict = Depends(get_current_admin),
db: Session = Depends(get_db),
):
"""保存采集的微信公众号文章"""
# 验证栏目
column = db.query(ColumnModel).filter(
ColumnModel.id == request.column_id,
ColumnModel.is_enabled == True
).first()
if not column:
raise HTTPException(status_code=400, detail="所选栏目不存在或已禁用")
# 准备图片存储目录(与 crawl 模块保持一致,使用项目根 storage/admin/images/YYYYMM)
settings_obj = get_settings()
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
upload_dir = os.path.join(base_dir, settings_obj.UPLOAD_DIR)
# 按年月创建子目录
year_month = datetime.now().strftime("%Y%m")
upload_dir = os.path.join(upload_dir, year_month)
os.makedirs(upload_dir, exist_ok=True)
# 下载封面图
local_cover = None
if request.cover_image:
filename = download_image(request.cover_image, upload_dir)
if filename:
local_cover = f"/storage/admin/images/{year_month}/{filename}"
# 添加到 Image 表
try:
img = Image(
filename=filename,
original_name=filename,
file_path=f"/storage/admin/images/{year_month}/{filename}",
module="wechat",
)
db.add(img)
db.flush()
except Exception:
pass
# 下载内容中的图片并替换URL
content = request.content
image_urls_to_download = set()
# 从 markdown 中找到所有图片 URL
img_pattern = re.compile(r'!\[.*?\]\((https?://[^\s)]+)\)')
for match in img_pattern.finditer(content):
img_url = match.group(1)
image_urls_to_download.add(img_url)
# 也包括请求中提供的图片列表
for img_url in request.images:
if img_url.startswith("http"):
image_urls_to_download.add(img_url)
# 下载并替换
url_map = {}
for img_url in image_urls_to_download:
filename = download_image(img_url, upload_dir)
if filename:
local_path = f"/storage/admin/images/{year_month}/{filename}"
url_map[img_url] = local_path
# 添加到 Image 表
try:
img = Image(
filename=filename,
original_name=filename,
file_path=f"/storage/admin/images/{year_month}/{filename}",
module="wechat",
)
db.add(img)
db.flush()
except Exception:
pass
# 替换 Markdown 中的图片URL
for old_url, local_path in url_map.items():
content = content.replace(
f"]({old_url})",
f"]({local_path})"
)
# 生成 slug
def generate_slug(text: str) -> str:
try:
from pypinyin import lazy_pinyin
py = lazy_pinyin(text, style=0)
slug = "-".join(py)
slug = re.sub(r"[^a-zA-Z0-9-]", "", slug).lower()
slug = re.sub(r"-+", "-", slug).strip("-")
return slug or f"article-{int(datetime.now().timestamp())}"
except ImportError:
import hashlib
return hashlib.md5(text.encode()).hexdigest()[:12]
slug = generate_slug(request.title)
# 检查 slug 唯一性
existing = db.query(Article).filter(Article.slug == slug).first()
if existing:
slug = f"{slug}-{int(datetime.now().timestamp())}"
# 创建文章
article = Article(
title=request.title,
slug=slug,
content=content,
content_type="markdown",
summary=request.summary or "",
cover_image=local_cover,
column_id=request.column_id,
author=request.author or "",
status="draft",
source_url=request.source_url or request.url,
)
db.add(article)
db.commit()
db.refresh(article)
return WechatSaveResponse(
code=200,
message="公众号文章采集并保存成功",
data=article.to_dict(include_content=True)
)
@router.post("/wechat-crawl/columns")
async def get_columns(
admin: dict = Depends(get_current_admin),
db: Session = Depends(get_db),
):
"""获取栏目列表(供前端下拉选择)"""
columns = db.query(ColumnModel).filter(
ColumnModel.is_enabled == True
).order_by(ColumnModel.sort_order).all()
return {
"code": 200,
"data": [c.to_dict() for c in columns]
}