Files
Oxicloud/src/infrastructure/services/zip_service.rs
T

263 lines
8.5 KiB
Rust
Raw Normal View History

2025-04-02 01:22:05 +02:00
use crate::{
application::dtos::file_dto::FileDto,
application::dtos::folder_dto::FolderDto,
application::ports::file_ports::FileRetrievalUseCase,
2026-02-14 01:29:34 +01:00
application::ports::inbound::FolderUseCase,
application::ports::zip_ports::ZipPort,
2026-02-14 01:29:34 +01:00
common::errors::{DomainError, ErrorKind, Result},
2025-04-02 01:22:05 +02:00
};
2026-02-14 01:29:34 +01:00
use async_trait::async_trait;
use std::io::{Cursor, Read, Write};
2025-04-02 01:22:05 +02:00
use std::sync::Arc;
2026-02-14 01:29:34 +01:00
use thiserror::Error;
use tracing::*;
use zip::{ZipWriter, write::SimpleFileOptions};
2025-04-02 01:22:05 +02:00
/// Error related to ZIP file creation
2025-04-02 01:22:05 +02:00
#[derive(Debug, Error)]
pub enum ZipError {
#[error("IO error: {0}")]
2025-04-02 01:22:05 +02:00
IoError(#[from] std::io::Error),
2026-02-14 01:29:34 +01:00
#[error("ZIP error: {0}")]
2025-04-02 01:22:05 +02:00
ZipError(#[from] zip::result::ZipError),
2026-02-14 01:29:34 +01:00
#[error("Error reading file: {0}")]
2025-04-02 01:22:05 +02:00
FileReadError(String),
2026-02-14 01:29:34 +01:00
#[error("Error getting folder contents: {0}")]
2025-04-02 01:22:05 +02:00
FolderContentsError(String),
2026-02-14 01:29:34 +01:00
#[error("Folder not found: {0}")]
2025-04-02 01:22:05 +02:00
FolderNotFound(String),
}
// Implement From<ZipError> for DomainError to allow the use of ?
2025-04-02 01:22:05 +02:00
impl From<ZipError> for DomainError {
fn from(err: ZipError) -> Self {
DomainError::new(ErrorKind::InternalError, "zip_service", err.to_string())
}
}
// Implement From<zip::result::ZipError> for DomainError directly
2025-04-02 01:22:05 +02:00
impl From<zip::result::ZipError> for DomainError {
fn from(err: zip::result::ZipError) -> Self {
DomainError::new(ErrorKind::InternalError, "zip_service", err.to_string())
}
}
/// Service for creating ZIP files
2025-04-02 01:22:05 +02:00
pub struct ZipService {
file_service: Arc<dyn FileRetrievalUseCase>,
2025-04-02 01:22:05 +02:00
folder_service: Arc<dyn FolderUseCase>,
}
impl ZipService {
/// Creates a new instance of the ZIP service with a reference to the file service
2026-02-14 01:29:34 +01:00
pub fn new(
file_service: Arc<dyn FileRetrievalUseCase>,
folder_service: Arc<dyn FolderUseCase>,
) -> Self {
2025-04-02 01:22:05 +02:00
Self {
file_service,
folder_service,
}
}
2026-02-14 01:29:34 +01:00
/// Creates a ZIP file with the contents of a folder and all its subfolders
/// Returns the ZIP bytes
2025-04-02 01:22:05 +02:00
pub async fn create_folder_zip(&self, folder_id: &str, folder_name: &str) -> Result<Vec<u8>> {
2026-02-14 01:29:34 +01:00
info!(
"Creating ZIP for folder: {} (ID: {})",
folder_name, folder_id
);
// Verify if the folder exists
2025-04-02 01:22:05 +02:00
let folder = match self.folder_service.get_folder(folder_id).await {
Ok(folder) => folder,
Err(e) => {
error!("Error getting folder {}: {}", folder_id, e);
2025-04-02 01:22:05 +02:00
return Err(ZipError::FolderNotFound(folder_id.to_string()).into());
}
};
2026-02-14 01:29:34 +01:00
// Create an in-memory buffer for the ZIP
2025-04-02 01:22:05 +02:00
let buf = Cursor::new(Vec::new());
let mut zip = ZipWriter::new(buf);
2026-02-14 01:29:34 +01:00
// Set compression options
2025-04-02 01:22:05 +02:00
let options = SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated)
.unix_permissions(0o755);
2026-02-14 01:29:34 +01:00
// Object to track processed folders and avoid cycles
2025-04-02 01:22:05 +02:00
let mut processed_folders = std::collections::HashSet::new();
2026-02-14 01:29:34 +01:00
// Process the root folder and build the ZIP
2025-04-02 01:22:05 +02:00
self.process_folder_recursively(
&mut zip,
&folder,
folder_name,
&options,
2026-02-14 01:29:34 +01:00
&mut processed_folders,
)
.await?;
// Finalize the ZIP and get the bytes
2025-04-02 01:22:05 +02:00
let mut zip_buf = zip.finish()?;
2026-02-14 01:29:34 +01:00
2025-04-02 01:22:05 +02:00
let mut bytes = Vec::new();
match zip_buf.read_to_end(&mut bytes) {
Ok(_) => Ok(bytes),
Err(e) => {
error!("Error reading finalized ZIP: {}", e);
2025-04-02 01:22:05 +02:00
Err(ZipError::IoError(e).into())
}
}
}
2026-02-14 01:29:34 +01:00
// Alternative implementation to avoid recursion in async
2025-04-02 01:22:05 +02:00
async fn process_folder_recursively(
&self,
zip: &mut ZipWriter<Cursor<Vec<u8>>>,
folder: &FolderDto,
path: &str,
options: &SimpleFileOptions,
2026-02-14 01:29:34 +01:00
processed_folders: &mut std::collections::HashSet<String>,
2025-04-02 01:22:05 +02:00
) -> Result<()> {
// Structure to represent pending work
2025-04-02 01:22:05 +02:00
struct PendingFolder {
folder: FolderDto,
path: String,
}
2026-02-14 01:29:34 +01:00
// Work queue for iterative processing
2025-04-02 01:22:05 +02:00
let mut work_queue = vec![PendingFolder {
folder: folder.clone(),
path: path.to_string(),
}];
2026-02-14 01:29:34 +01:00
// Process the queue while there are elements
2025-04-02 01:22:05 +02:00
while let Some(current) = work_queue.pop() {
let folder_id = current.folder.id.to_string();
2026-02-14 01:29:34 +01:00
// Avoid cycles
2025-04-02 01:22:05 +02:00
if processed_folders.contains(&folder_id) {
continue;
}
2026-02-14 01:29:34 +01:00
2025-04-02 01:22:05 +02:00
processed_folders.insert(folder_id.clone());
2026-02-14 01:29:34 +01:00
// Create the directory entry in the ZIP
2025-04-02 01:22:05 +02:00
let folder_path = format!("{}/", current.path);
match zip.add_directory(&folder_path, *options) {
Ok(_) => debug!("Folder added to ZIP: {}", folder_path),
2025-04-02 01:22:05 +02:00
Err(e) => {
warn!("Could not add folder to ZIP (it may already exist): {}", e);
// Continue even if creating the directory fails (it could be a duplicate)
2025-04-02 01:22:05 +02:00
}
}
2026-02-14 01:29:34 +01:00
// Add files from the folder to the ZIP
2025-04-02 01:22:05 +02:00
let files = match self.file_service.list_files(Some(&folder_id)).await {
Ok(files) => files,
Err(e) => {
error!("Error listing files in folder {}: {}", folder_id, e);
2026-02-14 01:29:34 +01:00
return Err(ZipError::FolderContentsError(format!(
"Error listing files: {}",
e
))
.into());
2025-04-02 01:22:05 +02:00
}
};
2026-02-14 01:29:34 +01:00
// Add each file to the ZIP
2025-04-02 01:22:05 +02:00
for file in files {
2026-02-14 01:29:34 +01:00
self.add_file_to_zip(zip, &file, &folder_path, options)
.await?;
2025-04-02 01:22:05 +02:00
}
2026-02-14 01:29:34 +01:00
// Process subfolders
2025-04-02 01:22:05 +02:00
let subfolders = match self.folder_service.list_folders(Some(&folder_id)).await {
Ok(folders) => folders,
Err(e) => {
error!("Error listing subfolders in {}: {}", folder_id, e);
2026-02-14 01:29:34 +01:00
return Err(ZipError::FolderContentsError(format!(
"Error listing subfolders: {}",
e
))
.into());
2025-04-02 01:22:05 +02:00
}
};
2026-02-14 01:29:34 +01:00
// Add subfolders to the queue
2025-04-02 01:22:05 +02:00
for subfolder in subfolders {
let subfolder_path = format!("{}/{}", current.path, subfolder.name);
work_queue.push(PendingFolder {
folder: subfolder,
path: subfolder_path,
});
}
}
2026-02-14 01:29:34 +01:00
2025-04-02 01:22:05 +02:00
Ok(())
}
2026-02-14 01:29:34 +01:00
// Adds a file to the ZIP
2025-04-02 01:22:05 +02:00
async fn add_file_to_zip(
&self,
zip: &mut ZipWriter<Cursor<Vec<u8>>>,
file: &FileDto,
folder_path: &str,
options: &SimpleFileOptions,
) -> Result<()> {
let file_path = format!("{}{}", folder_path, file.name);
info!("Adding file to ZIP: {}", file_path);
2026-02-14 01:29:34 +01:00
// Get the file content
2025-04-02 01:22:05 +02:00
let file_id = file.id.to_string();
let content = match self.file_service.get_file_content(&file_id).await {
Ok(content) => content,
Err(e) => {
error!("Error reading file content {}: {}", file_id, e);
2026-02-14 01:29:34 +01:00
return Err(ZipError::FileReadError(format!(
"Error reading file {}: {}",
file_id, e
))
.into());
2025-04-02 01:22:05 +02:00
}
};
2026-02-14 01:29:34 +01:00
// Write file to the ZIP
2025-04-02 01:22:05 +02:00
match zip.start_file_from_path(std::path::Path::new(&file_path), *options) {
2026-02-14 01:29:34 +01:00
Ok(_) => match zip.write_all(&content) {
Ok(_) => {
debug!("File added to ZIP: {}", file_path);
Ok(())
}
Err(e) => {
error!("Error writing file content {}: {}", file_path, e);
Err(ZipError::IoError(e).into())
2025-04-02 01:22:05 +02:00
}
},
Err(e) => {
error!("Error starting file in ZIP {}: {}", file_path, e);
2025-04-02 01:22:05 +02:00
Err(ZipError::ZipError(e).into())
}
}
}
}
// ─── Port implementation ─────────────────────────────────────────────────────
#[async_trait]
impl ZipPort for ZipService {
async fn create_folder_zip(
&self,
folder_id: &str,
folder_name: &str,
) -> std::result::Result<Vec<u8>, DomainError> {
self.create_folder_zip(folder_id, folder_name).await
}
2026-02-14 01:29:34 +01:00
}