Skip to content

Support deletion of removed image in client #104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 30 additions & 16 deletions client/src/ImageUpload/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,23 +81,36 @@ const ImageUpload = ({ onImageUpload, settingsImages }) => {
}
};

const deleteImage = async (filename) => {
const deleteImage = async (filename, isNotFound = false) => {
try {
const response = await axios.delete(`${config.SERVER_URL}/uploads/${filename}`);
showSnackbar(response.data.message, 'success');

// Update the state to remove the deleted image
const updatedImages = images.filter((image) => image.filename !== filename);
setImages(updatedImages);
onImageUpload(updatedImages);
} catch (error) {
if (error?.response?.data) {
showSnackbar(error.response.data.message, 'error');
} else {
showSnackbar(t("error.server_connection"), 'error');
if (isNotFound) {
const updatedImages = images.filter((image) => image.filename !== filename);
setImages(updatedImages);
onImageUpload(updatedImages);
} else {
const response = await axios.delete(`${config.SERVER_URL}/uploads/${filename}`);
showSnackbar(response.data.message, 'success');

// Update the state to remove the deleted image
const updatedImages = images.filter((image) => image.filename !== filename);
setImages(updatedImages);
onImageUpload(updatedImages);
}
} catch (error) {
if (error?.response?.data) {
showSnackbar(error.response.data.message, 'error');
} else {
showSnackbar(t("error.server_connection"), 'error');
}
console.error('Error deleting image:', error);
}
console.error('Error deleting image:', error);
}
};

const handleImageError = (index) => {
const updatedImages = [...images];
updatedImages[index].isNotFound = true;
setImages(updatedImages);
showSnackbar(t("error.image_not_found"), 'error');
};

const handleRemoveImage = (index) => {
Expand All @@ -110,7 +123,7 @@ const ImageUpload = ({ onImageUpload, settingsImages }) => {
}
}
if (imageToRemove && imageToRemove.filename) {
deleteImage(imageToRemove.filename);
deleteImage(imageToRemove.filename, imageToRemove.isNotFound);
} else {
console.error('Error deleting image: imageToRemove or imageToRemove.filename is undefined');
}
Expand Down Expand Up @@ -178,6 +191,7 @@ const ImageUpload = ({ onImageUpload, settingsImages }) => {
<img
src={image.preview || image.src}
alt="preview"
onError={() => handleImageError(index)}
style={{
width: '100px',
height: '100px',
Expand Down
3 changes: 2 additions & 1 deletion client/src/Localization/translation-de-DE.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ const translationDeDE = {
"hide_region": "Region ausblenden",
"show_region": "Region anzeigen",
"expand_selection": "Auswahl erweitern",
"collapse_selection": "Auswahl verkleinern"
"collapse_selection": "Auswahl verkleinern",
"error.image_not_found": "Bild nicht gefunden",
};

export default translationDeDE;
1 change: 1 addition & 0 deletions client/src/Localization/translation-en-EN.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ const translationEnEN = {
"show_region": "Show region",
"expand_selection": "Expand selection",
"collapse_selection": "Collapse selection",
"error.image_not_found": "Image not found",
};

export default translationEnEN;
48 changes: 26 additions & 22 deletions client/src/SnackbarContext/index.jsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
import { createContext, useState, useContext } from 'react';
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';

import { Box } from '@mui/material';

const SnackbarContext = createContext({
open: false,
message: '',
severity: 'info',
handleClose: () => {},
showSnackbar: () => {},
});

export const SnackbarProvider = ({ children }) => {
const [open, setOpen] = useState(false);
const [message, setMessage] = useState('');
const [severity, setSeverity] = useState('info');
const [messages, setMessages] = useState([]);

const handleClose = () => {
setOpen(false);
const showSnackbar = (message, severity = 'info') => {
setMessages((prevMessages) => [
...prevMessages,
{ id: new Date().getTime(), message, severity },
]);
};

const showSnackbar = (message, newSeverity = 'info') => {
setMessage(message);
setSeverity(newSeverity);
setOpen(true);
const handleClose = (index) => {
setMessages((prevMessages) => prevMessages.filter((msg, idx) => idx !== index));
};

return (
<SnackbarContext.Provider
value={{ open, message, severity, handleClose, showSnackbar }}
>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity={severity}>
{message}
</Alert>
</Snackbar>
<SnackbarContext.Provider value={{ showSnackbar }}>
<Box sx={{ position: 'fixed', bottom: 16, left: 16 }}>
{messages.map((msg, index) => (
<Snackbar
key={msg.id+index}
open
autoHideDuration={6000}
anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
sx={{ mb: index * 8 }}
>
<Alert onClose={() => handleClose(index)} severity={msg.severity}>
{msg.message}
</Alert>
</Snackbar>
))}
</Box>
{children}
</SnackbarContext.Provider>
);
Expand Down
11 changes: 10 additions & 1 deletion server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ def upload_file():

@app.route('/uploads/<filename>', methods=['GET'])
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
if os.path.exists(file_path):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
else:
return jsonify({"status": "error", "message": "File not found"}), 404

@app.route('/uploads/<filename>', methods=['DELETE'])
def delete_file(filename):
Expand Down Expand Up @@ -698,6 +702,11 @@ def get_images_info():
print('Error:', e)
return jsonify({'error': str(e)}), 500

@app.errorhandler(404)
def not_found(error):
return jsonify({"status": "error", "message": "Resource not found"}), 404


@app.route('/', methods=['GET'])
def main():
return '''
Expand Down
9 changes: 9 additions & 0 deletions server/tests/test_app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import unittest
from unittest.mock import patch
# import os
import json
from io import BytesIO
Expand Down Expand Up @@ -42,6 +43,14 @@ def test_images_name(self):
self.assertEqual(response.status_code, 200)
self.assertIn(b'configuration', response.data)

def test_uploaded_file_not_found(self):
with patch('os.path.exists') as mock_exists:
mock_exists.return_value = False
response = self.app.get('/uploads/example.png')
self.assertEqual(response.status_code, 404)
data = response.get_json()
self.assertEqual(data['status'], 'error')
self.assertEqual(data['message'], 'File not found')

# def test_save_annotate_info_success(self):
# annotate_data = {
Expand Down
Loading