Files
Oxicloud/src/application/services/file_management_service.rs
T
Diocrafts ee86c3a128 fix: resolve all clippy warnings and convert integration_tests to custom cfg
- Add type aliases (FileRow, FolderRow, FolderRowPaginated, FolderRowOptUser) to reduce type complexity
- Simplify redundant closures in app_password_handler and webdav_handler
- Remove needless borrow in auth_handler
- Collapse nested if/let chains in login_lockout, webdav_lock, auth, rate_limit
- Box LockEntry in acquire() Err variant to fix large enum variant warning
- Rename DeviceCodeStatus::from_str to parse to avoid should_implement_trait lint
- Add #[allow(clippy::too_many_arguments)] and #[allow(clippy::result_unit_err)] where appropriate
- Convert integration_tests from cargo feature to custom cfg attribute
- Add check-cfg lint config in Cargo.toml for integration_tests cfg
2026-03-04 23:55:08 +01:00

233 lines
7.7 KiB
Rust

use std::sync::Arc;
use crate::application::dtos::file_dto::FileDto;
use crate::application::ports::file_ports::FileManagementUseCase;
use crate::application::ports::storage_ports::{CopyFolderTreeResult, FileReadPort, FileWritePort};
use crate::application::ports::trash_ports::TrashUseCase;
use crate::application::services::trash_service::TrashService;
use crate::common::errors::DomainError;
use crate::infrastructure::repositories::pg::file_blob_read_repository::FileBlobReadRepository;
use crate::infrastructure::repositories::pg::file_blob_write_repository::FileBlobWriteRepository;
use tracing::{error, info, warn};
/// Service for file management operations (move, delete).
///
/// 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.
pub struct FileManagementService {
file_repository: Arc<FileBlobWriteRepository>,
file_read: Option<Arc<FileBlobReadRepository>>,
trash_service: Option<Arc<TrashService>>,
}
impl FileManagementService {
/// Creates a new FileManagementService.
pub fn new(file_repository: Arc<FileBlobWriteRepository>) -> Self {
Self {
file_repository,
file_read: None,
trash_service: None,
}
}
/// Creates a FileManagementService with a trash service and read repo for ownership checks.
pub fn with_trash(
file_repository: Arc<FileBlobWriteRepository>,
trash_service: Option<Arc<TrashService>>,
file_read: Option<Arc<FileBlobReadRepository>>,
) -> Self {
Self {
file_repository,
file_read,
trash_service,
}
}
/// Verifies ownership via the read repository.
async fn verify_owner(&self, file_id: &str, caller_id: &str) -> Result<(), DomainError> {
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",
))
}
}
}
impl FileManagementUseCase for FileManagementService {
async fn move_file(
&self,
file_id: &str,
folder_id: Option<String>,
) -> Result<FileDto, DomainError> {
info!(
"Moving file with ID: {} to folder: {:?}",
file_id, folder_id
);
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
})?;
info!(
"File moved successfully: {} (ID: {}) to folder: {:?}",
moved_file.name(),
moved_file.id(),
moved_file.folder_id()
);
Ok(FileDto::from(moved_file))
}
async fn move_file_owned(
&self,
file_id: &str,
caller_id: &str,
folder_id: Option<String>,
) -> Result<FileDto, DomainError> {
self.verify_owner(file_id, caller_id).await?;
self.move_file(file_id, folder_id).await
}
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))
}
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError> {
info!("Renaming file with ID: {} to \"{}\"", file_id, new_name);
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
})?;
info!(
"File renamed successfully: {} (ID: {})",
renamed_file.name(),
renamed_file.id()
);
Ok(FileDto::from(renamed_file))
}
async fn rename_file_owned(
&self,
file_id: &str,
caller_id: &str,
new_name: &str,
) -> Result<FileDto, DomainError> {
self.verify_owner(file_id, caller_id).await?;
self.rename_file(file_id, new_name).await
}
async fn delete_file(&self, id: &str) -> Result<(), DomainError> {
self.file_repository.delete_file(id).await
}
/// Smart delete: trash-first with dedup reference cleanup.
///
/// 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.
async fn delete_with_cleanup(&self, id: &str, user_id: &str) -> Result<bool, DomainError> {
// Step 1: Try trash (soft delete — file row stays, blob stays referenced)
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);
// 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.
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");
}
// Step 2: Permanent delete — trigger handles blob ref_count
warn!("Permanently deleting file: {}", id);
self.file_repository.delete_file(id).await?;
info!("File permanently deleted: {}", id);
Ok(false) // permanently deleted
}
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| {
error!(
"Error copying folder tree (source: {}): {}",
source_folder_id, e
);
e
})?;
info!(
"Folder tree copied: {} folders, {} files (new root: {})",
result.folders_copied, result.files_copied, result.new_root_folder_id
);
Ok(result)
}
}