This commit is contained in:
Iliyan Angelov
2025-12-02 22:16:57 +02:00
parent 2d770dd27b
commit e32527ae8c
3 changed files with 432 additions and 43 deletions

View File

@@ -595,14 +595,20 @@ async def delete_room_images(id: int, image_url: str=Query(..., description='Ima
room = db.query(Room).filter(Room.id == id).first()
if not room:
raise HTTPException(status_code=404, detail='Room not found')
# For external URLs, keep the full URL for matching
# For local files, normalize to path
is_external_url = image_url.startswith('http://') or image_url.startswith('https://')
normalized_url = image_url
if image_url.startswith('http://') or image_url.startswith('https://'):
from urllib.parse import urlparse
parsed = urlparse(image_url)
normalized_url = parsed.path
if not normalized_url.startswith('/'):
normalized_url = f'/{normalized_url}'
filename = Path(normalized_url).name
filename = None
if is_external_url:
# For external URLs, use the full URL as-is for matching
normalized_url = image_url
else:
# For local files, normalize the path
if not normalized_url.startswith('/'):
normalized_url = f'/{normalized_url}'
filename = Path(normalized_url).name
# Handle existing_images - it might be a list, a JSON string, or None
existing_images = room.images or []
@@ -620,13 +626,24 @@ async def delete_room_images(id: int, image_url: str=Query(..., description='Ima
updated_images = []
for img in existing_images:
stored_path = img if img.startswith('/') else f'/{img}'
stored_filename = Path(stored_path).name
if img != normalized_url and stored_path != normalized_url and (stored_filename != filename):
updated_images.append(img)
file_path = Path(__file__).parent.parent.parent / 'uploads' / 'rooms' / filename
if file_path.exists():
file_path.unlink()
# For external URLs, match by full URL (keep images that don't match)
if is_external_url:
# Keep the image if it doesn't match the URL we're deleting
if img != normalized_url:
updated_images.append(img)
else:
# For local files, match by path or filename (keep images that don't match)
stored_path = img if img.startswith('/') else f'/{img}'
stored_filename = Path(stored_path).name if '/' in str(stored_path) else stored_path
# Keep the image if it doesn't match any of the comparison criteria
if img != normalized_url and stored_path != normalized_url and (not filename or stored_filename != filename):
updated_images.append(img)
# Only try to delete the file if it's a local file (filename exists)
if filename:
file_path = Path(__file__).parent.parent.parent / 'uploads' / 'rooms' / filename
if file_path.exists():
file_path.unlink()
room.images = updated_images
db.commit()
return {'status': 'success', 'message': 'Image deleted successfully', 'data': {'images': updated_images}}