| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204 |
- from app.core.logger import logger
- from fastapi import APIRouter, Response, Query, Depends, UploadFile, File, Request
- from fastapi.responses import RedirectResponse
- from sqlalchemy.ext.asyncio import AsyncSession
- from app.core.database import get_db
- from app.utils.response import success
- from app.schemas.common import ApiResponse
- from app.schemas.http_session import HttpSessionCreate, HttpSessionOut
- from app.schemas.llm import ParseUserInputsOut, ParseUserInputsPayload
- from app.schemas.resource import FileUploadOut
- from app.schemas.short_url import ShortUrlCreate, ShortUrlOut
- from app.services.http_session_service import HttpSessionService
- from app.services.llm_service import LlmService
- from typing import Optional
- from redis.asyncio import Redis
- from app.core.redis import get_redis_client
- from app.core.auth import get_current_user
- from app.models.user import VasUser
- from app.core.biz_exception import BizLogicError
- from app.services.r2_storage_service import R2StorageService
- from app.services.seaweedfs_service import SeaweedFSService
- from app.services.short_url_service import ShortUrlService
- public_router = APIRouter()
- protected_router = APIRouter()
- admin_required_router = APIRouter()
- @admin_required_router.get("/ping", summary="心跳检测", tags=["测试接口"])
- async def ping():
- return {"message": "pong"}
- @admin_required_router.post("/http-session", summary="创建http session", tags=["会话管理"], response_model=ApiResponse[HttpSessionOut])
- async def http_session_create(
- data: HttpSessionCreate,
- db: AsyncSession = Depends(get_db)
- ):
- logger.info(f"[Create HttpSession] sid={data.session_id}")
- obj = await HttpSessionService.create(db, data)
- return success(data=obj)
- @admin_required_router.get("/http-session", summary="读取http session", tags=["会话管理"], response_model=ApiResponse[HttpSessionOut])
- async def http_session_get_by_sid(
- session_id: str = Query(...),
- db: AsyncSession = Depends(get_db)
- ):
- logger.info(f"[Get HttpSession] sid={session_id}")
- obj = await HttpSessionService.get_by_sid(db, session_id)
- return success(data=obj)
- @protected_router.post("/resource/upload_file", summary="上传文件(需登录鉴权)", tags=["文件管理"], response_model=ApiResponse[FileUploadOut])
- async def resource_upload_file(
- request: Request,
- file: UploadFile = File(...),
- current_user: VasUser = Depends(get_current_user),
- redis_client: Redis = Depends(get_redis_client),
- ):
- # 提取真实客户端 IP
- client_ip = (
- request.headers.get("cf-connecting-ip")
- or (request.headers.get("x-forwarded-for", "").split(",")[0].strip() or None)
- or (request.client.host if request.client else "unknown")
- )
- # 防刷机制 1:单 IP 频次限制(单个 IP 每分钟最多允许 3 次上传)
- ip_rate_key = f"rate:seaweedfs_upload:ip:{client_ip}"
- ip_count = await redis_client.incr(ip_rate_key)
- if ip_count == 1:
- await redis_client.expire(ip_rate_key, 60)
- elif ip_count > 3:
- raise BizLogicError("Too many upload requests from this IP address. Please try again later.")
- # 防刷机制 2:单用户频次限制(单个账号每分钟最多允许 3 次上传)
- user_rate_key = f"rate:seaweedfs_upload:user:{current_user.id}"
- user_count = await redis_client.incr(user_rate_key)
- if user_count == 1:
- await redis_client.expire(user_rate_key, 60)
- elif user_count > 3:
- raise BizLogicError("Too many upload requests for this account. Please try again later.")
- result = await SeaweedFSService.upload(file)
- return success(data=result)
- @public_router.get("/resource/download_file", summary="下载文件", tags=["文件管理"])
- async def resource_get_file(
- request: Request,
- fid: str = Query(...),
- redis_client: Redis = Depends(get_redis_client),
- ):
- # 下载防刷限制:单 IP 每分钟最多 60 次下载请求,防止高频消耗服务器下行带宽
- client_ip = (
- request.headers.get("cf-connecting-ip")
- or (request.headers.get("x-forwarded-for", "").split(",")[0].strip() or None)
- or (request.client.host if request.client else "unknown")
- )
- dl_rate_key = f"rate:seaweedfs_download:ip:{client_ip}"
- dl_count = await redis_client.incr(dl_rate_key)
- if dl_count == 1:
- await redis_client.expire(dl_rate_key, 60)
- elif dl_count > 60:
- raise BizLogicError("Download frequency limit exceeded. Please try again later.")
- data = await SeaweedFSService.get(fid)
- if not data:
- return Response(content=b"File not found", status_code=404, media_type="text/plain")
- content, mime = data
- return Response(content=content, media_type=mime)
- @protected_router.post("/r2/upload", summary="上传文件至 Cloudflare R2(需登录鉴权)", tags=["R2 对象存储"], response_model=ApiResponse[FileUploadOut])
- async def r2_upload_file(
- request: Request,
- file: UploadFile = File(...),
- bucket: Optional[str] = Query(None, description="目标存储桶名称(可选,留空使用环境变量默认配置)"),
- prefix: str = Query("uploads", description="存储目录前缀"),
- current_user: VasUser = Depends(get_current_user),
- redis_client: Redis = Depends(get_redis_client),
- ):
- # 提取真实客户端 IP(优先 Cloudflare CDN 提供的 cf-connecting-ip,其次 x-forwarded-for)
- client_ip = (
- request.headers.get("cf-connecting-ip")
- or (request.headers.get("x-forwarded-for", "").split(",")[0].strip() or None)
- or (request.client.host if request.client else "unknown")
- )
- # 防刷机制 1:单 IP 频次限制(单个 IP 每分钟最多允许 15 次上传,防止多账号集中在同个 IP 恶意刷量)
- ip_rate_key = f"rate:r2_upload:ip:{client_ip}"
- ip_count = await redis_client.incr(ip_rate_key)
- if ip_count == 1:
- await redis_client.expire(ip_rate_key, 60)
- elif ip_count > 3:
- raise BizLogicError("Too many upload requests from this IP address. Please try again later.")
- # 防刷机制 2:单用户频次限制(单个账号每分钟最多允许 10 次上传)
- user_rate_key = f"rate:r2_upload:user:{current_user.id}"
- user_count = await redis_client.incr(user_rate_key)
- if user_count == 1:
- await redis_client.expire(user_rate_key, 60)
- elif user_count > 3:
- raise BizLogicError("Too many upload requests for this account. Please try again later.")
- result = await R2StorageService.upload(file=file, bucket=bucket, prefix=prefix)
- return success(data=FileUploadOut(fid=result["fid"], url=result["url"]))
- @public_router.get("/r2/file", summary="从 Cloudflare R2 下载/预览文件", tags=["R2 对象存储"])
- async def r2_get_file(
- request: Request,
- key: str = Query(..., description="文件存储 key"),
- bucket: Optional[str] = Query(None, description="存储桶名称(可选)"),
- redis_client: Redis = Depends(get_redis_client),
- ):
- # 下载防刷限制:单 IP 每分钟最多 60 次下载请求,防止黑客对文件下载进行放大攻击
- client_ip = (
- request.headers.get("cf-connecting-ip")
- or (request.headers.get("x-forwarded-for", "").split(",")[0].strip() or None)
- or (request.client.host if request.client else "unknown")
- )
- dl_rate_key = f"rate:r2_download:ip:{client_ip}"
- dl_count = await redis_client.incr(dl_rate_key)
- if dl_count == 1:
- await redis_client.expire(dl_rate_key, 60)
- elif dl_count > 60:
- raise BizLogicError("Download frequency limit exceeded. Please try again later.")
- data = await R2StorageService.get_file(key=key, bucket=bucket)
- if not data:
- return Response(content=b"File not found", status_code=404, media_type="text/plain")
- content, mime = data
- return Response(
- content=content,
- media_type=mime,
- headers={"Cache-Control": "public, max-age=86400"}
- )
- @admin_required_router.post("/s/generate", summary="生成短链接地址<压缩地址长度>", tags=["Short URL"], response_model=ApiResponse[ShortUrlOut])
- async def short_url_generate(
- data: ShortUrlCreate,
- db: AsyncSession = Depends(get_db),
- ):
- """生成短链接"""
- record = await ShortUrlService.create_short_url(db, data.long_url)
- return success(data=record)
- @public_router.get("/s/{short_key}", summary="访问短链接地址<自动重定向到真实链接地址>", tags=["Short URL"])
- async def short_url_request(short_key: str, db: AsyncSession = Depends(get_db)):
- """访问短链接自动重定向"""
- long_url = await ShortUrlService.get_long_url(db, short_key)
- return RedirectResponse(url=long_url, status_code=302)
- @admin_required_router.post("/vas/llm/data_parsing", summary="llm数据解析", tags=["textskin"], response_model=ApiResponse[ParseUserInputsOut])
- async def vas_llm_data_parsing(
- payload: ParseUserInputsPayload,
- db: AsyncSession = Depends(get_db)
- ):
- out = await LlmService.handle_parse(db, payload)
- return success(data=out)
|