Удаление старых аватарок

This commit is contained in:
Artur 2026-05-03 17:51:19 +05:00
parent 981d322e1d
commit cf8c4fa0d6
1 changed files with 29 additions and 0 deletions

View File

@ -1,9 +1,12 @@
import os
from fastapi import Depends, APIRouter, HTTPException, Depends, Request from fastapi import Depends, APIRouter, HTTPException, Depends, Request
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.db import models from app.db import models
from app.core.security import get_current_user from app.core.security import get_current_user
from app.api import schemas from app.api import schemas
from app.core.config import config
from sqlalchemy import or_, and_, exists from sqlalchemy import or_, and_, exists
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from app.websocket import connection_manager from app.websocket import connection_manager
@ -19,6 +22,28 @@ def get_db():
db.close() db.close()
def _delete_old_avatar_file(file_id: str, db: Session):
upload_path = os.path.join('uploads', f"{file_id}.enc")
if os.path.exists(upload_path):
try:
os.remove(upload_path)
except OSError:
pass
cloud_item = db.query(models.CloudMediaItem).filter(
models.CloudMediaItem.file_id == file_id,
).all()
for item in cloud_item:
cloud_path = os.path.join(config.CLOUD_MEDIA_CACHE_FOLDER, item.local_filename)
if os.path.exists(cloud_path):
try:
os.remove(cloud_path)
except OSError:
pass
db.delete(item)
db.commit()
usersRouter = APIRouter( usersRouter = APIRouter(
prefix="/users", prefix="/users",
tags=[], tags=[],
@ -327,6 +352,10 @@ async def update_user_avatar(
user_to_update = db.merge(current_user) user_to_update = db.merge(current_user)
avatar_file_id = data.get("avatar_file_id") avatar_file_id = data.get("avatar_file_id")
if avatar_file_id: if avatar_file_id:
old_avatar_file_id = user_to_update.avatar_file_id
if old_avatar_file_id and old_avatar_file_id != avatar_file_id:
_delete_old_avatar_file(old_avatar_file_id, db)
user_to_update.avatar_file_id = avatar_file_id user_to_update.avatar_file_id = avatar_file_id
db.commit() db.commit()
print( print(