Spaces:
Running
Running
deploy from github actions
Browse files- app/main.py +42 -3
- app/routers/admin.py +14 -0
- app/routers/auth.py +17 -1
- app/schemas/user.py +3 -0
- app/utils/imgbb.py +13 -2
app/main.py
CHANGED
|
@@ -15,12 +15,45 @@ import app.models.process # Asegura que las tablas de tareas se registren en Ba
|
|
| 15 |
import app.models.midi # Registrar modelos de partituras/MIDI
|
| 16 |
import os
|
| 17 |
|
| 18 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from app.websocket_manager import manager
|
| 20 |
from app.websocket import ws_manager
|
| 21 |
|
| 22 |
app = FastAPI()
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
@app.on_event("startup")
|
| 25 |
async def startup_event():
|
| 26 |
import asyncio
|
|
@@ -30,7 +63,10 @@ async def startup_event():
|
|
| 30 |
print("[WebSocket] Event loop registered in connection managers.")
|
| 31 |
|
| 32 |
@app.websocket("/ws/admin")
|
| 33 |
-
async def websocket_admin_endpoint(websocket: WebSocket):
|
|
|
|
|
|
|
|
|
|
| 34 |
await ws_manager.connect(websocket)
|
| 35 |
try:
|
| 36 |
while True:
|
|
@@ -40,7 +76,10 @@ async def websocket_admin_endpoint(websocket: WebSocket):
|
|
| 40 |
ws_manager.disconnect(websocket)
|
| 41 |
|
| 42 |
@app.websocket("/ws/{user_id}")
|
| 43 |
-
async def websocket_endpoint(websocket: WebSocket, user_id: int):
|
|
|
|
|
|
|
|
|
|
| 44 |
await manager.connect(user_id, websocket)
|
| 45 |
try:
|
| 46 |
while True:
|
|
|
|
| 15 |
import app.models.midi # Registrar modelos de partituras/MIDI
|
| 16 |
import os
|
| 17 |
|
| 18 |
+
from typing import Optional
|
| 19 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query, status
|
| 20 |
+
from app.database import SessionLocal
|
| 21 |
+
from app.routers.auth import get_current_user
|
| 22 |
+
from app.routers.admin import get_current_admin
|
| 23 |
from app.websocket_manager import manager
|
| 24 |
from app.websocket import ws_manager
|
| 25 |
|
| 26 |
app = FastAPI()
|
| 27 |
|
| 28 |
+
# Mientras haya apps viejas instaladas que conectan sin token, se aceptan conexiones
|
| 29 |
+
# sin token. Con WS_REQUIRE_TOKEN=true el token pasa a ser obligatorio.
|
| 30 |
+
# Un token inválido o de otro usuario se rechaza siempre.
|
| 31 |
+
WS_REQUIRE_TOKEN = os.getenv("WS_REQUIRE_TOKEN", "false").lower() == "true"
|
| 32 |
+
|
| 33 |
+
async def _ws_user_allowed(token: Optional[str], user_id: int) -> bool:
|
| 34 |
+
if not token:
|
| 35 |
+
return not WS_REQUIRE_TOKEN
|
| 36 |
+
db = SessionLocal()
|
| 37 |
+
try:
|
| 38 |
+
user = await get_current_user(token=token, db=db)
|
| 39 |
+
return user.id == user_id
|
| 40 |
+
except Exception:
|
| 41 |
+
return False
|
| 42 |
+
finally:
|
| 43 |
+
db.close()
|
| 44 |
+
|
| 45 |
+
def _ws_admin_allowed(token: Optional[str]) -> bool:
|
| 46 |
+
if not token:
|
| 47 |
+
return not WS_REQUIRE_TOKEN
|
| 48 |
+
db = SessionLocal()
|
| 49 |
+
try:
|
| 50 |
+
get_current_admin(token=token, db=db)
|
| 51 |
+
return True
|
| 52 |
+
except Exception:
|
| 53 |
+
return False
|
| 54 |
+
finally:
|
| 55 |
+
db.close()
|
| 56 |
+
|
| 57 |
@app.on_event("startup")
|
| 58 |
async def startup_event():
|
| 59 |
import asyncio
|
|
|
|
| 63 |
print("[WebSocket] Event loop registered in connection managers.")
|
| 64 |
|
| 65 |
@app.websocket("/ws/admin")
|
| 66 |
+
async def websocket_admin_endpoint(websocket: WebSocket, token: Optional[str] = Query(None)):
|
| 67 |
+
if not _ws_admin_allowed(token):
|
| 68 |
+
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
| 69 |
+
return
|
| 70 |
await ws_manager.connect(websocket)
|
| 71 |
try:
|
| 72 |
while True:
|
|
|
|
| 76 |
ws_manager.disconnect(websocket)
|
| 77 |
|
| 78 |
@app.websocket("/ws/{user_id}")
|
| 79 |
+
async def websocket_endpoint(websocket: WebSocket, user_id: int, token: Optional[str] = Query(None)):
|
| 80 |
+
if not await _ws_user_allowed(token, user_id):
|
| 81 |
+
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
|
| 82 |
+
return
|
| 83 |
await manager.connect(user_id, websocket)
|
| 84 |
try:
|
| 85 |
while True:
|
app/routers/admin.py
CHANGED
|
@@ -10,6 +10,8 @@ from app.models.lyrics import Group, Lyric, Repertorio
|
|
| 10 |
from app.models.forum import ForumThread, ForumReply
|
| 11 |
from app.routers.auth import SECRET_KEY, ALGORITHM, verify_password, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES, get_password_hash
|
| 12 |
from app.utils.notifications import create_admin_notification
|
|
|
|
|
|
|
| 13 |
from pydantic import BaseModel
|
| 14 |
from typing import List, Optional
|
| 15 |
from datetime import datetime, timedelta
|
|
@@ -806,6 +808,18 @@ def update_admin_avatar(admin_id: int, data: AdminAvatarUpdate, db: Session = De
|
|
| 806 |
return {"avatar_url": admin.avatar_url}
|
| 807 |
|
| 808 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 809 |
@router.delete("/users/{user_id}")
|
| 810 |
def delete_user(user_id: int, db: Session = Depends(get_db), current_admin: AdminUser = Depends(get_current_admin)):
|
| 811 |
if not current_admin.perm_users:
|
|
|
|
| 10 |
from app.models.forum import ForumThread, ForumReply
|
| 11 |
from app.routers.auth import SECRET_KEY, ALGORITHM, verify_password, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES, get_password_hash
|
| 12 |
from app.utils.notifications import create_admin_notification
|
| 13 |
+
from app.utils.imgbb import upload_image_with_server_key, MAX_IMAGE_BASE64_CHARS
|
| 14 |
+
from app.schemas.user import ImageUpload
|
| 15 |
from pydantic import BaseModel
|
| 16 |
from typing import List, Optional
|
| 17 |
from datetime import datetime, timedelta
|
|
|
|
| 808 |
return {"avatar_url": admin.avatar_url}
|
| 809 |
|
| 810 |
|
| 811 |
+
@router.post("/upload-image")
|
| 812 |
+
def upload_admin_image(data: ImageUpload, current_admin: AdminUser = Depends(get_current_admin)):
|
| 813 |
+
"""Sube una imagen a ImgBB con la clave del servidor y devuelve su URL."""
|
| 814 |
+
if len(data.image_base64) > MAX_IMAGE_BASE64_CHARS:
|
| 815 |
+
raise HTTPException(status_code=413, detail="La imagen es demasiado grande (máximo 32 MB).")
|
| 816 |
+
try:
|
| 817 |
+
return {"url": upload_image_with_server_key(data.image_base64)}
|
| 818 |
+
except ValueError as e:
|
| 819 |
+
print(f"Error subiendo imagen del admin {current_admin.id}: {e}")
|
| 820 |
+
raise HTTPException(status_code=502, detail="No se pudo subir la imagen. Intenta de nuevo.")
|
| 821 |
+
|
| 822 |
+
|
| 823 |
@router.delete("/users/{user_id}")
|
| 824 |
def delete_user(user_id: int, db: Session = Depends(get_db), current_admin: AdminUser = Depends(get_current_admin)):
|
| 825 |
if not current_admin.perm_users:
|
app/routers/auth.py
CHANGED
|
@@ -6,7 +6,8 @@ from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
from app.database import get_db
|
| 8 |
from app.models.user import User, Device, CreditTransaction
|
| 9 |
-
from app.schemas.user import UserCreate, UserOut, Token, DeviceRegister, ForgotPasswordRequest, ResetPasswordRequest, ChangePasswordRequest, AvatarUpdate, UsernameUpdate
|
|
|
|
| 10 |
from passlib.context import CryptContext
|
| 11 |
from jose import JWTError, jwt
|
| 12 |
import os
|
|
@@ -592,6 +593,21 @@ def update_user_avatar(
|
|
| 592 |
return {"avatar_url": current_user.avatar_url}
|
| 593 |
|
| 594 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
@router.put("/users/me/username")
|
| 596 |
def update_username(
|
| 597 |
data: UsernameUpdate,
|
|
|
|
| 6 |
from sqlalchemy.orm import Session
|
| 7 |
from app.database import get_db
|
| 8 |
from app.models.user import User, Device, CreditTransaction
|
| 9 |
+
from app.schemas.user import UserCreate, UserOut, Token, DeviceRegister, ForgotPasswordRequest, ResetPasswordRequest, ChangePasswordRequest, AvatarUpdate, UsernameUpdate, ImageUpload
|
| 10 |
+
from app.utils.imgbb import upload_image_with_server_key, MAX_IMAGE_BASE64_CHARS
|
| 11 |
from passlib.context import CryptContext
|
| 12 |
from jose import JWTError, jwt
|
| 13 |
import os
|
|
|
|
| 593 |
return {"avatar_url": current_user.avatar_url}
|
| 594 |
|
| 595 |
|
| 596 |
+
@router.post("/users/me/upload-image")
|
| 597 |
+
def upload_user_image(
|
| 598 |
+
data: ImageUpload,
|
| 599 |
+
current_user: User = Depends(get_current_user)
|
| 600 |
+
):
|
| 601 |
+
"""Sube una imagen a ImgBB con la clave del servidor y devuelve su URL."""
|
| 602 |
+
if len(data.image_base64) > MAX_IMAGE_BASE64_CHARS:
|
| 603 |
+
raise HTTPException(status_code=413, detail="La imagen es demasiado grande (máximo 32 MB).")
|
| 604 |
+
try:
|
| 605 |
+
return {"url": upload_image_with_server_key(data.image_base64)}
|
| 606 |
+
except ValueError as e:
|
| 607 |
+
logger.warning(f"Error subiendo imagen del usuario {current_user.id}: {e}")
|
| 608 |
+
raise HTTPException(status_code=502, detail="No se pudo subir la imagen. Intenta de nuevo.")
|
| 609 |
+
|
| 610 |
+
|
| 611 |
@router.put("/users/me/username")
|
| 612 |
def update_username(
|
| 613 |
data: UsernameUpdate,
|
app/schemas/user.py
CHANGED
|
@@ -25,6 +25,9 @@ class UserOut(UserBase):
|
|
| 25 |
class AvatarUpdate(BaseModel):
|
| 26 |
avatar_url: str
|
| 27 |
|
|
|
|
|
|
|
|
|
|
| 28 |
class UsernameUpdate(BaseModel):
|
| 29 |
username: str
|
| 30 |
|
|
|
|
| 25 |
class AvatarUpdate(BaseModel):
|
| 26 |
avatar_url: str
|
| 27 |
|
| 28 |
+
class ImageUpload(BaseModel):
|
| 29 |
+
image_base64: str
|
| 30 |
+
|
| 31 |
class UsernameUpdate(BaseModel):
|
| 32 |
username: str
|
| 33 |
|
app/utils/imgbb.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import requests
|
| 2 |
import logging
|
| 3 |
import base64
|
|
@@ -13,10 +14,11 @@ IMGBB_UPLOAD_URL = "https://api.imgbb.com/1/upload"
|
|
| 13 |
|
| 14 |
_session = requests.Session()
|
| 15 |
|
| 16 |
-
def upload_image_to_imgbb(base64_str: str, api_key: str = None) -> str:
|
| 17 |
"""
|
| 18 |
Subir una imagen en formato base64 a ImgBB usando la clave de la iglesia y retornar la URL.
|
| 19 |
Si ya es una URL válida, se retorna directamente.
|
|
|
|
| 20 |
"""
|
| 21 |
if not base64_str:
|
| 22 |
return base64_str
|
|
@@ -34,7 +36,7 @@ def upload_image_to_imgbb(base64_str: str, api_key: str = None) -> str:
|
|
| 34 |
clean_base64 = base64_str.split(",", 1)[1]
|
| 35 |
|
| 36 |
# Si PIL está disponible, redimensionar/comprimir antes de subir a ImgBB
|
| 37 |
-
if Image:
|
| 38 |
try:
|
| 39 |
img_data = base64.b64decode(clean_base64)
|
| 40 |
img = Image.open(io.BytesIO(img_data))
|
|
@@ -75,6 +77,15 @@ def upload_image_to_imgbb(base64_str: str, api_key: str = None) -> str:
|
|
| 75 |
logger.error(f"Excepción subiendo a ImgBB: {e}")
|
| 76 |
raise ValueError("Ocurrió un error de conexión al subir la imagen.")
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
def validate_imgbb_key(api_key: str) -> bool:
|
| 79 |
"""
|
| 80 |
Valida una clave de ImgBB subiendo un pixel PNG 1x1 estándar.
|
|
|
|
| 1 |
+
import os
|
| 2 |
import requests
|
| 3 |
import logging
|
| 4 |
import base64
|
|
|
|
| 14 |
|
| 15 |
_session = requests.Session()
|
| 16 |
|
| 17 |
+
def upload_image_to_imgbb(base64_str: str, api_key: str = None, compress: bool = True) -> str:
|
| 18 |
"""
|
| 19 |
Subir una imagen en formato base64 a ImgBB usando la clave de la iglesia y retornar la URL.
|
| 20 |
Si ya es una URL válida, se retorna directamente.
|
| 21 |
+
Con compress=False se sube la imagen original (sin redimensionar ni pasar a JPEG).
|
| 22 |
"""
|
| 23 |
if not base64_str:
|
| 24 |
return base64_str
|
|
|
|
| 36 |
clean_base64 = base64_str.split(",", 1)[1]
|
| 37 |
|
| 38 |
# Si PIL está disponible, redimensionar/comprimir antes de subir a ImgBB
|
| 39 |
+
if Image and compress:
|
| 40 |
try:
|
| 41 |
img_data = base64.b64decode(clean_base64)
|
| 42 |
img = Image.open(io.BytesIO(img_data))
|
|
|
|
| 77 |
logger.error(f"Excepción subiendo a ImgBB: {e}")
|
| 78 |
raise ValueError("Ocurrió un error de conexión al subir la imagen.")
|
| 79 |
|
| 80 |
+
MAX_IMAGE_BASE64_CHARS = 43 * 1024 * 1024 # ~32 MB de imagen, el límite de ImgBB
|
| 81 |
+
|
| 82 |
+
def upload_image_with_server_key(base64_str: str) -> str:
|
| 83 |
+
"""
|
| 84 |
+
Sube la imagen original con la clave global de Melodix (IMGBB_API_KEY), para que
|
| 85 |
+
las apps no tengan que llevar la clave dentro.
|
| 86 |
+
"""
|
| 87 |
+
return upload_image_to_imgbb(base64_str, api_key=os.getenv("IMGBB_API_KEY"), compress=False)
|
| 88 |
+
|
| 89 |
def validate_imgbb_key(api_key: str) -> bool:
|
| 90 |
"""
|
| 91 |
Valida una clave de ImgBB subiendo un pixel PNG 1x1 estándar.
|