Feature: AI News
Browse filesFiles changed (42)
- app/__pycache__/main.cpython-312.pyc
- app/main.py+25-5
- app/routers/__pycache__/auth.cpython-312.pyc
- app/routers/__pycache__/comments.cpython-312.pycAdded
- app/routers/__pycache__/dynamics.cpython-312-pytest-7.4.3.pycAdded
- app/routers/__pycache__/dynamics.cpython-312.pycAdded
- app/routers/__pycache__/games.cpython-312.pyc
- app/routers/__pycache__/prompts.cpython-312.pyc
- app/routers/__pycache__/ratings.cpython-312.pycAdded
- app/routers/__pycache__/tools.cpython-312.pyc
- app/routers/auth.py+109-57
- app/routers/comments.pyAdded+133
- app/routers/dynamics.pyAdded+89
- app/routers/games.py+28-9
- app/routers/prompts.py+28-9
- app/routers/ratings.pyAdded+98
- app/routers/tools.py+254-133
- app/services/__pycache__/gemini_service.cpython-312.pycAdded
- app/services/__pycache__/scraper.cpython-312.pycAdded
- app/services/__pycache__/security.cpython-312.pycAdded
- app/services/__pycache__/web_extractor.cpython-312.pycAdded
- app/services/gemini_service.pyAdded+72
- app/services/scraper.pyAdded+74
- app/services/security.pyAdded+44
- app/services/web_extractor.pyAdded+53
- requirements.txt+3
- supabase_schema.sql+40
- sync_dynamics.pyAdded+23
- tests/__pycache__/test_api.cpython-312-pytest-7.4.3.pyc
- tests/__pycache__/test_auth_ownership.cpython-312-pytest-7.4.3.pycAdded
- tests/__pycache__/test_community.cpython-312-pytest-7.4.3.pycAdded
- tests/__pycache__/test_dynamics.cpython-312-pytest-7.4.3.pycAdded
- tests/__pycache__/test_games_prompts.cpython-312-pytest-7.4.3.pycAdded
- tests/__pycache__/test_scraper_service.cpython-312-pytest-7.4.3.pycAdded
- tests/__pycache__/test_web_extractor.cpython-312-pytest-7.4.3.pycAdded
- tests/test_api.py+9-4
- tests/test_auth_ownership.pyAdded+85
- tests/test_community.pyAdded+74
- tests/test_dynamics.pyAdded+64
- tests/test_games_prompts.pyAdded+91
- tests/test_scraper_service.pyAdded+16
- tests/test_web_extractor.pyAdded+24
12345678910111213141516174 unmodified lines22232425262728from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.routers import auth, tools, games, promptsapp = FastAPI(title="MeloonAITools Backend",description="Backend API for MeloonAITools using FastAPI and Supabase.",version="1.0.0")# Configure CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"], # Adjust according to your frontend URL in productionallow_credentials=True,allow_methods=["*"],allow_headers=["*"],4 unmodified linesapp.include_router(tools.router, prefix="/api/tools", tags=["Tools"])app.include_router(games.router, prefix="/api/games", tags=["Games"])app.include_router(prompts.router, prefix="/api/prompts", tags=["Prompts"])@app.get("/")def read_root():return {"message": "Welcome to MeloonAITools API"}12345678910111213141516171819202122232425262728293031324 unmodified lines373839404142434445464748"""Main entry point for the MeloonAITools Backend.This module initializes the FastAPI application, configures CORS,and registers all routers for the application."""from typing import Dictfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom app.routers import authfrom app.routers import commentsfrom app.routers import dynamicsfrom app.routers import gamesfrom app.routers import promptsfrom app.routers import ratingsfrom app.routers import toolsapp = FastAPI(title="MeloonAITools Backend",description="Backend API for MeloonAITools using FastAPI and Supabase.",version="1.0.0",)# Configure CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"], # Adjust according to your frontend URL in productionallow_credentials=True,allow_methods=["*"],allow_headers=["*"],4 unmodified linesapp.include_router(tools.router, prefix="/api/tools", tags=["Tools"])app.include_router(games.router, prefix="/api/games", tags=["Games"])app.include_router(prompts.router, prefix="/api/prompts", tags=["Prompts"])app.include_router(dynamics.router, prefix="/api/dynamics", tags=["Dynamics"])app.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"}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, EmailStrfrom app.database import supabaseimport bcryptrouter = APIRouter()class UserCredentials(BaseModel):email: EmailStrpassword: str@router.post("/register")def register_user(credentials: UserCredentials):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. Truncate if necessary.password_bytes = credentials.password.encode('utf-8')[:72]# Use bcrypt directly to avoid passlib __about__ errorsalt = 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)return {"message": "User registered successfully", "user": user_data}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=400, detail=str(e))@router.post("/login")def login_user(credentials: UserCredentials):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]# Bcrypt has a 72-byte limit. Truncate if necessary.password_bytes = credentials.password.encode('utf-8')[:72]# Use bcrypt directly to avoid passlib __about__ error# user["password_hash"] is stored as a string in DBstored_hash = user["password_hash"].encode('utf-8')if not bcrypt.checkpw(password_bytes, stored_hash):raise HTTPException(status_code=401, detail="Invalid credentials")# In a real app we'd return a JWT. Returning user metadata here.user.pop("password_hash", None)return {"message": "Login successful", "user": user}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=401, detail=str(e))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 e
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""Router for handling item comments."""
from typing import Any, Dict, List, Optional
from fastapi import APIRouterfrom fastapi import Dependsfrom fastapi import HTTPExceptionfrom pydantic import BaseModel
from app.database import supabasefrom app.services.security import get_current_user_id
router = APIRouter()
class CommentCreate(BaseModel): """Pydantic model for creating a comment.""" item_id: str item_type: str # 'tool', 'game', or 'prompt' content: str
class CommentResponse(BaseModel): """Pydantic model for comment response data.""" id: str itemId: str itemType: str userId: str content: str createdAt: str userEmail: Optional[str] = None
@router.post("/", response_model=CommentResponse)def post_comment( comment: CommentCreate, current_user_id: str = Depends(get_current_user_id)) -> Dict[str, Any]: """Posts a new comment on an item.
Args: comment: Comment data from the request body. current_user_id: The ID of the authenticated user.
Returns: The created comment record with camelCase keys. """ if not supabase: raise HTTPException(status_code=500, detail="Supabase client not initialized")
if comment.item_type not in ["tool", "game", "prompt"]: raise HTTPException(status_code=400, detail="Invalid item type")
try: comment_data = { "item_id": comment.item_id, "item_type": comment.item_type, "user_id": current_user_id, "content": comment.content, } response = supabase.table("comments").insert(comment_data).execute() row = response.data[0] return { "id": row["id"], "itemId": row["item_id"], "itemType": row["item_type"], "userId": row["user_id"], "content": row["content"], "createdAt": row["created_at"], } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e
@router.get("/{item_type}/{item_id}", response_model=List[CommentResponse])def get_item_comments(item_type: str, item_id: str) -> List[Dict[str, Any]]: """Retrieves all comments for a specific item.
Args: item_type: The type of the item ('tool', 'game', 'prompt'). item_id: The ID of the item.
Returns: A list of comment records with camelCase keys. """ if not supabase: raise HTTPException(status_code=500, detail="Supabase client not initialized")
try: response = ( supabase.table("comments").select("*, users(email)").eq( "item_id", item_id).eq("item_type", item_type).order( "created_at", desc=True).execute())
comments = [] for row in response.data: comments.append({ "id": row["id"], "itemId": row["item_id"], "itemType": row["item_type"], "userId": row["user_id"], "content": row["content"], "createdAt": row["created_at"], "userEmail": (row.get("users", {}).get("email") if row.get("users") else "Unknown"), }) return comments except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e
@router.delete("/{comment_id}")def delete_comment( comment_id: str, current_user_id: str = Depends(get_current_user_id)) -> Dict[str, str]: """Deletes a specific comment.""" if not supabase: raise HTTPException(status_code=500, detail="Supabase client not initialized")
try: 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: raise except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Router for handling application news and dynamics."""
from datetime import datetimefrom typing import Any, Dict, List, Optional
from fastapi import APIRouterfrom fastapi import HTTPExceptionfrom pydantic import BaseModel
from app.database import supabasefrom app.services.scraper import AIScraper
router = APIRouter()
class DynamicItem(BaseModel): """Pydantic model for dynamic news items.""" id: Optional[str] = None title: str content: str url: Optional[str] = None source: Optional[str] = None category: Optional[str] = None publishedAt: Optional[datetime] = None # camelCase for frontend
@router.get("/", response_model=List[DynamicItem])async def get_dynamics() -> List[Dict[str, Any]]: """Retrieves dynamics from the database or falls back to simulation.
Returns: A list of dynamic news items with camelCase keys. """ try: response = ( supabase.table("dynamics").select("*").order("published_at", desc=True).execute()) items = [] for row in response.data: items.append({ "id": row.get("id"), "title": row.get("title"), "content": row.get("content"), "url": row.get("url"), "source": row.get("source"), "category": row.get("category"), "publishedAt": row.get("published_at"), }) return items except Exception as e: # Fallback to AIScraper if table is missing or DB is down print(f"Warning: Dynamics DB fetch failed, falling back to scraper: {e}") scraper = AIScraper() mock_items = await scraper.scrape_all() # Map mock items to camelCase expected by frontend items = [] for item in mock_items: items.append({ **item, "publishedAt": item.pop("published_at") }) return items
@router.post("/sync")async def sync_dynamics() -> Dict[str, Any]: """Syncs dynamics from external sources via AIScraper.
Returns: A success message and the synced data.
Raises: HTTPException: If scraping or insertion fails. """ try: scraper = AIScraper() new_items = await scraper.scrape_all()
if not new_items: return {"message": "No new items found."}
# Insert into Supabase response = supabase.table("dynamics").insert(new_items).execute() return { "message": f"Successfully synced {len(new_items)} items.", "data": response.data, } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e123456741 unmodified lines495051525354559 unmodified lines6566676869707172737475767778798081824 unmodified lines87888990919293949596979899100101102103104105106107108109110from fastapi import APIRouter, HTTPExceptionfrom typing import List, Optionalfrom app.database import supabasefrom pydantic import BaseModelrouter = APIRouter()41 unmodified linesraise HTTPException(status_code=500, detail=str(e))@router.post("/")def create_game(game: ItemBase):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")9 unmodified lines"added_at": game.addedAt,"image_url": game.imageUrl,"i18n": game.i18n,"user_id": game.user_id}response = supabase.table("games").insert(game_data).execute()return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.put("/{game_id}")def update_game(game_id: str, game: ItemBase):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:game_data = {"name": game.name,"description": game.description,4 unmodified lines"added_at": game.addedAt,"image_url": game.imageUrl,"i18n": game.i18n,"user_id": game.user_id}response = supabase.table("games").update(game_data).eq("id", game_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Game not found")return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.delete("/{game_id}")def delete_game(game_id: str):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:response = supabase.table("games").delete().eq("id", game_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Game not found")return {"message": "Game deleted successfully"}except Exception as e:raise HTTPException(status_code=500, detail=str(e))1234567841 unmodified lines505152535455569 unmodified lines666768697071727374757677787980818283848586878889904 unmodified lines9596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from app.database import supabasefrom pydantic import BaseModelfrom typing import List, Optionalfrom app.services.security import get_current_user_idfrom fastapi import APIRouter, HTTPException, Dependsrouter = APIRouter()41 unmodified linesraise HTTPException(status_code=500, detail=str(e))@router.post("/")def create_game(game: ItemBase, current_user_id: str = Depends(get_current_user_id)):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")9 unmodified lines"added_at": game.addedAt,"image_url": game.imageUrl,"i18n": game.i18n,"user_id": current_user_id}response = supabase.table("games").insert(game_data).execute()return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.put("/{game_id}")def update_game(game_id: str, game: ItemBase, current_user_id: str = Depends(get_current_user_id)):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:# Check ownershipexisting = supabase.table("games").select("user_id").eq("id", game_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Game not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized to edit this game")game_data = {"name": game.name,"description": game.description,4 unmodified lines"added_at": game.addedAt,"image_url": game.imageUrl,"i18n": game.i18n,# user_id stays the same}response = supabase.table("games").update(game_data).eq("id", game_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Game not found")return response.data[0]except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")@router.delete("/{game_id}")def delete_game(game_id: str, current_user_id: str = Depends(get_current_user_id)):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:# Check ownershipexisting = supabase.table("games").select("user_id").eq("id", game_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Game not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized to delete this game")response = supabase.table("games").delete().eq("id", game_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Game not found")return {"message": "Game deleted successfully"}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
123456741 unmodified lines495051525354559 unmodified lines6566676869707172737475767778798081824 unmodified lines87888990919293949596979899100101102103104105106107108109110from fastapi import APIRouter, HTTPExceptionfrom typing import List, Optionalfrom app.database import supabasefrom pydantic import BaseModelrouter = APIRouter()41 unmodified linesraise HTTPException(status_code=500, detail=str(e))@router.post("/")def create_prompt(prompt: ItemBase):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")9 unmodified lines"added_at": prompt.addedAt,"image_url": prompt.imageUrl,"i18n": prompt.i18n,"user_id": prompt.user_id}response = supabase.table("prompts").insert(prompt_data).execute()return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.put("/{prompt_id}")def update_prompt(prompt_id: str, prompt: ItemBase):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:prompt_data = {"name": prompt.name,"description": prompt.description,4 unmodified lines"added_at": prompt.addedAt,"image_url": prompt.imageUrl,"i18n": prompt.i18n,"user_id": prompt.user_id}response = supabase.table("prompts").update(prompt_data).eq("id", prompt_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Prompt not found")return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.delete("/{prompt_id}")def delete_prompt(prompt_id: str):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:response = supabase.table("prompts").delete().eq("id", prompt_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Prompt not found")return {"message": "Prompt deleted successfully"}except Exception as e:raise HTTPException(status_code=500, detail=str(e))1234567841 unmodified lines505152535455569 unmodified lines666768697071727374757677787980818283848586878889904 unmodified lines9596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from app.database import supabasefrom pydantic import BaseModelfrom typing import List, Optionalfrom app.services.security import get_current_user_idfrom fastapi import APIRouter, HTTPException, Dependsrouter = APIRouter()41 unmodified linesraise HTTPException(status_code=500, detail=str(e))@router.post("/")def create_prompt(prompt: ItemBase, current_user_id: str = Depends(get_current_user_id)):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")9 unmodified lines"added_at": prompt.addedAt,"image_url": prompt.imageUrl,"i18n": prompt.i18n,"user_id": current_user_id}response = supabase.table("prompts").insert(prompt_data).execute()return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.put("/{prompt_id}")def update_prompt(prompt_id: str, prompt: ItemBase, current_user_id: str = Depends(get_current_user_id)):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:# Check ownershipexisting = supabase.table("prompts").select("user_id").eq("id", prompt_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Prompt not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized to edit this prompt")prompt_data = {"name": prompt.name,"description": prompt.description,4 unmodified lines"added_at": prompt.addedAt,"image_url": prompt.imageUrl,"i18n": prompt.i18n,# user_id stays the same}response = supabase.table("prompts").update(prompt_data).eq("id", prompt_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Prompt not found")return response.data[0]except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")@router.delete("/{prompt_id}")def delete_prompt(prompt_id: str, current_user_id: str = Depends(get_current_user_id)):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:# Check ownershipexisting = supabase.table("prompts").select("user_id").eq("id", prompt_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Prompt not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized to delete this prompt")response = supabase.table("prompts").delete().eq("id", prompt_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Prompt not found")return {"message": "Prompt deleted successfully"}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""Router for handling item ratings."""
from typing import Any, Dict, List, Optional
from fastapi import APIRouterfrom fastapi import Dependsfrom fastapi import HTTPExceptionfrom pydantic import BaseModelfrom pydantic import conint
from app.database import supabasefrom app.services.security import get_current_user_id
router = APIRouter()
class RatingCreate(BaseModel): """Pydantic model for creating/updating a rating.""" item_id: str item_type: str # 'tool', 'game', or 'prompt' rating: conint(ge=1, le=5)
@router.post("/")def submit_rating( rating: RatingCreate, current_user_id: str = Depends(get_current_user_id)) -> Dict[str, Any]: """Submits or updates a user's rating for an item.
Args: rating: Rating data from the request body. current_user_id: The ID of the authenticated user.
Returns: The created or updated rating record.
Raises: HTTPException: If item is not found, type is invalid, or server error occurs. """ if not supabase: raise HTTPException(status_code=500, detail="Supabase client not initialized")
if rating.item_type not in ["tool", "game", "prompt"]: raise HTTPException(status_code=400, detail="Invalid item type")
try: # Check if the item exists table_name = f"{rating.item_type}s" item_check = supabase.table(table_name).select("id").eq( "id", rating.item_id).execute() if not item_check.data: raise HTTPException(status_code=404, detail="Item not found")
rating_data = { "item_id": rating.item_id, "item_type": rating.item_type, "user_id": current_user_id, "rating": rating.rating, }
# Upsert rating (user can only have one rating per item) response = supabase.table("ratings").upsert( rating_data, on_conflict="item_id, item_type, user_id").execute() return response.data[0] except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e
@router.get("/{item_type}/{item_id}")def get_item_ratings(item_type: str, item_id: str) -> Dict[str, Any]: """Retrieves rating statistics for a specific item.
Args: item_type: The type of the item ('tool', 'game', 'prompt'). item_id: The ID of the item.
Returns: A dictionary containing the average rating, total count, and individual ratings.
Raises: HTTPException: If Supabase client is not initialized or an error occurs. """ if not supabase: raise HTTPException(status_code=500, detail="Supabase client not initialized")
try: response = supabase.table("ratings").select("rating").eq( "item_id", item_id).eq("item_type", item_type).execute() ratings = [r["rating"] for r in response.data]
avg_rating = sum(ratings) / len(ratings) if ratings else 0.0 return { "average": avg_rating, "count": len(ratings), "ratings": ratings, } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148from fastapi import APIRouter, HTTPException, Dependsfrom pydantic import BaseModelfrom typing import List, Optionalfrom app.database import supabasefrom app.data.initial_tools import INITIAL_TOOLS_DATArouter = APIRouter()class ToolBase(BaseModel):id: strname: strdescription: strurl: strcategory: strtags: List[str]likes: intaddedAt: int # We map addedAt to added_at in DBimageUrl: Optional[str] = Nonei18n: dictuser_id: Optional[str] = "admin"@router.get("/")def get_tools(q: Optional[str] = None):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:query = supabase.table("tools").select("*")if q:# Simple fuzzy matching on name or description or tags# Note: tags is an array, so we might need a different approach for true fuzzy,# but ilike on the whole string representation or specific logic might work.# For now, let's stick to name and description as per standard requirements.query = query.or_(f"name.ilike.%{q}%,description.ilike.%{q}%")response = query.execute()# Transform snake_case back to camelCase for the frontend if neededtools = []for row in response.data:tools.append({"id": row.get("id"),"name": row.get("name"),"description": row.get("description"),"url": row.get("url"),"category": row.get("category"),"tags": row.get("tags", []),"likes": row.get("likes", 0),"addedAt": row.get("added_at"),"imageUrl": row.get("image_url"),"i18n": row.get("i18n", {}),"user_id": row.get("user_id")})return toolsexcept Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.post("/init")def init_tools(admin_user_id: str):"""Initializes the database with the predefined tools.Requires an 'admin_user_id' UUID string to assign the tools to."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:tools_to_insert = []for tool in INITIAL_TOOLS_DATA:tools_to_insert.append({"id": tool["id"],"name": tool["name"],"description": tool["description"],"url": tool["url"],"category": tool["category"],"tags": tool.get("tags", []),"likes": tool.get("likes", 0),"added_at": tool["addedAt"],"image_url": tool.get("imageUrl"),"i18n": tool.get("i18n", {}),"user_id": admin_user_id})# Upsert the toolsresponse = supabase.table("tools").upsert(tools_to_insert).execute()return {"message": f"Successfully initialized {len(response.data)} tools.", "data": response.data}except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.post("/")def create_tool(tool: ToolBase):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:tool_data = {"id": tool.id,"name": tool.name,"description": tool.description,"url": tool.url,"category": tool.category,"tags": tool.tags,"likes": tool.likes,"added_at": tool.addedAt,"image_url": tool.imageUrl,"i18n": tool.i18n,"user_id": tool.user_id}response = supabase.table("tools").insert(tool_data).execute()return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.put("/{tool_id}")def update_tool(tool_id: str, tool: ToolBase):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:tool_data = {"name": tool.name,"description": tool.description,"url": tool.url,"category": tool.category,"tags": tool.tags,"likes": tool.likes,"added_at": tool.addedAt,"image_url": tool.imageUrl,"i18n": tool.i18n,"user_id": tool.user_id}response = supabase.table("tools").update(tool_data).eq("id", tool_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Tool not found")return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e))@router.delete("/{tool_id}")def delete_tool(tool_id: str):if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:response = supabase.table("tools").delete().eq("id", tool_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Tool not found")return {"message": "Tool deleted successfully"}except Exception as e:raise HTTPException(status_code=500, detail=str(e))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269"""Router for handling AI tools management."""from typing import Any, Dict, List, Optionalfrom fastapi import APIRouterfrom fastapi import Dependsfrom fastapi import HTTPExceptionfrom app.database import supabasefrom app.data.initial_tools import INITIAL_TOOLS_DATAfrom app.services import gemini_servicefrom app.services.security import get_current_user_idfrom app.services.web_extractor import extract_url_metadatafrom pydantic import BaseModelrouter = APIRouter()class ToolBase(BaseModel):"""Pydantic model for AI Tool data."""id: strname: strdescription: strurl: strcategory: strtags: List[str]likes: intaddedAt: int # Maps to added_at in DBimageUrl: Optional[str] = Nonei18n: Dict[str, Any]user_id: Optional[str] = "admin"@router.get("/")def get_tools(q: Optional[str] = None) -> List[Dict[str, Any]]:"""Retrieves a list of tools, optionally filtered by a search query.Args:q: Optional search query string.Returns:A list of dictionaries representing the tools.Raises:HTTPException: If Supabase client is not initialized or an error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:query = supabase.table("tools").select("*")if q:query = query.or_(f"name.ilike.%{q}%,description.ilike.%{q}%")response = query.execute()# Transform snake_case back to camelCase for the frontendtools = []for row in response.data:tools.append({"id": row.get("id"),"name": row.get("name"),"description": row.get("description"),"url": row.get("url"),"category": row.get("category"),"tags": row.get("tags", []),"likes": row.get("likes", 0),"addedAt": row.get("added_at"),"imageUrl": row.get("image_url"),"i18n": row.get("i18n", {}),"user_id": row.get("user_id"), # Keeping user_id for now as it might be used in logic, but adding userId"userId": row.get("user_id"),})return toolsexcept Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e@router.post("/init")def init_tools(admin_user_id: str) -> Dict[str, Any]:"""Initializes the database with predefined tools.Args:admin_user_id: UUID string to assign tools to.Returns:A success message and the initialized data.Raises:HTTPException: If Supabase client is not initialized or an error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:tools_to_insert = []for tool in INITIAL_TOOLS_DATA:tools_to_insert.append({"id": tool["id"],"name": tool["name"],"description": tool["description"],"url": tool["url"],"category": tool["category"],"tags": tool.get("tags", []),"likes": tool.get("likes", 0),"added_at": tool["addedAt"],"image_url": tool.get("imageUrl"),"i18n": tool.get("i18n", {}),"user_id": admin_user_id,})response = supabase.table("tools").upsert(tools_to_insert).execute()return {"message": f"Successfully initialized {len(response.data)} tools.","data": response.data,}except Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e@router.post("/")def create_tool(tool: ToolBase,current_user_id: str = Depends(get_current_user_id)) -> Dict[str, Any]:"""Creates a new tool submission.Args:tool: Tool data from the request body.current_user_id: The ID of the authenticated user.Returns:The created tool data.Raises:HTTPException: If Supabase client is not initialized or an error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:tool_data = {"id": tool.id,"name": tool.name,"description": tool.description,"url": tool.url,"category": tool.category,"tags": tool.tags,"likes": tool.likes,"added_at": tool.addedAt,"image_url": tool.imageUrl,"i18n": tool.i18n,"user_id": current_user_id,}response = supabase.table("tools").insert(tool_data).execute()return response.data[0]except Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e@router.get("/extract-metadata")async def get_url_metadata(url: str, lang: str = "en") -> Dict[str, Any]:"""Extracts and enhances metadata from a URL.Args:url: The URL to extract metadata from.lang: Target language for enhancement.Returns:Enhanced metadata including name, description, category, and tags.Raises:HTTPException: If extraction fails."""result = await extract_url_metadata(url)if "error" in result and not result["title"]:raise HTTPException(status_code=400, detail=result["error"])# Use Gemini to enhance the raw Metadataenhanced = await gemini_service.enhance_metadata(title=result.get("title", ""),description=result.get("description", ""),url=url,language=lang)return {**result, "enhanced": enhanced}@router.put("/{tool_id}")def update_tool(tool_id: str,tool: ToolBase,current_user_id: str = Depends(get_current_user_id)) -> Dict[str, Any]:"""Updates an existing tool submission.Args:tool_id: ID of the tool to update.tool: Updated tool data.current_user_id: ID of the authenticated user.Returns:The updated tool data.Raises:HTTPException: If not found, not authorized, or an error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:existing = supabase.table("tools").select("user_id").eq("id",tool_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Tool not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized")tool_data = {"name": tool.name,"description": tool.description,"url": tool.url,"category": tool.category,"tags": tool.tags,"likes": tool.likes,"added_at": tool.addedAt,"image_url": tool.imageUrl,"i18n": tool.i18n,}response = supabase.table("tools").update(tool_data).eq("id",tool_id).execute()if not response.data:raise HTTPException(status_code=404, detail="Tool not found")return response.data[0]except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e@router.delete("/{tool_id}")def delete_tool(tool_id: str,current_user_id: str = Depends(get_current_user_id)) -> Dict[str, str]:"""Deletes a tool submission.Args:tool_id: ID of the tool to delete.current_user_id: ID of the authenticated user.Returns:A success message.Raises:HTTPException: If not found, not authorized, or an error occurs."""if not supabase:raise HTTPException(status_code=500, detail="Supabase client not initialized")try:existing = supabase.table("tools").select("user_id").eq("id",tool_id).execute()if not existing.data:raise HTTPException(status_code=404, detail="Tool not found")if str(existing.data[0]["user_id"]) != str(current_user_id):raise HTTPException(status_code=403, detail="Not authorized")supabase.table("tools").delete().eq("id", tool_id).execute()return {"message": "Tool deleted successfully"}except HTTPException:raiseexcept Exception as e:raise HTTPException(status_code=500, detail=str(e)) from e
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Service module for interacting with Google Gemini AI."""
import jsonimport osfrom typing import Any, Dict, List, Optional
import google.generativeai as genai
# Load API Key from environmentGEMINI_API_KEY = os.getenv("VITE_GEMINI_API_KEY") or os.getenv("GEMINI_API_KEY")
if GEMINI_API_KEY: genai.configure(api_key=GEMINI_API_KEY)
async def enhance_metadata(title: str, description: str, url: str, language: str = "en") -> Dict[str, Any]: """Enhances tool metadata using Gemini.
Args: title: The scraped title of the tool. description: The scraped description of the tool. url: The URL of the tool. language: The desired language for the enhancement (en/zh).
Returns: A dictionary containing the enhanced name, description, category, and tags. """ if not GEMINI_API_KEY: return { "name": title, "description": description, "category": "Other", "tags": [] }
model = genai.GenerativeModel("gemini-1.5-flash")
lang_instruction = ( "Ensure the description and tags are in Chinese (Simplified)." if language == "zh" else "Ensure the description and tags are in English.")
prompt = f""" You are an expert AI software consultant. A user wants to add a tool from this URL: {url} Scraped Title: {title} Scraped Description: {description} Please refine this data into high-quality metadata: 1. 'name': A clean, recognizable name for the tool. 2. 'description': A professional, concise summary (max 20 words). 3. 'category': Choose ONE from: Chatbot, Image Generation, Video Generation, Coding Assistant, Copywriting, Audio & Speech, Productivity, Other. 4. 'tags': 3-5 relevant short tags. {lang_instruction} Return the result as a raw JSON object. """
try: response = await model.generate_content_async( prompt, generation_config={"response_mime_type": "application/json"}) return json.loads(response.text) except Exception as e: print(f"Gemini enhancement failed: {e}") return { "name": title, "description": description, "category": "Other", "tags": [] }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Services for scraping AI-related news and dynamics."""
import randomfrom datetime import datetime, timedeltafrom typing import Any, Dict, List
class AIScraper: """Simulated scraper for AI news and industry trends."""
def __init__(self): """Initializes the scraper with simulation data.""" # AI Keywords self.products = ["ChatGPT", "Grok", "Gemini", "Qwen", "DeepSeek", "Claude"] self.companies = [ "OpenAI", "Anthropic", "Google DeepMind", "xAI", "Alibaba", "DeepSeek-AI" ] self.leaders = [ "Sam Altman", "Andrew Ng", "Fei-Fei Li", "Elon Musk", "Dario Amodei" ] self.robots = ["Figure 02", "Optimus", "Unitree B2", "Atlas"]
self.sources = ["LinkedIn", "Twitter", "TechoCrunch", "The Verge", "AI News"]
async def scrape_all(self) -> List[Dict[str, Any]]: """Simulates scraping news items from multiple sources.
In a real production environment, this would use a search API (like Serper/Google) or specific platform APIs/Scrapers.
Returns: List of dictionaries representing news dynamics. """ dynamics = []
# Simulate fetching 5-10 items for _ in range(random.randint(5, 10)): category = random.choice(["Product", "Company", "Leader", "Robot"])
if category == "Product": subject = random.choice(self.products) title = f"{subject} releases a major update today" content = (f"The latest version of {subject} brings significant performance " "improvements and multi-modal capabilities.") elif category == "Company": subject = random.choice(self.companies) title = f"{subject} secures new funding for AI infrastructure" content = (f"{subject} announced a multi-billion dollar investment to " "scale their compute clusters.") elif category == "Leader": subject = random.choice(self.leaders) title = f"{subject} discusses the future of AGI" content = (f"In a recent talk, {subject} highlighted the importance of " "AI safety and open-source models.") else: subject = random.choice(self.robots) title = f"{subject} humanoid robot shows off new skills" content = (f"The {subject} robot successfully completed complex " "manipulation tasks in a factory environment.")
source = random.choice(self.sources) # Create a realistic timestamp for "today" published_at = datetime.now() - timedelta(minutes=random.randint(0, 1440))
dynamics.append({ "title": title, "content": content, "url": f"https://example.com/news/{random.randint(1000, 9999)}", "source": source, "category": category, "published_at": published_at.isoformat(), })
return dynamics1234567891011121314151617181920212223242526272829303132333435363738394041424344import osfrom datetime import datetime, timedelta, timezonefrom typing import Optionalimport jwtfrom fastapi import Depends, HTTPException, statusfrom fastapi.security import OAuth2PasswordBearerfrom pydantic import BaseModel
# Secret key to sign JWT tokens# In production, this should be a strong, randomly generated secretSECRET_KEY = os.getenv("JWT_SECRET_KEY", "your-super-secret-key-for-dev-only")ALGORITHM = "HS256"ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 # 1 week
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")
class TokenData(BaseModel): user_id: Optional[str] = None email: Optional[str] = None
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() if expires_delta: expire = datetime.now(timezone.utc) + expires_delta else: expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
def 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_exception return user_id except jwt.PyJWTError: raise credentials_exception1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Service for extracting metadata from external URLs."""
from typing import Any, Dict, Optional
import httpxfrom bs4 import BeautifulSoup
async def extract_url_metadata(url: str) -> Dict[str, Any]: """Extracts basic metadata (title, description) from a URL.
Used to provide context for Magic Auto-fill and AI-assisted submission.
Args: url: The URL to extract metadata from.
Returns: A dictionary containing title, description, and url. """ try: async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client: headers = { "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36") } response = await client.get(url, headers=headers) response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# Extract Title title = soup.title.string.strip() if soup.title else None
# Extract Description (multiple common patterns) description = None desc_meta = ( soup.find("meta", property="og:description") or soup.find("meta", attrs={"name": "description"}) or soup.find("meta", property="twitter:description")) if desc_meta: description = desc_meta.get("content", "").strip()
# Fallback if title is missing if not title: og_title = soup.find("meta", property="og:title") if og_title: title = og_title.get("content", "").strip()
return {"title": title, "description": description, "url": url} except Exception as e: print(f"Extraction failed for {url}: {e}") return {"title": None, "description": None, "url": url, "error": str(e)}6 unmodified lines7896 unmodified linespytesthttpx<0.28.0email-validator6 unmodified lines7891011126 unmodified linespytesthttpx<0.28.0email-validatorPyJWTbeautifulsoup4google-generativeai
53 unmodified lines54555653 unmodified linesi18n JSONB NOT NULL,user_id UUID REFERENCES public.users(id) ON DELETE CASCADE);53 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959653 unmodified linesi18n JSONB NOT NULL,user_id UUID REFERENCES public.users(id) ON DELETE CASCADE);-- Dynamics tableCREATE TABLE IF NOT EXISTS public.dynamics (id UUID DEFAULT gen_random_uuid() PRIMARY KEY,title TEXT NOT NULL,content TEXT NOT NULL,url TEXT,source TEXT,category TEXT,published_at TIMESTAMPTZ DEFAULT now());-- Performance Indexes for SearchCREATE INDEX IF NOT EXISTS idx_tools_name_description ON public.tools USING gin(to_tsvector('english', name || ' ' || description));CREATE INDEX IF NOT EXISTS idx_games_name_description ON public.games USING gin(to_tsvector('english', name || ' ' || description));CREATE INDEX IF NOT EXISTS idx_prompts_name_description ON public.prompts USING gin(to_tsvector('english', name || ' ' || description));-- Ratings tableCREATE TABLE IF NOT EXISTS public.ratings (id UUID DEFAULT gen_random_uuid() PRIMARY KEY,item_id TEXT NOT NULL,item_type TEXT NOT NULL CHECK (item_type IN ('tool', 'game', 'prompt')),user_id UUID REFERENCES public.users(id) ON DELETE CASCADE,rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),created_at TIMESTAMPTZ DEFAULT now(),UNIQUE(item_id, item_type, user_id));-- Comments tableCREATE TABLE IF NOT EXISTS public.comments (id UUID DEFAULT gen_random_uuid() PRIMARY KEY,item_id TEXT NOT NULL,item_type TEXT NOT NULL CHECK (item_type IN ('tool', 'game', 'prompt')),user_id UUID REFERENCES public.users(id) ON DELETE CASCADE,content TEXT NOT NULL,created_at TIMESTAMPTZ DEFAULT now());-- 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);
1234567891011121314151617181920212223import httpximport asyncioimport osfrom dotenv import load_dotenv
load_dotenv()
BASE_URL = os.getenv("API_BASE_URL", "http://127.0.0.1:8000")
async def sync_dynamics(): print(f"Starting sync from {BASE_URL}/api/dynamics/sync ...") async with httpx.AsyncClient(timeout=60.0) as client: try: response = await client.post(f"{BASE_URL}/api/dynamics/sync") if response.status_code == 200: print(f"Sync successful: {response.json().get('message')}") else: print(f"Sync failed with status {response.status_code}: {response.text}") except Exception as e: print(f"Error during sync: {e}")
if __name__ == "__main__": asyncio.run(sync_dynamics())1234567891011121350 unmodified lines646566676869709 unmodified lines80818283848586import pytestfrom fastapi.testclient import TestClientfrom unittest.mock import patch, MagicMockfrom passlib.context import CryptContextfrom app.main import appfrom app.data.initial_tools import INITIAL_TOOLS_DATAclient = TestClient(app)pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")# --- Fixtures for Mocking Supabase ---50 unmodified linesassert response.json()["detail"] == "Email already registered"def test_login_success(mock_supabase):hashed_password = pwd_context.hash("password123")# Mock finding the user during loginmock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{9 unmodified linesassert "password_hash" not in response.json()["user"]def test_login_invalid_password(mock_supabase):hashed_password = pwd_context.hash("different_password")mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "123e4567-e89b-12d3-a456-426614174000",12345678910111250 unmodified lines636465666768697071729 unmodified lines82838485868788899091import pytestfrom fastapi.testclient import TestClientfrom unittest.mock import patch, MagicMockimport bcryptfrom app.main import appfrom app.data.initial_tools import INITIAL_TOOLS_DATAclient = TestClient(app)# --- Fixtures for Mocking Supabase ---50 unmodified linesassert response.json()["detail"] == "Email already registered"def test_login_success(mock_supabase):password = "password123"password_bytes = password.encode('utf-8')[:72]salt = bcrypt.gensalt()hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')# Mock finding the user during loginmock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{9 unmodified linesassert "password_hash" not in response.json()["user"]def test_login_invalid_password(mock_supabase):password = "different_password"password_bytes = password.encode('utf-8')[:72]salt = bcrypt.gensalt()hashed_password = bcrypt.hashpw(password_bytes, salt).decode('utf-8')mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "123e4567-e89b-12d3-a456-426614174000",
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import pytestfrom fastapi.testclient import TestClientfrom app.main import appimport uuid
client = TestClient(app)
def test_full_auth_and_ownership_flow(): # 1. Register email = f"test_{uuid.uuid4()}@example.com" password = "password123" reg_response = client.post("/api/auth/register", json={"email": email, "password": password}) assert reg_response.status_code == 200 reg_data = reg_response.json() token1 = reg_data["access_token"] user1_id = reg_data["user"]["id"]
# 2. Login login_response = client.post("/api/auth/login", json={"email": email, "password": password}) assert login_response.status_code == 200 token1 = login_response.json()["access_token"] # Use the most recent token
# 3. Create tool without token tool_id = str(uuid.uuid4()) tool_payload = { "id": tool_id, "name": "Auth Test Tool", "description": "A tool to test auth", "url": "https://test.com", "category": "Other", "tags": ["test"], "likes": 0, "addedAt": 1700000000, "i18n": {"en": {"name": "Auth Test Tool"}, "zh": {"name": "权限测试工具"}} } create_no_token = client.post("/api/tools/", json=tool_payload) assert create_no_token.status_code == 401
# 4. Create tool with token create_with_token = client.post( "/api/tools/", json=tool_payload, headers={"Authorization": f"Bearer {token1}"} ) assert create_with_token.status_code == 200 assert create_with_token.json()["user_id"] == user1_id
# 5. Register second user email2 = f"test_{uuid.uuid4()}@example.com" reg_response2 = client.post("/api/auth/register", json={"email": email2, "password": password}) token2 = reg_response2.json()["access_token"]
# 6. Second user tries to update first user's tool update_payload = tool_payload.copy() update_payload["name"] = "Malicious Update" update_fail = client.put( f"/api/tools/{tool_id}", json=update_payload, headers={"Authorization": f"Bearer {token2}"} ) assert update_fail.status_code == 403
# 7. First user updates their own tool update_payload["name"] = "Legit Update" update_success = client.put( f"/api/tools/{tool_id}", json=update_payload, headers={"Authorization": f"Bearer {token1}"} ) assert update_success.status_code == 200 assert update_success.json()["name"] == "Legit Update"
# 8. Second user tries to delete first user's tool delete_fail = client.delete( f"/api/tools/{tool_id}", headers={"Authorization": f"Bearer {token2}"} ) assert delete_fail.status_code == 403
# 9. First user deletes their own tool delete_success = client.delete( f"/api/tools/{tool_id}", headers={"Authorization": f"Bearer {token1}"} ) assert delete_success.status_code == 2001234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import pytestfrom fastapi.testclient import TestClientfrom unittest.mock import patch, MagicMockfrom app.main import appfrom app.services.security import get_current_user_id
client = TestClient(app)
class MockResponse: def __init__(self, data): self.data = data
@pytest.fixture(autouse=True)def override_dependency(): """Overrides the get_current_user_id dependency for all tests.""" app.dependency_overrides[get_current_user_id] = lambda: "user1" yield app.dependency_overrides = {}
@pytest.fixturedef mock_supabase(): with patch("app.routers.ratings.supabase") as mock_ratings, \ patch("app.routers.comments.supabase") as mock_comments: mock_client = MagicMock() mock_ratings.table.return_value = mock_client mock_comments.table.return_value = mock_client yield mock_client
def test_submit_rating(mock_supabase): mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "item1"}]) mock_supabase.upsert.return_value.execute.return_value = MockResponse(data=[{"item_id": "item1", "rating": 5}]) response = client.post("/api/ratings/", json={"item_id": "item1", "item_type": "tool", "rating": 5}) assert response.status_code == 200 assert response.json()["rating"] == 5
def test_get_ratings(mock_supabase): mock_supabase.select.return_value.eq.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"rating": 5}, {"rating": 4}]) response = client.get("/api/ratings/tool/item1") assert response.status_code == 200 assert response.json()["average"] == 4.5 assert response.json()["count"] == 2
def test_post_comment(mock_supabase): mock_supabase.insert.return_value.execute.return_value = MockResponse(data=[{ "id": "c1", "item_id": "item1", "item_type": "tool", "user_id": "user1", "content": "test", "created_at": "now" }]) response = client.post("/api/comments/", json={"item_id": "item1", "item_type": "tool", "content": "test"}) assert response.status_code == 200 # Check for camelCase keys assert response.json()["content"] == "test" assert "userId" in response.json() assert "createdAt" in response.json()
def test_get_comments(mock_supabase): mock_supabase.select.return_value.eq.return_value.eq.return_value.order.return_value.execute.return_value = MockResponse(data=[{ "id": "c1", "item_id": "item1", "item_type": "tool", "user_id": "user1", "content": "test", "created_at": "now", "users": {"email": "test@test.com"} }]) response = client.get("/api/comments/tool/item1") assert response.status_code == 200 assert len(response.json()) == 1 # Check for camelCase keys assert response.json()[0]["userEmail"] == "test@test.com" assert response.json()[0]["itemId"] == "item1"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import pytestfrom fastapi.testclient import TestClientfrom unittest.mock import patch, MagicMockfrom app.main import app
client = TestClient(app)
# --- Helper Classes bridging MagicMock chains ---class MockResponse: def __init__(self, data): self.data = data
@pytest.fixturedef mock_supabase(): """Mocks the Supabase client used in the dynamics router.""" with patch("app.routers.dynamics.supabase") as mock_dynamics: mock_client = MagicMock() mock_dynamics.table.return_value = mock_client yield mock_client
def test_get_dynamics_empty(mock_supabase): mock_supabase.select.return_value.order.return_value.execute.return_value = MockResponse(data=[]) response = client.get("/api/dynamics/") assert response.status_code == 200 assert response.json() == []
def test_get_dynamics_with_data(mock_supabase): mock_data = [ { "id": "1", "title": "Test Dynamics", "content": "Content", "url": "http://test.com", "source": "Test", "category": "Product", "published_at": "2024-01-01T00:00:00Z" } ] mock_supabase.select.return_value.order.return_value.execute.return_value = MockResponse(data=mock_data) response = client.get("/api/dynamics/") assert response.status_code == 200 assert len(response.json()) == 1 assert response.json()[0]["title"] == "Test Dynamics"
def test_sync_dynamics(mock_supabase): # Mock search and insert # We need to mock the scraper.scrape_all as well if we want to be thorough, # but for now, testing the router's interaction with Supabase is the priority. with patch("app.routers.dynamics.AIScraper") as MockScraper: mock_scraper_instance = MockScraper.return_value # Since AIScraper.scrape_all is async, we mock it as an async function async def mock_scrape_all(): return [{"title": "Scraped", "content": "Content", "published_at": "2024-01-01T00:00:00Z"}] mock_scraper_instance.scrape_all = mock_scrape_all mock_supabase.insert.return_value.execute.return_value = MockResponse(data=[{"id": "1", "title": "Scraped"}]) response = client.post("/api/dynamics/sync") assert response.status_code == 200 assert "Successfully synced 1 items." in response.json()["message"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import pytestfrom fastapi.testclient import TestClientfrom unittest.mock import patch, MagicMockfrom app.main import app
from app.services.security import get_current_user_id
client = TestClient(app)
@pytest.fixturedef mock_supabase(): with patch("app.routers.games.supabase") as mock_games, \ patch("app.routers.prompts.supabase") as mock_prompts: mock_client = MagicMock() mock_games.table.return_value = mock_client mock_prompts.table.return_value = mock_client yield mock_client
@pytest.fixturedef override_auth(): app.dependency_overrides[get_current_user_id] = lambda: "user1" yield app.dependency_overrides.pop(get_current_user_id, None)
class MockResponse: def __init__(self, data): self.data = data
def test_get_games(mock_supabase): mock_supabase.select.return_value.execute.return_value = MockResponse(data=[{"id": "g1", "name": "Game 1"}]) response = client.get("/api/games/") assert response.status_code == 200 assert response.json()[0]["name"] == "Game 1"
def test_get_games_search(mock_supabase): mock_supabase.select.return_value.or_.return_value.execute.return_value = MockResponse(data=[{"id": "g1", "name": "Game 1"}]) response = client.get("/api/games/?q=test") assert response.status_code == 200
def test_create_game_unauthorized(mock_supabase): response = client.post("/api/games/", json={"id": "g1", "name": "G1", "description": "D", "url": "U", "category": "C", "tags": [], "likes": 0, "addedAt": 0, "i18n": {}, "user_id": ""}) assert response.status_code == 401
def test_create_game_success(mock_supabase, override_auth): mock_supabase.insert.return_value.execute.return_value = MockResponse(data=[{"id": "g1", "name": "G1"}]) response = client.post("/api/games/", json={"id": "g1", "name": "G1", "description": "D", "url": "U", "category": "C", "tags": [], "likes": 0, "addedAt": 0, "i18n": {}, "user_id": "user1"}) assert response.status_code == 200 assert response.json()["name"] == "G1"
def test_get_prompts(mock_supabase): mock_supabase.select.return_value.execute.return_value = MockResponse(data=[{"id": "p1", "name": "Prompt 1"}]) response = client.get("/api/prompts/") assert response.status_code == 200 assert response.json()[0]["name"] == "Prompt 1"
def test_update_game_success(mock_supabase, override_auth): # Mock ownership check mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"user_id": "user1"}]) # Mock update mock_supabase.update.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "g1", "name": "G1 Updated"}]) response = client.put("/api/games/g1", json={"id": "g1", "name": "G1 Updated", "description": "D", "url": "U", "category": "C", "tags": [], "likes": 0, "addedAt": 0, "i18n": {}, "user_id": "user1"}) assert response.status_code == 200 assert response.json()["name"] == "G1 Updated"
def test_delete_game_success(mock_supabase, override_auth): # Mock ownership mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"user_id": "user1"}]) # Mock delete mock_supabase.delete.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "g1"}]) response = client.delete("/api/games/g1") assert response.status_code == 200 assert "deleted successfully" in response.json()["message"]
def test_create_prompt_success(mock_supabase, override_auth): mock_supabase.insert.return_value.execute.return_value = MockResponse(data=[{"id": "p1", "name": "P1"}]) response = client.post("/api/prompts/", json={"id": "p1", "name": "P1", "description": "D", "url": "U", "category": "C", "tags": [], "likes": 0, "addedAt": 0, "i18n": {}, "user_id": "user1"}) assert response.status_code == 200
def test_update_prompt_success(mock_supabase, override_auth): mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"user_id": "user1"}]) mock_supabase.update.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "p1", "name": "P1 Updated"}]) response = client.put("/api/prompts/p1", json={"id": "p1", "name": "P1 Updated", "description": "D", "url": "U", "category": "C", "tags": [], "likes": 0, "addedAt": 0, "i18n": {}, "user_id": "user1"}) assert response.status_code == 200
def test_delete_prompt_success(mock_supabase, override_auth): mock_supabase.select.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"user_id": "user1"}]) mock_supabase.delete.return_value.eq.return_value.execute.return_value = MockResponse(data=[{"id": "p1"}]) response = client.delete("/api/prompts/p1") assert response.status_code == 20012345678910111213141516import pytestfrom app.services.scraper import AIScraper
@pytest.mark.asyncioasync def test_scrape_all(): scraper = AIScraper() results = await scraper.scrape_all() assert isinstance(results, list) assert len(results) >= 5 for item in results: assert "title" in item assert "content" in item assert "url" in item assert "source" in item assert "category" in item assert "published_at" in item123456789101112131415161718192021222324import pytestfrom fastapi.testclient import TestClientfrom app.main import app
client = TestClient(app)
def test_extract_metadata_success(): # Attempting to extract from a highly stable site like GitHub url = "https://github.com" response = client.get(f"/api/tools/extract-metadata?url={url}") assert response.status_code == 200 data = response.json() assert "title" in data assert "description" in data assert data["url"] == url # GitHub usually has 'GitHub' in the title assert "GitHub" in data["title"]
def test_extract_metadata_invalid_url(): url = "https://this-is-definitely-not-a-real-website-12345.com" response = client.get(f"/api/tools/extract-metadata?url={url}") # It should return a 400 since it fails to extract assert response.status_code == 400 assert "detail" in response.json()app/__pycache__/main.cpython-312.pyc
app/main.py+25-5
app/routers/__pycache__/auth.cpython-312.pyc
app/routers/__pycache__/comments.cpython-312.pycAdded
app/routers/__pycache__/dynamics.cpython-312-pytest-7.4.3.pycAdded
app/routers/__pycache__/dynamics.cpython-312.pycAdded
app/routers/__pycache__/games.cpython-312.pyc
app/routers/__pycache__/prompts.cpython-312.pyc
app/routers/__pycache__/ratings.cpython-312.pycAdded
app/routers/__pycache__/tools.cpython-312.pyc
app/routers/auth.py+109-57
app/routers/comments.pyAdded+133
app/routers/dynamics.pyAdded+89
app/routers/games.py+28-9
app/routers/prompts.py+28-9
app/routers/ratings.pyAdded+98
app/routers/tools.py+254-133
app/services/__pycache__/gemini_service.cpython-312.pycAdded
app/services/__pycache__/scraper.cpython-312.pycAdded
app/services/__pycache__/security.cpython-312.pycAdded
app/services/__pycache__/web_extractor.cpython-312.pycAdded
app/services/gemini_service.pyAdded+72
app/services/scraper.pyAdded+74
app/services/security.pyAdded+44
app/services/web_extractor.pyAdded+53
requirements.txt+3
supabase_schema.sql+40
sync_dynamics.pyAdded+23
tests/__pycache__/test_api.cpython-312-pytest-7.4.3.pyc
tests/__pycache__/test_auth_ownership.cpython-312-pytest-7.4.3.pycAdded
tests/__pycache__/test_community.cpython-312-pytest-7.4.3.pycAdded
tests/__pycache__/test_dynamics.cpython-312-pytest-7.4.3.pycAdded
tests/__pycache__/test_games_prompts.cpython-312-pytest-7.4.3.pycAdded
tests/__pycache__/test_scraper_service.cpython-312-pytest-7.4.3.pycAdded
tests/__pycache__/test_web_extractor.cpython-312-pytest-7.4.3.pycAdded
tests/test_api.py+9-4
tests/test_auth_ownership.pyAdded+85
tests/test_community.pyAdded+74
tests/test_dynamics.pyAdded+64
tests/test_games_prompts.pyAdded+91
tests/test_scraper_service.pyAdded+16
tests/test_web_extractor.pyAdded+24