Spaces:
Running
Running
Download app/routers/forums.py from Isaac105/melodix-api: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/routers/forums.py
- Command line
-
hf download hf://spaces/Isaac105/melodix-api/app/routers/forums.py
-
curl -L -o forums.py https://huggingface.co/spaces/Isaac105/melodix-api/resolve/main/app/routers/forums.py
17.2 kB
| """ | |
| Router de Foros Comunitarios de Melodix. | |
| Endpoints públicos (sin auth): listar hilos, ver detalle de hilo. | |
| Endpoints protegidos (con auth): crear hilo, responder, eliminar propio. | |
| """ | |
| import logging | |
| from typing import Optional | |
| from datetime import datetime | |
| import time | |
| from collections import defaultdict | |
| from fastapi import APIRouter, Depends, HTTPException, Query, status | |
| from sqlalchemy.orm import Session | |
| from sqlalchemy import func, or_ | |
| from pydantic import BaseModel | |
| from app.database import get_db | |
| from app.models.forum import ForumThread, ForumReply | |
| from app.models.user import User | |
| from app.routers.auth import get_current_user, oauth2_scheme | |
| from app.utils.notifications import create_admin_notification | |
| logger = logging.getLogger(__name__) | |
| router = APIRouter(prefix="/forums", tags=["forums"]) | |
| # ========================================== | |
| # SCHEMAS | |
| # ========================================== | |
| class ThreadCreate(BaseModel): | |
| title: str | |
| body: str | |
| class ReplyCreate(BaseModel): | |
| body: str | |
| class UserBrief(BaseModel): | |
| id: int | |
| username: str | |
| avatar_url: Optional[str] = None | |
| class Config: | |
| from_attributes = True | |
| class ReplyOut(BaseModel): | |
| id: int | |
| thread_id: int | |
| body: str | |
| created_at: datetime | |
| user: UserBrief | |
| class Config: | |
| from_attributes = True | |
| class ThreadSummary(BaseModel): | |
| id: int | |
| title: str | |
| body: str | |
| created_at: datetime | |
| updated_at: Optional[datetime] = None | |
| reply_count: int | |
| user: UserBrief | |
| replies: Optional[list[ReplyOut]] = [] | |
| class ThreadDetail(BaseModel): | |
| id: int | |
| title: str | |
| body: str | |
| created_at: datetime | |
| updated_at: Optional[datetime] = None | |
| user: UserBrief | |
| replies: list[ReplyOut] | |
| # ========================================== | |
| # HELPER: Optional auth (devuelve None si no hay token) | |
| # ========================================== | |
| def get_optional_user( | |
| db: Session = Depends(get_db), | |
| token: Optional[str] = Depends(oauth2_scheme) | |
| ): | |
| """Intenta extraer el usuario del token, pero no falla si no hay token.""" | |
| if not token: | |
| return None | |
| try: | |
| return get_current_user(token=token, db=db) | |
| except Exception: | |
| return None | |
| class RateLimiter: | |
| def __init__(self, requests: int, window_secs: int): | |
| self.requests = requests | |
| self.window_secs = window_secs | |
| self.history = defaultdict(list) | |
| def __call__(self, current_user: User = Depends(get_current_user)): | |
| key = current_user.id | |
| now = time.time() | |
| # Filtrar timestamps que estén fuera de la ventana de tiempo | |
| self.history[key] = [t for t in self.history[key] if now - t < self.window_secs] | |
| if len(self.history[key]) >= self.requests: | |
| raise HTTPException( | |
| status_code=status.HTTP_429_TOO_MANY_REQUESTS, | |
| detail="Has excedido el límite de publicaciones. Por favor, espera un momento." | |
| ) | |
| self.history[key].append(now) | |
| # Limitadores: máximo 2 hilos por minuto y 5 respuestas por minuto | |
| thread_limiter = RateLimiter(requests=2, window_secs=60) | |
| reply_limiter = RateLimiter(requests=5, window_secs=60) | |
| # ========================================== | |
| # PUBLIC ENDPOINTS (no auth required) | |
| # ========================================== | |
| def list_threads( | |
| q: Optional[str] = Query(None, description="Buscar por título o contenido"), | |
| skip: int = Query(0, ge=0), | |
| limit: int = Query(30, ge=1, le=100), | |
| db: Session = Depends(get_db) | |
| ): | |
| """ | |
| Lista todos los hilos del foro (paginados). | |
| Búsqueda opcional por ?q=texto que filtra por título y cuerpo. | |
| """ | |
| query = db.query(ForumThread).filter(ForumThread.is_deleted == False) | |
| if q and q.strip(): | |
| search_term = f"%{q.strip()}%" | |
| query = query.filter( | |
| or_( | |
| ForumThread.title.ilike(search_term), | |
| ForumThread.body.ilike(search_term) | |
| ) | |
| ) | |
| # Ordenar por más reciente primero | |
| threads = query.order_by(ForumThread.created_at.desc()).offset(skip).limit(limit).all() | |
| if not threads: | |
| return [] | |
| thread_ids = [t.id for t in threads] | |
| # 1. Obtener conteos de respuestas de todos los hilos en una consulta agrupada (SQL group_by) | |
| counts_query = db.query( | |
| ForumReply.thread_id, | |
| func.count(ForumReply.id).label("count") | |
| ).filter( | |
| ForumReply.thread_id.in_(thread_ids), | |
| ForumReply.is_deleted == False | |
| ).group_by(ForumReply.thread_id).all() | |
| counts_map = {row[0]: row[1] for row in counts_query} | |
| # 2. Obtener las respuestas activas de todos los hilos en una sola consulta | |
| all_replies = db.query(ForumReply).filter( | |
| ForumReply.thread_id.in_(thread_ids), | |
| ForumReply.is_deleted == False | |
| ).order_by(ForumReply.created_at.asc()).all() | |
| # Agrupar las primeras 3 respuestas de cada hilo en memoria (Python) | |
| replies_map = defaultdict(list) | |
| for r in all_replies: | |
| if len(replies_map[r.thread_id]) < 3: | |
| replies_map[r.thread_id].append(r) | |
| result = [] | |
| for t in threads: | |
| reply_count = counts_map.get(t.id, 0) | |
| thread_replies = replies_map[t.id] | |
| replies_out = [ | |
| ReplyOut( | |
| id=r.id, | |
| thread_id=r.thread_id, | |
| body=r.body, | |
| created_at=r.created_at, | |
| user=UserBrief( | |
| id=r.user.id, | |
| username=r.user.username, | |
| avatar_url=r.user.avatar_url | |
| ) | |
| ) | |
| for r in thread_replies | |
| ] | |
| result.append(ThreadSummary( | |
| id=t.id, | |
| title=t.title, | |
| body=t.body, | |
| created_at=t.created_at, | |
| updated_at=t.updated_at, | |
| reply_count=reply_count, | |
| user=UserBrief( | |
| id=t.user.id, | |
| username=t.user.username, | |
| avatar_url=t.user.avatar_url | |
| ), | |
| replies=replies_out | |
| )) | |
| return result | |
| def get_thread(thread_id: int, db: Session = Depends(get_db)): | |
| """ | |
| Obtiene el detalle de un hilo con todas sus respuestas. | |
| """ | |
| thread = db.query(ForumThread).filter( | |
| ForumThread.id == thread_id, | |
| ForumThread.is_deleted == False | |
| ).first() | |
| if not thread: | |
| raise HTTPException(status_code=404, detail="Hilo no encontrado") | |
| replies = db.query(ForumReply).filter( | |
| ForumReply.thread_id == thread_id, | |
| ForumReply.is_deleted == False | |
| ).order_by(ForumReply.created_at.asc()).all() | |
| return ThreadDetail( | |
| id=thread.id, | |
| title=thread.title, | |
| body=thread.body, | |
| created_at=thread.created_at, | |
| updated_at=thread.updated_at, | |
| user=UserBrief( | |
| id=thread.user.id, | |
| username=thread.user.username, | |
| avatar_url=thread.user.avatar_url | |
| ), | |
| replies=[ | |
| ReplyOut( | |
| id=r.id, | |
| thread_id=r.thread_id, | |
| body=r.body, | |
| created_at=r.created_at, | |
| user=UserBrief( | |
| id=r.user.id, | |
| username=r.user.username, | |
| avatar_url=r.user.avatar_url | |
| ) | |
| ) | |
| for r in replies | |
| ] | |
| ) | |
| # ========================================== | |
| # PROTECTED ENDPOINTS (auth required) | |
| # ========================================== | |
| def create_thread( | |
| data: ThreadCreate, | |
| db: Session = Depends(get_db), | |
| current_user: User = Depends(get_current_user), | |
| _rate: None = Depends(thread_limiter) | |
| ): | |
| """Crea un nuevo hilo en el foro. Requiere autenticación.""" | |
| if current_user.is_forum_banned: | |
| raise HTTPException(status_code=403, detail="Tu cuenta ha sido suspendida del foro por un administrador.") | |
| if not data.title.strip(): | |
| raise HTTPException(status_code=400, detail="El título es obligatorio") | |
| if len(data.title.strip()) > 100: | |
| raise HTTPException(status_code=400, detail="El título no puede superar los 100 caracteres") | |
| if not data.body.strip(): | |
| raise HTTPException(status_code=400, detail="El contenido es obligatorio") | |
| if len(data.body.strip()) > 3000: | |
| raise HTTPException(status_code=400, detail="El contenido no puede superar los 3000 caracteres") | |
| thread = ForumThread( | |
| user_id=current_user.id, | |
| title=data.title.strip(), | |
| body=data.body.strip() | |
| ) | |
| db.add(thread) | |
| db.commit() | |
| db.refresh(thread) | |
| logger.info(f"[Foro] Nuevo hilo #{thread.id} por {current_user.username}: {thread.title}") | |
| # Registrar en el log de administración | |
| try: | |
| create_admin_notification( | |
| db, | |
| title="Nuevo hilo en el foro", | |
| message=f"El usuario '{current_user.username}' publicó un nuevo hilo: '{thread.title}'.", | |
| category="forum" | |
| ) | |
| except Exception: | |
| pass # No interrumpir la creación si falla la notificación | |
| return ThreadDetail( | |
| id=thread.id, | |
| title=thread.title, | |
| body=thread.body, | |
| created_at=thread.created_at, | |
| updated_at=thread.updated_at, | |
| user=UserBrief( | |
| id=current_user.id, | |
| username=current_user.username, | |
| avatar_url=current_user.avatar_url | |
| ), | |
| replies=[] | |
| ) | |
| def delete_thread( | |
| thread_id: int, | |
| db: Session = Depends(get_db), | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """Elimina (soft-delete) un hilo. Solo el autor puede eliminarlo.""" | |
| thread = db.query(ForumThread).filter( | |
| ForumThread.id == thread_id, | |
| ForumThread.is_deleted == False | |
| ).first() | |
| if not thread: | |
| raise HTTPException(status_code=404, detail="Hilo no encontrado") | |
| if thread.user_id != current_user.id: | |
| raise HTTPException(status_code=403, detail="Solo el autor puede eliminar este hilo") | |
| thread.is_deleted = True | |
| db.commit() | |
| logger.info(f"[Foro] Hilo #{thread_id} eliminado (soft) por {current_user.username}") | |
| def create_reply( | |
| thread_id: int, | |
| data: ReplyCreate, | |
| db: Session = Depends(get_db), | |
| current_user: User = Depends(get_current_user), | |
| _rate: None = Depends(reply_limiter) | |
| ): | |
| """Responde a un hilo del foro. Requiere autenticación.""" | |
| if current_user.is_forum_banned: | |
| raise HTTPException(status_code=403, detail="Tu cuenta ha sido suspendida del foro por un administrador.") | |
| thread = db.query(ForumThread).filter( | |
| ForumThread.id == thread_id, | |
| ForumThread.is_deleted == False | |
| ).first() | |
| if not thread: | |
| raise HTTPException(status_code=404, detail="Hilo no encontrado") | |
| if not data.body.strip(): | |
| raise HTTPException(status_code=400, detail="La respuesta no puede estar vacía") | |
| if len(data.body.strip()) > 3000: | |
| raise HTTPException(status_code=400, detail="La respuesta no puede superar los 3000 caracteres") | |
| reply = ForumReply( | |
| thread_id=thread_id, | |
| user_id=current_user.id, | |
| body=data.body.strip() | |
| ) | |
| db.add(reply) | |
| # Actualizar el updated_at del hilo para que suba en relevancia | |
| thread.updated_at = datetime.utcnow() | |
| db.commit() | |
| db.refresh(reply) | |
| logger.info(f"[Foro] Nueva respuesta #{reply.id} en hilo #{thread_id} por {current_user.username}") | |
| return ReplyOut( | |
| id=reply.id, | |
| thread_id=reply.thread_id, | |
| body=reply.body, | |
| created_at=reply.created_at, | |
| user=UserBrief( | |
| id=current_user.id, | |
| username=current_user.username, | |
| avatar_url=current_user.avatar_url | |
| ) | |
| ) | |
| def delete_reply( | |
| reply_id: int, | |
| db: Session = Depends(get_db), | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """Elimina (soft-delete) una respuesta. Solo el autor puede eliminarla.""" | |
| reply = db.query(ForumReply).filter( | |
| ForumReply.id == reply_id, | |
| ForumReply.is_deleted == False | |
| ).first() | |
| if not reply: | |
| raise HTTPException(status_code=404, detail="Respuesta no encontrada") | |
| if reply.user_id != current_user.id: | |
| raise HTTPException(status_code=403, detail="Solo el autor puede eliminar esta respuesta") | |
| reply.is_deleted = True | |
| db.commit() | |
| logger.info(f"[Foro] Respuesta #{reply_id} eliminada (soft) por {current_user.username}") | |
| def update_thread( | |
| thread_id: int, | |
| data: ThreadCreate, | |
| db: Session = Depends(get_db), | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """Edita un hilo. Solo el autor puede editarlo dentro de los primeros 10 minutos.""" | |
| thread = db.query(ForumThread).filter( | |
| ForumThread.id == thread_id, | |
| ForumThread.is_deleted == False | |
| ).first() | |
| if not thread: | |
| raise HTTPException(status_code=404, detail="Hilo no encontrado") | |
| if thread.user_id != current_user.id: | |
| raise HTTPException(status_code=403, detail="Solo el autor puede editar este hilo") | |
| # Validar límite de 10 minutos | |
| elapsed_minutes = (datetime.utcnow() - thread.created_at).total_seconds() / 60.0 | |
| if elapsed_minutes > 10.0: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="El tiempo límite de 10 minutos para editar este hilo ha expirado." | |
| ) | |
| if not data.title.strip(): | |
| raise HTTPException(status_code=400, detail="El título es obligatorio") | |
| if len(data.title.strip()) > 100: | |
| raise HTTPException(status_code=400, detail="El título no puede superar los 100 caracteres") | |
| if not data.body.strip(): | |
| raise HTTPException(status_code=400, detail="El contenido es obligatorio") | |
| if len(data.body.strip()) > 3000: | |
| raise HTTPException(status_code=400, detail="El contenido no puede superar los 3000 caracteres") | |
| thread.title = data.title.strip() | |
| thread.body = data.body.strip() | |
| thread.updated_at = datetime.utcnow() | |
| db.commit() | |
| db.refresh(thread) | |
| logger.info(f"[Foro] Hilo #{thread_id} editado por {current_user.username}") | |
| replies = db.query(ForumReply).filter( | |
| ForumReply.thread_id == thread_id, | |
| ForumReply.is_deleted == False | |
| ).order_by(ForumReply.created_at.asc()).all() | |
| return ThreadDetail( | |
| id=thread.id, | |
| title=thread.title, | |
| body=thread.body, | |
| created_at=thread.created_at, | |
| updated_at=thread.updated_at, | |
| user=UserBrief( | |
| id=thread.user.id, | |
| username=thread.user.username, | |
| avatar_url=thread.user.avatar_url | |
| ), | |
| replies=[ | |
| ReplyOut( | |
| id=r.id, | |
| thread_id=r.thread_id, | |
| body=r.body, | |
| created_at=r.created_at, | |
| user=UserBrief( | |
| id=r.user.id, | |
| username=r.user.username, | |
| avatar_url=r.user.avatar_url | |
| ) | |
| ) | |
| for r in replies | |
| ] | |
| ) | |
| def update_reply( | |
| reply_id: int, | |
| data: ReplyCreate, | |
| db: Session = Depends(get_db), | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """Edita una respuesta. Solo el autor puede editarla dentro de los primeros 10 minutos.""" | |
| reply = db.query(ForumReply).filter( | |
| ForumReply.id == reply_id, | |
| ForumReply.is_deleted == False | |
| ).first() | |
| if not reply: | |
| raise HTTPException(status_code=404, detail="Respuesta no encontrada") | |
| if reply.user_id != current_user.id: | |
| raise HTTPException(status_code=403, detail="Solo el autor puede editar esta respuesta") | |
| # Validar límite de 10 minutos | |
| elapsed_minutes = (datetime.utcnow() - reply.created_at).total_seconds() / 60.0 | |
| if elapsed_minutes > 10.0: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="El tiempo límite de 10 minutos para editar esta respuesta ha expirado." | |
| ) | |
| if not data.body.strip(): | |
| raise HTTPException(status_code=400, detail="La respuesta no puede estar vacía") | |
| if len(data.body.strip()) > 3000: | |
| raise HTTPException(status_code=400, detail="La respuesta no puede superar los 3000 caracteres") | |
| reply.body = data.body.strip() | |
| db.commit() | |
| db.refresh(reply) | |
| logger.info(f"[Foro] Respuesta #{reply_id} editada por {current_user.username}") | |
| return ReplyOut( | |
| id=reply.id, | |
| thread_id=reply.thread_id, | |
| body=reply.body, | |
| created_at=reply.created_at, | |
| user=UserBrief( | |
| id=reply.user.id, | |
| username=reply.user.username, | |
| avatar_url=reply.user.avatar_url | |
| ) | |
| ) | |