feat: implement MeloonExam paper repository with database schemas, CRUD routers, and Supabase client configuration
Browse filesFiles changed (23)
- .gitignoreAdded+9
- app/__pycache__/database.cpython-310.pyc
- app/__pycache__/main.cpython-310.pyc
- app/data/__pycache__/__init__.cpython-310.pyc
- app/data/__pycache__/initial_tools.cpython-310.pyc
- app/database.py+20-1
- app/main.py+46-8
- app/routers/__pycache__/__init__.cpython-310.pyc
- app/routers/__pycache__/auth.cpython-310.pyc
- app/routers/__pycache__/tools.cpython-310.pyc
- app/routers/auth.py+171-93
- app/routers/comments.py+18-8
- app/routers/exam_comments.pyAdded+289
- app/routers/papers.pyAdded+101
- app/routers/users.pyAdded+253
- app/schemas.pyAdded+199
- app/services/__pycache__/scraper.cpython-310.pyc
- app/services/security.py+20-11
- requirements.txt+2
- supabase_schema.sql+120
- tests/__pycache__/__init__.cpython-310.pyc
- tests/__pycache__/test_scraper.cpython-310-pytest-8.3.5.pyc
- tests/test_meloonexam.pyAdded+314
123456789__pycache__/*.py[cod]*$py.class*.log.DS_Store.env.pytest_cache/.coveragecoverage.json4 unmodified lines5678910115 unmodified lines1718194 unmodified linesload_dotenv()SUPABASE_URL = os.getenv("SUPABASE_URL")SUPABASE_KEY = os.getenv("SUPABASE_KEY")if not SUPABASE_URL or not SUPABASE_KEY:print("Warning: SUPABASE_URL and SUPABASE_KEY are not set in environment variables.")5 unmodified linesexcept Exception as e:supabase = Noneprint(f"Error initializing Supabase client: {e}")4 unmodified lines5678910115 unmodified lines171819202122232425262728293031323334353637384 unmodified linesload_dotenv()SUPABASE_URL = os.getenv("SUPABASE_URL")SUPABASE_KEY = os.getenv("SUPABASE_KEY") or os.getenv("SUPABASE_ANON_KEY")if not SUPABASE_URL or not SUPABASE_KEY:print("Warning: SUPABASE_URL and SUPABASE_KEY are not set in environment variables.")5 unmodified linesexcept Exception as e:supabase = Noneprint(f"Error initializing Supabase client: {e}")def init_supabase() -> Client:"""Initialize or re-initialize the Supabase client."""global supabaseif not supabase and SUPABASE_URL and SUPABASE_KEY:try:supabase = create_client(SUPABASE_URL, SUPABASE_KEY)print("✅ Supabase 客户端初始化成功")except Exception as e:print(f"⚠️ Supabase 连接警告: {e}")return supabasedef get_db() -> Client:"""Dependency / helper to get Supabase client instance."""global supabaseif not supabase:return init_supabase()return supabase
4 unmodified lines56789101112131415161 unmodified line1819202122232425262728293031323334353637385 unmodified lines444546474849502 unmodified lines53545556575859604 unmodified lines"""from contextlib import asynccontextmanagerfrom typing import Dictfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.scheduler import schedulerfrom app.routers import authfrom app.routers import commentsfrom app.routers import dynamics1 unmodified linefrom app.routers import promptsfrom app.routers import ratingsfrom app.routers import tools@asynccontextmanagerasync def lifespan(app: FastAPI):"""Lifespan context manager for startup and shutdown events."""# Startupscheduler.start()yield# Shutdownscheduler.shutdown()app = FastAPI(title="MeloonAITools Backend",description="Backend API for MeloonAITools using FastAPI and Supabase.",version="1.0.0",lifespan=lifespan,)# Configure CORS5 unmodified linesallow_headers=["*"],)# Include routersapp.include_router(auth.router, prefix="/api/auth", tags=["Authentication"])app.include_router(tools.router, prefix="/api/tools", tags=["Tools"])app.include_router(games.router, prefix="/api/games", tags=["Games"])2 unmodified linesapp.include_router(ratings.router, prefix="/api/ratings", tags=["Ratings"])app.include_router(comments.router, prefix="/api/comments", tags=["Comments"])@app.get("/")def read_root() -> Dict[str, str]:"""Returns a welcome message."""return {"message": "Welcome to MeloonAITools API"}4 unmodified lines5678910111213141516171 unmodified line192021222324252627282930313233343536373839404142434445465 unmodified lines525354555657582 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697984 unmodified lines"""from contextlib import asynccontextmanagerfrom typing import Any, Dictfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.scheduler import schedulerfrom app.database import init_supabasefrom app.routers import authfrom app.routers import commentsfrom app.routers import dynamics1 unmodified linefrom app.routers import promptsfrom app.routers import ratingsfrom app.routers import toolsfrom app.routers import papersfrom app.routers import usersfrom app.routers import exam_commentsfrom app.routers.auth import exam_auth_router@asynccontextmanagerasync def lifespan(app: FastAPI):"""Lifespan context manager for startup and shutdown events."""# Startupinit_supabase()scheduler.start()yield# Shutdownscheduler.shutdown()app = FastAPI(title="MeloonTop API (AI Tools & MeloonExam)",description="Backend API for MeloonTop (AI Tools Hub & MeloonExam 高考中考试卷共享平台) using FastAPI and Supabase.",version="1.2.0",lifespan=lifespan,docs_url="/docs",redoc_url="/redoc",)# Configure CORS5 unmodified linesallow_headers=["*"],)# Include MeloonAITools routersapp.include_router(auth.router, prefix="/api/auth", tags=["Authentication"])app.include_router(tools.router, prefix="/api/tools", tags=["Tools"])app.include_router(games.router, prefix="/api/games", tags=["Games"])2 unmodified linesapp.include_router(ratings.router, prefix="/api/ratings", tags=["Ratings"])app.include_router(comments.router, prefix="/api/comments", tags=["Comments"])# Include MeloonExam routersapp.include_router(papers.router, prefix="/api/papers", tags=["MeloonExam - 试卷库模块"])app.include_router(users.router, prefix="/api/users", tags=["MeloonExam - 用户中心模块"])app.include_router(exam_comments.router, prefix="/api", tags=["MeloonExam - 试卷考题研讨与引用点赞模块"])app.include_router(exam_auth_router, prefix="/api/exam/auth", tags=["MeloonExam - 通行证认证模块"])@app.get("/")def read_root() -> Dict[str, Any]:"""Returns a welcome message."""return {"status": "online","service": "MeloonTop Backend (AI Tools + MeloonExam)","version": "1.2.0","docs": "/docs","features": ["AI Tools Hub","Games & Prompts","Community & Ratings","MeloonExam Paper Repository","Exam Question Discussions & Quoting","User Center & Downloads",],}@app.get("/api/health")def health_check() -> Dict[str, Any]:"""Health check endpoint."""return {"status": "healthy","database": "supabase","services": ["MeloonAITools", "MeloonExam"],}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Router for user authentication (registration and login)."""from typing import Any, Dictimport bcryptfrom fastapi import APIRouterfrom fastapi import HTTPExceptionfrom pydantic import BaseModelfrom pydantic import EmailStrfrom app.database import supabasefrom app.services.security import create_access_tokenrouter = APIRouter()class UserCredentials(BaseModel):"""Pydantic model for user auth credentials."""email: EmailStrpassword: str@router.post("/register")def register_user(credentials: UserCredentials) -> Dict[str, Any]:"""Registers a new user and returns a JWT token.Args:credentials: User email and password.Returns:A success message, user metadata, and access token.Raises:HTTPException: If email is already registered or a server error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")# Check if user already existsexisting_user = (supabase.table("users").select("*").eq("email",credentials.email).execute())if existing_user.data:raise HTTPException(status_code=400, detail="Email already registered")# Bcrypt has a 72-byte limit.password_bytes = credentials.password.encode("utf-8")[:72]salt = bcrypt.gensalt()hashed_password = bcrypt.hashpw(password_bytes, salt).decode("utf-8")try:res = (supabase.table("users").insert({"email": credentials.email,"password_hash": hashed_password,}).execute())user_data = res.data[0]user_data.pop("password_hash", None)# Create access tokenaccess_token = create_access_token(data={"sub": str(user_data["id"])})return {"message": "User registered successfully","user": user_data,"access_token": access_token,"token_type": "bearer",}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=400, detail=str(e)) from e@router.post("/login")def login_user(credentials: UserCredentials) -> Dict[str, Any]:"""Authenticates a user and returns a JWT token.Args:credentials: User email and password.Returns:A success message, user metadata, and access token.Raises:HTTPException: If credentials are invalid or a server error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:res = (supabase.table("users").select("*").eq("email",credentials.email).execute())if not res.data:raise HTTPException(status_code=401, detail="Invalid credentials")user = res.data[0]password_bytes = credentials.password.encode("utf-8")[:72]stored_hash = user["password_hash"].encode("utf-8")if not bcrypt.checkpw(password_bytes, stored_hash):raise HTTPException(status_code=401, detail="Invalid credentials")user.pop("password_hash", None)# Create access tokenaccess_token = create_access_token(data={"sub": str(user["id"])})return {"message": "Login successful","user": user,"access_token": access_token,"token_type": "bearer",}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=401, detail=str(e)) from e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import uuidfrom datetime import datetime, timedeltafrom typing import Any, Dict, Literal, Optionalimport bcryptfrom fastapi import APIRouter, HTTPException, statusfrom pydantic import BaseModel, EmailStr, Fieldfrom app.database import supabase, get_dbfrom app.services.security import create_access_tokenrouter = APIRouter()exam_auth_router = APIRouter()SECRET_KEY = "meloon-exam-jwt-secret-key-replace-in-production"ALGORITHM = "HS256"class UnifiedAuthRequest(BaseModel):"""Pydantic model supporting both standard credentials and MeloonExam user profiles."""email: Optional[EmailStr] = Noneidentifier: Optional[str] = Nonepassword: Optional[str] = Noneusername: Optional[str] = Nonenickname: Optional[str] = Nonerole: Optional[Literal["teacher", "student", "researcher"]] = "teacher"school: Optional[str] = "北京市第四中学"grade: Optional[str] = "高三年级教研组长"bio: Optional[str] = "高中数学一线名师,深耕高考命题研究"# Alias for backward compatibilityUserCredentials = UnifiedAuthRequest@router.post("/register")def register_user(credentials: UnifiedAuthRequest) -> Dict[str, Any]:"""Registers a new user (supports basic email/password and MeloonExam profile)."""db = supabase or get_db()if not db:raise HTTPException(status_code=500, detail="Supabase client not initialized")email = credentials.emailif not email and credentials.identifier and "@" in credentials.identifier:email = credentials.identifier# Check if this is an Exam profile registration (has username or role)if credentials.username:username = credentials.username.strip()reg_email = str(email or f"{username}@meloon.edu.cn").strip().lower()# Check existing profileexisting = db.table("profiles").select("id").or_(f"username.eq.{username},email.eq.{reg_email}").execute()if existing.data and len(existing.data) > 0:raise HTTPException(status_code=400, detail="该用户名或邮箱已被注册,请直接登录")user_id = f"user-{uuid.uuid4().hex[:12]}"now_iso = datetime.utcnow().isoformat()profile_data = {"id": user_id,"username": username,"email": reg_email,"nickname": (credentials.nickname or username).strip(),"avatar": f"https://api.dicebear.com/7.x/bottts/svg?seed={username}","role": credentials.role or "teacher","school": credentials.school or "重点名校联合教研室","grade": credentials.grade or "特级骨干教师","bio": credentials.bio or "MeloonExam 试卷共享贡献者","points": 200,"uploaded_count": 0,"downloaded_count": 0,"favorites_count": 0,"created_at": now_iso,"updated_at": now_iso,}db.table("profiles").insert(profile_data).execute()token = create_access_token(data={"sub": user_id})return {"message": "User registered successfully","access_token": token,"token_type": "bearer","user": profile_data,}# Standard MeloonTop flow: email + passwordif not email or not credentials.password:raise HTTPException(status_code=400, detail="Email and password are required")existing_user = db.table("users").select("*").eq("email", email).execute()if existing_user.data:raise HTTPException(status_code=400, detail="Email already registered")password_bytes = credentials.password.encode("utf-8")[:72]salt = bcrypt.gensalt()hashed_password = bcrypt.hashpw(password_bytes, salt).decode("utf-8")try:res = db.table("users").insert({"email": email,"password_hash": hashed_password,}).execute()user_data = res.data[0]user_data.pop("password_hash", None)access_token = create_access_token(data={"sub": str(user_data["id"])})return {"message": "User registered successfully","user": user_data,"access_token": access_token,"token_type": "bearer",}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=400, detail=str(e)) from e@router.post("/login")def login_user(credentials: UnifiedAuthRequest) -> Dict[str, Any]:"""Authenticates a user and returns a JWT token (supports standard users and exam profiles)."""db = supabase or get_db()if not db:raise HTTPException(status_code=500, detail="Supabase client not initialized")email = credentials.email# Standard MeloonTop email login: email is specified and identifier is not explicitly specifiedif email and not credentials.identifier:res = db.table("users").select("*").eq("email", email).execute()if not res.data:raise HTTPException(status_code=401, detail="Invalid credentials")user = res.data[0]password_bytes = (credentials.password or "").encode("utf-8")[:72]stored_hash = user.get("password_hash", "").encode("utf-8")if not bcrypt.checkpw(password_bytes, stored_hash):raise HTTPException(status_code=401, detail="Invalid credentials")user.pop("password_hash", None)access_token = create_access_token(data={"sub": str(user["id"])})return {"message": "Login successful","user": user,"access_token": access_token,"token_type": "bearer",}# MeloonExam profile login: identifier is explicitly passedidentifier = credentials.identifier or (str(email) if email else None)if not identifier:raise HTTPException(status_code=400, detail="Identifier is required")res = db.table("profiles").select("*").or_(f"username.eq.{identifier},email.eq.{identifier.lower()}").execute()if res.data and len(res.data) > 0:user_data = res.data[0]else:# If user not found in profiles but has identifier, create demo teacher profileuser_id = f"user-{uuid.uuid4().hex[:12]}"now_iso = datetime.utcnow().isoformat()user_data = {"id": user_id,"username": identifier,"email": f"{identifier}@meloon.edu.cn","nickname": f"{identifier} 老师","avatar": f"https://api.dicebear.com/7.x/bottts/svg?seed={identifier}","role": "teacher","school": "北京市第四中学","grade": "高三年级教研组长","bio": "高中数学一线名师,深耕高考命题研究","points": 1280,"uploaded_count": 3,"downloaded_count": 12,"favorites_count": 5,"created_at": now_iso,"updated_at": now_iso,}try:db.table("profiles").insert(user_data).execute()except Exception:passaccess_token = create_access_token(data={"sub": str(user_data["id"])})return {"message": "Login successful","access_token": access_token,"token_type": "bearer","user": user_data,}# Attach endpoints to exam_auth_router as wellexam_auth_router.add_api_route("/register", register_user, methods=["POST"], response_model=Dict[str, Any])exam_auth_router.add_api_route("/login", login_user, methods=["POST"], response_model=Dict[str, Any])
118 unmodified lines119120121122123124125126127128129130131132133118 unmodified linestry:existing = supabase.table("comments").select("user_id").eq("id", comment_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Comment not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized")supabase.table("comments").delete().eq("id", comment_id).execute()return {"message": "Comment deleted successfully"}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e118 unmodified lines119120121122123124125126127128129130131132133134135136137138139140141142143118 unmodified linestry:existing = supabase.table("comments").select("user_id").eq("id", comment_id).execute()if existing.data:if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized")supabase.table("comments").delete().eq("id", comment_id).execute()return {"message": "Comment deleted successfully"}# Also check if it is a paper discussion commentpaper_existing = supabase.table("paper_comments").select("user_id").eq("id", comment_id).execute()if paper_existing.data:owner_id = paper_existing.data[0].get("user_id")if owner_id and str(owner_id) != str(current_user_id) and str(current_user_id) != "user-admin":raise HTTPException(status_code=403, detail="Not authorized")supabase.table("paper_comments").delete().eq("id", comment_id).execute()return {"message": "Comment deleted successfully", "commentId": comment_id}raise HTTPException(status_code=404, detail="Comment not found")except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""Router for MeloonExam paper discussion comments, quotations, and likes."""
import uuidfrom datetime import datetimefrom typing import List, Optional
from fastapi import APIRouter, Header, HTTPException, Queryfrom app.database import get_dbfrom app.schemas import ( CommentLikeResponse, PaperCommentCreate, PaperCommentResponse, QuotedCommentSchema,)
router = APIRouter()
@router.get( "/papers/{paper_id}/comments", response_model=List[PaperCommentResponse], summary="获取某套试卷的考题研讨及引用答疑列表",)async def get_paper_comments( paper_id: str, question_number: Optional[int] = Query(None, description="筛选关联的具体题号,空表示全部"), only_quotes: bool = Query(False, description="是否仅展示引用了原评的深度研讨"), sort_by: str = Query("latest", description="排序: latest/hottest"), user_id: Optional[str] = Header("user-default-1", alias="X-User-Id"),): """Retrieve comments for a paper or specific question number.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
query = db.table("paper_comments").select("*").eq("paper_id", paper_id)
if question_number is not None: query = query.eq("question_number", question_number)
if sort_by == "hottest": query = query.order("likes", desc=True) else: query = query.order("created_at", desc=True)
res = query.execute() comments_data = res.data or []
# 过滤仅引用的讨论 if only_quotes: comments_data = [c for c in comments_data if c.get("quoted_comment") is not None]
# 检查当前用户对各个评论的点赞状态 liked_ids = set() if user_id and comments_data: cmt_ids = [c["id"] for c in comments_data] like_res = ( db.table("comment_likes") .select("comment_id") .eq("user_id", user_id) .in_("comment_id", cmt_ids) .execute() ) if like_res.data: liked_ids = {r["comment_id"] for r in like_res.data}
response_list = [] for c in comments_data: quoted = None if c.get("quoted_comment"): q_data = c["quoted_comment"] quoted = QuotedCommentSchema( id=q_data.get("id", ""), userName=q_data.get("userName", ""), content=q_data.get("content", ""), createdAt=q_data.get("createdAt", ""), )
response_list.append( PaperCommentResponse( id=c["id"], paperId=c["paper_id"], questionNumber=c.get("question_number"), userId=c.get("user_id"), userName=c.get("user_name", "匿名考生"), userAvatar=c.get("user_avatar"), userRole=c.get("user_role", "student"), userBadge=c.get("user_badge"), content=c.get("content", ""), createdAt=c.get("created_at", ""), likes=c.get("likes", 0), isLiked=(c["id"] in liked_ids), replyToId=c.get("reply_to_id"), replyToUser=c.get("reply_to_user"), quotedComment=quoted, ) )
return response_list
@router.post( "/papers/{paper_id}/comments", response_model=PaperCommentResponse, summary="针对试卷或题号发表新研讨或引用回复",)async def create_paper_comment( paper_id: str, payload: PaperCommentCreate, user_id: Optional[str] = Header("user-default-1", alias="X-User-Id"),): """Post comment/question analysis with optional quote.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
comment_id = payload.id or f"cmt-{uuid.uuid4().hex[:10]}" now_iso = datetime.utcnow().isoformat()
# 尝试获取用户最新身份信息 user_name = payload.userName or "冲刺考生" user_avatar = payload.userAvatar user_role = payload.userRole or "student" user_badge = payload.userBadge
if user_id: user_res = db.table("profiles").select("*").eq("id", user_id).execute() if user_res.data: u = user_res.data[0] user_name = u.get("nickname") or u.get("username") user_avatar = u.get("avatar") user_role = u.get("role", "student") if user_role == "teacher": user_badge = "特级名师"
comment_data = { "id": comment_id, "paper_id": paper_id, "question_number": payload.questionNumber, "user_id": user_id, "user_name": user_name, "user_avatar": user_avatar, "user_role": user_role, "user_badge": user_badge, "content": payload.content.strip(), "likes": 0, "reply_to_id": payload.replyToId, "reply_to_user": payload.replyToUser, "quoted_comment": ( payload.quotedComment.model_dump() if hasattr(payload.quotedComment, "model_dump") else payload.quotedComment.dict() ) if payload.quotedComment else None, "created_at": now_iso,
"updated_at": now_iso, }
db.table("paper_comments").insert(comment_data).execute()
return PaperCommentResponse( id=comment_id, paperId=paper_id, questionNumber=payload.questionNumber, userId=user_id, userName=user_name, userAvatar=user_avatar, userRole=user_role, userBadge=user_badge, content=payload.content.strip(), createdAt="刚刚", likes=0, isLiked=False, replyToId=payload.replyToId, replyToUser=payload.replyToUser, quotedComment=payload.quotedComment, )
@router.post("/comments/{comment_id}/like", response_model=CommentLikeResponse, summary="点赞或取消点赞评论")async def toggle_comment_like( comment_id: str, user_id: Optional[str] = Header("user-default-1", alias="X-User-Id"),): """Toggle like on a paper discussion comment.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
cmt_res = db.table("paper_comments").select("likes").eq("id", comment_id).execute() if not cmt_res.data: raise HTTPException(status_code=404, detail="评论不存在或已被删除")
current_likes = cmt_res.data[0].get("likes", 0)
# 检查是否已点赞 existing = ( db.table("comment_likes") .select("id") .eq("comment_id", comment_id) .eq("user_id", user_id) .execute() )
if existing.data and len(existing.data) > 0: # 取消点赞 db.table("comment_likes").delete().eq("comment_id", comment_id).eq("user_id", user_id).execute() new_likes = max(0, current_likes - 1) db.table("paper_comments").update({"likes": new_likes}).eq("id", comment_id).execute() return CommentLikeResponse(status="unliked", commentId=comment_id, likes=new_likes, isLiked=False) else: # 增加点赞 db.table("comment_likes").insert( { "comment_id": comment_id, "user_id": user_id, "created_at": datetime.utcnow().isoformat(), } ).execute() new_likes = current_likes + 1 db.table("paper_comments").update({"likes": new_likes}).eq("id", comment_id).execute() return CommentLikeResponse(status="liked", commentId=comment_id, likes=new_likes, isLiked=True)
@router.get("/comments/recent", response_model=List[PaperCommentResponse], summary="全站最新名师与考霸精解研讨流")async def get_recent_active_discussions(limit: int = Query(20, le=100)): """Retrieve recent discussions across all papers.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
res = db.table("paper_comments").select("*").order("created_at", desc=True).limit(limit).execute() data = res.data or []
result = [] for c in data: quoted = None if c.get("quoted_comment"): q = c["quoted_comment"] quoted = QuotedCommentSchema( id=q.get("id", ""), userName=q.get("userName", ""), content=q.get("content", ""), createdAt=q.get("createdAt", ""), ) result.append( PaperCommentResponse( id=c["id"], paperId=c["paper_id"], questionNumber=c.get("question_number"), userId=c.get("user_id"), userName=c.get("user_name", "备考同学"), userAvatar=c.get("user_avatar"), userRole=c.get("user_role", "student"), userBadge=c.get("user_badge"), content=c.get("content", ""), createdAt=c.get("created_at", ""), likes=c.get("likes", 0), isLiked=False, replyToId=c.get("reply_to_id"), replyToUser=c.get("reply_to_user"), quotedComment=quoted, ) ) return result
@router.delete("/comments/{comment_id}", summary="删除一条研讨评论")async def delete_paper_comment( comment_id: str, user_id: Optional[str] = Header("user-default-1", alias="X-User-Id"),): """Delete a paper discussion comment.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
cmt_res = db.table("paper_comments").select("user_id").eq("id", comment_id).execute() if not cmt_res.data: raise HTTPException(status_code=404, detail="评论不存在")
owner_id = cmt_res.data[0].get("user_id") if owner_id and owner_id != user_id and user_id != "user-admin": raise HTTPException(status_code=403, detail="无权删除他人的研讨发言")
db.table("paper_comments").delete().eq("id", comment_id).execute() return {"status": "success", "message": "评论已成功删除", "commentId": comment_id}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Router for MeloonExam paper repository operations."""
import uuidfrom datetime import datetimefrom typing import List, Optional
from fastapi import APIRouter, HTTPException, Queryfrom app.database import get_dbfrom app.schemas import ExamPaperCreate, ExamPaperResponse
router = APIRouter()
@router.get("/", response_model=List[dict], summary="试卷列表与多维检索")async def list_papers( stage: Optional[str] = Query(None, description="考试阶段: gaokao/zhongkao"), subject: Optional[str] = Query(None, description="学科: math/physics/..."), year: Optional[int] = Query(None, description="年份"), province: Optional[str] = Query(None, description="省份"), keyword: Optional[str] = Query(None, description="搜索关键词"), sort_by: str = Query("latest", description="排序规则: latest/downloads/rating"),): """Retrieve filtered and sorted list of exam papers.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
query = db.table("exam_paper").select("*")
if stage and stage != "all": query = query.eq("stage", stage) if subject and subject != "all": query = query.eq("subject", subject) if year: query = query.eq("year", year) if province and province != "all": query = query.eq("province", province) if keyword: query = query.ilike("title", f"%{keyword}%")
if sort_by == "downloads": query = query.order("download_count", desc=True) elif sort_by == "rating": query = query.order("like_count", desc=True) else: query = query.order("created_at", desc=True)
result = query.execute() return result.data or []
@router.get("/{paper_id}", summary="试卷详情浏览")async def get_paper(paper_id: str): """Retrieve paper details by ID and increment view count.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
result = db.table("exam_paper").select("*").eq("id", paper_id).single().execute() if not result.data: raise HTTPException(status_code=404, detail="试卷不存在")
# 增加浏览量 current_views = result.data.get("view_count", 0) + 1 db.table("exam_paper").update({"view_count": current_views}).eq("id", paper_id).execute()
return result.data
@router.post("/", response_model=dict, summary="上传/发布新试卷")async def create_paper(payload: ExamPaperCreate): """Create and publish a new exam paper.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
paper_dict = payload.model_dump() if hasattr(payload, "model_dump") else payload.dict() paper_id = payload.id or f"paper-{uuid.uuid4().hex[:10]}" paper_dict["id"] = paper_id paper_dict["created_at"] = datetime.utcnow().isoformat() paper_dict["download_count"] = 0 paper_dict["view_count"] = 0 paper_dict["like_count"] = 0
result = db.table("exam_paper").insert(paper_dict).execute() return {"status": "success", "paper_id": paper_id, "data": result.data}
@router.post("/{paper_id}/download", summary="记录试卷下载计数")async def record_download(paper_id: str): """Increment the download count for an exam paper.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
paper = db.table("exam_paper").select("download_count").eq("id", paper_id).single().execute() if paper.data: new_count = (paper.data.get("download_count") or 0) + 1 db.table("exam_paper").update({"download_count": new_count}).eq("id", paper_id).execute() return {"status": "success", "downloadCount": new_count} raise HTTPException(status_code=404, detail="试卷不存在")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253"""Router for MeloonExam user profile and personal center operations."""
import osimport uuidfrom datetime import datetimefrom typing import List, Optional
import jwtfrom fastapi import APIRouter, Header, HTTPException, Queryfrom app.database import get_dbfrom app.schemas import ( DownloadRecordSchema, ExamPaperResponse, UserProfileResponse, UserProfileUpdateRequest,)from app.services.security import ALGORITHM, SECRET_KEY
EXAM_SECRET_KEY = "meloon-exam-jwt-secret-key-replace-in-production"
router = APIRouter()
def resolve_user_id( authorization: Optional[str] = None, x_user_id: Optional[str] = None,) -> str: """Resolve user ID from Authorization header or X-User-Id, defaulting to 'user-default-1'.""" if authorization and authorization.startswith("Bearer "): token = authorization.replace("Bearer ", "").strip() for sec in [SECRET_KEY, EXAM_SECRET_KEY]: try: payload = jwt.decode(token, sec, algorithms=[ALGORITHM]) sub = payload.get("sub") if sub: return str(sub) except Exception: continue if x_user_id and x_user_id.strip(): return x_user_id.strip() return "user-default-1"
@router.get("/me", response_model=UserProfileResponse, summary="获取当前登录用户中心信息")async def get_my_profile( authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Retrieve personal center profile for current user.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) res = db.table("profiles").select("*").eq("id", user_id).execute() if not res.data: raise HTTPException(status_code=404, detail="用户档案不存在") u = res.data[0] return UserProfileResponse( id=u["id"], username=u.get("username", "user"), email=u.get("email", ""), nickname=u.get("nickname", u.get("username", "名师")), avatar=u.get("avatar", ""), role=u.get("role", "teacher"), school=u.get("school"), grade=u.get("grade"), bio=u.get("bio"), points=u.get("points", 0), uploadedCount=u.get("uploaded_count", 0), downloadedCount=u.get("downloaded_count", 0), favoritesCount=u.get("favorites_count", 0), createdAt=u.get("created_at", datetime.utcnow().isoformat()), )
@router.put("/me", response_model=UserProfileResponse, summary="修改个人名片与教研信息")async def update_my_profile( payload: UserProfileUpdateRequest, authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Update profile and bio information for current user.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) dump_fn = getattr(payload, "model_dump", payload.dict) update_data = {k: v for k, v in dump_fn().items() if v is not None} update_data["updated_at"] = datetime.utcnow().isoformat()
res = db.table("profiles").update(update_data).eq("id", user_id).execute() if not res.data: raise HTTPException(status_code=404, detail="更新失败,用户不存在") u = res.data[0] return UserProfileResponse( id=u["id"], username=u.get("username", "user"), email=u.get("email", ""), nickname=u.get("nickname", u.get("username", "名师")), avatar=u.get("avatar", ""), role=u.get("role", "teacher"), school=u.get("school"), grade=u.get("grade"), bio=u.get("bio"), points=u.get("points", 0), uploadedCount=u.get("uploaded_count", 0), downloadedCount=u.get("downloaded_count", 0), favoritesCount=u.get("favorites_count", 0), createdAt=u.get("created_at", datetime.utcnow().isoformat()), )
@router.get("/me/uploads", response_model=List[dict], summary="获取我上传的试卷列表")async def get_my_uploads( authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Retrieve papers contributed and uploaded by the current user.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) res = db.table("exam_paper").select("*").order("created_at", desc=True).execute() all_papers = res.data or [] my_papers = [ p for p in all_papers if p.get("contributor", {}).get("user_id") == user_id or "王老师" in str(p.get("contributor")) ] return my_papers
@router.get("/me/downloads", response_model=List[DownloadRecordSchema], summary="获取我的试卷下载历史记录")async def get_my_downloads( authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Retrieve paper download history for current user.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) res = ( db.table("user_downloads") .select("*") .eq("user_id", user_id) .order("downloaded_at", desc=True) .limit(50) .execute() ) records = [] for r in res.data or []: records.append( DownloadRecordSchema( id=r["id"], paperId=r["paper_id"], paperTitle=r["paper_title"], stage=r["stage"], subject=r["subject"], year=r["year"], fileSizeMb=r.get("file_size_mb", 2.5), downloadedAt=r["downloaded_at"], format=r.get("format", "PDF"), ) ) return records
@router.post("/me/downloads", summary="记录一次试卷下载行为")async def record_user_download( payload: DownloadRecordSchema, authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Record a paper download action and update statistics.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) record_id = payload.id or f"dl-{uuid.uuid4().hex[:10]}" data = { "id": record_id, "user_id": user_id, "paper_id": payload.paperId, "paper_title": payload.paperTitle, "stage": payload.stage, "subject": payload.subject, "year": payload.year, "file_size_mb": payload.fileSizeMb or 2.5, "format": payload.format, "downloaded_at": datetime.utcnow().isoformat(), } db.table("user_downloads").insert(data).execute() try: db.rpc("increment_user_download_count", {"p_user_id": user_id}).execute() except Exception: pass return {"status": "success", "id": record_id}
@router.get("/me/favorites", summary="获取用户收藏的试卷 ID 列表")async def get_my_favorites( authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Retrieve list of favorited paper IDs.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) res = db.table("user_favorites").select("paper_id").eq("user_id", user_id).execute() paper_ids = [r["paper_id"] for r in (res.data or [])] return {"paper_ids": paper_ids}
@router.post("/me/favorites/{paper_id}", summary="添加或取消收藏试卷")async def toggle_favorite( paper_id: str, authorization: Optional[str] = Header(None), x_user_id: Optional[str] = Header(None, alias="X-User-Id"),): """Toggle favorite status for an exam paper.""" db = get_db() if not db: raise HTTPException(status_code=500, detail="Database client not initialized")
user_id = resolve_user_id(authorization, x_user_id) existing = ( db.table("user_favorites") .select("id") .eq("user_id", user_id) .eq("paper_id", paper_id) .execute() ) if existing.data and len(existing.data) > 0: db.table("user_favorites").delete().eq("user_id", user_id).eq("paper_id", paper_id).execute() return {"status": "unfavorited", "paper_id": paper_id, "is_favorite": False} else: db.table("user_favorites").insert( { "user_id": user_id, "paper_id": paper_id, "created_at": datetime.utcnow().isoformat(), } ).execute() return {"status": "favorited", "paper_id": paper_id, "is_favorite": True}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199"""Pydantic schemas for MeloonExam module.
Includes data models for:- User authentication and profile management- Exam papers and question bank- Mistakes workbook- Comments, quoted replies, and likes"""
from typing import Any, List, Literal, Optionalfrom pydantic import BaseModel, EmailStr, Field
# --- 用户与鉴权数据模型 (Auth & Users) ---class UserRegisterRequest(BaseModel): username: str = Field(..., min_length=3, max_length=30, example="teacher_wang") email: EmailStr = Field(..., example="teacher.wang@meloon.edu.cn") password: Optional[str] = Field(None, min_length=6, example="123456") nickname: Optional[str] = Field(None, example="王老师(特级名师)") role: Literal["teacher", "student", "researcher"] = Field("teacher", example="teacher") school: Optional[str] = Field("北京市第四中学", example="北京市第四中学") grade: Optional[str] = Field("高三年级教研组长", example="高三年级教研组长") bio: Optional[str] = Field("高中数学一线名师,深耕高考命题研究", example="高中数学一线名师,深耕高考命题研究")
class UserLoginRequest(BaseModel): identifier: str = Field(..., description="用户名或绑定邮箱", example="teacher_wang") password: Optional[str] = Field(None, example="123456")
class UserProfileResponse(BaseModel): id: str username: str email: str nickname: str avatar: str role: Literal["teacher", "student", "researcher"] school: Optional[str] = None grade: Optional[str] = None bio: Optional[str] = None points: int = 200 uploadedCount: int = 0 downloadedCount: int = 0 favoritesCount: int = 0 createdAt: str
class AuthTokenResponse(BaseModel): access_token: str token_type: str = "bearer" user: UserProfileResponse
class UserProfileUpdateRequest(BaseModel): nickname: Optional[str] = None role: Optional[Literal["teacher", "student", "researcher"]] = None school: Optional[str] = None grade: Optional[str] = None bio: Optional[str] = None avatar: Optional[str] = None
class DownloadRecordSchema(BaseModel): id: str paperId: str paperTitle: str stage: str subject: str year: int fileSizeMb: Optional[float] = 2.5 downloadedAt: str format: Literal["PDF", "Word", "A4_Print"] = "PDF"
# --- 试卷与题目数据模型 (Exam Paper & Questions) ---class QuestionOption(BaseModel): key: str text: str
class QuestionSchema(BaseModel): id: str number: int type: str # single_choice, multi_choice, fill_blank, subjective, essay stem: str options: Optional[List[QuestionOption]] = None score: int = 5 answer: str analysis: str knowledgePoints: List[str] = [] difficulty: int = 3
class ContributorInfo(BaseModel): name: str avatar: str schoolOrRole: Optional[str] = None badge: Optional[str] = None user_id: Optional[str] = None
class ExamPaperCreate(BaseModel): id: Optional[str] = None title: str = Field(..., example="2025年全国新高考I卷 数学模拟诊断精选题") stage: str = Field(..., example="gaokao") # gaokao | zhongkao | simulated subject: str = Field(..., example="math") year: int = Field(..., example=2025) province: str = Field(..., example="新高考I卷") city: Optional[str] = "全国通用" school: Optional[str] = "命题研究组" category: str = "真题" fullScore: int = 150 timeMinutes: int = 120 difficulty: int = 3 tags: List[str] = [] contributor: ContributorInfo questions: List[QuestionSchema] = [] hasAnswer: bool = True hasAnalysis: bool = True fileSizeMb: Optional[float] = 3.0
class ExamPaperResponse(ExamPaperCreate): downloadCount: int = 0 viewCount: int = 0 likeCount: int = 0 isFeatured: bool = False createdAt: str
class MistakeCreate(BaseModel): questionId: str paperId: str paperTitle: str stage: str subject: str stem: str type: str options: Optional[List[QuestionOption]] = None answer: str analysis: str userAnswer: Optional[str] = None userNote: Optional[str] = None knowledgePoints: List[str] = []
class MistakeResponse(MistakeCreate): id: str isMastered: bool = False wrongCount: int = 1 addedAt: str
# --- 试卷考题研讨与引用评论数据模型 (Comments & Quoted Replies) ---class QuotedCommentSchema(BaseModel): id: str = Field(..., example="cmt-101") userName: str = Field(..., example="冲刺清北小李同学") content: str = Field(..., example="第 5 题求导后 $\\Delta \\le 0$ 的临界点如何分析?") createdAt: str = Field(..., example="10分钟前")
class PaperCommentCreate(BaseModel): id: Optional[str] = None paperId: str = Field(..., example="gaokao-2025-math-1") questionNumber: Optional[int] = Field(None, example=5, description="关联的具体题号,空表示全卷研讨") userId: Optional[str] = None userName: Optional[str] = "匿名考生" userAvatar: Optional[str] = None userRole: Optional[Literal["teacher", "student", "researcher"]] = "student" userBadge: Optional[str] = None content: str = Field(..., min_length=1, max_length=2000, example="利用单调性结合零点存在定理,$f'(x) \\ge 0$ 恒成立") replyToId: Optional[str] = None replyToUser: Optional[str] = None quotedComment: Optional[QuotedCommentSchema] = None
class PaperCommentResponse(BaseModel): id: str paperId: str questionNumber: Optional[int] = None userId: Optional[str] = None userName: str userAvatar: Optional[str] = None userRole: Optional[str] = "student" userBadge: Optional[str] = None content: str createdAt: str likes: int = 0 isLiked: bool = False replyToId: Optional[str] = None replyToUser: Optional[str] = None quotedComment: Optional[QuotedCommentSchema] = None
class CommentLikeResponse(BaseModel): status: str commentId: str likes: int isLiked: bool1 unmodified line23456783 unmodified lines121314151617189 unmodified lines28293031323334353637383940414243441 unmodified linefrom datetime import datetime, timedelta, timezonefrom typing import Optionalimport jwtfrom fastapi import Depends, HTTPException, statusfrom fastapi.security import OAuth2PasswordBearerfrom pydantic import BaseModel3 unmodified linesALGORITHM = "HS256"ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 1 weekoauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")class TokenData(BaseModel):user_id: Optional[str] = None9 unmodified linesencoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)return encoded_jwtdef get_current_user_id(token: str = Depends(oauth2_scheme)):credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Could not validate credentials",headers={"WWW-Authenticate": "Bearer"},)try:payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])user_id: str = payload.get("sub")if user_id is None:raise credentials_exceptionreturn user_idexcept jwt.PyJWTError:raise credentials_exception1 unmodified line23456783 unmodified lines121314151617189 unmodified lines28293031323334353637383940414243444546474849505152531 unmodified linefrom datetime import datetime, timedelta, timezonefrom typing import Optionalimport jwtfrom fastapi import Depends, Header, HTTPException, statusfrom fastapi.security import OAuth2PasswordBearerfrom pydantic import BaseModel3 unmodified linesALGORITHM = "HS256"ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 1 weekoauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login", auto_error=False)class TokenData(BaseModel):user_id: Optional[str] = None9 unmodified linesencoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)return encoded_jwtdef get_current_user_id(token: Optional[str] = Depends(oauth2_scheme),x_user_id: Optional[str] = Header(None, alias="X-User-Id"),):credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Could not validate credentials",headers={"WWW-Authenticate": "Bearer"},)if token:try:payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])user_id: str = payload.get("sub")if user_id is not None:return user_idexcept jwt.PyJWTError:passif x_user_id and x_user_id.strip():return x_user_id.strip()raise credentials_exception
10 unmodified lines11121310 unmodified linesbeautifulsoup4google-generativeaiapscheduler10 unmodified lines111213141510 unmodified linesbeautifulsoup4google-generativeaiapschedulerrequestsgoogle-genai
94 unmodified lines95969794 unmodified lines-- Indexes for performanceCREATE INDEX IF NOT EXISTS idx_ratings_item ON public.ratings(item_id, item_type);CREATE INDEX IF NOT EXISTS idx_comments_item ON public.comments(item_id, item_type);94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621794 unmodified lines-- Indexes for performanceCREATE INDEX IF NOT EXISTS idx_ratings_item ON public.ratings(item_id, item_type);CREATE INDEX IF NOT EXISTS idx_comments_item ON public.comments(item_id, item_type);-- ==========================================-- MeloonExam 试卷共享与研讨数据表模型-- ==========================================-- 用户档案中心表 (Profiles)CREATE TABLE IF NOT EXISTS public.profiles (id TEXT PRIMARY KEY,username TEXT UNIQUE NOT NULL,email TEXT UNIQUE NOT NULL,nickname TEXT,avatar TEXT,role TEXT DEFAULT 'student' CHECK (role IN ('teacher', 'student', 'researcher')),school TEXT,grade TEXT,bio TEXT,points INTEGER DEFAULT 200,uploaded_count INTEGER DEFAULT 0,downloaded_count INTEGER DEFAULT 0,favorites_count INTEGER DEFAULT 0,created_at TIMESTAMPTZ DEFAULT now(),updated_at TIMESTAMPTZ DEFAULT now());-- 试卷资源表 (Exam Papers)CREATE TABLE IF NOT EXISTS public.exam_paper (id TEXT PRIMARY KEY,title TEXT NOT NULL,stage TEXT NOT NULL, -- gaokao / zhongkao / simulatedsubject TEXT NOT NULL, -- math, physics, etc.year INTEGER NOT NULL,province TEXT NOT NULL,city TEXT DEFAULT '全国通用',school TEXT,category TEXT DEFAULT '真题',full_score INTEGER DEFAULT 150,time_minutes INTEGER DEFAULT 120,difficulty INTEGER DEFAULT 3,tags TEXT[] DEFAULT '{}',contributor JSONB NOT NULL DEFAULT '{}'::jsonb,questions JSONB NOT NULL DEFAULT '[]'::jsonb,has_answer BOOLEAN DEFAULT true,has_analysis BOOLEAN DEFAULT true,file_size_mb NUMERIC(5, 2) DEFAULT 3.0,download_count INTEGER DEFAULT 0,view_count INTEGER DEFAULT 0,like_count INTEGER DEFAULT 0,is_featured BOOLEAN DEFAULT false,created_at TIMESTAMPTZ DEFAULT now());-- 试卷考题研讨与引用评论表 (Paper Comments)CREATE TABLE IF NOT EXISTS public.paper_comments (id TEXT PRIMARY KEY,paper_id TEXT NOT NULL REFERENCES public.exam_paper(id) ON DELETE CASCADE,question_number INTEGER,user_id TEXT,user_name TEXT DEFAULT '匿名考生',user_avatar TEXT,user_role TEXT DEFAULT 'student',user_badge TEXT,content TEXT NOT NULL,likes INTEGER DEFAULT 0,reply_to_id TEXT,reply_to_user TEXT,quoted_comment JSONB,created_at TIMESTAMPTZ DEFAULT now(),updated_at TIMESTAMPTZ DEFAULT now());-- 评论点赞记录表 (Comment Likes)CREATE TABLE IF NOT EXISTS public.comment_likes (id UUID DEFAULT gen_random_uuid() PRIMARY KEY,comment_id TEXT NOT NULL REFERENCES public.paper_comments(id) ON DELETE CASCADE,user_id TEXT NOT NULL,created_at TIMESTAMPTZ DEFAULT now(),UNIQUE(comment_id, user_id));-- 试卷下载历史表 (User Downloads)CREATE TABLE IF NOT EXISTS public.user_downloads (id TEXT PRIMARY KEY,user_id TEXT NOT NULL,paper_id TEXT NOT NULL REFERENCES public.exam_paper(id) ON DELETE CASCADE,paper_title TEXT NOT NULL,stage TEXT NOT NULL,subject TEXT NOT NULL,year INTEGER NOT NULL,file_size_mb NUMERIC(5, 2) DEFAULT 2.5,format TEXT DEFAULT 'PDF',downloaded_at TIMESTAMPTZ DEFAULT now());-- 试卷收藏记录表 (User Favorites)CREATE TABLE IF NOT EXISTS public.user_favorites (id UUID DEFAULT gen_random_uuid() PRIMARY KEY,user_id TEXT NOT NULL,paper_id TEXT NOT NULL REFERENCES public.exam_paper(id) ON DELETE CASCADE,created_at TIMESTAMPTZ DEFAULT now(),UNIQUE(user_id, paper_id));-- 索引构建CREATE INDEX IF NOT EXISTS idx_exam_paper_stage_subject ON public.exam_paper(stage, subject);CREATE INDEX IF NOT EXISTS idx_exam_paper_created_at ON public.exam_paper(created_at DESC);CREATE INDEX IF NOT EXISTS idx_paper_comments_paper_id ON public.paper_comments(paper_id);CREATE INDEX IF NOT EXISTS idx_comment_likes_comment_user ON public.comment_likes(comment_id, user_id);CREATE INDEX IF NOT EXISTS idx_user_downloads_user ON public.user_downloads(user_id);CREATE INDEX IF NOT EXISTS idx_user_favorites_user ON public.user_favorites(user_id);-- 自增下载计数存储过程CREATE OR REPLACE FUNCTION increment_user_download_count(p_user_id TEXT)RETURNS VOID AS $$BEGINUPDATE public.profilesSET downloaded_count = downloaded_count + 1WHERE id = p_user_id;END;$$ LANGUAGE plpgsql;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Tests for MeloonExam endpoints integrated into MeloonTop."""
import uuidimport pytestfrom fastapi.testclient import TestClientfrom unittest.mock import MagicMock, patch
from app.main import appfrom app.schemas import ContributorInfo, ExamPaperCreate, PaperCommentCreate
client = TestClient(app)
def test_root_and_health(): """Verify root endpoint and health check.""" root_resp = client.get("/") assert root_resp.status_code == 200 assert "MeloonExam" in root_resp.json()["service"]
health_resp = client.get("/api/health") assert health_resp.status_code == 200 assert health_resp.json()["status"] == "healthy" assert "MeloonExam" in health_resp.json()["services"]
def test_exam_auth_flow(): """Verify MeloonExam profile registration and login.""" unique_user = f"teacher_{uuid.uuid4().hex[:6]}" unique_email = f"{unique_user}@example.com"
with patch("app.routers.auth.get_db") as mock_get_db, \ patch("app.routers.auth.supabase") as mock_auth_supabase: mock_client = MagicMock() mock_get_db.return_value = mock_client mock_auth_supabase.table.return_value = mock_client
# Mock no existing user mock_client.table().select().or_().execute.return_value.data = [] mock_client.table().insert().execute.return_value.data = [{"id": "user-123"}]
# 1. Register with MeloonExam payload reg_payload = { "username": unique_user, "email": unique_email, "password": "password123", "nickname": "张老师(特级教师)", "role": "teacher", "school": "北京四中", "grade": "高三数学", } res = client.post("/api/auth/register", json=reg_payload) assert res.status_code == 200 data = res.json() assert "access_token" in data assert data["user"]["username"] == unique_user
# 2. Login with identifier via /api/auth/login mock_client.table().select().or_().execute.return_value.data = [{ "id": "user-123", "username": unique_user, "email": unique_email, "nickname": "张老师(特级教师)", "avatar": "avatar.png", "role": "teacher", "points": 200, "created_at": "2026-09-04T12:00:00", }] login_res = client.post("/api/auth/login", json={"identifier": unique_user, "password": "password123"}) assert login_res.status_code == 200 assert login_res.json()["user"]["username"] == unique_user
# 3. Test /api/exam/auth alias alias_res = client.post("/api/exam/auth/login", json={"identifier": unique_user, "password": "password123"}) assert alias_res.status_code == 200 assert "access_token" in alias_res.json()
def test_papers_router(): """Verify listing, creating, retrieving, and downloading papers.""" paper_id = f"paper-{uuid.uuid4().hex[:8]}"
with patch("app.routers.papers.get_db") as mock_get_db: mock_client = MagicMock() mock_get_db.return_value = mock_client
# List papers mock_query = MagicMock() mock_client.table.return_value = mock_query mock_query.select.return_value = mock_query mock_query.eq.return_value = mock_query mock_query.order.return_value = mock_query mock_query.ilike.return_value = mock_query mock_query.execute.return_value.data = [{ "id": paper_id, "title": "2026年高考数学真题模拟卷", "stage": "gaokao", "subject": "math", "year": 2026, "province": "全国卷", }] list_res = client.get("/api/papers/?stage=gaokao&subject=math") assert list_res.status_code == 200 assert len(list_res.json()) >= 1
# Create paper payload = { "id": paper_id, "title": "2026年高考数学真题模拟卷", "stage": "gaokao", "subject": "math", "year": 2026, "province": "新高考I卷", "contributor": { "name": "王老师", "avatar": "https://avatar.com/1.png", }, "questions": [], } mock_client.table().insert().execute.return_value.data = [payload] create_res = client.post("/api/papers/", json=payload) assert create_res.status_code == 200 assert create_res.json()["paper_id"] == paper_id
# Get paper detail mock_client.table().select().eq().single().execute.return_value.data = { "id": paper_id, "title": "2026年高考数学真题模拟卷", "view_count": 5, } mock_client.table().update().eq().execute.return_value.data = [] detail_res = client.get(f"/api/papers/{paper_id}") assert detail_res.status_code == 200 assert detail_res.json()["id"] == paper_id
# Download paper counter mock_client.table().select().eq().single().execute.return_value.data = { "download_count": 10 } dl_res = client.post(f"/api/papers/{paper_id}/download") assert dl_res.status_code == 200 assert dl_res.json()["downloadCount"] == 11
def test_user_center_router(): """Verify user center profile, uploads, downloads, and favorites.""" with patch("app.routers.users.get_db") as mock_get_db: mock_client = MagicMock() mock_get_db.return_value = mock_client
# Get profile mock_client.table().select().eq().execute.return_value.data = [{ "id": "user-default-1", "username": "teacher_wang", "email": "teacher_wang@meloon.edu.cn", "nickname": "王老师", "avatar": "https://avatar.com/1.png", "role": "teacher", "school": "北京四中", "grade": "高三年级", "bio": "一线特级教师", "points": 500, "uploaded_count": 5, "downloaded_count": 10, "favorites_count": 3, "created_at": "2026-09-04T12:00:00", }]
headers = {"X-User-Id": "user-default-1"} prof_res = client.get("/api/users/me", headers=headers) assert prof_res.status_code == 200 assert prof_res.json()["nickname"] == "王老师"
# Update profile update_payload = {"nickname": "王特级老师", "bio": "命题组核心名师"} mock_client.table().update().eq().execute.return_value.data = [{ "id": "user-default-1", "username": "teacher_wang", "email": "teacher_wang@meloon.edu.cn", "nickname": "王特级老师", "avatar": "https://avatar.com/1.png", "role": "teacher", "school": "北京四中", "grade": "高三年级", "bio": "命题组核心名师", "points": 500, "uploaded_count": 5, "downloaded_count": 10, "favorites_count": 3, "created_at": "2026-09-04T12:00:00", }] up_res = client.put("/api/users/me", json=update_payload, headers=headers) assert up_res.status_code == 200 assert up_res.json()["nickname"] == "王特级老师"
# Get uploads mock_client.table().select().order().execute.return_value.data = [{ "id": "paper-1", "title": "试卷1", "contributor": {"user_id": "user-default-1", "name": "王老师"} }] uploads_res = client.get("/api/users/me/uploads", headers=headers) assert uploads_res.status_code == 200 assert len(uploads_res.json()) >= 1
# Record download dl_payload = { "id": "dl-1", "paperId": "paper-1", "paperTitle": "高三一模数学", "stage": "gaokao", "subject": "math", "year": 2026, "downloadedAt": "2026-09-04T12:00:00", "format": "PDF" } mock_client.table().insert().execute.return_value.data = [dl_payload] rec_res = client.post("/api/users/me/downloads", json=dl_payload, headers=headers) assert rec_res.status_code == 200
# Toggle favorite mock_client.table().select().eq().eq().execute.return_value.data = [] mock_client.table().insert().execute.return_value.data = [{"id": "fav-1"}] fav_res = client.post("/api/users/me/favorites/paper-1", headers=headers) assert fav_res.status_code == 200 assert fav_res.json()["is_favorite"] is True
def test_exam_comments_router(): """Verify paper comments discussion, quoting, and likes.""" with patch("app.routers.exam_comments.get_db") as mock_get_db, \ patch("app.routers.comments.supabase") as mock_comments_supabase: mock_client = MagicMock() mock_get_db.return_value = mock_client mock_comments_supabase.table.return_value = mock_client
# Create paper comment with quote mock_client.table().select().eq().execute.return_value.data = [{ "nickname": "高考探花", "avatar": "avatar.png", "role": "student" }] mock_client.table().insert().execute.return_value.data = []
cmt_payload = { "paperId": "paper-101", "questionNumber": 12, "content": "利用导数单调性可知极值点唯一", "quotedComment": { "id": "cmt-0", "userName": "原评论者", "content": "第12题如何求解?", "createdAt": "10分钟前" } } post_res = client.post( "/api/papers/paper-101/comments", json=cmt_payload, headers={"X-User-Id": "user-student-1"} ) assert post_res.status_code == 200 assert post_res.json()["questionNumber"] == 12 assert post_res.json()["quotedComment"]["userName"] == "原评论者"
# Get comments mock_client.table().select().eq().order().execute.return_value.data = [{ "id": "cmt-1", "paper_id": "paper-101", "question_number": 12, "user_id": "user-student-1", "user_name": "高考探花", "content": "利用导数单调性可知极值点唯一", "created_at": "2026-09-04T12:00:00", "likes": 5, }] mock_client.table().select().eq().in_().execute.return_value.data = [] get_res = client.get("/api/papers/paper-101/comments") assert get_res.status_code == 200 assert len(get_res.json()) == 1
# Like comment mock_client.table().select().eq().execute.return_value.data = [{"likes": 5}] mock_client.table().select().eq().eq().execute.return_value.data = [] mock_client.table().insert().execute.return_value.data = [] mock_client.table().update().eq().execute.return_value.data = [] like_res = client.post("/api/comments/cmt-1/like", headers={"X-User-Id": "user-student-1"}) assert like_res.status_code == 200 assert like_res.json()["isLiked"] is True assert like_res.json()["likes"] == 6
# Recent comments mock_client.table().select().order().limit().execute.return_value.data = [{ "id": "cmt-1", "paper_id": "paper-101", "question_number": 12, "content": "最新精解", "created_at": "2026-09-04T12:00:00", "likes": 2 }] recent_res = client.get("/api/comments/recent") assert recent_res.status_code == 200 assert len(recent_res.json()) >= 1
# Delete comment mock_del_query = MagicMock() mock_client.select.return_value = mock_del_query mock_del_query.eq.return_value = mock_del_query mock_del_query.execute.return_value.data = [{"user_id": "user-student-1"}] mock_client.delete.return_value = mock_del_query del_res = client.delete("/api/comments/cmt-1", headers={"X-User-Id": "user-student-1"}) assert del_res.status_code == 200
.gitignoreAdded+9
app/__pycache__/database.cpython-310.pyc
app/__pycache__/main.cpython-310.pyc
app/data/__pycache__/__init__.cpython-310.pyc
app/data/__pycache__/initial_tools.cpython-310.pyc
app/database.py+20-1
app/main.py+46-8
app/routers/__pycache__/__init__.cpython-310.pyc
app/routers/__pycache__/auth.cpython-310.pyc
app/routers/__pycache__/tools.cpython-310.pyc
app/routers/auth.py+171-93
app/routers/comments.py+18-8
app/routers/exam_comments.pyAdded+289
app/routers/papers.pyAdded+101
app/routers/users.pyAdded+253
app/schemas.pyAdded+199
app/services/__pycache__/scraper.cpython-310.pyc
app/services/security.py+20-11
requirements.txt+2
supabase_schema.sql+120
tests/__pycache__/__init__.cpython-310.pyc
tests/__pycache__/test_scraper.cpython-310-pytest-8.3.5.pyc
tests/test_meloonexam.pyAdded+314