2026-02-14 01:29:34 +01:00
|
|
|
use std::sync::Arc;
|
2025-03-19 19:52:12 +01:00
|
|
|
|
|
|
|
|
use crate::application::dtos::file_dto::FileDto;
|
2026-05-14 00:03:03 +02:00
|
|
|
use crate::application::ports::file_lifecycle::FileDeletedHook;
|
2026-02-14 01:29:34 +01:00
|
|
|
use crate::application::ports::file_ports::FileManagementUseCase;
|
2026-03-04 17:18:39 +01:00
|
|
|
use crate::application::ports::storage_ports::{CopyFolderTreeResult, FileReadPort, FileWritePort};
|
2026-02-08 13:40:23 +01:00
|
|
|
use crate::application::ports::trash_ports::TrashUseCase;
|
2026-03-04 23:55:08 +01:00
|
|
|
use crate::application::services::trash_service::TrashService;
|
2025-03-19 19:52:12 +01:00
|
|
|
use crate::common::errors::DomainError;
|
2026-05-09 00:06:30 +02:00
|
|
|
use crate::domain::services::path_service::validate_storage_name;
|
2026-03-04 17:18:39 +01:00
|
|
|
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
|
2026-03-03 15:36:42 +00:00
|
|
|
use crate::infrastructure::repositories::pg::file_blob_write_repository::FileBlobWriteRepository;
|
2026-03-17 16:53:55 +08:00
|
|
|
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
|
2026-04-11 17:39:17 +02:00
|
|
|
use crate::infrastructure::services::file_content_cache::FileContentCache;
|
2026-03-04 23:55:08 +01:00
|
|
|
use tracing::{error, info, warn};
|
2026-03-07 14:59:32 +01:00
|
|
|
use uuid::Uuid;
|
2025-03-19 19:52:12 +01:00
|
|
|
|
2026-02-08 13:40:23 +01:00
|
|
|
/// Service for file management operations (move, delete).
|
|
|
|
|
///
|
2026-02-22 22:07:46 +01:00
|
|
|
/// Blob ref_count bookkeeping on deletion is handled by the PG trigger
|
|
|
|
|
/// `trg_files_decrement_blob_ref` (fires on DELETE FROM storage.files).
|
|
|
|
|
/// This service only orchestrates trash vs. permanent delete — it never
|
|
|
|
|
/// touches ref_count directly.
|
2025-03-19 19:52:12 +01:00
|
|
|
pub struct FileManagementService {
|
2026-03-03 15:36:42 +00:00
|
|
|
file_repository: Arc<FileBlobWriteRepository>,
|
2026-03-04 17:18:39 +01:00
|
|
|
file_read: Option<Arc<FileBlobReadRepository>>,
|
2026-03-17 16:53:55 +08:00
|
|
|
folder_repo: Option<Arc<FolderDbRepository>>,
|
2026-03-03 15:36:42 +00:00
|
|
|
trash_service: Option<Arc<TrashService>>,
|
2026-04-11 17:39:17 +02:00
|
|
|
content_cache: Option<Arc<FileContentCache>>,
|
2026-05-14 00:03:03 +02:00
|
|
|
/// Hooks fired after a file is permanently deleted.
|
|
|
|
|
file_deleted_hooks: Vec<Arc<dyn FileDeletedHook>>,
|
2025-03-19 19:52:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl FileManagementService {
|
2026-02-22 22:07:46 +01:00
|
|
|
/// Creates a new FileManagementService.
|
2026-03-03 15:36:42 +00:00
|
|
|
pub fn new(file_repository: Arc<FileBlobWriteRepository>) -> Self {
|
2026-02-08 13:40:23 +01:00
|
|
|
Self {
|
|
|
|
|
file_repository,
|
2026-03-04 17:18:39 +01:00
|
|
|
file_read: None,
|
2026-03-17 16:53:55 +08:00
|
|
|
folder_repo: None,
|
2026-02-08 13:40:23 +01:00
|
|
|
trash_service: None,
|
2026-04-11 17:39:17 +02:00
|
|
|
content_cache: None,
|
2026-05-14 00:03:03 +02:00
|
|
|
file_deleted_hooks: Vec::new(),
|
2026-02-08 13:40:23 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-17 16:53:55 +08:00
|
|
|
/// Creates a FileManagementService with a trash service, read repo, and folder repo for ownership checks.
|
2026-02-22 22:07:46 +01:00
|
|
|
pub fn with_trash(
|
2026-03-03 15:36:42 +00:00
|
|
|
file_repository: Arc<FileBlobWriteRepository>,
|
|
|
|
|
trash_service: Option<Arc<TrashService>>,
|
2026-03-04 17:18:39 +01:00
|
|
|
file_read: Option<Arc<FileBlobReadRepository>>,
|
2026-03-17 16:53:55 +08:00
|
|
|
folder_repo: Option<Arc<FolderDbRepository>>,
|
2026-04-11 17:39:17 +02:00
|
|
|
content_cache: Option<Arc<FileContentCache>>,
|
2026-02-08 13:40:23 +01:00
|
|
|
) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
file_repository,
|
2026-03-04 17:18:39 +01:00
|
|
|
file_read,
|
2026-03-17 16:53:55 +08:00
|
|
|
folder_repo,
|
2026-02-08 13:40:23 +01:00
|
|
|
trash_service,
|
2026-04-11 17:39:17 +02:00
|
|
|
content_cache,
|
2026-05-14 00:03:03 +02:00
|
|
|
file_deleted_hooks: Vec::new(),
|
2026-02-08 13:40:23 +01:00
|
|
|
}
|
2025-03-19 19:52:12 +01:00
|
|
|
}
|
2026-03-04 17:18:39 +01:00
|
|
|
|
2026-05-14 00:03:03 +02:00
|
|
|
/// Registers a hook to fire after a file is permanently deleted.
|
|
|
|
|
pub fn with_file_deleted_hook(mut self, hook: Arc<dyn FileDeletedHook>) -> Self {
|
|
|
|
|
self.file_deleted_hooks.push(hook);
|
|
|
|
|
self
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-04 17:18:39 +01:00
|
|
|
/// Verifies ownership via the read repository.
|
2026-03-07 14:59:32 +01:00
|
|
|
async fn verify_owner(&self, file_id: &str, caller_id: Uuid) -> Result<(), DomainError> {
|
2026-03-04 17:18:39 +01:00
|
|
|
if let Some(read) = &self.file_read {
|
|
|
|
|
read.verify_file_owner(file_id, caller_id).await
|
|
|
|
|
} else {
|
|
|
|
|
// Fallback: no read repo injected — deny by default (fail-closed)
|
|
|
|
|
Err(DomainError::internal_error(
|
|
|
|
|
"FileManagement",
|
|
|
|
|
"Ownership verification unavailable",
|
|
|
|
|
))
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-03-17 16:53:55 +08:00
|
|
|
|
|
|
|
|
/// Verifies that the target folder is owned by the caller.
|
|
|
|
|
/// If folder_id is None (root), ownership is implicitly granted.
|
|
|
|
|
async fn verify_target_folder_owner(
|
|
|
|
|
&self,
|
|
|
|
|
folder_id: &Option<String>,
|
|
|
|
|
caller_id: Uuid,
|
|
|
|
|
) -> Result<(), DomainError> {
|
|
|
|
|
let folder_id = match folder_id {
|
|
|
|
|
Some(id) => id,
|
|
|
|
|
None => return Ok(()), // Moving to root is always allowed
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if let Some(folder_repo) = &self.folder_repo {
|
|
|
|
|
let folder_owner = folder_repo.get_folder_user_id(folder_id).await?;
|
|
|
|
|
if folder_owner != caller_id {
|
|
|
|
|
return Err(DomainError::not_found(
|
|
|
|
|
"Folder",
|
|
|
|
|
"Target folder not found or access denied",
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
} else {
|
|
|
|
|
// Fallback: no folder repo injected — deny by default (fail-closed)
|
|
|
|
|
Err(DomainError::internal_error(
|
|
|
|
|
"FileManagement",
|
|
|
|
|
"Folder ownership verification unavailable",
|
|
|
|
|
))
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-03-19 19:52:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl FileManagementUseCase for FileManagementService {
|
2026-02-08 13:40:23 +01:00
|
|
|
async fn move_file(
|
|
|
|
|
&self,
|
|
|
|
|
file_id: &str,
|
|
|
|
|
folder_id: Option<String>,
|
|
|
|
|
) -> Result<FileDto, DomainError> {
|
2026-02-14 01:29:34 +01:00
|
|
|
info!(
|
|
|
|
|
"Moving file with ID: {} to folder: {:?}",
|
|
|
|
|
file_id, folder_id
|
|
|
|
|
);
|
2026-02-08 13:40:23 +01:00
|
|
|
|
2026-02-14 01:29:34 +01:00
|
|
|
let moved_file = self
|
|
|
|
|
.file_repository
|
|
|
|
|
.move_file(file_id, folder_id)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
error!("Error moving file (ID: {}): {}", file_id, e);
|
|
|
|
|
e
|
|
|
|
|
})?;
|
2026-02-08 13:40:23 +01:00
|
|
|
|
|
|
|
|
info!(
|
|
|
|
|
"File moved successfully: {} (ID: {}) to folder: {:?}",
|
|
|
|
|
moved_file.name(),
|
|
|
|
|
moved_file.id(),
|
|
|
|
|
moved_file.folder_id()
|
|
|
|
|
);
|
|
|
|
|
|
2025-03-19 19:52:12 +01:00
|
|
|
Ok(FileDto::from(moved_file))
|
|
|
|
|
}
|
2026-02-08 13:40:23 +01:00
|
|
|
|
2026-03-04 17:18:39 +01:00
|
|
|
async fn move_file_owned(
|
|
|
|
|
&self,
|
|
|
|
|
file_id: &str,
|
2026-03-07 14:59:32 +01:00
|
|
|
caller_id: Uuid,
|
2026-03-04 17:18:39 +01:00
|
|
|
folder_id: Option<String>,
|
|
|
|
|
) -> Result<FileDto, DomainError> {
|
2026-03-17 16:53:55 +08:00
|
|
|
// Verify file ownership first
|
2026-03-04 17:18:39 +01:00
|
|
|
self.verify_owner(file_id, caller_id).await?;
|
2026-03-17 16:53:55 +08:00
|
|
|
// Verify target folder ownership (prevents file from "disappearing")
|
2026-03-26 09:46:50 +01:00
|
|
|
self.verify_target_folder_owner(&folder_id, caller_id)
|
|
|
|
|
.await?;
|
2026-03-04 17:18:39 +01:00
|
|
|
self.move_file(file_id, folder_id).await
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-14 20:22:19 +01:00
|
|
|
async fn copy_file(
|
|
|
|
|
&self,
|
|
|
|
|
file_id: &str,
|
|
|
|
|
target_folder_id: Option<String>,
|
|
|
|
|
) -> Result<FileDto, DomainError> {
|
|
|
|
|
info!(
|
|
|
|
|
"Copying file with ID: {} to folder: {:?}",
|
|
|
|
|
file_id, target_folder_id
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let copied_file = self
|
|
|
|
|
.file_repository
|
|
|
|
|
.copy_file(file_id, target_folder_id)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
error!("Error copying file (ID: {}): {}", file_id, e);
|
|
|
|
|
e
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
info!(
|
|
|
|
|
"File copied successfully: {} (ID: {}) to folder: {:?}",
|
|
|
|
|
copied_file.name(),
|
|
|
|
|
copied_file.id(),
|
|
|
|
|
copied_file.folder_id()
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
Ok(FileDto::from(copied_file))
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-05 10:30:39 +01:00
|
|
|
async fn copy_file_owned(
|
|
|
|
|
&self,
|
|
|
|
|
file_id: &str,
|
2026-03-07 14:59:32 +01:00
|
|
|
caller_id: Uuid,
|
2026-03-05 10:30:39 +01:00
|
|
|
target_folder_id: Option<String>,
|
|
|
|
|
) -> Result<FileDto, DomainError> {
|
|
|
|
|
self.verify_owner(file_id, caller_id).await?;
|
2026-05-11 23:00:55 +02:00
|
|
|
self.verify_target_folder_owner(&target_folder_id, caller_id)
|
|
|
|
|
.await?;
|
2026-03-05 10:30:39 +01:00
|
|
|
self.copy_file(file_id, target_folder_id).await
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-14 01:29:34 +01:00
|
|
|
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError> {
|
2026-05-09 00:06:30 +02:00
|
|
|
if let Err(reason) = validate_storage_name(new_name) {
|
|
|
|
|
return Err(DomainError::validation_error(format!(
|
|
|
|
|
"Invalid file name '{new_name}': {reason}"
|
|
|
|
|
)));
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-08 22:44:42 +01:00
|
|
|
info!("Renaming file with ID: {} to \"{}\"", file_id, new_name);
|
|
|
|
|
|
2026-02-14 01:29:34 +01:00
|
|
|
let renamed_file = self
|
|
|
|
|
.file_repository
|
|
|
|
|
.rename_file(file_id, new_name)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
error!("Error renaming file (ID: {}): {}", file_id, e);
|
|
|
|
|
e
|
|
|
|
|
})?;
|
2026-02-08 22:44:42 +01:00
|
|
|
|
|
|
|
|
info!(
|
|
|
|
|
"File renamed successfully: {} (ID: {})",
|
|
|
|
|
renamed_file.name(),
|
|
|
|
|
renamed_file.id()
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
Ok(FileDto::from(renamed_file))
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-04 17:18:39 +01:00
|
|
|
async fn rename_file_owned(
|
|
|
|
|
&self,
|
|
|
|
|
file_id: &str,
|
2026-03-07 14:59:32 +01:00
|
|
|
caller_id: Uuid,
|
2026-03-04 17:18:39 +01:00
|
|
|
new_name: &str,
|
|
|
|
|
) -> Result<FileDto, DomainError> {
|
|
|
|
|
self.verify_owner(file_id, caller_id).await?;
|
|
|
|
|
self.rename_file(file_id, new_name).await
|
|
|
|
|
}
|
|
|
|
|
|
2025-03-19 19:52:12 +01:00
|
|
|
async fn delete_file(&self, id: &str) -> Result<(), DomainError> {
|
2026-03-07 19:15:36 +01:00
|
|
|
self.file_repository.delete_file(id).await?;
|
2026-04-11 17:39:17 +02:00
|
|
|
if let Some(cc) = &self.content_cache {
|
|
|
|
|
cc.invalidate(id).await;
|
|
|
|
|
}
|
2026-05-14 00:03:03 +02:00
|
|
|
for hook in &self.file_deleted_hooks {
|
|
|
|
|
hook.on_file_deleted(id).await;
|
2026-03-07 19:15:36 +01:00
|
|
|
}
|
|
|
|
|
Ok(())
|
2025-03-19 19:52:12 +01:00
|
|
|
}
|
2026-02-08 13:40:23 +01:00
|
|
|
|
2026-03-07 14:59:32 +01:00
|
|
|
async fn delete_file_owned(&self, id: &str, caller_id: Uuid) -> Result<(), DomainError> {
|
2026-03-05 10:30:39 +01:00
|
|
|
self.verify_owner(id, caller_id).await?;
|
|
|
|
|
self.delete_file(id).await
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-08 13:40:23 +01:00
|
|
|
/// Smart delete: trash-first with dedup reference cleanup.
|
2026-02-22 22:07:46 +01:00
|
|
|
///
|
|
|
|
|
/// Blob ref_count bookkeeping is handled entirely by the PG trigger
|
|
|
|
|
/// `trg_files_decrement_blob_ref` which fires on DELETE FROM storage.files.
|
|
|
|
|
/// We do NOT decrement here — trashing is a soft-delete (UPDATE, not DELETE)
|
|
|
|
|
/// so the blob must remain referenced until the file is permanently deleted.
|
2026-03-07 14:59:32 +01:00
|
|
|
async fn delete_with_cleanup(&self, id: &str, user_id: Uuid) -> Result<bool, DomainError> {
|
2026-02-22 22:07:46 +01:00
|
|
|
// Step 1: Try trash (soft delete — file row stays, blob stays referenced)
|
2026-02-08 13:40:23 +01:00
|
|
|
if let Some(trash) = &self.trash_service {
|
|
|
|
|
info!("Moving file to trash: {}", id);
|
|
|
|
|
match trash.move_to_trash(id, "file", user_id).await {
|
|
|
|
|
Ok(_) => {
|
|
|
|
|
info!("File successfully moved to trash: {}", id);
|
2026-04-11 17:39:17 +02:00
|
|
|
// Invalidate content cache — trashed files must not be served.
|
|
|
|
|
if let Some(cc) = &self.content_cache {
|
|
|
|
|
cc.invalidate(id).await;
|
|
|
|
|
}
|
2026-02-22 22:07:46 +01:00
|
|
|
// Do NOT decrement blob ref here — the file row still exists
|
|
|
|
|
// (is_trashed = TRUE). The trigger will decrement when the
|
|
|
|
|
// row is actually DELETEd during trash emptying.
|
2026-02-08 13:40:23 +01:00
|
|
|
return Ok(true); // trashed
|
|
|
|
|
}
|
|
|
|
|
Err(err) => {
|
|
|
|
|
error!("Could not move file to trash: {:?}", err);
|
|
|
|
|
warn!("Falling back to permanent delete");
|
|
|
|
|
// fall through
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
warn!("Trash service not available, using permanent delete");
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-22 22:07:46 +01:00
|
|
|
// Step 2: Permanent delete — trigger handles blob ref_count
|
2026-02-08 13:40:23 +01:00
|
|
|
warn!("Permanently deleting file: {}", id);
|
|
|
|
|
self.file_repository.delete_file(id).await?;
|
2026-04-11 17:39:17 +02:00
|
|
|
if let Some(cc) = &self.content_cache {
|
|
|
|
|
cc.invalidate(id).await;
|
|
|
|
|
}
|
2026-05-14 00:03:03 +02:00
|
|
|
for hook in &self.file_deleted_hooks {
|
|
|
|
|
hook.on_file_deleted(id).await;
|
2026-03-07 19:15:36 +01:00
|
|
|
}
|
2026-02-08 13:40:23 +01:00
|
|
|
info!("File permanently deleted: {}", id);
|
|
|
|
|
|
|
|
|
|
Ok(false) // permanently deleted
|
|
|
|
|
}
|
2026-02-24 19:28:00 +01:00
|
|
|
|
|
|
|
|
async fn copy_folder_tree(
|
|
|
|
|
&self,
|
|
|
|
|
source_folder_id: &str,
|
|
|
|
|
target_parent_id: Option<String>,
|
|
|
|
|
dest_name: Option<String>,
|
|
|
|
|
) -> Result<CopyFolderTreeResult, DomainError> {
|
|
|
|
|
info!(
|
|
|
|
|
"Copying folder tree: source={}, target_parent={:?}, dest_name={:?}",
|
|
|
|
|
source_folder_id, target_parent_id, dest_name
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let result = self
|
|
|
|
|
.file_repository
|
|
|
|
|
.copy_folder_tree(source_folder_id, target_parent_id, dest_name)
|
|
|
|
|
.await
|
|
|
|
|
.map_err(|e| {
|
2026-02-25 10:28:34 +01:00
|
|
|
error!(
|
|
|
|
|
"Error copying folder tree (source: {}): {}",
|
|
|
|
|
source_folder_id, e
|
|
|
|
|
);
|
2026-02-24 19:28:00 +01:00
|
|
|
e
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
info!(
|
|
|
|
|
"Folder tree copied: {} folders, {} files (new root: {})",
|
|
|
|
|
result.folders_copied, result.files_copied, result.new_root_folder_id
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
Ok(result)
|
|
|
|
|
}
|
2026-05-11 22:58:33 +02:00
|
|
|
|
|
|
|
|
async fn copy_folder_tree_owned(
|
|
|
|
|
&self,
|
|
|
|
|
source_folder_id: &str,
|
|
|
|
|
caller_id: Uuid,
|
|
|
|
|
target_parent_id: Option<String>,
|
|
|
|
|
dest_name: Option<String>,
|
|
|
|
|
) -> Result<CopyFolderTreeResult, DomainError> {
|
|
|
|
|
if let Some(folder_repo) = &self.folder_repo {
|
|
|
|
|
let owner = folder_repo.get_folder_user_id(source_folder_id).await?;
|
|
|
|
|
if owner != caller_id {
|
|
|
|
|
return Err(DomainError::not_found(
|
|
|
|
|
"Folder",
|
|
|
|
|
"Source folder not found or access denied",
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
return Err(DomainError::internal_error(
|
|
|
|
|
"FileManagement",
|
|
|
|
|
"Folder ownership verification unavailable",
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
self.verify_target_folder_owner(&target_parent_id, caller_id)
|
|
|
|
|
.await?;
|
|
|
|
|
self.copy_folder_tree(source_folder_id, target_parent_id, dest_name)
|
|
|
|
|
.await
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
}
|