fix: critical bugs from deep audit
- Fix copy_files() data loss: implement real copy_file across full stack (FileWritePort, FileManagementUseCase, stubs, service, repository with atomic CTE + dedup ref_count increment, batch_operations caller) - Fix plaintext password in replace_default_admin: hash password via PasswordHasherPort before User::new() - Fix CalendarService hardcoded user_id: unify CalendarUseCase trait with explicit user_id parameter on all methods, remove zombie _for_user duplicates and hardcoded 'current_user_id', update 20 CalDAV handler call sites - Previous session: migrate DedupService to PostgreSQL (storage.blobs), atomic CTEs with compensation for file/folder repository operations
This commit is contained in:
@@ -106,23 +106,33 @@ pub trait CalendarStoragePort: Send + Sync + 'static {
|
|||||||
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Port for calendar use cases
|
/// Port for calendar use cases.
|
||||||
|
///
|
||||||
|
/// All methods require an explicit `user_id` parameter for authorization.
|
||||||
|
/// The CalDAV protocol handler extracts the user identity from JWT claims
|
||||||
|
/// and passes it through.
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait CalendarUseCase: Send + Sync + 'static {
|
pub trait CalendarUseCase: Send + Sync + 'static {
|
||||||
// Calendar operations
|
// Calendar operations
|
||||||
async fn create_calendar(
|
async fn create_calendar(
|
||||||
&self,
|
&self,
|
||||||
calendar: CreateCalendarDto,
|
calendar: CreateCalendarDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarDto, DomainError>;
|
) -> Result<CalendarDto, DomainError>;
|
||||||
async fn update_calendar(
|
async fn update_calendar(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
update: UpdateCalendarDto,
|
update: UpdateCalendarDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarDto, DomainError>;
|
) -> Result<CalendarDto, DomainError>;
|
||||||
async fn delete_calendar(&self, calendar_id: &str) -> Result<(), DomainError>;
|
async fn delete_calendar(&self, calendar_id: &str, user_id: &str) -> Result<(), DomainError>;
|
||||||
async fn get_calendar(&self, calendar_id: &str) -> Result<CalendarDto, DomainError>;
|
async fn get_calendar(
|
||||||
async fn list_my_calendars(&self) -> Result<Vec<CalendarDto>, DomainError>;
|
&self,
|
||||||
async fn list_shared_calendars(&self) -> Result<Vec<CalendarDto>, DomainError>;
|
calendar_id: &str,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<CalendarDto, DomainError>;
|
||||||
|
async fn list_my_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError>;
|
||||||
|
async fn list_shared_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError>;
|
||||||
async fn list_public_calendars(
|
async fn list_public_calendars(
|
||||||
&self,
|
&self,
|
||||||
limit: Option<i64>,
|
limit: Option<i64>,
|
||||||
@@ -133,90 +143,57 @@ pub trait CalendarUseCase: Send + Sync + 'static {
|
|||||||
async fn share_calendar(
|
async fn share_calendar(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
user_id: &str,
|
target_user_id: &str,
|
||||||
access_level: &str,
|
access_level: &str,
|
||||||
|
caller_user_id: &str,
|
||||||
) -> Result<(), DomainError>;
|
) -> Result<(), DomainError>;
|
||||||
async fn remove_calendar_sharing(
|
async fn remove_calendar_sharing(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
user_id: &str,
|
target_user_id: &str,
|
||||||
|
caller_user_id: &str,
|
||||||
) -> Result<(), DomainError>;
|
) -> Result<(), DomainError>;
|
||||||
async fn get_calendar_shares(
|
async fn get_calendar_shares(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<Vec<(String, String)>, DomainError>;
|
) -> Result<Vec<(String, String)>, DomainError>;
|
||||||
|
|
||||||
// Event operations
|
// Event operations
|
||||||
async fn create_event(&self, event: CreateEventDto) -> Result<CalendarEventDto, DomainError>;
|
async fn create_event(
|
||||||
|
&self,
|
||||||
|
event: CreateEventDto,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<CalendarEventDto, DomainError>;
|
||||||
async fn create_event_from_ical(
|
async fn create_event_from_ical(
|
||||||
&self,
|
&self,
|
||||||
event: CreateEventICalDto,
|
event: CreateEventICalDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarEventDto, DomainError>;
|
) -> Result<CalendarEventDto, DomainError>;
|
||||||
async fn update_event(
|
async fn update_event(
|
||||||
&self,
|
&self,
|
||||||
event_id: &str,
|
event_id: &str,
|
||||||
update: UpdateEventDto,
|
update: UpdateEventDto,
|
||||||
|
user_id: &str,
|
||||||
|
) -> Result<CalendarEventDto, DomainError>;
|
||||||
|
async fn delete_event(&self, event_id: &str, user_id: &str) -> Result<(), DomainError>;
|
||||||
|
async fn get_event(
|
||||||
|
&self,
|
||||||
|
event_id: &str,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarEventDto, DomainError>;
|
) -> Result<CalendarEventDto, DomainError>;
|
||||||
async fn delete_event(&self, event_id: &str) -> Result<(), DomainError>;
|
|
||||||
async fn get_event(&self, event_id: &str) -> Result<CalendarEventDto, DomainError>;
|
|
||||||
async fn list_events(
|
async fn list_events(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
limit: Option<i64>,
|
limit: Option<i64>,
|
||||||
offset: Option<i64>,
|
offset: Option<i64>,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
||||||
async fn get_events_in_range(
|
async fn get_events_in_range(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
start: DateTime<Utc>,
|
start: DateTime<Utc>,
|
||||||
end: DateTime<Utc>,
|
end: DateTime<Utc>,
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
|
||||||
|
|
||||||
// ─── User-contextualized variants (for CalDAV protocol handler) ──
|
|
||||||
async fn create_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar: CreateCalendarDto,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarDto, DomainError>;
|
|
||||||
async fn update_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
update: UpdateCalendarDto,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarDto, DomainError>;
|
|
||||||
async fn delete_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<(), DomainError>;
|
|
||||||
async fn get_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarDto, DomainError>;
|
|
||||||
async fn list_my_calendars_for_user(
|
|
||||||
&self,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<Vec<CalendarDto>, DomainError>;
|
|
||||||
async fn list_events_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
limit: Option<i64>,
|
|
||||||
offset: Option<i64>,
|
|
||||||
user_id: &str,
|
user_id: &str,
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
||||||
async fn get_events_in_range_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
start: DateTime<Utc>,
|
|
||||||
end: DateTime<Utc>,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError>;
|
|
||||||
async fn create_event_from_ical_for_user(
|
|
||||||
&self,
|
|
||||||
event: CreateEventICalDto,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarEventDto, DomainError>;
|
|
||||||
async fn delete_event_for_user(&self, event_id: &str, user_id: &str)
|
|
||||||
-> Result<(), DomainError>;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -138,6 +138,13 @@ pub trait FileManagementUseCase: Send + Sync + 'static {
|
|||||||
folder_id: Option<String>,
|
folder_id: Option<String>,
|
||||||
) -> Result<FileDto, DomainError>;
|
) -> Result<FileDto, DomainError>;
|
||||||
|
|
||||||
|
/// Copies a file to another folder (zero-copy with dedup).
|
||||||
|
async fn copy_file(
|
||||||
|
&self,
|
||||||
|
file_id: &str,
|
||||||
|
target_folder_id: Option<String>,
|
||||||
|
) -> Result<FileDto, DomainError>;
|
||||||
|
|
||||||
/// Renames a file
|
/// Renames a file
|
||||||
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError>;
|
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError>;
|
||||||
|
|
||||||
|
|||||||
@@ -115,6 +115,16 @@ pub trait FileWritePort: Send + Sync + 'static {
|
|||||||
size: u64,
|
size: u64,
|
||||||
) -> Result<(File, PathBuf), DomainError>;
|
) -> Result<(File, PathBuf), DomainError>;
|
||||||
|
|
||||||
|
/// Copies a file to a (possibly different) folder.
|
||||||
|
///
|
||||||
|
/// With blob-dedup, this only creates a new metadata row and increments
|
||||||
|
/// the blob reference count — zero disk I/O for the content.
|
||||||
|
async fn copy_file(
|
||||||
|
&self,
|
||||||
|
file_id: &str,
|
||||||
|
target_folder_id: Option<String>,
|
||||||
|
) -> Result<File, DomainError>;
|
||||||
|
|
||||||
// ── Trash operations ──
|
// ── Trash operations ──
|
||||||
|
|
||||||
/// Moves a file to the trash
|
/// Moves a file to the trash
|
||||||
|
|||||||
@@ -168,7 +168,7 @@ impl AuthApplicationService {
|
|||||||
/// Returns whether OIDC is configured and enabled
|
/// Returns whether OIDC is configured and enabled
|
||||||
pub fn oidc_enabled(&self) -> bool {
|
pub fn oidc_enabled(&self) -> bool {
|
||||||
let state = self.oidc.read().unwrap();
|
let state = self.oidc.read().unwrap();
|
||||||
state.service.is_some() && state.config.as_ref().is_some_and(|c| c.enabled)
|
state.service.is_some() && state.config.as_ref().map_or(false, |c| c.enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns whether password login is disabled (OIDC-only mode)
|
/// Returns whether password login is disabled (OIDC-only mode)
|
||||||
@@ -177,7 +177,7 @@ impl AuthApplicationService {
|
|||||||
state
|
state
|
||||||
.config
|
.config
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.is_some_and(|c| c.disable_password_login)
|
.map_or(false, |c| c.disable_password_login)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a clone of the OIDC config if available
|
/// Returns a clone of the OIDC config if available
|
||||||
@@ -664,11 +664,23 @@ impl AuthApplicationService {
|
|||||||
// Admin quota, capped to available disk space
|
// Admin quota, capped to available disk space
|
||||||
let admin_quota = self.capped_quota(&admin_role);
|
let admin_quota = self.capped_quota(&admin_role);
|
||||||
|
|
||||||
|
// Hash the password (same as register / admin_create_user)
|
||||||
|
let password_hash = self
|
||||||
|
.password_hasher
|
||||||
|
.hash_password(&dto.password)
|
||||||
|
.map_err(|e| {
|
||||||
|
DomainError::new(
|
||||||
|
ErrorKind::InternalError,
|
||||||
|
"User",
|
||||||
|
format!("Error hashing password: {}", e),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
// Create the new admin user
|
// Create the new admin user
|
||||||
let user = User::new(
|
let user = User::new(
|
||||||
dto.username.clone(),
|
dto.username.clone(),
|
||||||
dto.email.clone(),
|
dto.email.clone(),
|
||||||
dto.password.clone(),
|
password_hash,
|
||||||
admin_role,
|
admin_role,
|
||||||
admin_quota,
|
admin_quota,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ impl BatchOperationService {
|
|||||||
// Acquire semaphore permit
|
// Acquire semaphore permit
|
||||||
let permit = semaphore.acquire().await.unwrap();
|
let permit = semaphore.acquire().await.unwrap();
|
||||||
|
|
||||||
let copy_result = mgmt.move_file(&file_id, target_folder.clone()).await;
|
let copy_result = mgmt.copy_file(&file_id, target_folder.clone()).await;
|
||||||
|
|
||||||
// Release the permit explicitly (also released on drop)
|
// Release the permit explicitly (also released on drop)
|
||||||
drop(permit);
|
drop(permit);
|
||||||
|
|||||||
@@ -24,13 +24,8 @@ impl CalendarUseCase for CalendarService {
|
|||||||
async fn create_calendar(
|
async fn create_calendar(
|
||||||
&self,
|
&self,
|
||||||
calendar: CreateCalendarDto,
|
calendar: CreateCalendarDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarDto, DomainError> {
|
) -> Result<CalendarDto, DomainError> {
|
||||||
// This function requires the current user context which will come from middleware
|
|
||||||
// For now, we'll use a dummy implementation that needs to be completed
|
|
||||||
|
|
||||||
// In a real implementation, get user_id from current user context
|
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.create_calendar(calendar, user_id)
|
.create_calendar(calendar, user_id)
|
||||||
.await
|
.await
|
||||||
@@ -40,20 +35,12 @@ impl CalendarUseCase for CalendarService {
|
|||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
update: UpdateCalendarDto,
|
update: UpdateCalendarDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarDto, DomainError> {
|
) -> Result<CalendarDto, DomainError> {
|
||||||
// In a real implementation, we would:
|
|
||||||
// 1. Get the current user ID from middleware
|
|
||||||
// 2. Verify that the user has access to this calendar
|
|
||||||
// 3. Update the calendar if they have permission
|
|
||||||
|
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if user has access
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(calendar_id, user_id)
|
.check_calendar_access(calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access {
|
if !has_access {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -61,21 +48,16 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to update this calendar",
|
"You don't have permission to update this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.update_calendar(calendar_id, update)
|
.update_calendar(calendar_id, update)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete_calendar(&self, calendar_id: &str) -> Result<(), DomainError> {
|
async fn delete_calendar(&self, calendar_id: &str, user_id: &str) -> Result<(), DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if user has access
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(calendar_id, user_id)
|
.check_calendar_access(calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access {
|
if !has_access {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -83,22 +65,19 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to delete this calendar",
|
"You don't have permission to delete this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage.delete_calendar(calendar_id).await
|
self.calendar_storage.delete_calendar(calendar_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_calendar(&self, calendar_id: &str) -> Result<CalendarDto, DomainError> {
|
async fn get_calendar(
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
&self,
|
||||||
|
calendar_id: &str,
|
||||||
// Get the calendar
|
user_id: &str,
|
||||||
|
) -> Result<CalendarDto, DomainError> {
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
||||||
|
|
||||||
// Check if user has access or if calendar is public
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(calendar_id, user_id)
|
.check_calendar_access(calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access && !calendar.is_public {
|
if !has_access && !calendar.is_public {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -106,19 +85,14 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to view this calendar",
|
"You don't have permission to view this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(calendar)
|
Ok(calendar)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_my_calendars(&self) -> Result<Vec<CalendarDto>, DomainError> {
|
async fn list_my_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
self.calendar_storage.list_calendars_by_owner(user_id).await
|
self.calendar_storage.list_calendars_by_owner(user_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_shared_calendars(&self) -> Result<Vec<CalendarDto>, DomainError> {
|
async fn list_shared_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.list_calendars_shared_with_user(user_id)
|
.list_calendars_shared_with_user(user_id)
|
||||||
.await
|
.await
|
||||||
@@ -131,7 +105,6 @@ impl CalendarUseCase for CalendarService {
|
|||||||
) -> Result<Vec<CalendarDto>, DomainError> {
|
) -> Result<Vec<CalendarDto>, DomainError> {
|
||||||
let limit = limit.unwrap_or(100);
|
let limit = limit.unwrap_or(100);
|
||||||
let offset = offset.unwrap_or(0);
|
let offset = offset.unwrap_or(0);
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.list_public_calendars(limit, offset)
|
.list_public_calendars(limit, offset)
|
||||||
.await
|
.await
|
||||||
@@ -140,24 +113,18 @@ impl CalendarUseCase for CalendarService {
|
|||||||
async fn share_calendar(
|
async fn share_calendar(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
user_id: &str,
|
target_user_id: &str,
|
||||||
access_level: &str,
|
access_level: &str,
|
||||||
|
caller_user_id: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let current_user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if current user has access
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
||||||
|
if calendar.owner_id != caller_user_id {
|
||||||
// Only the owner can share the calendar
|
|
||||||
if calendar.owner_id != current_user_id {
|
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
"Calendar",
|
"Calendar",
|
||||||
"Only the calendar owner can change sharing settings",
|
"Only the calendar owner can change sharing settings",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate access_level
|
|
||||||
match access_level {
|
match access_level {
|
||||||
"read" | "write" | "owner" => {}
|
"read" | "write" | "owner" => {}
|
||||||
_ => {
|
_ => {
|
||||||
@@ -171,66 +138,55 @@ impl CalendarUseCase for CalendarService {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.share_calendar(calendar_id, user_id, access_level)
|
.share_calendar(calendar_id, target_user_id, access_level)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn remove_calendar_sharing(
|
async fn remove_calendar_sharing(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
user_id: &str,
|
target_user_id: &str,
|
||||||
|
caller_user_id: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
let current_user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if current user has access
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
||||||
|
if calendar.owner_id != caller_user_id {
|
||||||
// Only the owner can change sharing settings
|
|
||||||
if calendar.owner_id != current_user_id {
|
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
"Calendar",
|
"Calendar",
|
||||||
"Only the calendar owner can change sharing settings",
|
"Only the calendar owner can change sharing settings",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.remove_calendar_sharing(calendar_id, user_id)
|
.remove_calendar_sharing(calendar_id, target_user_id)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_calendar_shares(
|
async fn get_calendar_shares(
|
||||||
&self,
|
&self,
|
||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<Vec<(String, String)>, DomainError> {
|
) -> Result<Vec<(String, String)>, DomainError> {
|
||||||
let current_user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if current user has access
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
||||||
|
if calendar.owner_id != user_id {
|
||||||
// Only the owner can view sharing settings
|
|
||||||
if calendar.owner_id != current_user_id {
|
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
"Calendar",
|
"Calendar",
|
||||||
"Only the calendar owner can view sharing settings",
|
"Only the calendar owner can view sharing settings",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage.get_calendar_shares(calendar_id).await
|
self.calendar_storage.get_calendar_shares(calendar_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_event(&self, event: CreateEventDto) -> Result<CalendarEventDto, DomainError> {
|
async fn create_event(
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
&self,
|
||||||
|
event: CreateEventDto,
|
||||||
// Check if user has access to the calendar
|
user_id: &str,
|
||||||
|
) -> Result<CalendarEventDto, DomainError> {
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
.check_calendar_access(&event.calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access {
|
if !has_access {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -238,22 +194,18 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to add events to this calendar",
|
"You don't have permission to add events to this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage.create_event(event).await
|
self.calendar_storage.create_event(event).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_event_from_ical(
|
async fn create_event_from_ical(
|
||||||
&self,
|
&self,
|
||||||
event: CreateEventICalDto,
|
event: CreateEventICalDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarEventDto, DomainError> {
|
) -> Result<CalendarEventDto, DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if user has access to the calendar
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
.check_calendar_access(&event.calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access {
|
if !has_access {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -261,7 +213,6 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to add events to this calendar",
|
"You don't have permission to add events to this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage.create_event_from_ical(event).await
|
self.calendar_storage.create_event_from_ical(event).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,18 +220,13 @@ impl CalendarUseCase for CalendarService {
|
|||||||
&self,
|
&self,
|
||||||
event_id: &str,
|
event_id: &str,
|
||||||
update: UpdateEventDto,
|
update: UpdateEventDto,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<CalendarEventDto, DomainError> {
|
) -> Result<CalendarEventDto, DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Get the event to find its calendar
|
|
||||||
let event = self.calendar_storage.get_event(event_id).await?;
|
let event = self.calendar_storage.get_event(event_id).await?;
|
||||||
|
|
||||||
// Check if user has access to the calendar
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
.check_calendar_access(&event.calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access {
|
if !has_access {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -288,22 +234,15 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to update events in this calendar",
|
"You don't have permission to update events in this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage.update_event(event_id, update).await
|
self.calendar_storage.update_event(event_id, update).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete_event(&self, event_id: &str) -> Result<(), DomainError> {
|
async fn delete_event(&self, event_id: &str, user_id: &str) -> Result<(), DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Get the event to find its calendar
|
|
||||||
let event = self.calendar_storage.get_event(event_id).await?;
|
let event = self.calendar_storage.get_event(event_id).await?;
|
||||||
|
|
||||||
// Check if user has access to the calendar
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
.check_calendar_access(&event.calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access {
|
if !has_access {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -311,28 +250,23 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to delete events in this calendar",
|
"You don't have permission to delete events in this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
self.calendar_storage.delete_event(event_id).await
|
self.calendar_storage.delete_event(event_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_event(&self, event_id: &str) -> Result<CalendarEventDto, DomainError> {
|
async fn get_event(
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
&self,
|
||||||
|
event_id: &str,
|
||||||
// Get the event
|
user_id: &str,
|
||||||
|
) -> Result<CalendarEventDto, DomainError> {
|
||||||
let event = self.calendar_storage.get_event(event_id).await?;
|
let event = self.calendar_storage.get_event(event_id).await?;
|
||||||
|
|
||||||
// Check if user has access to the calendar
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
.check_calendar_access(&event.calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Check if calendar is public
|
|
||||||
let calendar = self
|
let calendar = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.get_calendar(&event.calendar_id)
|
.get_calendar(&event.calendar_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if !has_access && !calendar.is_public {
|
if !has_access && !calendar.is_public {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -340,7 +274,6 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to view events in this calendar",
|
"You don't have permission to view events in this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(event)
|
Ok(event)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -349,18 +282,13 @@ impl CalendarUseCase for CalendarService {
|
|||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
limit: Option<i64>,
|
limit: Option<i64>,
|
||||||
offset: Option<i64>,
|
offset: Option<i64>,
|
||||||
|
user_id: &str,
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError> {
|
) -> Result<Vec<CalendarEventDto>, DomainError> {
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if user has access to the calendar
|
|
||||||
let has_access = self
|
let has_access = self
|
||||||
.calendar_storage
|
.calendar_storage
|
||||||
.check_calendar_access(calendar_id, user_id)
|
.check_calendar_access(calendar_id, user_id)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// Check if calendar is public
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
||||||
|
|
||||||
if !has_access && !calendar.is_public {
|
if !has_access && !calendar.is_public {
|
||||||
return Err(DomainError::new(
|
return Err(DomainError::new(
|
||||||
ErrorKind::AccessDenied,
|
ErrorKind::AccessDenied,
|
||||||
@@ -368,12 +296,9 @@ impl CalendarUseCase for CalendarService {
|
|||||||
"You don't have permission to view events in this calendar",
|
"You don't have permission to view events in this calendar",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use pagination if provided
|
|
||||||
if limit.is_some() || offset.is_some() {
|
if limit.is_some() || offset.is_some() {
|
||||||
let limit = limit.unwrap_or(100);
|
let limit = limit.unwrap_or(100);
|
||||||
let offset = offset.unwrap_or(0);
|
let offset = offset.unwrap_or(0);
|
||||||
|
|
||||||
self.calendar_storage
|
self.calendar_storage
|
||||||
.list_events_by_calendar_paginated(calendar_id, limit, offset)
|
.list_events_by_calendar_paginated(calendar_id, limit, offset)
|
||||||
.await
|
.await
|
||||||
@@ -389,148 +314,6 @@ impl CalendarUseCase for CalendarService {
|
|||||||
calendar_id: &str,
|
calendar_id: &str,
|
||||||
start: DateTime<Utc>,
|
start: DateTime<Utc>,
|
||||||
end: DateTime<Utc>,
|
end: DateTime<Utc>,
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError> {
|
|
||||||
let user_id = "current_user_id"; // This should come from middleware
|
|
||||||
|
|
||||||
// Check if user has access to the calendar
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Check if calendar is public
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
|
||||||
|
|
||||||
if !has_access && !calendar.is_public {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to view events in this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
self.calendar_storage
|
|
||||||
.get_events_in_time_range(calendar_id, &start, &end)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── User-contextualized variants (for CalDAV protocol handler) ──
|
|
||||||
|
|
||||||
async fn create_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar: CreateCalendarDto,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarDto, DomainError> {
|
|
||||||
self.calendar_storage
|
|
||||||
.create_calendar(calendar, user_id)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn update_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
update: UpdateCalendarDto,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarDto, DomainError> {
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
if !has_access {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to update this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
self.calendar_storage
|
|
||||||
.update_calendar(calendar_id, update)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
if !has_access {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to delete this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
self.calendar_storage.delete_calendar(calendar_id).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_calendar_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarDto, DomainError> {
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
if !has_access && !calendar.is_public {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to view this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(calendar)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list_my_calendars_for_user(
|
|
||||||
&self,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<Vec<CalendarDto>, DomainError> {
|
|
||||||
self.calendar_storage.list_calendars_by_owner(user_id).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn list_events_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
limit: Option<i64>,
|
|
||||||
offset: Option<i64>,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError> {
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
|
|
||||||
if !has_access && !calendar.is_public {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to view events in this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if limit.is_some() || offset.is_some() {
|
|
||||||
let limit = limit.unwrap_or(100);
|
|
||||||
let offset = offset.unwrap_or(0);
|
|
||||||
self.calendar_storage
|
|
||||||
.list_events_by_calendar_paginated(calendar_id, limit, offset)
|
|
||||||
.await
|
|
||||||
} else {
|
|
||||||
self.calendar_storage
|
|
||||||
.list_events_by_calendar(calendar_id)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_events_in_range_for_user(
|
|
||||||
&self,
|
|
||||||
calendar_id: &str,
|
|
||||||
start: DateTime<Utc>,
|
|
||||||
end: DateTime<Utc>,
|
|
||||||
user_id: &str,
|
user_id: &str,
|
||||||
) -> Result<Vec<CalendarEventDto>, DomainError> {
|
) -> Result<Vec<CalendarEventDto>, DomainError> {
|
||||||
let has_access = self
|
let has_access = self
|
||||||
@@ -549,43 +332,4 @@ impl CalendarUseCase for CalendarService {
|
|||||||
.get_events_in_time_range(calendar_id, &start, &end)
|
.get_events_in_time_range(calendar_id, &start, &end)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_event_from_ical_for_user(
|
|
||||||
&self,
|
|
||||||
event: CreateEventICalDto,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<CalendarEventDto, DomainError> {
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
if !has_access {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to add events to this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
self.calendar_storage.create_event_from_ical(event).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn delete_event_for_user(
|
|
||||||
&self,
|
|
||||||
event_id: &str,
|
|
||||||
user_id: &str,
|
|
||||||
) -> Result<(), DomainError> {
|
|
||||||
let event = self.calendar_storage.get_event(event_id).await?;
|
|
||||||
let has_access = self
|
|
||||||
.calendar_storage
|
|
||||||
.check_calendar_access(&event.calendar_id, user_id)
|
|
||||||
.await?;
|
|
||||||
if !has_access {
|
|
||||||
return Err(DomainError::new(
|
|
||||||
ErrorKind::AccessDenied,
|
|
||||||
"Calendar",
|
|
||||||
"You don't have permission to delete events in this calendar",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
self.calendar_storage.delete_event(event_id).await
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,6 +121,35 @@ impl FileManagementUseCase for FileManagementService {
|
|||||||
Ok(FileDto::from(moved_file))
|
Ok(FileDto::from(moved_file))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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> {
|
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError> {
|
||||||
info!("Renaming file with ID: {} to \"{}\"", file_id, new_name);
|
info!("Renaming file with ID: {} to \"{}\"", file_id, new_name);
|
||||||
|
|
||||||
|
|||||||
+224
-132
@@ -1,50 +1,54 @@
|
|||||||
|
use sqlx::PgPool;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use sqlx::PgPool;
|
|
||||||
|
|
||||||
use crate::application::services::auth_application_service::AuthApplicationService;
|
|
||||||
use crate::application::services::admin_settings_service::AdminSettingsService;
|
use crate::application::services::admin_settings_service::AdminSettingsService;
|
||||||
|
use crate::application::services::auth_application_service::AuthApplicationService;
|
||||||
|
|
||||||
use crate::infrastructure::services::path_service::PathService;
|
|
||||||
use crate::infrastructure::repositories::share_fs_repository::ShareFsRepository;
|
|
||||||
use crate::infrastructure::repositories::pg::{
|
|
||||||
FolderDbRepository, FileBlobReadRepository, FileBlobWriteRepository, TrashDbRepository,
|
|
||||||
};
|
|
||||||
use crate::infrastructure::services::file_system_i18n_service::FileSystemI18nService;
|
|
||||||
use crate::infrastructure::services::file_content_cache::{FileContentCache, FileContentCacheConfig};
|
|
||||||
use crate::infrastructure::services::trash_cleanup_service::TrashCleanupService;
|
|
||||||
use crate::application::services::folder_service::FolderService;
|
|
||||||
use crate::application::services::i18n_application_service::I18nApplicationService;
|
|
||||||
use crate::application::services::trash_service::TrashService;
|
|
||||||
use crate::application::services::search_service::SearchService;
|
|
||||||
use crate::application::services::share_service::ShareService;
|
|
||||||
use crate::application::services::favorites_service::FavoritesService;
|
|
||||||
use crate::application::services::recent_service::RecentService;
|
|
||||||
use crate::application::ports::trash_ports::TrashUseCase;
|
|
||||||
use crate::application::ports::inbound::{FolderUseCase, SearchUseCase};
|
|
||||||
use crate::application::ports::outbound::FolderStoragePort;
|
|
||||||
use crate::application::ports::favorites_ports::FavoritesUseCase;
|
|
||||||
use crate::application::ports::recent_ports::RecentItemsUseCase;
|
|
||||||
use crate::application::ports::file_ports::{FileUploadUseCase, FileRetrievalUseCase, FileManagementUseCase, FileUseCaseFactory};
|
|
||||||
use crate::application::ports::storage_ports::{FileReadPort, FileWritePort};
|
|
||||||
use crate::application::services::{FileUploadService, FileRetrievalService, FileManagementService, AppFileUseCaseFactory};
|
|
||||||
use crate::common::errors::DomainError;
|
|
||||||
use crate::domain::services::i18n_service::I18nService;
|
|
||||||
use crate::common::config::AppConfig;
|
|
||||||
use crate::application::ports::cache_ports::ContentCachePort;
|
use crate::application::ports::cache_ports::ContentCachePort;
|
||||||
use crate::application::ports::thumbnail_ports::ThumbnailPort;
|
|
||||||
use crate::application::ports::transcode_ports::ImageTranscodePort;
|
|
||||||
use crate::application::ports::dedup_ports::DedupPort;
|
|
||||||
use crate::application::ports::chunked_upload_ports::ChunkedUploadPort;
|
use crate::application::ports::chunked_upload_ports::ChunkedUploadPort;
|
||||||
use crate::application::ports::compression_ports::CompressionPort;
|
use crate::application::ports::compression_ports::CompressionPort;
|
||||||
|
use crate::application::ports::dedup_ports::DedupPort;
|
||||||
|
use crate::application::ports::favorites_ports::FavoritesUseCase;
|
||||||
|
use crate::application::ports::file_ports::{
|
||||||
|
FileManagementUseCase, FileRetrievalUseCase, FileUploadUseCase, FileUseCaseFactory,
|
||||||
|
};
|
||||||
|
use crate::application::ports::inbound::{FolderUseCase, SearchUseCase};
|
||||||
|
use crate::application::ports::outbound::FolderStoragePort;
|
||||||
|
use crate::application::ports::recent_ports::RecentItemsUseCase;
|
||||||
|
use crate::application::ports::storage_ports::{FileReadPort, FileWritePort};
|
||||||
|
use crate::application::ports::thumbnail_ports::ThumbnailPort;
|
||||||
|
use crate::application::ports::transcode_ports::ImageTranscodePort;
|
||||||
|
use crate::application::ports::trash_ports::TrashUseCase;
|
||||||
use crate::application::ports::zip_ports::ZipPort;
|
use crate::application::ports::zip_ports::ZipPort;
|
||||||
|
use crate::application::services::favorites_service::FavoritesService;
|
||||||
|
use crate::application::services::folder_service::FolderService;
|
||||||
|
use crate::application::services::i18n_application_service::I18nApplicationService;
|
||||||
|
use crate::application::services::recent_service::RecentService;
|
||||||
|
use crate::application::services::search_service::SearchService;
|
||||||
|
use crate::application::services::share_service::ShareService;
|
||||||
|
use crate::application::services::trash_service::TrashService;
|
||||||
|
use crate::application::services::{
|
||||||
|
AppFileUseCaseFactory, FileManagementService, FileRetrievalService, FileUploadService,
|
||||||
|
};
|
||||||
|
use crate::common::config::AppConfig;
|
||||||
|
use crate::common::errors::DomainError;
|
||||||
|
use crate::domain::services::i18n_service::I18nService;
|
||||||
|
use crate::infrastructure::repositories::pg::{
|
||||||
|
FileBlobReadRepository, FileBlobWriteRepository, FolderDbRepository, TrashDbRepository,
|
||||||
|
};
|
||||||
|
use crate::infrastructure::repositories::share_fs_repository::ShareFsRepository;
|
||||||
|
use crate::infrastructure::services::file_content_cache::{
|
||||||
|
FileContentCache, FileContentCacheConfig,
|
||||||
|
};
|
||||||
|
use crate::infrastructure::services::file_system_i18n_service::FileSystemI18nService;
|
||||||
|
use crate::infrastructure::services::path_service::PathService;
|
||||||
|
use crate::infrastructure::services::trash_cleanup_service::TrashCleanupService;
|
||||||
|
|
||||||
use crate::common::stubs::{
|
use crate::common::stubs::{
|
||||||
StubZipPort, StubCompressionPort,
|
StubCompressionPort, StubDedupPort, StubFileManagementUseCase, StubFileReadPort,
|
||||||
StubFileReadPort, StubFileWritePort, StubFolderStoragePort,
|
StubFileRetrievalUseCase, StubFileUploadUseCase, StubFileUseCaseFactory, StubFileWritePort,
|
||||||
StubI18nService, StubFolderUseCase, StubFileUploadUseCase,
|
StubFolderStoragePort, StubFolderUseCase, StubI18nService, StubSearchUseCase, StubZipPort,
|
||||||
StubFileRetrievalUseCase, StubFileManagementUseCase, StubFileUseCaseFactory,
|
|
||||||
StubSearchUseCase, StubDedupPort,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Factory for the different application components
|
/// Factory for the different application components
|
||||||
@@ -89,7 +93,10 @@ impl AppServiceFactory {
|
|||||||
/// Initializes the core system services.
|
/// Initializes the core system services.
|
||||||
///
|
///
|
||||||
/// Requires a `PgPool` because `DedupService` stores its index in PostgreSQL.
|
/// Requires a `PgPool` because `DedupService` stores its index in PostgreSQL.
|
||||||
pub async fn create_core_services(&self, db_pool: &Arc<PgPool>) -> Result<CoreServices, DomainError> {
|
pub async fn create_core_services(
|
||||||
|
&self,
|
||||||
|
db_pool: &Arc<PgPool>,
|
||||||
|
) -> Result<CoreServices, DomainError> {
|
||||||
// Path service (still needed for blob storage root + thumbnails)
|
// Path service (still needed for blob storage root + thumbnails)
|
||||||
let path_service = Arc::new(PathService::new(self.storage_path.clone()));
|
let path_service = Arc::new(PathService::new(self.storage_path.clone()));
|
||||||
|
|
||||||
@@ -107,7 +114,7 @@ impl AppServiceFactory {
|
|||||||
&self.storage_path,
|
&self.storage_path,
|
||||||
5000, // max 5000 thumbnails in cache
|
5000, // max 5000 thumbnails in cache
|
||||||
100 * 1024 * 1024, // max 100MB cache
|
100 * 1024 * 1024, // max 100MB cache
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
// Initialize thumbnail directories
|
// Initialize thumbnail directories
|
||||||
thumbnail_service.initialize().await?;
|
thumbnail_service.initialize().await?;
|
||||||
@@ -115,7 +122,9 @@ impl AppServiceFactory {
|
|||||||
// Chunked upload service for large files (>10MB)
|
// Chunked upload service for large files (>10MB)
|
||||||
let chunked_temp_dir = std::path::PathBuf::from(&self.storage_path).join(".uploads");
|
let chunked_temp_dir = std::path::PathBuf::from(&self.storage_path).join(".uploads");
|
||||||
let chunked_upload_service = Arc::new(
|
let chunked_upload_service = Arc::new(
|
||||||
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(chunked_temp_dir)
|
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(
|
||||||
|
chunked_temp_dir,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Image transcoding service for automatic WebP conversion
|
// Image transcoding service for automatic WebP conversion
|
||||||
@@ -124,22 +133,27 @@ impl AppServiceFactory {
|
|||||||
&self.storage_path,
|
&self.storage_path,
|
||||||
2000, // max 2000 transcoded images in cache
|
2000, // max 2000 transcoded images in cache
|
||||||
50 * 1024 * 1024, // max 50MB in-memory cache
|
50 * 1024 * 1024, // max 50MB in-memory cache
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
image_transcode_service.initialize().await?;
|
image_transcode_service.initialize().await?;
|
||||||
|
|
||||||
// Deduplication service — PRIMARY blob storage engine (PostgreSQL-backed index)
|
// Deduplication service — PRIMARY blob storage engine (PostgreSQL-backed index)
|
||||||
let dedup_service = Arc::new(
|
let dedup_service = Arc::new(
|
||||||
crate::infrastructure::services::dedup_service::DedupService::new(&self.storage_path, db_pool.clone())
|
crate::infrastructure::services::dedup_service::DedupService::new(
|
||||||
|
&self.storage_path,
|
||||||
|
db_pool.clone(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
dedup_service.initialize().await?;
|
dedup_service.initialize().await?;
|
||||||
|
|
||||||
// Compression service (gzip)
|
// Compression service (gzip)
|
||||||
let compression_service: Arc<dyn CompressionPort> = Arc::new(
|
let compression_service: Arc<dyn CompressionPort> = Arc::new(
|
||||||
crate::infrastructure::services::compression_service::GzipCompressionService::new()
|
crate::infrastructure::services::compression_service::GzipCompressionService::new(),
|
||||||
);
|
);
|
||||||
|
|
||||||
tracing::info!("Core services initialized: path service, file content cache, thumbnails, chunked upload, image transcode, dedup (PRIMARY blob storage), compression");
|
tracing::info!(
|
||||||
|
"Core services initialized: path service, file content cache, thumbnails, chunked upload, image transcode, dedup (PRIMARY blob storage), compression"
|
||||||
|
);
|
||||||
|
|
||||||
Ok(CoreServices {
|
Ok(CoreServices {
|
||||||
path_service,
|
path_service,
|
||||||
@@ -157,7 +171,11 @@ impl AppServiceFactory {
|
|||||||
/// Initializes the repository services (blob-storage model).
|
/// Initializes the repository services (blob-storage model).
|
||||||
///
|
///
|
||||||
/// Requires a PgPool since all metadata lives in PostgreSQL.
|
/// Requires a PgPool since all metadata lives in PostgreSQL.
|
||||||
pub fn create_repository_services(&self, core: &CoreServices, db_pool: &Arc<PgPool>) -> RepositoryServices {
|
pub fn create_repository_services(
|
||||||
|
&self,
|
||||||
|
core: &CoreServices,
|
||||||
|
db_pool: &Arc<PgPool>,
|
||||||
|
) -> RepositoryServices {
|
||||||
// Folder repository — PostgreSQL-backed virtual folders
|
// Folder repository — PostgreSQL-backed virtual folders
|
||||||
let folder_repo_concrete = Arc::new(FolderDbRepository::new(db_pool.clone()));
|
let folder_repo_concrete = Arc::new(FolderDbRepository::new(db_pool.clone()));
|
||||||
let folder_repository: Arc<dyn FolderStoragePort> = folder_repo_concrete.clone();
|
let folder_repository: Arc<dyn FolderStoragePort> = folder_repo_concrete.clone();
|
||||||
@@ -176,21 +194,24 @@ impl AppServiceFactory {
|
|||||||
));
|
));
|
||||||
|
|
||||||
// I18n repository
|
// I18n repository
|
||||||
let i18n_repository = Arc::new(FileSystemI18nService::new(
|
let i18n_repository = Arc::new(FileSystemI18nService::new(self.locales_path.clone()));
|
||||||
self.locales_path.clone()
|
|
||||||
));
|
|
||||||
|
|
||||||
// Trash repository — reads soft-delete flags from storage.files/folders
|
// Trash repository — reads soft-delete flags from storage.files/folders
|
||||||
let trash_repository = if core.config.features.enable_trash {
|
let trash_repository = if core.config.features.enable_trash {
|
||||||
Some(Arc::new(TrashDbRepository::new(
|
Some(Arc::new(TrashDbRepository::new(
|
||||||
db_pool.clone(),
|
db_pool.clone(),
|
||||||
core.config.storage.trash_retention_days,
|
core.config.storage.trash_retention_days,
|
||||||
)) as Arc<dyn crate::domain::repositories::trash_repository::TrashRepository>)
|
))
|
||||||
|
as Arc<
|
||||||
|
dyn crate::domain::repositories::trash_repository::TrashRepository,
|
||||||
|
>)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
tracing::info!("Repository services initialized with 100% blob storage model (PG metadata + DedupService blobs)");
|
tracing::info!(
|
||||||
|
"Repository services initialized with 100% blob storage model (PG metadata + DedupService blobs)"
|
||||||
|
);
|
||||||
|
|
||||||
RepositoryServices {
|
RepositoryServices {
|
||||||
folder_repository,
|
folder_repository,
|
||||||
@@ -210,9 +231,7 @@ impl AppServiceFactory {
|
|||||||
trash_service: Option<Arc<dyn TrashUseCase>>,
|
trash_service: Option<Arc<dyn TrashUseCase>>,
|
||||||
) -> ApplicationServices {
|
) -> ApplicationServices {
|
||||||
// Main services
|
// Main services
|
||||||
let folder_service = Arc::new(FolderService::new(
|
let folder_service = Arc::new(FolderService::new(repos.folder_repository.clone()));
|
||||||
repos.folder_repository.clone()
|
|
||||||
));
|
|
||||||
|
|
||||||
// Refactored services with all infrastructure ports
|
// Refactored services with all infrastructure ports
|
||||||
// In blob model, dedup is handled by the repository — no separate write-behind needed
|
// In blob model, dedup is handled by the repository — no separate write-behind needed
|
||||||
@@ -237,12 +256,10 @@ impl AppServiceFactory {
|
|||||||
|
|
||||||
let file_use_case_factory = Arc::new(AppFileUseCaseFactory::new(
|
let file_use_case_factory = Arc::new(AppFileUseCaseFactory::new(
|
||||||
repos.file_read_repository.clone(),
|
repos.file_read_repository.clone(),
|
||||||
repos.file_write_repository.clone()
|
repos.file_write_repository.clone(),
|
||||||
));
|
));
|
||||||
|
|
||||||
let i18n_service = Arc::new(I18nApplicationService::new(
|
let i18n_service = Arc::new(I18nApplicationService::new(repos.i18n_repository.clone()));
|
||||||
repos.i18n_repository.clone()
|
|
||||||
));
|
|
||||||
|
|
||||||
// Search service with cache
|
// Search service with cache
|
||||||
let search_service: Option<Arc<dyn SearchUseCase>> = Some(Arc::new(SearchService::new(
|
let search_service: Option<Arc<dyn SearchUseCase>> = Some(Arc::new(SearchService::new(
|
||||||
@@ -316,9 +333,7 @@ impl AppServiceFactory {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let share_repository = Arc::new(ShareFsRepository::new(
|
let share_repository = Arc::new(ShareFsRepository::new(Arc::new(self.config.clone())));
|
||||||
Arc::new(self.config.clone())
|
|
||||||
));
|
|
||||||
|
|
||||||
// Build a password hasher for share password verification
|
// Build a password hasher for share password verification
|
||||||
let password_hasher: Arc<dyn crate::application::ports::auth_ports::PasswordHasherPort> =
|
let password_hasher: Arc<dyn crate::application::ports::auth_ports::PasswordHasherPort> =
|
||||||
@@ -337,12 +352,9 @@ impl AppServiceFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creates the favorites service (requires database)
|
/// Creates the favorites service (requires database)
|
||||||
pub fn create_favorites_service(
|
pub fn create_favorites_service(&self, db_pool: &Arc<PgPool>) -> Arc<dyn FavoritesUseCase> {
|
||||||
&self,
|
|
||||||
db_pool: &Arc<PgPool>,
|
|
||||||
) -> Arc<dyn FavoritesUseCase> {
|
|
||||||
let repo = Arc::new(
|
let repo = Arc::new(
|
||||||
crate::infrastructure::repositories::pg::FavoritesPgRepository::new(db_pool.clone())
|
crate::infrastructure::repositories::pg::FavoritesPgRepository::new(db_pool.clone()),
|
||||||
);
|
);
|
||||||
let service = Arc::new(FavoritesService::new(repo));
|
let service = Arc::new(FavoritesService::new(repo));
|
||||||
tracing::info!("Favorites service initialized");
|
tracing::info!("Favorites service initialized");
|
||||||
@@ -350,16 +362,12 @@ impl AppServiceFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creates the recent items service (requires database)
|
/// Creates the recent items service (requires database)
|
||||||
pub fn create_recent_service(
|
pub fn create_recent_service(&self, db_pool: &Arc<PgPool>) -> Arc<dyn RecentItemsUseCase> {
|
||||||
&self,
|
|
||||||
db_pool: &Arc<PgPool>,
|
|
||||||
) -> Arc<dyn RecentItemsUseCase> {
|
|
||||||
let repo = Arc::new(
|
let repo = Arc::new(
|
||||||
crate::infrastructure::repositories::pg::RecentItemsPgRepository::new(db_pool.clone())
|
crate::infrastructure::repositories::pg::RecentItemsPgRepository::new(db_pool.clone()),
|
||||||
);
|
);
|
||||||
let service = Arc::new(RecentService::new(
|
let service = Arc::new(RecentService::new(
|
||||||
repo,
|
repo, 50, // Maximum recent items per user
|
||||||
50 // Maximum recent items per user
|
|
||||||
));
|
));
|
||||||
tracing::info!("Recent items service initialized");
|
tracing::info!("Recent items service initialized");
|
||||||
service
|
service
|
||||||
@@ -394,13 +402,13 @@ impl AppServiceFactory {
|
|||||||
db_pool: &Arc<PgPool>,
|
db_pool: &Arc<PgPool>,
|
||||||
) -> Arc<dyn crate::application::ports::storage_ports::StorageUsagePort> {
|
) -> Arc<dyn crate::application::ports::storage_ports::StorageUsagePort> {
|
||||||
let user_repository = Arc::new(
|
let user_repository = Arc::new(
|
||||||
crate::infrastructure::repositories::pg::UserPgRepository::new(db_pool.clone())
|
crate::infrastructure::repositories::pg::UserPgRepository::new(db_pool.clone()),
|
||||||
);
|
);
|
||||||
let service = Arc::new(
|
let service = Arc::new(
|
||||||
crate::application::services::storage_usage_service::StorageUsageService::new(
|
crate::application::services::storage_usage_service::StorageUsageService::new(
|
||||||
repos.file_read_repository.clone(),
|
repos.file_read_repository.clone(),
|
||||||
user_repository,
|
user_repository,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
tracing::info!("Storage usage service initialized");
|
tracing::info!("Storage usage service initialized");
|
||||||
service
|
service
|
||||||
@@ -415,7 +423,10 @@ impl AppServiceFactory {
|
|||||||
) -> Result<AppState, DomainError> {
|
) -> Result<AppState, DomainError> {
|
||||||
// Database is REQUIRED in 100% blob storage model
|
// Database is REQUIRED in 100% blob storage model
|
||||||
let pool = db_pool.clone().ok_or_else(|| {
|
let pool = db_pool.clone().ok_or_else(|| {
|
||||||
DomainError::internal_error("Database", "PostgreSQL database is required for blob storage model")
|
DomainError::internal_error(
|
||||||
|
"Database",
|
||||||
|
"PostgreSQL database is required for blob storage model",
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// 1. Core services (PgPool needed for DedupService index)
|
// 1. Core services (PgPool needed for DedupService index)
|
||||||
@@ -437,7 +448,9 @@ impl AppServiceFactory {
|
|||||||
// 6. Database-dependent services (PgPool always available in blob model)
|
// 6. Database-dependent services (PgPool always available in blob model)
|
||||||
let favorites_service: Option<Arc<dyn FavoritesUseCase>>;
|
let favorites_service: Option<Arc<dyn FavoritesUseCase>>;
|
||||||
let recent_service: Option<Arc<dyn RecentItemsUseCase>>;
|
let recent_service: Option<Arc<dyn RecentItemsUseCase>>;
|
||||||
let storage_usage_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>>;
|
let storage_usage_service: Option<
|
||||||
|
Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>,
|
||||||
|
>;
|
||||||
let mut auth_services: Option<crate::common::di::AuthServices> = None;
|
let mut auth_services: Option<crate::common::di::AuthServices> = None;
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -457,7 +470,9 @@ impl AppServiceFactory {
|
|||||||
&self.config,
|
&self.config,
|
||||||
pool.clone(),
|
pool.clone(),
|
||||||
Some(apps.folder_service_concrete.clone()),
|
Some(apps.folder_service_concrete.clone()),
|
||||||
).await {
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(services) => {
|
Ok(services) => {
|
||||||
tracing::info!("Authentication services initialized successfully");
|
tracing::info!("Authentication services initialized successfully");
|
||||||
auth_services = Some(services);
|
auth_services = Some(services);
|
||||||
@@ -477,7 +492,7 @@ impl AppServiceFactory {
|
|||||||
crate::infrastructure::services::zip_service::ZipService::new(
|
crate::infrastructure::services::zip_service::ZipService::new(
|
||||||
apps.file_retrieval_service.clone(),
|
apps.file_retrieval_service.clone(),
|
||||||
apps.folder_service.clone(),
|
apps.folder_service.clone(),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
let mut core = core;
|
let mut core = core;
|
||||||
core.zip_service = zip_service;
|
core.zip_service = zip_service;
|
||||||
@@ -505,7 +520,7 @@ impl AppServiceFactory {
|
|||||||
// 9b. Wire admin settings service when auth is available
|
// 9b. Wire admin settings service when auth is available
|
||||||
if let Some(auth_svc) = &app_state.auth_service {
|
if let Some(auth_svc) = &app_state.auth_service {
|
||||||
let settings_repo = Arc::new(
|
let settings_repo = Arc::new(
|
||||||
crate::infrastructure::repositories::pg::SettingsPgRepository::new(pool.clone())
|
crate::infrastructure::repositories::pg::SettingsPgRepository::new(pool.clone()),
|
||||||
);
|
);
|
||||||
let server_base_url = self.config.base_url();
|
let server_base_url = self.config.base_url();
|
||||||
|
|
||||||
@@ -521,20 +536,30 @@ impl AppServiceFactory {
|
|||||||
|
|
||||||
// Hot-reload OIDC from DB settings if configured
|
// Hot-reload OIDC from DB settings if configured
|
||||||
match admin_svc.load_effective_oidc_config().await {
|
match admin_svc.load_effective_oidc_config().await {
|
||||||
Ok(eff) if eff.enabled && !eff.issuer_url.is_empty()
|
Ok(eff)
|
||||||
&& !eff.client_id.is_empty() && !eff.client_secret.is_empty() =>
|
if eff.enabled
|
||||||
|
&& !eff.issuer_url.is_empty()
|
||||||
|
&& !eff.client_id.is_empty()
|
||||||
|
&& !eff.client_secret.is_empty() =>
|
||||||
{
|
{
|
||||||
let oidc_svc = Arc::new(
|
let oidc_svc = Arc::new(
|
||||||
crate::infrastructure::services::oidc_service::OidcService::new(eff.clone())
|
crate::infrastructure::services::oidc_service::OidcService::new(
|
||||||
|
eff.clone(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
auth_svc.auth_application_service.reload_oidc(oidc_svc, eff);
|
auth_svc.auth_application_service.reload_oidc(oidc_svc, eff);
|
||||||
tracing::info!("OIDC config loaded from admin settings (database)");
|
tracing::info!("OIDC config loaded from admin settings (database)");
|
||||||
}
|
}
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
tracing::info!("No active OIDC config in admin settings — using env vars or defaults");
|
tracing::info!(
|
||||||
|
"No active OIDC config in admin settings — using env vars or defaults"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!("Failed to load OIDC settings from database (table may not exist yet): {}", e);
|
tracing::warn!(
|
||||||
|
"Failed to load OIDC settings from database (table may not exist yet): {}",
|
||||||
|
e
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -544,11 +569,17 @@ impl AppServiceFactory {
|
|||||||
// 10. Wire CalDAV/CardDAV services
|
// 10. Wire CalDAV/CardDAV services
|
||||||
{
|
{
|
||||||
// CalDAV
|
// CalDAV
|
||||||
let calendar_repo: Arc<dyn crate::domain::repositories::calendar_repository::CalendarRepository> = Arc::new(
|
let calendar_repo: Arc<
|
||||||
crate::infrastructure::repositories::pg::CalendarPgRepository::new(pool.clone())
|
dyn crate::domain::repositories::calendar_repository::CalendarRepository,
|
||||||
|
> = Arc::new(
|
||||||
|
crate::infrastructure::repositories::pg::CalendarPgRepository::new(pool.clone()),
|
||||||
);
|
);
|
||||||
let event_repo: Arc<dyn crate::domain::repositories::calendar_event_repository::CalendarEventRepository> = Arc::new(
|
let event_repo: Arc<
|
||||||
crate::infrastructure::repositories::pg::CalendarEventPgRepository::new(pool.clone())
|
dyn crate::domain::repositories::calendar_event_repository::CalendarEventRepository,
|
||||||
|
> = Arc::new(
|
||||||
|
crate::infrastructure::repositories::pg::CalendarEventPgRepository::new(
|
||||||
|
pool.clone(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
let calendar_storage = Arc::new(
|
let calendar_storage = Arc::new(
|
||||||
crate::infrastructure::adapters::calendar_storage_adapter::CalendarStorageAdapter::new(
|
crate::infrastructure::adapters::calendar_storage_adapter::CalendarStorageAdapter::new(
|
||||||
@@ -557,19 +588,32 @@ impl AppServiceFactory {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
let calendar_service = Arc::new(
|
let calendar_service = Arc::new(
|
||||||
crate::application::services::calendar_service::CalendarService::new(calendar_storage)
|
crate::application::services::calendar_service::CalendarService::new(
|
||||||
|
calendar_storage,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
app_state.calendar_use_case = Some(
|
||||||
|
calendar_service
|
||||||
|
as Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>,
|
||||||
);
|
);
|
||||||
app_state.calendar_use_case = Some(calendar_service as Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>);
|
|
||||||
|
|
||||||
// CardDAV
|
// CardDAV
|
||||||
let address_book_repo: Arc<dyn crate::domain::repositories::address_book_repository::AddressBookRepository> = Arc::new(
|
let address_book_repo: Arc<
|
||||||
crate::infrastructure::repositories::pg::AddressBookPgRepository::new(pool.clone())
|
dyn crate::domain::repositories::address_book_repository::AddressBookRepository,
|
||||||
|
> = Arc::new(
|
||||||
|
crate::infrastructure::repositories::pg::AddressBookPgRepository::new(pool.clone()),
|
||||||
);
|
);
|
||||||
let contact_repo: Arc<dyn crate::domain::repositories::contact_repository::ContactRepository> = Arc::new(
|
let contact_repo: Arc<
|
||||||
crate::infrastructure::repositories::pg::ContactPgRepository::new(pool.clone())
|
dyn crate::domain::repositories::contact_repository::ContactRepository,
|
||||||
|
> = Arc::new(
|
||||||
|
crate::infrastructure::repositories::pg::ContactPgRepository::new(pool.clone()),
|
||||||
);
|
);
|
||||||
let group_repo: Arc<dyn crate::domain::repositories::contact_repository::ContactGroupRepository> = Arc::new(
|
let group_repo: Arc<
|
||||||
crate::infrastructure::repositories::pg::ContactGroupPgRepository::new(pool.clone())
|
dyn crate::domain::repositories::contact_repository::ContactGroupRepository,
|
||||||
|
> = Arc::new(
|
||||||
|
crate::infrastructure::repositories::pg::ContactGroupPgRepository::new(
|
||||||
|
pool.clone(),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
let contact_storage = Arc::new(
|
let contact_storage = Arc::new(
|
||||||
crate::infrastructure::adapters::contact_storage_adapter::ContactStorageAdapter::new(
|
crate::infrastructure::adapters::contact_storage_adapter::ContactStorageAdapter::new(
|
||||||
@@ -578,8 +622,12 @@ impl AppServiceFactory {
|
|||||||
group_repo,
|
group_repo,
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
app_state.addressbook_use_case = Some(contact_storage.clone() as Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>);
|
app_state.addressbook_use_case = Some(contact_storage.clone()
|
||||||
app_state.contact_use_case = Some(contact_storage as Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>);
|
as Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>);
|
||||||
|
app_state.contact_use_case = Some(
|
||||||
|
contact_storage
|
||||||
|
as Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>,
|
||||||
|
);
|
||||||
|
|
||||||
tracing::info!("CalDAV and CardDAV services initialized with PostgreSQL repositories");
|
tracing::info!("CalDAV and CardDAV services initialized with PostgreSQL repositories");
|
||||||
}
|
}
|
||||||
@@ -610,7 +658,8 @@ pub struct RepositoryServices {
|
|||||||
pub file_read_repository: Arc<dyn FileReadPort>,
|
pub file_read_repository: Arc<dyn FileReadPort>,
|
||||||
pub file_write_repository: Arc<dyn FileWritePort>,
|
pub file_write_repository: Arc<dyn FileWritePort>,
|
||||||
pub i18n_repository: Arc<dyn I18nService>,
|
pub i18n_repository: Arc<dyn I18nService>,
|
||||||
pub trash_repository: Option<Arc<dyn crate::domain::repositories::trash_repository::TrashRepository>>,
|
pub trash_repository:
|
||||||
|
Option<Arc<dyn crate::domain::repositories::trash_repository::TrashRepository>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Container for application services
|
/// Container for application services
|
||||||
@@ -652,11 +701,14 @@ pub struct AppState {
|
|||||||
pub share_service: Option<Arc<dyn crate::application::ports::share_ports::ShareUseCase>>,
|
pub share_service: Option<Arc<dyn crate::application::ports::share_ports::ShareUseCase>>,
|
||||||
pub favorites_service: Option<Arc<dyn FavoritesUseCase>>,
|
pub favorites_service: Option<Arc<dyn FavoritesUseCase>>,
|
||||||
pub recent_service: Option<Arc<dyn RecentItemsUseCase>>,
|
pub recent_service: Option<Arc<dyn RecentItemsUseCase>>,
|
||||||
pub storage_usage_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>>,
|
pub storage_usage_service:
|
||||||
|
Option<Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>>,
|
||||||
pub calendar_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUseCase>>,
|
pub calendar_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUseCase>>,
|
||||||
pub contact_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUseCase>>,
|
pub contact_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUseCase>>,
|
||||||
pub calendar_use_case: Option<Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>>,
|
pub calendar_use_case:
|
||||||
pub addressbook_use_case: Option<Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>>,
|
Option<Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>>,
|
||||||
|
pub addressbook_use_case:
|
||||||
|
Option<Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>>,
|
||||||
pub contact_use_case: Option<Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>>,
|
pub contact_use_case: Option<Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -668,16 +720,22 @@ impl Default for AppState {
|
|||||||
let config = crate::common::config::AppConfig::default();
|
let config = crate::common::config::AppConfig::default();
|
||||||
let path_service = Arc::new(
|
let path_service = Arc::new(
|
||||||
crate::infrastructure::services::path_service::PathService::new(
|
crate::infrastructure::services::path_service::PathService::new(
|
||||||
std::path::PathBuf::from("./storage")
|
std::path::PathBuf::from("./storage"),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
let i18n_repository = Arc::new(StubI18nService) as Arc<dyn crate::domain::services::i18n_service::I18nService>;
|
let i18n_repository = Arc::new(StubI18nService)
|
||||||
let folder_service = Arc::new(StubFolderUseCase) as Arc<dyn crate::application::ports::inbound::FolderUseCase>;
|
as Arc<dyn crate::domain::services::i18n_service::I18nService>;
|
||||||
let file_upload_service = Arc::new(StubFileUploadUseCase) as Arc<dyn crate::application::ports::file_ports::FileUploadUseCase>;
|
let folder_service = Arc::new(StubFolderUseCase)
|
||||||
let file_retrieval_service = Arc::new(StubFileRetrievalUseCase) as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>;
|
as Arc<dyn crate::application::ports::inbound::FolderUseCase>;
|
||||||
let file_management_service = Arc::new(StubFileManagementUseCase) as Arc<dyn crate::application::ports::file_ports::FileManagementUseCase>;
|
let file_upload_service = Arc::new(StubFileUploadUseCase)
|
||||||
let file_use_case_factory = Arc::new(StubFileUseCaseFactory) as Arc<dyn crate::application::ports::file_ports::FileUseCaseFactory>;
|
as Arc<dyn crate::application::ports::file_ports::FileUploadUseCase>;
|
||||||
|
let file_retrieval_service = Arc::new(StubFileRetrievalUseCase)
|
||||||
|
as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>;
|
||||||
|
let file_management_service = Arc::new(StubFileManagementUseCase)
|
||||||
|
as Arc<dyn crate::application::ports::file_ports::FileManagementUseCase>;
|
||||||
|
let file_use_case_factory = Arc::new(StubFileUseCaseFactory)
|
||||||
|
as Arc<dyn crate::application::ports::file_ports::FileUseCaseFactory>;
|
||||||
|
|
||||||
// Create file content cache for stub
|
// Create file content cache for stub
|
||||||
let file_content_cache = Arc::new(FileContentCache::new(FileContentCacheConfig::default()));
|
let file_content_cache = Arc::new(FileContentCache::new(FileContentCacheConfig::default()));
|
||||||
@@ -688,14 +746,14 @@ impl Default for AppState {
|
|||||||
&std::path::PathBuf::from("./storage"),
|
&std::path::PathBuf::from("./storage"),
|
||||||
100,
|
100,
|
||||||
10 * 1024 * 1024,
|
10 * 1024 * 1024,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Create dummy chunked upload service
|
// Create dummy chunked upload service
|
||||||
let dummy_chunked_upload_service: Arc<dyn ChunkedUploadPort> = Arc::new(
|
let dummy_chunked_upload_service: Arc<dyn ChunkedUploadPort> = Arc::new(
|
||||||
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(
|
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(
|
||||||
std::path::PathBuf::from("./storage/.uploads")
|
std::path::PathBuf::from("./storage/.uploads"),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Create dummy image transcode service
|
// Create dummy image transcode service
|
||||||
@@ -704,7 +762,7 @@ impl Default for AppState {
|
|||||||
&std::path::PathBuf::from("./storage"),
|
&std::path::PathBuf::from("./storage"),
|
||||||
100,
|
100,
|
||||||
10 * 1024 * 1024,
|
10 * 1024 * 1024,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Stub dedup service (Default is only used for routing stubs, never for real I/O)
|
// Stub dedup service (Default is only used for routing stubs, never for real I/O)
|
||||||
@@ -729,21 +787,27 @@ impl Default for AppState {
|
|||||||
|
|
||||||
// Repository services using stubs
|
// Repository services using stubs
|
||||||
let repository_services = RepositoryServices {
|
let repository_services = RepositoryServices {
|
||||||
folder_repository: Arc::new(StubFolderStoragePort) as Arc<dyn crate::application::ports::outbound::FolderStoragePort>,
|
folder_repository: Arc::new(StubFolderStoragePort)
|
||||||
|
as Arc<dyn crate::application::ports::outbound::FolderStoragePort>,
|
||||||
folder_repo_concrete: dummy_folder_repo_concrete,
|
folder_repo_concrete: dummy_folder_repo_concrete,
|
||||||
file_read_repository: Arc::new(StubFileReadPort) as Arc<dyn crate::application::ports::storage_ports::FileReadPort>,
|
file_read_repository: Arc::new(StubFileReadPort)
|
||||||
file_write_repository: Arc::new(StubFileWritePort) as Arc<dyn crate::application::ports::storage_ports::FileWritePort>,
|
as Arc<dyn crate::application::ports::storage_ports::FileReadPort>,
|
||||||
|
file_write_repository: Arc::new(StubFileWritePort)
|
||||||
|
as Arc<dyn crate::application::ports::storage_ports::FileWritePort>,
|
||||||
i18n_repository,
|
i18n_repository,
|
||||||
trash_repository: None,
|
trash_repository: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Dummy concrete services for compatibility
|
// Dummy concrete services for compatibility
|
||||||
let dummy_folder_storage = Arc::new(StubFolderStoragePort) as Arc<dyn crate::application::ports::outbound::FolderStoragePort>;
|
let dummy_folder_storage = Arc::new(StubFolderStoragePort)
|
||||||
|
as Arc<dyn crate::application::ports::outbound::FolderStoragePort>;
|
||||||
let folder_service_concrete = Arc::new(FolderService::new(dummy_folder_storage));
|
let folder_service_concrete = Arc::new(FolderService::new(dummy_folder_storage));
|
||||||
|
|
||||||
// Dummy I18nApplicationService
|
// Dummy I18nApplicationService
|
||||||
let dummy_i18n_app_service = crate::application::services::i18n_application_service::I18nApplicationService::new(
|
let dummy_i18n_app_service =
|
||||||
Arc::new(StubI18nService) as Arc<dyn crate::domain::services::i18n_service::I18nService>
|
crate::application::services::i18n_application_service::I18nApplicationService::new(
|
||||||
|
Arc::new(StubI18nService)
|
||||||
|
as Arc<dyn crate::domain::services::i18n_service::I18nService>,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Application services using stubs
|
// Application services using stubs
|
||||||
@@ -756,7 +820,8 @@ impl Default for AppState {
|
|||||||
file_use_case_factory,
|
file_use_case_factory,
|
||||||
i18n_service: Arc::new(dummy_i18n_app_service),
|
i18n_service: Arc::new(dummy_i18n_app_service),
|
||||||
trash_service: None,
|
trash_service: None,
|
||||||
search_service: Some(Arc::new(StubSearchUseCase) as Arc<dyn crate::application::ports::inbound::SearchUseCase>),
|
search_service: Some(Arc::new(StubSearchUseCase)
|
||||||
|
as Arc<dyn crate::application::ports::inbound::SearchUseCase>),
|
||||||
share_service: None,
|
share_service: None,
|
||||||
favorites_service: None,
|
favorites_service: None,
|
||||||
recent_service: None,
|
recent_service: None,
|
||||||
@@ -821,11 +886,15 @@ impl AppState {
|
|||||||
/// This keeps `routes.rs` free of any `crate::infrastructure` references.
|
/// This keeps `routes.rs` free of any `crate::infrastructure` references.
|
||||||
pub fn for_routing(
|
pub fn for_routing(
|
||||||
folder_service: Arc<FolderService>,
|
folder_service: Arc<FolderService>,
|
||||||
file_retrieval_service: Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>,
|
file_retrieval_service: Arc<
|
||||||
|
dyn crate::application::ports::file_ports::FileRetrievalUseCase,
|
||||||
|
>,
|
||||||
file_upload_service: Arc<dyn FileUploadUseCase>,
|
file_upload_service: Arc<dyn FileUploadUseCase>,
|
||||||
file_management_service: Arc<dyn FileManagementUseCase>,
|
file_management_service: Arc<dyn FileManagementUseCase>,
|
||||||
folder_use_case: Arc<dyn crate::application::ports::inbound::FolderUseCase>,
|
folder_use_case: Arc<dyn crate::application::ports::inbound::FolderUseCase>,
|
||||||
i18n_service: Option<Arc<crate::application::services::i18n_application_service::I18nApplicationService>>,
|
i18n_service: Option<
|
||||||
|
Arc<crate::application::services::i18n_application_service::I18nApplicationService>,
|
||||||
|
>,
|
||||||
trash_service: Option<Arc<dyn TrashUseCase>>,
|
trash_service: Option<Arc<dyn TrashUseCase>>,
|
||||||
search_service: Option<Arc<dyn crate::application::ports::inbound::SearchUseCase>>,
|
search_service: Option<Arc<dyn crate::application::ports::inbound::SearchUseCase>>,
|
||||||
share_service: Option<Arc<dyn crate::application::ports::share_ports::ShareUseCase>>,
|
share_service: Option<Arc<dyn crate::application::ports::share_ports::ShareUseCase>>,
|
||||||
@@ -860,9 +929,11 @@ impl AppState {
|
|||||||
// Create real ZipService with the actual file/folder services
|
// Create real ZipService with the actual file/folder services
|
||||||
state.core.zip_service = Arc::new(
|
state.core.zip_service = Arc::new(
|
||||||
crate::infrastructure::services::zip_service::ZipService::new(
|
crate::infrastructure::services::zip_service::ZipService::new(
|
||||||
file_retrieval_service as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>,
|
file_retrieval_service
|
||||||
folder_service.clone() as Arc<dyn crate::application::ports::inbound::FolderUseCase>,
|
as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>,
|
||||||
)
|
folder_service.clone()
|
||||||
|
as Arc<dyn crate::application::ports::inbound::FolderUseCase>,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
state
|
state
|
||||||
@@ -878,7 +949,10 @@ impl AppState {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_share_service(mut self, share_service: Arc<dyn crate::application::ports::share_ports::ShareUseCase>) -> Self {
|
pub fn with_share_service(
|
||||||
|
mut self,
|
||||||
|
share_service: Arc<dyn crate::application::ports::share_ports::ShareUseCase>,
|
||||||
|
) -> Self {
|
||||||
self.share_service = Some(share_service);
|
self.share_service = Some(share_service);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@@ -893,32 +967,50 @@ impl AppState {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_storage_usage_service(mut self, storage_usage_service: Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>) -> Self {
|
pub fn with_storage_usage_service(
|
||||||
|
mut self,
|
||||||
|
storage_usage_service: Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>,
|
||||||
|
) -> Self {
|
||||||
self.storage_usage_service = Some(storage_usage_service);
|
self.storage_usage_service = Some(storage_usage_service);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_calendar_service(mut self, calendar_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>) -> Self {
|
pub fn with_calendar_service(
|
||||||
|
mut self,
|
||||||
|
calendar_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>,
|
||||||
|
) -> Self {
|
||||||
self.calendar_service = Some(calendar_service);
|
self.calendar_service = Some(calendar_service);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_contact_service(mut self, contact_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>) -> Self {
|
pub fn with_contact_service(
|
||||||
|
mut self,
|
||||||
|
contact_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>,
|
||||||
|
) -> Self {
|
||||||
self.contact_service = Some(contact_service);
|
self.contact_service = Some(contact_service);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_calendar_use_case(mut self, calendar_use_case: Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>) -> Self {
|
pub fn with_calendar_use_case(
|
||||||
|
mut self,
|
||||||
|
calendar_use_case: Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>,
|
||||||
|
) -> Self {
|
||||||
self.calendar_use_case = Some(calendar_use_case);
|
self.calendar_use_case = Some(calendar_use_case);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_addressbook_use_case(mut self, addressbook_use_case: Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>) -> Self {
|
pub fn with_addressbook_use_case(
|
||||||
|
mut self,
|
||||||
|
addressbook_use_case: Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>,
|
||||||
|
) -> Self {
|
||||||
self.addressbook_use_case = Some(addressbook_use_case);
|
self.addressbook_use_case = Some(addressbook_use_case);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_contact_use_case(mut self, contact_use_case: Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>) -> Self {
|
pub fn with_contact_use_case(
|
||||||
|
mut self,
|
||||||
|
contact_use_case: Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>,
|
||||||
|
) -> Self {
|
||||||
self.contact_use_case = Some(contact_use_case);
|
self.contact_use_case = Some(contact_use_case);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -168,6 +168,14 @@ impl FileWritePort for StubFileWritePort {
|
|||||||
Ok(File::default())
|
Ok(File::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn copy_file(
|
||||||
|
&self,
|
||||||
|
_file_id: &str,
|
||||||
|
_target_folder_id: Option<String>,
|
||||||
|
) -> Result<File, DomainError> {
|
||||||
|
Ok(File::default())
|
||||||
|
}
|
||||||
|
|
||||||
async fn rename_file(&self, _file_id: &str, _new_name: &str) -> Result<File, DomainError> {
|
async fn rename_file(&self, _file_id: &str, _new_name: &str) -> Result<File, DomainError> {
|
||||||
Ok(File::default())
|
Ok(File::default())
|
||||||
}
|
}
|
||||||
@@ -483,6 +491,14 @@ impl FileManagementUseCase for StubFileManagementUseCase {
|
|||||||
Ok(FileDto::default())
|
Ok(FileDto::default())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn copy_file(
|
||||||
|
&self,
|
||||||
|
_file_id: &str,
|
||||||
|
_folder_id: Option<String>,
|
||||||
|
) -> Result<FileDto, DomainError> {
|
||||||
|
Ok(FileDto::default())
|
||||||
|
}
|
||||||
|
|
||||||
async fn rename_file(&self, _file_id: &str, _new_name: &str) -> Result<FileDto, DomainError> {
|
async fn rename_file(&self, _file_id: &str, _new_name: &str) -> Result<FileDto, DomainError> {
|
||||||
Ok(FileDto::default())
|
Ok(FileDto::default())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,6 @@ pub mod pg;
|
|||||||
|
|
||||||
// Re-exportar para facilitar acceso
|
// Re-exportar para facilitar acceso
|
||||||
pub use pg::{
|
pub use pg::{
|
||||||
FileBlobReadRepository, FileBlobWriteRepository, FolderDbRepository,
|
FileBlobReadRepository, FileBlobWriteRepository, FolderDbRepository, SessionPgRepository,
|
||||||
SessionPgRepository, TrashDbRepository, UserPgRepository,
|
TrashDbRepository, UserPgRepository,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -64,9 +64,7 @@ impl FileBlobReadRepository {
|
|||||||
created_at: i64,
|
created_at: i64,
|
||||||
modified_at: i64,
|
modified_at: i64,
|
||||||
) -> Result<File, DomainError> {
|
) -> Result<File, DomainError> {
|
||||||
let storage_path = self
|
let storage_path = self.build_file_path(folder_id.as_deref(), &name).await?;
|
||||||
.build_file_path(folder_id.as_deref(), &name)
|
|
||||||
.await?;
|
|
||||||
File::with_timestamps(
|
File::with_timestamps(
|
||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
@@ -115,10 +113,7 @@ impl FileReadPort for FileBlobReadRepository {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_files(
|
async fn list_files(&self, folder_id: Option<&str>) -> Result<Vec<File>, DomainError> {
|
||||||
&self,
|
|
||||||
folder_id: Option<&str>,
|
|
||||||
) -> Result<Vec<File>, DomainError> {
|
|
||||||
let rows: Vec<(String, String, Option<String>, i64, String, i64, i64)> =
|
let rows: Vec<(String, String, Option<String>, i64, String, i64, i64)> =
|
||||||
if let Some(fid) = folder_id {
|
if let Some(fid) = folder_id {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
@@ -264,8 +259,7 @@ impl FileReadPort for FileBlobReadRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
current_parent.ok_or_else(|| {
|
current_parent
|
||||||
DomainError::not_found("Folder", format!("parent for path: {path}"))
|
.ok_or_else(|| DomainError::not_found("Folder", format!("parent for path: {path}")))
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,9 +66,7 @@ impl FileBlobWriteRepository {
|
|||||||
created_at: i64,
|
created_at: i64,
|
||||||
modified_at: i64,
|
modified_at: i64,
|
||||||
) -> Result<File, DomainError> {
|
) -> Result<File, DomainError> {
|
||||||
let storage_path = self
|
let storage_path = self.build_file_path(folder_id.as_deref(), &name).await?;
|
||||||
.build_file_path(folder_id.as_deref(), &name)
|
|
||||||
.await?;
|
|
||||||
File::with_timestamps(
|
File::with_timestamps(
|
||||||
id,
|
id,
|
||||||
name,
|
name,
|
||||||
@@ -113,8 +111,8 @@ impl FileWritePort for FileBlobWriteRepository {
|
|||||||
.await?;
|
.await?;
|
||||||
let blob_hash = dedup_result.hash().to_string();
|
let blob_hash = dedup_result.hash().to_string();
|
||||||
|
|
||||||
// Insert file metadata
|
// Insert file metadata — if this fails, compensate by removing the blob ref
|
||||||
let row = sqlx::query_as::<_, (String, i64, i64)>(
|
let row = match sqlx::query_as::<_, (String, i64, i64)>(
|
||||||
r#"
|
r#"
|
||||||
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
|
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
|
||||||
VALUES ($1, $2::uuid, $3, $4, $5, $6)
|
VALUES ($1, $2::uuid, $3, $4, $5, $6)
|
||||||
@@ -131,17 +129,31 @@ impl FileWritePort for FileBlobWriteRepository {
|
|||||||
.bind(&content_type)
|
.bind(&content_type)
|
||||||
.fetch_one(self.pool.as_ref())
|
.fetch_one(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
{
|
||||||
if let sqlx::Error::Database(ref db_err) = e {
|
Ok(row) => row,
|
||||||
if db_err.code().as_deref() == Some("23505") {
|
Err(e) => {
|
||||||
return DomainError::already_exists(
|
// ── Compensation: undo the blob ref so it doesn't become orphaned ──
|
||||||
"File",
|
if let Err(rollback_err) = self.dedup.remove_reference(&blob_hash).await {
|
||||||
format!("{name} already exists in folder"),
|
tracing::error!(
|
||||||
|
"Blob orphaned after failed INSERT — hash: {}, err: {}",
|
||||||
|
&blob_hash[..12],
|
||||||
|
rollback_err
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if let sqlx::Error::Database(ref db_err) = e {
|
||||||
|
if db_err.code().as_deref() == Some("23505") {
|
||||||
|
return Err(DomainError::already_exists(
|
||||||
|
"File",
|
||||||
|
format!("{name} already exists in folder"),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
DomainError::internal_error("FileBlobWrite", format!("insert: {e}"))
|
}
|
||||||
})?;
|
return Err(DomainError::internal_error(
|
||||||
|
"FileBlobWrite",
|
||||||
|
format!("insert: {e}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"💾 BLOB WRITE: {} ({} bytes, hash: {})",
|
"💾 BLOB WRITE: {} ({} bytes, hash: {})",
|
||||||
@@ -150,15 +162,7 @@ impl FileWritePort for FileBlobWriteRepository {
|
|||||||
&blob_hash[..12]
|
&blob_hash[..12]
|
||||||
);
|
);
|
||||||
|
|
||||||
self.row_to_file(
|
self.row_to_file(row.0, name, folder_id, size, content_type, row.1, row.2)
|
||||||
row.0,
|
|
||||||
name,
|
|
||||||
folder_id,
|
|
||||||
size,
|
|
||||||
content_type,
|
|
||||||
row.1,
|
|
||||||
row.2,
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,11 +215,90 @@ impl FileWritePort for FileBlobWriteRepository {
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn rename_file(
|
async fn copy_file(
|
||||||
&self,
|
&self,
|
||||||
file_id: &str,
|
file_id: &str,
|
||||||
new_name: &str,
|
target_folder_id: Option<String>,
|
||||||
) -> Result<File, DomainError> {
|
) -> Result<File, DomainError> {
|
||||||
|
// Atomic CTE: read source file → insert new row with same blob_hash → increment ref_count.
|
||||||
|
// Single round-trip; blob content is NOT copied (dedup makes this zero-copy).
|
||||||
|
let target_fid = target_folder_id.clone();
|
||||||
|
|
||||||
|
let row = sqlx::query_as::<
|
||||||
|
_,
|
||||||
|
(
|
||||||
|
String,
|
||||||
|
String,
|
||||||
|
Option<String>,
|
||||||
|
i64,
|
||||||
|
String,
|
||||||
|
i64,
|
||||||
|
i64,
|
||||||
|
String,
|
||||||
|
),
|
||||||
|
>(
|
||||||
|
r#"
|
||||||
|
WITH src AS (
|
||||||
|
SELECT name, folder_id, user_id, blob_hash, size, mime_type
|
||||||
|
FROM storage.files
|
||||||
|
WHERE id = $1::uuid AND NOT is_trashed
|
||||||
|
),
|
||||||
|
new_file AS (
|
||||||
|
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
|
||||||
|
SELECT name,
|
||||||
|
COALESCE($2::uuid, folder_id),
|
||||||
|
user_id,
|
||||||
|
blob_hash,
|
||||||
|
size,
|
||||||
|
mime_type
|
||||||
|
FROM src
|
||||||
|
RETURNING id::text, name, folder_id::text, size, mime_type,
|
||||||
|
EXTRACT(EPOCH FROM created_at)::bigint,
|
||||||
|
EXTRACT(EPOCH FROM updated_at)::bigint,
|
||||||
|
blob_hash
|
||||||
|
)
|
||||||
|
SELECT * FROM new_file
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.bind(file_id)
|
||||||
|
.bind(&target_fid)
|
||||||
|
.fetch_optional(self.pool.as_ref())
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
if let sqlx::Error::Database(ref db_err) = e {
|
||||||
|
if db_err.code().as_deref() == Some("23505") {
|
||||||
|
return DomainError::already_exists(
|
||||||
|
"File",
|
||||||
|
"File with that name already exists in target folder".to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DomainError::internal_error("FileBlobWrite", format!("copy: {e}"))
|
||||||
|
})?
|
||||||
|
.ok_or_else(|| DomainError::not_found("File", file_id))?;
|
||||||
|
|
||||||
|
let blob_hash = &row.7;
|
||||||
|
|
||||||
|
// Increment blob reference count (best-effort; INSERT already succeeded)
|
||||||
|
if let Err(e) = self.dedup.add_reference(blob_hash).await {
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to increment blob ref for copy {}: {}",
|
||||||
|
&blob_hash[..12],
|
||||||
|
e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
"📋 BLOB COPY: {} (hash: {}, zero-copy via dedup)",
|
||||||
|
row.1,
|
||||||
|
&blob_hash[..12]
|
||||||
|
);
|
||||||
|
|
||||||
|
self.row_to_file(row.0, row.1, row.2, row.3, row.4, row.5, row.6)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<File, DomainError> {
|
||||||
let row = sqlx::query_as::<_, (String, String, Option<String>, i64, String, i64, i64)>(
|
let row = sqlx::query_as::<_, (String, String, Option<String>, i64, String, i64, i64)>(
|
||||||
r#"
|
r#"
|
||||||
UPDATE storage.files
|
UPDATE storage.files
|
||||||
@@ -248,30 +331,19 @@ impl FileWritePort for FileBlobWriteRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn delete_file(&self, id: &str) -> Result<(), DomainError> {
|
async fn delete_file(&self, id: &str) -> Result<(), DomainError> {
|
||||||
// Get blob_hash before deleting so we can decrement ref
|
// Atomic DELETE RETURNING — one round-trip instead of SELECT + DELETE
|
||||||
let hash = sqlx::query_scalar::<_, String>(
|
let hash = sqlx::query_scalar::<_, String>(
|
||||||
"SELECT blob_hash FROM storage.files WHERE id = $1::uuid",
|
"DELETE FROM storage.files WHERE id = $1::uuid RETURNING blob_hash",
|
||||||
)
|
)
|
||||||
.bind(id)
|
.bind(id)
|
||||||
.fetch_optional(self.pool.as_ref())
|
.fetch_optional(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("hash lookup: {e}")))?;
|
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("delete: {e}")))?
|
||||||
|
.ok_or_else(|| DomainError::not_found("File", id))?;
|
||||||
|
|
||||||
let result = sqlx::query("DELETE FROM storage.files WHERE id = $1::uuid")
|
// Decrement blob reference (best-effort after successful DELETE)
|
||||||
.bind(id)
|
if let Err(e) = self.dedup.remove_reference(&hash).await {
|
||||||
.execute(self.pool.as_ref())
|
tracing::warn!("Failed to decrement blob ref for {}: {}", &hash[..12], e);
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("delete: {e}")))?;
|
|
||||||
|
|
||||||
if result.rows_affected() == 0 {
|
|
||||||
return Err(DomainError::not_found("File", id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decrement blob reference
|
|
||||||
if let Some(h) = hash {
|
|
||||||
if let Err(e) = self.dedup.remove_reference(&h).await {
|
|
||||||
tracing::warn!("Failed to decrement blob ref for {}: {}", &h[..12], e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -282,37 +354,56 @@ impl FileWritePort for FileBlobWriteRepository {
|
|||||||
file_id: &str,
|
file_id: &str,
|
||||||
content: Vec<u8>,
|
content: Vec<u8>,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
// Get old blob hash to decrement ref
|
// Store new content first (blob store is idempotent)
|
||||||
let old_hash = sqlx::query_scalar::<_, String>(
|
|
||||||
"SELECT blob_hash FROM storage.files WHERE id = $1::uuid",
|
|
||||||
)
|
|
||||||
.bind(file_id)
|
|
||||||
.fetch_optional(self.pool.as_ref())
|
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("old hash: {e}")))?
|
|
||||||
.ok_or_else(|| DomainError::not_found("File", file_id))?;
|
|
||||||
|
|
||||||
// Store new content
|
|
||||||
let new_size = content.len() as i64;
|
let new_size = content.len() as i64;
|
||||||
let dedup_result = self.dedup.store_bytes(&content, None).await?;
|
let dedup_result = self.dedup.store_bytes(&content, None).await?;
|
||||||
let new_hash = dedup_result.hash().to_string();
|
let new_hash = dedup_result.hash().to_string();
|
||||||
|
|
||||||
// Update file metadata
|
// Atomic CTE: capture old hash then update in one round-trip, no TOCTOU.
|
||||||
sqlx::query(
|
// The `old` CTE locks + reads the row *before* the update touches it.
|
||||||
|
let old_hash = match sqlx::query_scalar::<_, String>(
|
||||||
r#"
|
r#"
|
||||||
UPDATE storage.files
|
WITH old AS (
|
||||||
|
SELECT id, blob_hash FROM storage.files WHERE id = $3::uuid FOR UPDATE
|
||||||
|
)
|
||||||
|
UPDATE storage.files f
|
||||||
SET blob_hash = $1, size = $2, updated_at = NOW()
|
SET blob_hash = $1, size = $2, updated_at = NOW()
|
||||||
WHERE id = $3::uuid
|
FROM old
|
||||||
|
WHERE f.id = old.id
|
||||||
|
RETURNING old.blob_hash
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.bind(&new_hash)
|
.bind(&new_hash)
|
||||||
.bind(new_size)
|
.bind(new_size)
|
||||||
.bind(file_id)
|
.bind(file_id)
|
||||||
.execute(self.pool.as_ref())
|
.fetch_optional(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("update: {e}")))?;
|
{
|
||||||
|
Ok(Some(old)) => old,
|
||||||
|
Ok(None) => {
|
||||||
|
// File not found — compensate: remove the new blob ref
|
||||||
|
if let Err(e) = self.dedup.remove_reference(&new_hash).await {
|
||||||
|
tracing::error!("Blob orphaned after missing file: {}", e);
|
||||||
|
}
|
||||||
|
return Err(DomainError::not_found("File", file_id));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
// UPDATE failed — compensate: remove the new blob ref
|
||||||
|
if let Err(rollback_err) = self.dedup.remove_reference(&new_hash).await {
|
||||||
|
tracing::error!(
|
||||||
|
"Blob orphaned after failed UPDATE — hash: {}, err: {}",
|
||||||
|
&new_hash[..12],
|
||||||
|
rollback_err
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Err(DomainError::internal_error(
|
||||||
|
"FileBlobWrite",
|
||||||
|
format!("update: {e}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Decrement old blob ref (only if hash changed)
|
// Decrement old blob ref (only if hash changed, best-effort)
|
||||||
if old_hash != new_hash {
|
if old_hash != new_hash {
|
||||||
if let Err(e) = self.dedup.remove_reference(&old_hash).await {
|
if let Err(e) = self.dedup.remove_reference(&old_hash).await {
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
|
|||||||
@@ -34,7 +34,9 @@ impl FolderDbRepository {
|
|||||||
|
|
||||||
/// Get the pool, panicking if stub.
|
/// Get the pool, panicking if stub.
|
||||||
fn pool(&self) -> &PgPool {
|
fn pool(&self) -> &PgPool {
|
||||||
self.pool.as_deref().expect("FolderDbRepository: pool not available (stub instance)")
|
self.pool
|
||||||
|
.as_deref()
|
||||||
|
.expect("FolderDbRepository: pool not available (stub instance)")
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── helpers ──────────────────────────────────────────────────
|
// ── helpers ──────────────────────────────────────────────────
|
||||||
@@ -181,14 +183,10 @@ impl FolderRepository for FolderDbRepository {
|
|||||||
.map_err(|e| DomainError::internal_error("FolderDb", format!("get: {e}")))?
|
.map_err(|e| DomainError::internal_error("FolderDb", format!("get: {e}")))?
|
||||||
.ok_or_else(|| DomainError::not_found("Folder", id))?;
|
.ok_or_else(|| DomainError::not_found("Folder", id))?;
|
||||||
|
|
||||||
self.row_to_folder(row.0, row.1, row.2, row.3, row.4)
|
self.row_to_folder(row.0, row.1, row.2, row.3, row.4).await
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_folder_by_path(
|
async fn get_folder_by_path(&self, storage_path: &StoragePath) -> Result<Folder, DomainError> {
|
||||||
&self,
|
|
||||||
storage_path: &StoragePath,
|
|
||||||
) -> Result<Folder, DomainError> {
|
|
||||||
// Walk the path segments to find the folder.
|
// Walk the path segments to find the folder.
|
||||||
let path_str = storage_path.to_string();
|
let path_str = storage_path.to_string();
|
||||||
let segments: Vec<&str> = path_str.split('/').filter(|s| !s.is_empty()).collect();
|
let segments: Vec<&str> = path_str.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
@@ -235,10 +233,7 @@ impl FolderRepository for FolderDbRepository {
|
|||||||
self.get_folder(¤t_id).await
|
self.get_folder(¤t_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_folders(
|
async fn list_folders(&self, parent_id: Option<&str>) -> Result<Vec<Folder>, DomainError> {
|
||||||
&self,
|
|
||||||
parent_id: Option<&str>,
|
|
||||||
) -> Result<Vec<Folder>, DomainError> {
|
|
||||||
let rows: Vec<(String, String, Option<String>, i64, i64)> = if let Some(pid) = parent_id {
|
let rows: Vec<(String, String, Option<String>, i64, i64)> = if let Some(pid) = parent_id {
|
||||||
sqlx::query_as(
|
sqlx::query_as(
|
||||||
r#"
|
r#"
|
||||||
@@ -347,11 +342,7 @@ impl FolderRepository for FolderDbRepository {
|
|||||||
Ok((folders, total))
|
Ok((folders, total))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn rename_folder(
|
async fn rename_folder(&self, id: &str, new_name: String) -> Result<Folder, DomainError> {
|
||||||
&self,
|
|
||||||
id: &str,
|
|
||||||
new_name: String,
|
|
||||||
) -> Result<Folder, DomainError> {
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
r#"
|
r#"
|
||||||
UPDATE storage.folders
|
UPDATE storage.folders
|
||||||
@@ -429,43 +420,42 @@ impl FolderRepository for FolderDbRepository {
|
|||||||
// ── Trash operations ──
|
// ── Trash operations ──
|
||||||
|
|
||||||
async fn move_to_trash(&self, folder_id: &str) -> Result<(), DomainError> {
|
async fn move_to_trash(&self, folder_id: &str) -> Result<(), DomainError> {
|
||||||
// Soft-delete: set is_trashed = true and remember original parent
|
// Atomic CTE: trash folder + all descendant files in a single statement.
|
||||||
let result = sqlx::query(
|
// PostgreSQL executes the entire CTE as one atomic operation — no
|
||||||
|
// intermediate state where the folder is trashed but files are not.
|
||||||
|
let result = sqlx::query_scalar::<_, i64>(
|
||||||
r#"
|
r#"
|
||||||
|
WITH trash_folder AS (
|
||||||
UPDATE storage.folders
|
UPDATE storage.folders
|
||||||
SET is_trashed = TRUE,
|
SET is_trashed = TRUE,
|
||||||
trashed_at = NOW(),
|
trashed_at = NOW(),
|
||||||
original_parent_id = parent_id,
|
original_parent_id = parent_id,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = $1::uuid AND NOT is_trashed
|
WHERE id = $1::uuid AND NOT is_trashed
|
||||||
"#,
|
RETURNING id
|
||||||
)
|
),
|
||||||
.bind(folder_id)
|
descendants AS (
|
||||||
.execute(self.pool())
|
SELECT id FROM trash_folder
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::internal_error("FolderDb", format!("trash: {e}")))?;
|
|
||||||
|
|
||||||
if result.rows_affected() == 0 {
|
|
||||||
return Err(DomainError::not_found("Folder", folder_id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also trash all files inside the folder (recursively)
|
|
||||||
sqlx::query(
|
|
||||||
r#"
|
|
||||||
WITH RECURSIVE descendants AS (
|
|
||||||
SELECT id FROM storage.folders WHERE id = $1::uuid
|
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
|
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
|
||||||
)
|
),
|
||||||
|
trash_files AS (
|
||||||
UPDATE storage.files
|
UPDATE storage.files
|
||||||
SET is_trashed = TRUE, trashed_at = NOW(), original_folder_id = folder_id
|
SET is_trashed = TRUE, trashed_at = NOW(), original_folder_id = folder_id
|
||||||
WHERE folder_id IN (SELECT id FROM descendants) AND NOT is_trashed
|
WHERE folder_id IN (SELECT id FROM descendants) AND NOT is_trashed
|
||||||
|
RETURNING 1
|
||||||
|
)
|
||||||
|
SELECT COUNT(*) FROM trash_folder
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.bind(folder_id)
|
.bind(folder_id)
|
||||||
.execute(self.pool())
|
.fetch_one(self.pool())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::internal_error("FolderDb", format!("trash files: {e}")))?;
|
.map_err(|e| DomainError::internal_error("FolderDb", format!("trash: {e}")))?;
|
||||||
|
|
||||||
|
if result == 0 {
|
||||||
|
return Err(DomainError::not_found("Folder", folder_id));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -475,9 +465,10 @@ impl FolderRepository for FolderDbRepository {
|
|||||||
folder_id: &str,
|
folder_id: &str,
|
||||||
_original_path: &str,
|
_original_path: &str,
|
||||||
) -> Result<(), DomainError> {
|
) -> Result<(), DomainError> {
|
||||||
// Restore: set is_trashed = false, restore parent_id from original_parent_id
|
// Atomic CTE: restore folder + all descendant files in a single statement.
|
||||||
let result = sqlx::query(
|
let result = sqlx::query_scalar::<_, i64>(
|
||||||
r#"
|
r#"
|
||||||
|
WITH restore_folder AS (
|
||||||
UPDATE storage.folders
|
UPDATE storage.folders
|
||||||
SET is_trashed = FALSE,
|
SET is_trashed = FALSE,
|
||||||
trashed_at = NULL,
|
trashed_at = NULL,
|
||||||
@@ -485,37 +476,33 @@ impl FolderRepository for FolderDbRepository {
|
|||||||
original_parent_id = NULL,
|
original_parent_id = NULL,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = $1::uuid AND is_trashed
|
WHERE id = $1::uuid AND is_trashed
|
||||||
"#,
|
RETURNING id
|
||||||
)
|
),
|
||||||
.bind(folder_id)
|
descendants AS (
|
||||||
.execute(self.pool())
|
SELECT id FROM restore_folder
|
||||||
.await
|
|
||||||
.map_err(|e| DomainError::internal_error("FolderDb", format!("restore: {e}")))?;
|
|
||||||
|
|
||||||
if result.rows_affected() == 0 {
|
|
||||||
return Err(DomainError::not_found("Folder", folder_id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also restore files that were trashed with this folder
|
|
||||||
sqlx::query(
|
|
||||||
r#"
|
|
||||||
WITH RECURSIVE descendants AS (
|
|
||||||
SELECT id FROM storage.folders WHERE id = $1::uuid
|
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
|
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
|
||||||
)
|
),
|
||||||
|
restore_files AS (
|
||||||
UPDATE storage.files
|
UPDATE storage.files
|
||||||
SET is_trashed = FALSE,
|
SET is_trashed = FALSE,
|
||||||
trashed_at = NULL,
|
trashed_at = NULL,
|
||||||
folder_id = COALESCE(original_folder_id, folder_id),
|
folder_id = COALESCE(original_folder_id, folder_id),
|
||||||
original_folder_id = NULL
|
original_folder_id = NULL
|
||||||
WHERE folder_id IN (SELECT id FROM descendants) AND is_trashed
|
WHERE folder_id IN (SELECT id FROM descendants) AND is_trashed
|
||||||
|
RETURNING 1
|
||||||
|
)
|
||||||
|
SELECT COUNT(*) FROM restore_folder
|
||||||
"#,
|
"#,
|
||||||
)
|
)
|
||||||
.bind(folder_id)
|
.bind(folder_id)
|
||||||
.execute(self.pool())
|
.fetch_one(self.pool())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DomainError::internal_error("FolderDb", format!("restore files: {e}")))?;
|
.map_err(|e| DomainError::internal_error("FolderDb", format!("restore: {e}")))?;
|
||||||
|
|
||||||
|
if result == 0 {
|
||||||
|
return Err(DomainError::not_found("Folder", folder_id));
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -562,9 +549,7 @@ impl FolderDbRepository {
|
|||||||
.map_err(|e| DomainError::internal_error("FolderDb", format!("home folder: {e}")))?;
|
.map_err(|e| DomainError::internal_error("FolderDb", format!("home folder: {e}")))?;
|
||||||
|
|
||||||
match row {
|
match row {
|
||||||
Some((id, ca, ma)) => {
|
Some((id, ca, ma)) => self.row_to_folder(id, name.to_string(), None, ca, ma).await,
|
||||||
self.row_to_folder(id, name.to_string(), None, ca, ma).await
|
|
||||||
}
|
|
||||||
None => {
|
None => {
|
||||||
// Already exists — fetch it
|
// Already exists — fetch it
|
||||||
let existing = sqlx::query_as::<_, (String, i64, i64)>(
|
let existing = sqlx::query_as::<_, (String, i64, i64)>(
|
||||||
@@ -580,9 +565,7 @@ impl FolderDbRepository {
|
|||||||
.bind(user_id)
|
.bind(user_id)
|
||||||
.fetch_one(self.pool())
|
.fetch_one(self.pool())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| DomainError::internal_error("FolderDb", format!("home fetch: {e}")))?;
|
||||||
DomainError::internal_error("FolderDb", format!("home fetch: {e}"))
|
|
||||||
})?;
|
|
||||||
self.row_to_folder(existing.0, name.to_string(), None, existing.1, existing.2)
|
self.row_to_folder(existing.0, name.to_string(), None, existing.1, existing.2)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -591,9 +574,7 @@ impl FolderDbRepository {
|
|||||||
|
|
||||||
/// Returns user_id for a given folder. Used by file repositories.
|
/// Returns user_id for a given folder. Used by file repositories.
|
||||||
pub async fn get_folder_user_id(&self, folder_id: &str) -> Result<String, DomainError> {
|
pub async fn get_folder_user_id(&self, folder_id: &str) -> Result<String, DomainError> {
|
||||||
sqlx::query_scalar::<_, String>(
|
sqlx::query_scalar::<_, String>("SELECT user_id FROM storage.folders WHERE id = $1::uuid")
|
||||||
"SELECT user_id FROM storage.folders WHERE id = $1::uuid",
|
|
||||||
)
|
|
||||||
.bind(folder_id)
|
.bind(folder_id)
|
||||||
.fetch_optional(self.pool())
|
.fetch_optional(self.pool())
|
||||||
.await
|
.await
|
||||||
|
|||||||
@@ -86,9 +86,7 @@ impl TrashRepository for TrashDbRepository {
|
|||||||
.bind(user_id.to_string())
|
.bind(user_id.to_string())
|
||||||
.fetch_all(self.pool.as_ref())
|
.fetch_all(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| DomainError::internal_error("TrashDb", format!("list: {e}")))?;
|
||||||
DomainError::internal_error("TrashDb", format!("list: {e}"))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(rows
|
Ok(rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -98,11 +96,7 @@ impl TrashRepository for TrashDbRepository {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_trash_item(
|
async fn get_trash_item(&self, id: &Uuid, user_id: &Uuid) -> Result<Option<TrashedItem>> {
|
||||||
&self,
|
|
||||||
id: &Uuid,
|
|
||||||
user_id: &Uuid,
|
|
||||||
) -> Result<Option<TrashedItem>> {
|
|
||||||
let row = sqlx::query_as::<_, (Uuid, String, String, String, Option<DateTime<Utc>>)>(
|
let row = sqlx::query_as::<_, (Uuid, String, String, String, Option<DateTime<Utc>>)>(
|
||||||
r#"
|
r#"
|
||||||
SELECT id, name, item_type, user_id, trashed_at
|
SELECT id, name, item_type, user_id, trashed_at
|
||||||
@@ -114,9 +108,7 @@ impl TrashRepository for TrashDbRepository {
|
|||||||
.bind(user_id.to_string())
|
.bind(user_id.to_string())
|
||||||
.fetch_optional(self.pool.as_ref())
|
.fetch_optional(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| DomainError::internal_error("TrashDb", format!("get: {e}")))?;
|
||||||
DomainError::internal_error("TrashDb", format!("get: {e}"))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(row.map(|(id, name, item_type, uid, trashed_at)| {
|
Ok(row.map(|(id, name, item_type, uid, trashed_at)| {
|
||||||
self.row_to_trashed_item(id, name, item_type, uid, trashed_at)
|
self.row_to_trashed_item(id, name, item_type, uid, trashed_at)
|
||||||
@@ -139,26 +131,18 @@ impl TrashRepository for TrashDbRepository {
|
|||||||
|
|
||||||
async fn clear_trash(&self, user_id: &Uuid) -> Result<()> {
|
async fn clear_trash(&self, user_id: &Uuid) -> Result<()> {
|
||||||
// Delete all trashed files for this user
|
// Delete all trashed files for this user
|
||||||
sqlx::query(
|
sqlx::query("DELETE FROM storage.files WHERE user_id = $1 AND is_trashed = TRUE")
|
||||||
"DELETE FROM storage.files WHERE user_id = $1 AND is_trashed = TRUE",
|
|
||||||
)
|
|
||||||
.bind(user_id.to_string())
|
.bind(user_id.to_string())
|
||||||
.execute(self.pool.as_ref())
|
.execute(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| DomainError::internal_error("TrashDb", format!("clear files: {e}")))?;
|
||||||
DomainError::internal_error("TrashDb", format!("clear files: {e}"))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// Delete all trashed folders for this user
|
// Delete all trashed folders for this user
|
||||||
sqlx::query(
|
sqlx::query("DELETE FROM storage.folders WHERE user_id = $1 AND is_trashed = TRUE")
|
||||||
"DELETE FROM storage.folders WHERE user_id = $1 AND is_trashed = TRUE",
|
|
||||||
)
|
|
||||||
.bind(user_id.to_string())
|
.bind(user_id.to_string())
|
||||||
.execute(self.pool.as_ref())
|
.execute(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| DomainError::internal_error("TrashDb", format!("clear folders: {e}")))?;
|
||||||
DomainError::internal_error("TrashDb", format!("clear folders: {e}"))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -177,9 +161,7 @@ impl TrashRepository for TrashDbRepository {
|
|||||||
.bind(cutoff)
|
.bind(cutoff)
|
||||||
.fetch_all(self.pool.as_ref())
|
.fetch_all(self.pool.as_ref())
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| DomainError::internal_error("TrashDb", format!("expired: {e}")))?;
|
||||||
DomainError::internal_error("TrashDb", format!("expired: {e}"))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(rows
|
Ok(rows
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|||||||
@@ -209,9 +209,7 @@ impl DedupService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Atomic write: temp file → rename
|
// Atomic write: temp file → rename
|
||||||
let temp_path = self
|
let temp_path = self.temp_root.join(format!("{}.tmp", uuid::Uuid::new_v4()));
|
||||||
.temp_root
|
|
||||||
.join(format!("{}.tmp", uuid::Uuid::new_v4()));
|
|
||||||
fs::write(&temp_path, content).await.map_err(|e| {
|
fs::write(&temp_path, content).await.map_err(|e| {
|
||||||
DomainError::internal_error("Dedup", format!("Failed to write temp blob: {}", e))
|
DomainError::internal_error("Dedup", format!("Failed to write temp blob: {}", e))
|
||||||
})?;
|
})?;
|
||||||
@@ -258,10 +256,7 @@ impl DedupService {
|
|||||||
let file_size = fs::metadata(source_path)
|
let file_size = fs::metadata(source_path)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
DomainError::internal_error(
|
DomainError::internal_error("Dedup", format!("Failed to get file metadata: {}", e))
|
||||||
"Dedup",
|
|
||||||
format!("Failed to get file metadata: {}", e),
|
|
||||||
)
|
|
||||||
})?
|
})?
|
||||||
.len();
|
.len();
|
||||||
|
|
||||||
|
|||||||
@@ -171,7 +171,7 @@ async fn handle_propfind(
|
|||||||
if path.is_empty() {
|
if path.is_empty() {
|
||||||
// Root CalDAV path — list user's calendars
|
// Root CalDAV path — list user's calendars
|
||||||
let calendars = calendar_service
|
let calendars = calendar_service
|
||||||
.list_my_calendars_for_user(&user.id)
|
.list_my_calendars(&user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list calendars: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to list calendars: {}", e)))?;
|
||||||
|
|
||||||
@@ -198,13 +198,13 @@ async fn handle_propfind(
|
|||||||
if parts.len() == 1 {
|
if parts.len() == 1 {
|
||||||
// Calendar collection
|
// Calendar collection
|
||||||
let calendar = calendar_service
|
let calendar = calendar_service
|
||||||
.get_calendar_for_user(calendar_id, &user.id)
|
.get_calendar(calendar_id, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
|
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
|
||||||
|
|
||||||
let events = if depth != "0" {
|
let events = if depth != "0" {
|
||||||
calendar_service
|
calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
} else {
|
} else {
|
||||||
@@ -235,7 +235,7 @@ async fn handle_propfind(
|
|||||||
let ical_uid = event_file.trim_end_matches(".ics");
|
let ical_uid = event_file.trim_end_matches(".ics");
|
||||||
|
|
||||||
let events = calendar_service
|
let events = calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
||||||
|
|
||||||
@@ -295,14 +295,14 @@ async fn handle_report(
|
|||||||
CalDavReportType::CalendarQuery { time_range, .. } => {
|
CalDavReportType::CalendarQuery { time_range, .. } => {
|
||||||
if let Some((start, end)) = time_range {
|
if let Some((start, end)) = time_range {
|
||||||
calendar_service
|
calendar_service
|
||||||
.get_events_in_range_for_user(calendar_id, *start, *end, &user.id)
|
.get_events_in_range(calendar_id, *start, *end, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
AppError::internal_error(format!("Failed to query events: {}", e))
|
AppError::internal_error(format!("Failed to query events: {}", e))
|
||||||
})?
|
})?
|
||||||
} else {
|
} else {
|
||||||
calendar_service
|
calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
AppError::internal_error(format!("Failed to list events: {}", e))
|
AppError::internal_error(format!("Failed to list events: {}", e))
|
||||||
@@ -311,7 +311,7 @@ async fn handle_report(
|
|||||||
}
|
}
|
||||||
CalDavReportType::CalendarMultiget { hrefs, .. } => {
|
CalDavReportType::CalendarMultiget { hrefs, .. } => {
|
||||||
let all_events = calendar_service
|
let all_events = calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
||||||
|
|
||||||
@@ -321,7 +321,7 @@ async fn handle_report(
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
CalDavReportType::SyncCollection { .. } => calendar_service
|
CalDavReportType::SyncCollection { .. } => calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?,
|
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?,
|
||||||
};
|
};
|
||||||
@@ -377,7 +377,7 @@ async fn handle_mkcalendar(
|
|||||||
};
|
};
|
||||||
|
|
||||||
calendar_service
|
calendar_service
|
||||||
.create_calendar_for_user(create_dto, &user.id)
|
.create_calendar(create_dto, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to create calendar: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to create calendar: {}", e)))?;
|
||||||
|
|
||||||
@@ -417,7 +417,7 @@ async fn handle_put(
|
|||||||
|
|
||||||
let existing = if let Some(ref uid) = ical_uid {
|
let existing = if let Some(ref uid) = ical_uid {
|
||||||
let events = calendar_service
|
let events = calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
events.into_iter().find(|e| e.ical_uid == *uid)
|
events.into_iter().find(|e| e.ical_uid == *uid)
|
||||||
@@ -428,7 +428,7 @@ async fn handle_put(
|
|||||||
if let Some(existing_event) = existing {
|
if let Some(existing_event) = existing {
|
||||||
// Update existing event — re-create from iCal for full fidelity
|
// Update existing event — re-create from iCal for full fidelity
|
||||||
calendar_service
|
calendar_service
|
||||||
.delete_event_for_user(&existing_event.id, &user.id)
|
.delete_event(&existing_event.id, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to update event: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to update event: {}", e)))?;
|
||||||
|
|
||||||
@@ -437,7 +437,7 @@ async fn handle_put(
|
|||||||
ical_data,
|
ical_data,
|
||||||
};
|
};
|
||||||
let event = calendar_service
|
let event = calendar_service
|
||||||
.create_event_from_ical_for_user(create_dto, &user.id)
|
.create_event_from_ical(create_dto, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to recreate event: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to recreate event: {}", e)))?;
|
||||||
|
|
||||||
@@ -453,7 +453,7 @@ async fn handle_put(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let event = calendar_service
|
let event = calendar_service
|
||||||
.create_event_from_ical_for_user(create_dto, &user.id)
|
.create_event_from_ical(create_dto, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to create event: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to create event: {}", e)))?;
|
||||||
|
|
||||||
@@ -492,12 +492,12 @@ async fn handle_get(
|
|||||||
if parts.len() < 2 {
|
if parts.len() < 2 {
|
||||||
// GET on calendar collection
|
// GET on calendar collection
|
||||||
let events = calendar_service
|
let events = calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
||||||
|
|
||||||
let calendar = calendar_service
|
let calendar = calendar_service
|
||||||
.get_calendar_for_user(calendar_id, &user.id)
|
.get_calendar(calendar_id, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
|
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
|
||||||
|
|
||||||
@@ -515,7 +515,7 @@ async fn handle_get(
|
|||||||
let ical_uid = event_file.trim_end_matches(".ics");
|
let ical_uid = event_file.trim_end_matches(".ics");
|
||||||
|
|
||||||
let events = calendar_service
|
let events = calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
||||||
|
|
||||||
@@ -602,7 +602,7 @@ async fn handle_delete(
|
|||||||
|
|
||||||
if parts.len() < 2 {
|
if parts.len() < 2 {
|
||||||
calendar_service
|
calendar_service
|
||||||
.delete_calendar_for_user(calendar_id, &user.id)
|
.delete_calendar(calendar_id, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to delete calendar: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to delete calendar: {}", e)))?;
|
||||||
} else {
|
} else {
|
||||||
@@ -610,7 +610,7 @@ async fn handle_delete(
|
|||||||
let ical_uid = event_file.trim_end_matches(".ics");
|
let ical_uid = event_file.trim_end_matches(".ics");
|
||||||
|
|
||||||
let events = calendar_service
|
let events = calendar_service
|
||||||
.list_events_for_user(calendar_id, None, None, &user.id)
|
.list_events(calendar_id, None, None, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
|
||||||
|
|
||||||
@@ -620,7 +620,7 @@ async fn handle_delete(
|
|||||||
.ok_or_else(|| AppError::not_found(format!("Event not found: {}", ical_uid)))?;
|
.ok_or_else(|| AppError::not_found(format!("Event not found: {}", ical_uid)))?;
|
||||||
|
|
||||||
calendar_service
|
calendar_service
|
||||||
.delete_event_for_user(&event.id, &user.id)
|
.delete_event(&event.id, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to delete event: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to delete event: {}", e)))?;
|
||||||
}
|
}
|
||||||
@@ -675,7 +675,7 @@ async fn handle_proppatch(
|
|||||||
|
|
||||||
if update.name.is_some() || update.description.is_some() || update.color.is_some() {
|
if update.name.is_some() || update.description.is_some() || update.color.is_some() {
|
||||||
calendar_service
|
calendar_service
|
||||||
.update_calendar_for_user(calendar_id, update, &user.id)
|
.update_calendar(calendar_id, update, &user.id)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| AppError::internal_error(format!("Failed to update calendar: {}", e)))?;
|
.map_err(|e| AppError::internal_error(format!("Failed to update calendar: {}", e)))?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
use std::sync::Arc;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use axum::{
|
use axum::{
|
||||||
extract::{Path, State, Query},
|
|
||||||
http::{StatusCode, header, HeaderName, HeaderValue, Response},
|
|
||||||
response::IntoResponse,
|
|
||||||
Json,
|
Json,
|
||||||
|
extract::{Path, Query, State},
|
||||||
|
http::{HeaderName, HeaderValue, Response, StatusCode, header},
|
||||||
|
response::IntoResponse,
|
||||||
};
|
};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::application::services::folder_service::FolderService;
|
use crate::application::dtos::folder_dto::{CreateFolderDto, MoveFolderDto, RenameFolderDto};
|
||||||
use crate::application::dtos::folder_dto::{CreateFolderDto, RenameFolderDto, MoveFolderDto};
|
|
||||||
use crate::application::dtos::pagination::PaginationRequestDto;
|
use crate::application::dtos::pagination::PaginationRequestDto;
|
||||||
use crate::common::errors::ErrorKind;
|
|
||||||
use crate::application::ports::inbound::FolderUseCase;
|
use crate::application::ports::inbound::FolderUseCase;
|
||||||
|
use crate::application::services::folder_service::FolderService;
|
||||||
use crate::common::di::AppState as GlobalAppState;
|
use crate::common::di::AppState as GlobalAppState;
|
||||||
use crate::interfaces::middleware::auth::{OptionalAuthUser, AuthUser};
|
use crate::common::errors::ErrorKind;
|
||||||
|
use crate::interfaces::middleware::auth::{AuthUser, OptionalAuthUser};
|
||||||
|
|
||||||
type AppState = Arc<FolderService>;
|
type AppState = Arc<FolderService>;
|
||||||
|
|
||||||
@@ -37,14 +37,16 @@ impl FolderHandler {
|
|||||||
let home_folder_name = format!("My Folder - {}", auth_user.username);
|
let home_folder_name = format!("My Folder - {}", auth_user.username);
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"create_folder: parent_id is None for user '{}', looking up home folder '{}'",
|
"create_folder: parent_id is None for user '{}', looking up home folder '{}'",
|
||||||
auth_user.username, home_folder_name
|
auth_user.username,
|
||||||
|
home_folder_name
|
||||||
);
|
);
|
||||||
match service.list_folders(None).await {
|
match service.list_folders(None).await {
|
||||||
Ok(folders) => {
|
Ok(folders) => {
|
||||||
if let Some(home) = folders.iter().find(|f| f.name == home_folder_name) {
|
if let Some(home) = folders.iter().find(|f| f.name == home_folder_name) {
|
||||||
tracing::info!(
|
tracing::info!(
|
||||||
"create_folder: resolved home folder ID '{}' for user '{}'",
|
"create_folder: resolved home folder ID '{}' for user '{}'",
|
||||||
home.id, auth_user.username
|
home.id,
|
||||||
|
auth_user.username
|
||||||
);
|
);
|
||||||
dto.parent_id = Some(home.id.clone());
|
dto.parent_id = Some(home.id.clone());
|
||||||
} else {
|
} else {
|
||||||
@@ -55,7 +57,10 @@ impl FolderHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("create_folder: failed to list folders for home resolution: {}", e);
|
tracing::error!(
|
||||||
|
"create_folder: failed to list folders for home resolution: {}",
|
||||||
|
e
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,18 +150,20 @@ impl FolderHandler {
|
|||||||
parent_id: Option<&str>,
|
parent_id: Option<&str>,
|
||||||
) -> axum::response::Response {
|
) -> axum::response::Response {
|
||||||
match service.list_folders(parent_id).await {
|
match service.list_folders(parent_id).await {
|
||||||
Ok(folders) => {
|
Ok(folders) => (StatusCode::OK, Json(folders)).into_response(),
|
||||||
(StatusCode::OK, Json(folders)).into_response()
|
|
||||||
},
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let status = match err.kind {
|
let status = match err.kind {
|
||||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
};
|
};
|
||||||
|
|
||||||
(status, Json(serde_json::json!({
|
(
|
||||||
|
status,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": err.to_string()
|
"error": err.to_string()
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -172,7 +179,9 @@ impl FolderHandler {
|
|||||||
Ok(folders) => {
|
Ok(folders) => {
|
||||||
// Only filter at root level (parent_id == None)
|
// Only filter at root level (parent_id == None)
|
||||||
let filtered = if parent_id.is_none() {
|
let filtered = if parent_id.is_none() {
|
||||||
folders.into_iter().filter(|f| {
|
folders
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| {
|
||||||
// Skip hidden/system folders
|
// Skip hidden/system folders
|
||||||
if f.name.starts_with('.') {
|
if f.name.starts_with('.') {
|
||||||
return false;
|
return false;
|
||||||
@@ -183,20 +192,25 @@ impl FolderHandler {
|
|||||||
}
|
}
|
||||||
// Non-home folders are visible to everyone
|
// Non-home folders are visible to everyone
|
||||||
true
|
true
|
||||||
}).collect()
|
})
|
||||||
|
.collect()
|
||||||
} else {
|
} else {
|
||||||
folders
|
folders
|
||||||
};
|
};
|
||||||
(StatusCode::OK, Json(filtered)).into_response()
|
(StatusCode::OK, Json(filtered)).into_response()
|
||||||
},
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let status = match err.kind {
|
let status = match err.kind {
|
||||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
};
|
};
|
||||||
(status, Json(serde_json::json!({
|
(
|
||||||
|
status,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": err.to_string()
|
"error": err.to_string()
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,9 +222,7 @@ impl FolderHandler {
|
|||||||
parent_id: Option<&str>,
|
parent_id: Option<&str>,
|
||||||
) -> axum::response::Response {
|
) -> axum::response::Response {
|
||||||
match service.list_folders_paginated(parent_id, &pagination).await {
|
match service.list_folders_paginated(parent_id, &pagination).await {
|
||||||
Ok(paginated_result) => {
|
Ok(paginated_result) => (StatusCode::OK, Json(paginated_result)).into_response(),
|
||||||
(StatusCode::OK, Json(paginated_result)).into_response()
|
|
||||||
},
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let status = match err.kind {
|
let status = match err.kind {
|
||||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||||
@@ -218,9 +230,13 @@ impl FolderHandler {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Return a JSON error response
|
// Return a JSON error response
|
||||||
(status, Json(serde_json::json!({
|
(
|
||||||
|
status,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": err.to_string()
|
"error": err.to_string()
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -241,9 +257,13 @@ impl FolderHandler {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Return a proper JSON error response
|
// Return a proper JSON error response
|
||||||
(status, Json(serde_json::json!({
|
(
|
||||||
|
status,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": err.to_string()
|
"error": err.to_string()
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -293,7 +313,10 @@ impl FolderHandler {
|
|||||||
OptionalAuthUser(auth_user): OptionalAuthUser,
|
OptionalAuthUser(auth_user): OptionalAuthUser,
|
||||||
Path(id): Path<String>,
|
Path(id): Path<String>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
let user_id = auth_user.as_ref().map(|u| u.id.as_str()).unwrap_or("anonymous");
|
let user_id = auth_user
|
||||||
|
.as_ref()
|
||||||
|
.map(|u| u.id.as_str())
|
||||||
|
.unwrap_or("anonymous");
|
||||||
// Check if trash service is available
|
// Check if trash service is available
|
||||||
if let Some(trash_service) = &state.trash_service {
|
if let Some(trash_service) = &state.trash_service {
|
||||||
tracing::info!("Moving folder to trash: {}", id);
|
tracing::info!("Moving folder to trash: {}", id);
|
||||||
@@ -303,9 +326,12 @@ impl FolderHandler {
|
|||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
tracing::info!("Folder successfully moved to trash: {}", id);
|
tracing::info!("Folder successfully moved to trash: {}", id);
|
||||||
return StatusCode::NO_CONTENT.into_response();
|
return StatusCode::NO_CONTENT.into_response();
|
||||||
},
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::warn!("Could not move folder to trash, falling back to permanent delete: {}", err);
|
tracing::warn!(
|
||||||
|
"Could not move folder to trash, falling back to permanent delete: {}",
|
||||||
|
err
|
||||||
|
);
|
||||||
// Fall through to regular delete if trash fails
|
// Fall through to regular delete if trash fails
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -317,7 +343,7 @@ impl FolderHandler {
|
|||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
tracing::info!("Folder permanently deleted: {}", id);
|
tracing::info!("Folder permanently deleted: {}", id);
|
||||||
StatusCode::NO_CONTENT.into_response()
|
StatusCode::NO_CONTENT.into_response()
|
||||||
},
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::error!("Error deleting folder: {}", err);
|
tracing::error!("Error deleting folder: {}", err);
|
||||||
|
|
||||||
@@ -326,9 +352,13 @@ impl FolderHandler {
|
|||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
};
|
};
|
||||||
|
|
||||||
(status, Json(serde_json::json!({
|
(
|
||||||
|
status,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": format!("Error deleting folder: {}", err)
|
"error": format!("Error deleting folder: {}", err)
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -354,7 +384,10 @@ impl FolderHandler {
|
|||||||
// Create the ZIP file
|
// Create the ZIP file
|
||||||
match zip_service.create_folder_zip(&id, &folder.name).await {
|
match zip_service.create_folder_zip(&id, &folder.name).await {
|
||||||
Ok(zip_data) => {
|
Ok(zip_data) => {
|
||||||
tracing::info!("ZIP file created successfully, size: {} bytes", zip_data.len());
|
tracing::info!(
|
||||||
|
"ZIP file created successfully, size: {} bytes",
|
||||||
|
zip_data.len()
|
||||||
|
);
|
||||||
|
|
||||||
// Setup headers for download
|
// Setup headers for download
|
||||||
let filename = format!("{}.zip", folder.name);
|
let filename = format!("{}.zip", folder.name);
|
||||||
@@ -362,9 +395,16 @@ impl FolderHandler {
|
|||||||
|
|
||||||
// Build response with the ZIP data
|
// Build response with the ZIP data
|
||||||
let mut headers = HashMap::new();
|
let mut headers = HashMap::new();
|
||||||
headers.insert(header::CONTENT_TYPE.to_string(), "application/zip".to_string());
|
headers.insert(
|
||||||
headers.insert(header::CONTENT_DISPOSITION.to_string(), content_disposition);
|
header::CONTENT_TYPE.to_string(),
|
||||||
headers.insert(header::CONTENT_LENGTH.to_string(), zip_data.len().to_string());
|
"application/zip".to_string(),
|
||||||
|
);
|
||||||
|
headers
|
||||||
|
.insert(header::CONTENT_DISPOSITION.to_string(), content_disposition);
|
||||||
|
headers.insert(
|
||||||
|
header::CONTENT_LENGTH.to_string(),
|
||||||
|
zip_data.len().to_string(),
|
||||||
|
);
|
||||||
|
|
||||||
// Build the response
|
// Build the response
|
||||||
let mut response = Response::builder()
|
let mut response = Response::builder()
|
||||||
@@ -376,20 +416,24 @@ impl FolderHandler {
|
|||||||
for (name, value) in headers {
|
for (name, value) in headers {
|
||||||
response.headers_mut().insert(
|
response.headers_mut().insert(
|
||||||
HeaderName::from_bytes(name.as_bytes()).unwrap(),
|
HeaderName::from_bytes(name.as_bytes()).unwrap(),
|
||||||
HeaderValue::from_str(&value).unwrap()
|
HeaderValue::from_str(&value).unwrap(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
response
|
response
|
||||||
},
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::error!("Error creating ZIP file: {}", err);
|
tracing::error!("Error creating ZIP file: {}", err);
|
||||||
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": format!("Error creating ZIP file: {}", err)
|
"error": format!("Error creating ZIP file: {}", err)
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::error!("Folder not found: {}", err);
|
tracing::error!("Folder not found: {}", err);
|
||||||
let status = match err.kind {
|
let status = match err.kind {
|
||||||
@@ -397,9 +441,13 @@ impl FolderHandler {
|
|||||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
};
|
};
|
||||||
|
|
||||||
(status, Json(serde_json::json!({
|
(
|
||||||
|
status,
|
||||||
|
Json(serde_json::json!({
|
||||||
"error": format!("Error finding folder: {}", err)
|
"error": format!("Error finding folder: {}", err)
|
||||||
}))).into_response()
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user