83 lines
3.3 KiB
Python
83 lines
3.3 KiB
Python
from fastapi import HTTPException, UploadFile
|
||
from datetime import datetime
|
||
from app.db.database import users_collection
|
||
from app.core.config import FILES_URL
|
||
|
||
class SkinService:
|
||
async def set_skin(self, username: str, skin_file: UploadFile, skin_model: str = "classic"):
|
||
"""Установка или замена скина через загрузку файла"""
|
||
# Проверяем тип файла
|
||
if not skin_file.content_type.startswith('image/'):
|
||
raise HTTPException(status_code=400, detail="File must be an image")
|
||
|
||
# Проверяем размер файла (максимум 2MB)
|
||
max_size = 2 * 1024 * 1024 # 2MB
|
||
contents = await skin_file.read()
|
||
if len(contents) > max_size:
|
||
raise HTTPException(status_code=400, detail="File too large (max 2MB)")
|
||
|
||
# Удаляем старый скин, если есть
|
||
user = await users_collection.find_one({"username": username})
|
||
if user and user.get("skin_url"):
|
||
from urllib.parse import urlparse
|
||
import os
|
||
old_url = user["skin_url"]
|
||
# Получаем имя файла из url
|
||
old_filename = os.path.basename(urlparse(old_url).path)
|
||
old_path = os.path.join("app/static/skins", old_filename)
|
||
print(f"Trying to delete old skin at: {old_path}")
|
||
if os.path.exists(old_path):
|
||
try:
|
||
os.remove(old_path)
|
||
except Exception:
|
||
pass
|
||
|
||
# Создаем папку для скинов, если ее нет
|
||
from pathlib import Path
|
||
skin_dir = Path("app/static/skins")
|
||
skin_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
# Генерируем имя файла
|
||
skin_filename = f"{username}_{int(datetime.now().timestamp())}.png"
|
||
skin_path = skin_dir / skin_filename
|
||
|
||
# Сохраняем файл
|
||
with open(skin_path, "wb") as f:
|
||
f.write(contents)
|
||
|
||
# Обновляем запись пользователя
|
||
result = await users_collection.update_one(
|
||
{"username": username},
|
||
{"$set": {
|
||
"skin_url": f"{FILES_URL}/skins/{skin_filename}",
|
||
"skin_model": skin_model
|
||
}}
|
||
)
|
||
|
||
if result.modified_count == 0:
|
||
raise HTTPException(status_code=404, detail="User not found")
|
||
return {"status": "success"}
|
||
|
||
async def remove_skin(self, username: str):
|
||
"""Удаление скина"""
|
||
user = await users_collection.find_one({"username": username})
|
||
if not user:
|
||
raise HTTPException(status_code=404, detail="User not found")
|
||
|
||
# Удаляем файл скина, если он существует
|
||
if user.get("skin_url") and user["skin_url"].startswith("/skins/"):
|
||
import os
|
||
try:
|
||
os.remove(f"skins/{user['skin_url'].split('/')[-1]}")
|
||
except:
|
||
pass
|
||
|
||
result = await users_collection.update_one(
|
||
{"username": username},
|
||
{"$unset": {
|
||
"skin_url": "",
|
||
"skin_model": ""
|
||
}}
|
||
)
|
||
return {"status": "success"}
|