Админ: управление медиа партии (добавление/удаление в любой момент)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -2,24 +2,29 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Query, Request, Response, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlmodel import Session
|
||||
|
||||
from app.auth.deps import get_current_admin
|
||||
from app.core import security
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.timeutil import iso_utc
|
||||
from app.db.session import get_session
|
||||
from app.models import User
|
||||
from app.routers.matches import build_match_read
|
||||
from app.routers.matches import attachment_read, build_match_read
|
||||
from app.schemas import api as s
|
||||
from app.services import (
|
||||
achievement_service,
|
||||
admin_service,
|
||||
attachment_service,
|
||||
audit_service,
|
||||
faction_service,
|
||||
match_service,
|
||||
user_service,
|
||||
)
|
||||
|
||||
_ACHIEVEMENT_ICON_MAX_BYTES = 2 * 1024 * 1024 # 2 МБ
|
||||
_ATTACHMENT_MAX_BYTES = 10 * 1024 * 1024 # 10 МБ
|
||||
from app.services.match_service import ParticipantInput
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
@@ -292,6 +297,70 @@ def delete_match(
|
||||
return s.OkResponse()
|
||||
|
||||
|
||||
# ─── Медиа партии (админ правит в любой момент) ───────────────────────────────
|
||||
|
||||
@router.get("/matches/{match_id}/attachments", response_model=list[s.AttachmentRead])
|
||||
def admin_list_attachments(
|
||||
match_id: int,
|
||||
session: Session = Depends(get_session),
|
||||
_admin: User = Depends(get_current_admin),
|
||||
) -> list[s.AttachmentRead]:
|
||||
match_service.get_match(session, match_id) # 404 если партии нет
|
||||
return [
|
||||
attachment_read(a, f"/api/admin/matches/{match_id}")
|
||||
for a in attachment_service.list_for_match(session, match_id)
|
||||
]
|
||||
|
||||
|
||||
@router.post("/matches/{match_id}/attachments", response_model=s.AttachmentRead)
|
||||
def admin_add_attachment(
|
||||
match_id: int,
|
||||
file: UploadFile = File(...),
|
||||
session: Session = Depends(get_session),
|
||||
admin: User = Depends(get_current_admin),
|
||||
) -> s.AttachmentRead:
|
||||
match = match_service.get_match(session, match_id)
|
||||
content = file.file.read(_ATTACHMENT_MAX_BYTES + 1)
|
||||
if len(content) > _ATTACHMENT_MAX_BYTES:
|
||||
raise ValidationError("Файл слишком большой (макс. 10 МБ).")
|
||||
ext = user_service.sniff_image_ext(content)
|
||||
if ext is None:
|
||||
raise ValidationError("Поддерживаются только изображения PNG, JPEG или WebP.")
|
||||
att = attachment_service.add_photo(
|
||||
session, match, admin, content, ext, user_service.avatar_media_type(ext)
|
||||
)
|
||||
return attachment_read(att, f"/api/admin/matches/{match_id}")
|
||||
|
||||
|
||||
@router.delete("/matches/{match_id}/attachments/{attachment_id}", response_model=s.OkResponse)
|
||||
def admin_delete_attachment(
|
||||
match_id: int,
|
||||
attachment_id: int,
|
||||
session: Session = Depends(get_session),
|
||||
_admin: User = Depends(get_current_admin),
|
||||
) -> s.OkResponse:
|
||||
match = match_service.get_match(session, match_id)
|
||||
attachment_service.delete(session, match, attachment_id)
|
||||
return s.OkResponse()
|
||||
|
||||
|
||||
@router.get("/matches/{match_id}/attachments/{attachment_id}")
|
||||
def admin_get_attachment(
|
||||
match_id: int,
|
||||
attachment_id: int,
|
||||
session: Session = Depends(get_session),
|
||||
_admin: User = Depends(get_current_admin),
|
||||
) -> FileResponse:
|
||||
match_service.get_match(session, match_id)
|
||||
att = attachment_service.get_for_match(session, match_id, attachment_id)
|
||||
path = attachment_service.file_path(att)
|
||||
if not path.exists():
|
||||
raise NotFoundError("Файл не найден.")
|
||||
return FileResponse(
|
||||
path, media_type=att.mime_type, headers={"Cache-Control": "private, max-age=3600"}
|
||||
)
|
||||
|
||||
|
||||
# ─── Ачивки (определения; выдача игрокам — на будущее) ────────────────────────
|
||||
|
||||
@router.get("/achievements", response_model=list[s.AchievementRead])
|
||||
@@ -343,8 +412,6 @@ def upload_achievement_icon(
|
||||
file: UploadFile = File(...),
|
||||
_admin: User = Depends(get_current_admin),
|
||||
) -> dict:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
content = file.file.read(_ACHIEVEMENT_ICON_MAX_BYTES + 1)
|
||||
if len(content) > _ACHIEVEMENT_ICON_MAX_BYTES:
|
||||
raise ValidationError("Файл слишком большой (макс. 2 МБ).")
|
||||
|
||||
@@ -91,6 +91,45 @@ def test_no_changes_after_finish(client: TestClient, engine, monkeypatch, tmp_pa
|
||||
assert client.get(f"/api/matches/{mid}").json()["attachments"][0]["id"] == aid
|
||||
|
||||
|
||||
def test_admin_manage_attachments_on_finished(
|
||||
client: TestClient, engine, make_admin, monkeypatch, tmp_path
|
||||
):
|
||||
_use_tmp_uploads(monkeypatch, tmp_path)
|
||||
me, gid, p2, mid = _start(client, engine)
|
||||
fin = finish_match(
|
||||
client, mid, [{"user_id": me["id"], "place": 1}, {"user_id": p2, "place": 2}],
|
||||
win_reason="objectives",
|
||||
)
|
||||
assert fin.status_code == 200, fin.text
|
||||
|
||||
make_admin("admin", "secret123")
|
||||
assert client.post(
|
||||
"/api/admin/auth/login",
|
||||
json={"username": "admin", "password": "secret123"},
|
||||
headers=csrf_headers(client),
|
||||
).status_code == 200
|
||||
|
||||
# Админ добавляет медиа к ЗАВЕРШЁННОЙ партии (игроку это запрещено).
|
||||
up = client.post(
|
||||
f"/api/admin/matches/{mid}/attachments",
|
||||
files={"file": ("a.png", PNG, "image/png")},
|
||||
headers=csrf_headers(client),
|
||||
)
|
||||
assert up.status_code == 200, up.text
|
||||
aid = up.json()["id"]
|
||||
assert up.json()["url"] == f"/api/admin/matches/{mid}/attachments/{aid}"
|
||||
|
||||
assert any(a["id"] == aid for a in client.get(f"/api/admin/matches/{mid}/attachments").json())
|
||||
g = client.get(f"/api/admin/matches/{mid}/attachments/{aid}")
|
||||
assert g.status_code == 200 and g.content == PNG
|
||||
|
||||
d = client.delete(
|
||||
f"/api/admin/matches/{mid}/attachments/{aid}", headers=csrf_headers(client)
|
||||
)
|
||||
assert d.status_code == 200, d.text
|
||||
assert client.get(f"/api/admin/matches/{mid}/attachments").json() == []
|
||||
|
||||
|
||||
def test_non_member_cannot_view(client: TestClient, engine, monkeypatch, tmp_path):
|
||||
_use_tmp_uploads(monkeypatch, tmp_path)
|
||||
_me, _gid, _p2, mid = _start(client, engine)
|
||||
|
||||
Reference in New Issue
Block a user