KNEO-Academy/src/services/file_service.py

77 lines
3.0 KiB
Python

import os
import shutil
from PyQt5.QtWidgets import QFileDialog, QMessageBox
class FileService:
def __init__(self, main_window, upload_dir):
self.main_window = main_window
self.upload_dir = upload_dir
self.destination = None
def upload_file(self):
"""Handle file upload process"""
try:
print("Calling QFileDialog.getOpenFileName")
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(
self.main_window,
"Upload File",
"",
"All Files (*)",
options=options
)
print("File path obtained:", file_path)
if file_path:
print("Checking if upload directory exists")
if not os.path.exists(self.upload_dir):
os.makedirs(self.upload_dir)
print(f"Created UPLOAD_DIR: {self.upload_dir}")
print("Checking if original file exists:", file_path)
if not os.path.exists(file_path):
self.show_message(QMessageBox.Critical, "Error", "Selected file not found")
return None
file_name = os.path.basename(file_path)
self.destination = os.path.join(self.upload_dir, file_name)
print("Target path:", self.destination)
# Check if target path is writable
try:
print("Testing file write permission")
with open(self.destination, 'wb') as test_file:
pass
os.remove(self.destination)
print("Test file creation and deletion successful")
except PermissionError:
self.show_message(QMessageBox.Critical, "Error", "Cannot write to target directory")
return None
print("Starting file copy")
shutil.copy2(file_path, self.destination)
print("File copy complete")
self.show_message(QMessageBox.Information, "Success", f"File uploaded to: {self.destination}")
return self.destination
return None
except Exception as e:
import traceback
print("Exception during upload process:\n", traceback.format_exc())
self.show_message(QMessageBox.Critical, "Error", f"Upload error: {str(e)}")
return None
def show_message(self, icon, title, message):
"""Display a message box with custom styling"""
msgBox = QMessageBox(self.main_window)
msgBox.setIcon(icon)
msgBox.setWindowTitle(title)
msgBox.setText(message)
msgBox.setStyleSheet("""
QLabel { color: white; }
QPushButton { color: white; }
QMessageBox { background-color: #2b2b2b; }
""")
msgBox.exec_()