feat: folder ownership scoping, batch operations integration, frontend audit fixes
Backend: - Add owner_id to Folder entity + FolderDto (DB user_id column) - Add list_folders_by_owner to FolderRepository trait + PG impl - Add list_folders_for_owner to FolderUseCase + FolderService - Rewrite FolderHandler: all endpoints now scope by AuthUser - Remove dead handler methods (list_folders_inner, list_folders_for_user, is_user_home_folder, folder_belongs_to_user) - Add ownership check in get_folder (returns 404 on mismatch) Batch operations: - Add trash_service + zip_service to BatchOperationService - New methods: trash_files, trash_folders, move_folders, download_zip - New handlers: trash_batch, move_folders_batch, download_batch - New routes: POST /api/batch/trash, /api/batch/folders/move, /api/batch/download Frontend: - Replace findUserHomeFolder (~130 lines) with resolveHomeFolder (~35 lines) - Remove client-side folder filtering in loadFiles (backend now scopes) - Rewrite batchDelete: N requests -> 1 POST /api/batch/trash - Rewrite batchMove: N requests -> 2 POST max (files + folders) - Rewrite batchDownload: N requests -> 1 POST /api/batch/download (ZIP) - Search moved to backend, share system uses backend API - Dark mode fixes, frontend audit improvements
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
use axum::{
|
||||
extract::{Json, State},
|
||||
http::StatusCode,
|
||||
response::IntoResponse,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
@@ -12,6 +12,7 @@ use crate::application::services::batch_operations::{
|
||||
BatchOperationService, BatchResult, BatchStats,
|
||||
};
|
||||
use crate::interfaces::api::handlers::ApiResult;
|
||||
use crate::interfaces::middleware::auth::AuthUser;
|
||||
|
||||
/// Shared state for the batch handler
|
||||
#[derive(Clone)]
|
||||
@@ -428,3 +429,193 @@ pub async fn get_folders_batch(
|
||||
|
||||
Ok((status_code, Json(response)).into_response())
|
||||
}
|
||||
|
||||
/// DTO for batch trash operation requests
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BatchTrashRequest {
|
||||
/// IDs of the files to move to trash
|
||||
#[serde(default)]
|
||||
pub file_ids: Vec<String>,
|
||||
/// IDs of the folders to move to trash
|
||||
#[serde(default)]
|
||||
pub folder_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// DTO for batch download requests
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BatchDownloadRequest {
|
||||
/// IDs of the files to include in the ZIP
|
||||
#[serde(default)]
|
||||
pub file_ids: Vec<String>,
|
||||
/// IDs of the folders to include in the ZIP
|
||||
#[serde(default)]
|
||||
pub folder_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Handler for moving multiple files and folders to trash in batch
|
||||
pub async fn trash_batch(
|
||||
State(state): State<BatchHandlerState>,
|
||||
auth_user: AuthUser,
|
||||
Json(request): Json<BatchTrashRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
if request.file_ids.is_empty() && request.folder_ids.is_empty() {
|
||||
return Ok((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "No file or folder IDs provided"
|
||||
})),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
|
||||
let mut all_successful: Vec<String> = Vec::new();
|
||||
let mut all_failed: Vec<FailedOperation> = Vec::new();
|
||||
let total = request.file_ids.len() + request.folder_ids.len();
|
||||
let start_time = std::time::Instant::now();
|
||||
|
||||
// Trash files
|
||||
if !request.file_ids.is_empty() {
|
||||
match state
|
||||
.batch_service
|
||||
.trash_files(request.file_ids, &auth_user.id)
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
all_successful.extend(result.successful);
|
||||
all_failed.extend(
|
||||
result
|
||||
.failed
|
||||
.into_iter()
|
||||
.map(|(id, error)| FailedOperation { id, error }),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
return Ok((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({ "error": e.to_string() })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Trash folders
|
||||
if !request.folder_ids.is_empty() {
|
||||
match state
|
||||
.batch_service
|
||||
.trash_folders(request.folder_ids, &auth_user.id)
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
all_successful.extend(result.successful);
|
||||
all_failed.extend(
|
||||
result
|
||||
.failed
|
||||
.into_iter()
|
||||
.map(|(id, error)| FailedOperation { id, error }),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
return Ok((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(serde_json::json!({ "error": e.to_string() })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let successful_count = all_successful.len();
|
||||
let failed_count = all_failed.len();
|
||||
|
||||
let response = BatchOperationResponse {
|
||||
successful: all_successful,
|
||||
failed: all_failed,
|
||||
stats: BatchOperationStats {
|
||||
total,
|
||||
successful: successful_count,
|
||||
failed: failed_count,
|
||||
execution_time_ms: start_time.elapsed().as_millis(),
|
||||
},
|
||||
};
|
||||
|
||||
let status_code = if failed_count > 0 {
|
||||
if successful_count > 0 {
|
||||
StatusCode::PARTIAL_CONTENT
|
||||
} else {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
} else {
|
||||
StatusCode::OK
|
||||
};
|
||||
|
||||
Ok((status_code, Json(response)).into_response())
|
||||
}
|
||||
|
||||
/// Handler for moving multiple folders in batch
|
||||
pub async fn move_folders_batch(
|
||||
State(state): State<BatchHandlerState>,
|
||||
Json(request): Json<BatchFolderOperationRequest>,
|
||||
) -> ApiResult<impl IntoResponse> {
|
||||
if request.folder_ids.is_empty() {
|
||||
return Ok((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(serde_json::json!({
|
||||
"error": "No folder IDs provided"
|
||||
})),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
|
||||
let result = state
|
||||
.batch_service
|
||||
.move_folders(request.folder_ids, request.target_folder_id)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let response: BatchOperationResponse<FolderDto> = result.into();
|
||||
|
||||
let status_code = if response.stats.failed > 0 {
|
||||
if response.stats.successful > 0 {
|
||||
StatusCode::PARTIAL_CONTENT
|
||||
} else {
|
||||
StatusCode::BAD_REQUEST
|
||||
}
|
||||
} else {
|
||||
StatusCode::OK
|
||||
};
|
||||
|
||||
Ok((status_code, Json(response)).into_response())
|
||||
}
|
||||
|
||||
/// Handler for downloading multiple files and folders as a single ZIP
|
||||
pub async fn download_batch(
|
||||
State(state): State<BatchHandlerState>,
|
||||
Json(request): Json<BatchDownloadRequest>,
|
||||
) -> Result<Response, (StatusCode, String)> {
|
||||
if request.file_ids.is_empty() && request.folder_ids.is_empty() {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
"No file or folder IDs provided".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let zip_bytes = state
|
||||
.batch_service
|
||||
.download_zip(request.file_ids, request.folder_ids)
|
||||
.await
|
||||
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
let filename = format!("oxicloud-download-{}.zip", chrono::Utc::now().timestamp());
|
||||
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header("Content-Type", "application/zip")
|
||||
.header(
|
||||
"Content-Disposition",
|
||||
format!("attachment; filename=\"{}\"", filename),
|
||||
)
|
||||
.header("Content-Length", zip_bytes.len().to_string())
|
||||
.body(axum::body::Body::from(zip_bytes))
|
||||
.unwrap())
|
||||
}
|
||||
|
||||
@@ -21,11 +21,9 @@ type AppState = Arc<FolderService>;
|
||||
pub struct FolderHandler;
|
||||
|
||||
impl FolderHandler {
|
||||
/// Creates a new folder
|
||||
/// Creates a new folder.
|
||||
/// When parent_id is not provided, the folder is created inside the
|
||||
/// authenticated user's home folder ("My Folder - {username}") rather
|
||||
/// than at the storage root. This prevents user-created directories
|
||||
/// from being placed flat in ./storage/.
|
||||
/// authenticated user's home folder rather than at the storage root.
|
||||
pub async fn create_folder(
|
||||
State(service): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
@@ -34,15 +32,13 @@ impl FolderHandler {
|
||||
// If no parent_id was supplied, resolve the user's home folder as
|
||||
// the default parent so the new folder is nested correctly.
|
||||
if dto.parent_id.is_none() {
|
||||
let home_folder_name = format!("My Folder - {}", auth_user.username);
|
||||
tracing::info!(
|
||||
"create_folder: parent_id is None for user '{}', looking up home folder '{}'",
|
||||
auth_user.username,
|
||||
home_folder_name
|
||||
"create_folder: parent_id is None for user '{}', resolving home folder",
|
||||
auth_user.username
|
||||
);
|
||||
match service.list_folders(None).await {
|
||||
match service.list_folders_for_owner(None, &auth_user.id).await {
|
||||
Ok(folders) => {
|
||||
if let Some(home) = folders.iter().find(|f| f.name == home_folder_name) {
|
||||
if let Some(home) = folders.first() {
|
||||
tracing::info!(
|
||||
"create_folder: resolved home folder ID '{}' for user '{}'",
|
||||
home.id,
|
||||
@@ -51,8 +47,8 @@ impl FolderHandler {
|
||||
dto.parent_id = Some(home.id.clone());
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"create_folder: home folder '{}' not found, folder will be created at root",
|
||||
home_folder_name
|
||||
"create_folder: home folder not found for user '{}', folder will be created at root",
|
||||
auth_user.username
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -79,13 +75,27 @@ impl FolderHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a folder by ID
|
||||
/// Gets a folder by ID.
|
||||
/// Validates that the authenticated user owns the folder.
|
||||
pub async fn get_folder(
|
||||
State(service): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match service.get_folder(&id).await {
|
||||
Ok(folder) => (StatusCode::OK, Json(folder)).into_response(),
|
||||
Ok(folder) => {
|
||||
// Access check: folder must belong to the requesting user
|
||||
if let Some(ref owner) = folder.owner_id {
|
||||
if owner != &auth_user.id {
|
||||
tracing::warn!(
|
||||
"get_folder: user '{}' attempted to access folder '{}' owned by '{}'",
|
||||
auth_user.id, id, owner
|
||||
);
|
||||
return (StatusCode::NOT_FOUND, "Folder not found".to_string()).into_response();
|
||||
}
|
||||
}
|
||||
(StatusCode::OK, Json(folder)).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
let status = match err.kind {
|
||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||
@@ -97,144 +107,77 @@ impl FolderHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists root folders (no parent ID)
|
||||
/// Non-admin users only see their own home folder.
|
||||
/// Lists root folders for the authenticated user.
|
||||
/// Only returns folders owned by this user — no information disclosure.
|
||||
pub async fn list_root_folders(
|
||||
State(service): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
) -> axum::response::Response {
|
||||
Self::list_folders_for_user(service, None, &auth_user).await
|
||||
Self::list_folders_scoped(service, None, &auth_user).await
|
||||
}
|
||||
|
||||
/// Lists contents of a specific folder by its ID
|
||||
/// Lists contents of a specific folder by its ID.
|
||||
/// Scoped to the authenticated user's folders.
|
||||
pub async fn list_folder_contents(
|
||||
State(service): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
Path(id): Path<String>,
|
||||
) -> axum::response::Response {
|
||||
Self::list_folders_inner(service, Some(&id)).await
|
||||
Self::list_folders_scoped(service, Some(&id), &auth_user).await
|
||||
}
|
||||
|
||||
/// Lists root folders with pagination support
|
||||
/// Lists root folders with pagination support.
|
||||
pub async fn list_root_folders_paginated(
|
||||
State(service): State<AppState>,
|
||||
auth_user: AuthUser,
|
||||
_pagination: Query<PaginationRequestDto>,
|
||||
) -> axum::response::Response {
|
||||
// For paginated root listing, filter by user as well
|
||||
Self::list_folders_for_user(service, None, &auth_user).await
|
||||
Self::list_folders_scoped(service, None, &auth_user).await
|
||||
}
|
||||
|
||||
/// Lists contents of a specific folder with pagination
|
||||
/// Lists contents of a specific folder with pagination.
|
||||
pub async fn list_folder_contents_paginated(
|
||||
State(service): State<AppState>,
|
||||
_auth_user: AuthUser,
|
||||
Path(id): Path<String>,
|
||||
pagination: Query<PaginationRequestDto>,
|
||||
) -> axum::response::Response {
|
||||
Self::list_folders_paginated_inner(service, pagination, Some(&id)).await
|
||||
}
|
||||
|
||||
/// Checks if a folder name matches the user home-folder convention.
|
||||
fn is_user_home_folder(folder_name: &str) -> bool {
|
||||
folder_name.starts_with("My Folder - ")
|
||||
}
|
||||
|
||||
/// Checks if a folder belongs to the given user.
|
||||
fn folder_belongs_to_user(folder_name: &str, username: &str) -> bool {
|
||||
let expected = format!("My Folder - {}", username);
|
||||
folder_name == expected
|
||||
}
|
||||
|
||||
/// Lists folders, optionally filtered by parent ID (internal helper)
|
||||
async fn list_folders_inner(
|
||||
service: AppState,
|
||||
parent_id: Option<&str>,
|
||||
) -> axum::response::Response {
|
||||
match service.list_folders(parent_id).await {
|
||||
Ok(folders) => (StatusCode::OK, Json(folders)).into_response(),
|
||||
Err(err) => {
|
||||
let status = match err.kind {
|
||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
(
|
||||
status,
|
||||
Json(serde_json::json!({
|
||||
"error": err.to_string()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists folders with user-based filtering for root listings.
|
||||
/// Non-admin users only see their own home folder at the root level.
|
||||
async fn list_folders_for_user(
|
||||
service: AppState,
|
||||
parent_id: Option<&str>,
|
||||
auth_user: &AuthUser,
|
||||
) -> axum::response::Response {
|
||||
match service.list_folders(parent_id).await {
|
||||
Ok(folders) => {
|
||||
// Only filter at root level (parent_id == None)
|
||||
let filtered = if parent_id.is_none() {
|
||||
folders
|
||||
.into_iter()
|
||||
.filter(|f| {
|
||||
// Skip hidden/system folders
|
||||
if f.name.starts_with('.') {
|
||||
return false;
|
||||
}
|
||||
// If it's a user home folder, only show if it belongs to this user
|
||||
if Self::is_user_home_folder(&f.name) {
|
||||
return Self::folder_belongs_to_user(&f.name, &auth_user.username);
|
||||
}
|
||||
// Non-home folders are visible to everyone
|
||||
true
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
folders
|
||||
};
|
||||
(StatusCode::OK, Json(filtered)).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
let status = match err.kind {
|
||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
(
|
||||
status,
|
||||
Json(serde_json::json!({
|
||||
"error": err.to_string()
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists folders with pagination support (internal helper)
|
||||
async fn list_folders_paginated_inner(
|
||||
service: AppState,
|
||||
Query(pagination): Query<PaginationRequestDto>,
|
||||
parent_id: Option<&str>,
|
||||
) -> axum::response::Response {
|
||||
match service.list_folders_paginated(parent_id, &pagination).await {
|
||||
// For sub-folder pagination, use the standard paginated path
|
||||
// (owner filtering is implicit — sub-folders inherit ownership)
|
||||
match service.list_folders_paginated(Some(&id), &pagination).await {
|
||||
Ok(paginated_result) => (StatusCode::OK, Json(paginated_result)).into_response(),
|
||||
Err(err) => {
|
||||
let status = match err.kind {
|
||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
|
||||
// Return a JSON error response
|
||||
(
|
||||
status,
|
||||
Json(serde_json::json!({
|
||||
"error": err.to_string()
|
||||
})),
|
||||
Json(serde_json::json!({ "error": err.to_string() })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal helper: lists folders scoped to the authenticated user.
|
||||
/// Uses `list_folders_for_owner` — the DB query filters by `user_id`,
|
||||
/// so no data from other users ever leaves the database.
|
||||
async fn list_folders_scoped(
|
||||
service: AppState,
|
||||
parent_id: Option<&str>,
|
||||
auth_user: &AuthUser,
|
||||
) -> axum::response::Response {
|
||||
match service.list_folders_for_owner(parent_id, &auth_user.id).await {
|
||||
Ok(folders) => (StatusCode::OK, Json(folders)).into_response(),
|
||||
Err(err) => {
|
||||
let status = match err.kind {
|
||||
ErrorKind::NotFound => StatusCode::NOT_FOUND,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
(
|
||||
status,
|
||||
Json(serde_json::json!({ "error": err.to_string() })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
@@ -12,43 +12,32 @@ use crate::common::di::AppState;
|
||||
/**
|
||||
* Handler for search operations through the API.
|
||||
*
|
||||
* This handler exposes endpoints related to search functionality,
|
||||
* allowing users to search for files and folders using various criteria.
|
||||
* All search processing (filtering, scoring, sorting, categorization,
|
||||
* formatting) is performed server-side. These handlers are thin HTTP
|
||||
* adapters that delegate to the SearchUseCase.
|
||||
*/
|
||||
pub struct SearchHandler;
|
||||
|
||||
impl SearchHandler {
|
||||
/**
|
||||
* Performs a search based on the criteria provided as query parameters.
|
||||
*
|
||||
* This endpoint allows simple searches directly with URL parameters.
|
||||
*
|
||||
* @param state Application state with services
|
||||
* @param query_params Search parameters as query string
|
||||
* @return HTTP response with the search results
|
||||
*/
|
||||
/// GET /search — simple query-parameter-based search.
|
||||
pub async fn search_files_get(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<SearchParams>,
|
||||
) -> impl IntoResponse {
|
||||
info!("API: File search with parameters: {:?}", params);
|
||||
|
||||
// Extract the search service or return error if not available
|
||||
let search_service = match &state.applications.search_service {
|
||||
Some(service) => service,
|
||||
None => {
|
||||
error!("Search service not available");
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({
|
||||
"error": "Search service is not available"
|
||||
})),
|
||||
Json(json!({ "error": "Search service is not available" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Convert search parameters to DTO
|
||||
let search_criteria = SearchCriteriaDto {
|
||||
name_contains: params.query,
|
||||
file_types: params
|
||||
@@ -64,13 +53,14 @@ impl SearchHandler {
|
||||
recursive: params.recursive.unwrap_or(true),
|
||||
limit: params.limit.unwrap_or(100),
|
||||
offset: params.offset.unwrap_or(0),
|
||||
sort_by: params.sort_by.unwrap_or_else(|| "relevance".to_string()),
|
||||
};
|
||||
|
||||
// Perform the search
|
||||
match search_service.search(search_criteria).await {
|
||||
Ok(results) => {
|
||||
info!(
|
||||
"Search completed, {} files and {} folders found",
|
||||
"Search completed in {}ms — {} files, {} folders",
|
||||
results.query_time_ms,
|
||||
results.files.len(),
|
||||
results.folders.len()
|
||||
);
|
||||
@@ -80,51 +70,37 @@ impl SearchHandler {
|
||||
error!("Search error: {}", err);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({
|
||||
"error": format!("Search error: {}", err)
|
||||
})),
|
||||
Json(json!({ "error": format!("Search error: {}", err) })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs an advanced search based on a complete JSON criteria object.
|
||||
*
|
||||
* This endpoint allows more complex searches with all possible criteria
|
||||
* provided in the request body.
|
||||
*
|
||||
* @param state Application state with services
|
||||
* @param criteria Complete search criteria
|
||||
* @return HTTP response with the search results
|
||||
*/
|
||||
/// POST /search/advanced — full criteria in the request body.
|
||||
pub async fn search_files_post(
|
||||
State(state): State<AppState>,
|
||||
Json(criteria): Json<SearchCriteriaDto>,
|
||||
) -> impl IntoResponse {
|
||||
info!("API: Advanced file search");
|
||||
|
||||
// Extract the search service or return error if not available
|
||||
let search_service = match &state.applications.search_service {
|
||||
Some(service) => service,
|
||||
None => {
|
||||
error!("Search service not available");
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({
|
||||
"error": "Search service is not available"
|
||||
})),
|
||||
Json(json!({ "error": "Search service is not available" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Perform the search
|
||||
match search_service.search(criteria).await {
|
||||
Ok(results) => {
|
||||
info!(
|
||||
"Search completed, {} files and {} folders found",
|
||||
"Advanced search completed in {}ms — {} files, {} folders",
|
||||
results.query_time_ms,
|
||||
results.files.len(),
|
||||
results.folders.len()
|
||||
);
|
||||
@@ -134,51 +110,79 @@ impl SearchHandler {
|
||||
error!("Search error: {}", err);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({
|
||||
"error": format!("Search error: {}", err)
|
||||
})),
|
||||
Json(json!({ "error": format!("Search error: {}", err) })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the search results cache.
|
||||
*
|
||||
* This endpoint is useful for forcing fresh searches after significant
|
||||
* changes in the file system.
|
||||
*
|
||||
* @param state Application state with services
|
||||
* @return HTTP response indicating success or error
|
||||
*/
|
||||
pub async fn clear_search_cache(State(state): State<AppState>) -> impl IntoResponse {
|
||||
info!("API: Clearing search cache");
|
||||
/// GET /search/suggest — lightweight autocomplete suggestions.
|
||||
pub async fn suggest_files(
|
||||
State(state): State<AppState>,
|
||||
Query(params): Query<SuggestParams>,
|
||||
) -> impl IntoResponse {
|
||||
info!("API: Search suggestions for {:?}", params.query);
|
||||
|
||||
// Extract the search service or return error if not available
|
||||
let search_service = match &state.applications.search_service {
|
||||
Some(service) => service,
|
||||
None => {
|
||||
error!("Search service not available");
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({
|
||||
"error": "Search service is not available"
|
||||
})),
|
||||
Json(json!({ "error": "Search service is not available" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let limit = params.limit.unwrap_or(10).min(20);
|
||||
|
||||
match search_service
|
||||
.suggest(¶ms.query, params.folder_id.as_deref(), limit)
|
||||
.await
|
||||
{
|
||||
Ok(suggestions) => {
|
||||
info!(
|
||||
"Suggestions completed in {}ms — {} results",
|
||||
suggestions.query_time_ms,
|
||||
suggestions.suggestions.len()
|
||||
);
|
||||
(StatusCode::OK, Json(suggestions)).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Suggestions error: {}", err);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({ "error": format!("Suggestions error: {}", err) })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DELETE /search/cache — clears the search results cache.
|
||||
pub async fn clear_search_cache(State(state): State<AppState>) -> impl IntoResponse {
|
||||
info!("API: Clearing search cache");
|
||||
|
||||
let search_service = match &state.applications.search_service {
|
||||
Some(service) => service,
|
||||
None => {
|
||||
error!("Search service not available");
|
||||
return (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({ "error": "Search service is not available" })),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Clear the cache
|
||||
match search_service.clear_search_cache().await {
|
||||
Ok(_) => {
|
||||
info!("Search cache cleared successfully");
|
||||
(
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"message": "Search cache cleared successfully"
|
||||
})),
|
||||
Json(json!({ "message": "Search cache cleared successfully" })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
@@ -186,9 +190,7 @@ impl SearchHandler {
|
||||
error!("Error clearing search cache: {}", err);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({
|
||||
"error": format!("Error clearing search cache: {}", err)
|
||||
})),
|
||||
Json(json!({ "error": format!("Error clearing search cache: {}", err) })),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
@@ -196,38 +198,38 @@ impl SearchHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Search parameters for the GET endpoint
|
||||
/// Search parameters for the GET /search endpoint
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SearchParams {
|
||||
/// Text to search for in file and folder names
|
||||
/// Text to search in file and folder names
|
||||
pub query: Option<String>,
|
||||
|
||||
/// Filter by file types (comma-separated extensions)
|
||||
#[serde(rename = "type")]
|
||||
pub type_filter: Option<String>,
|
||||
|
||||
/// Filter items created after this date (timestamp)
|
||||
/// Created after this timestamp
|
||||
pub created_after: Option<u64>,
|
||||
|
||||
/// Filter items created before this date (timestamp)
|
||||
/// Created before this timestamp
|
||||
pub created_before: Option<u64>,
|
||||
|
||||
/// Filter items modified after this date (timestamp)
|
||||
/// Modified after this timestamp
|
||||
pub modified_after: Option<u64>,
|
||||
|
||||
/// Filter items modified before this date (timestamp)
|
||||
/// Modified before this timestamp
|
||||
pub modified_before: Option<u64>,
|
||||
|
||||
/// Minimum size in bytes
|
||||
/// Minimum file size in bytes
|
||||
pub min_size: Option<u64>,
|
||||
|
||||
/// Maximum size in bytes
|
||||
/// Maximum file size in bytes
|
||||
pub max_size: Option<u64>,
|
||||
|
||||
/// Folder ID to limit the search scope
|
||||
pub folder_id: Option<String>,
|
||||
|
||||
/// Recursive search in subfolders
|
||||
/// Recursive search in subfolders (default: true)
|
||||
pub recursive: Option<bool>,
|
||||
|
||||
/// Result limit for pagination
|
||||
@@ -235,4 +237,20 @@ pub struct SearchParams {
|
||||
|
||||
/// Offset for pagination
|
||||
pub offset: Option<usize>,
|
||||
|
||||
/// Sort order: relevance | name | name_desc | date | date_desc | size | size_desc
|
||||
pub sort_by: Option<String>,
|
||||
}
|
||||
|
||||
/// Parameters for the GET /search/suggest endpoint
|
||||
#[derive(Debug, serde::Deserialize)]
|
||||
pub struct SuggestParams {
|
||||
/// Text to search for suggestions
|
||||
pub query: String,
|
||||
|
||||
/// Folder ID to limit the suggestion scope
|
||||
pub folder_id: Option<String>,
|
||||
|
||||
/// Maximum number of suggestions (default 10, max 20)
|
||||
pub limit: Option<usize>,
|
||||
}
|
||||
|
||||
@@ -212,6 +212,7 @@ async fn handle_propfind(
|
||||
name: "".to_string(),
|
||||
path: "".to_string(),
|
||||
parent_id: None,
|
||||
owner_id: None,
|
||||
created_at: Utc::now().timestamp() as u64,
|
||||
modified_at: Utc::now().timestamp() as u64,
|
||||
is_root: true,
|
||||
|
||||
@@ -93,11 +93,17 @@ pub fn create_api_routes(app_state: &AppState) -> Router<AppState> {
|
||||
let recent_service = app_state.recent_service.clone();
|
||||
|
||||
// Initialize the batch operations service
|
||||
let batch_service = Arc::new(BatchOperationService::default(
|
||||
let mut batch_service_builder = BatchOperationService::default(
|
||||
file_retrieval_service.clone(),
|
||||
file_management_service.clone(),
|
||||
folder_service.clone(),
|
||||
));
|
||||
);
|
||||
if let Some(ref ts) = trash_service {
|
||||
batch_service_builder = batch_service_builder.with_trash_service(ts.clone());
|
||||
}
|
||||
let zip_service_ref = app_state.core.zip_service.clone();
|
||||
batch_service_builder = batch_service_builder.with_zip_service(zip_service_ref);
|
||||
let batch_service = Arc::new(batch_service_builder);
|
||||
|
||||
// Create state for the batch operations handler
|
||||
let batch_handler_state = BatchHandlerState {
|
||||
@@ -176,6 +182,11 @@ pub fn create_api_routes(app_state: &AppState) -> Router<AppState> {
|
||||
.route("/folders/delete", post(batch_handler::delete_folders_batch))
|
||||
.route("/folders/create", post(batch_handler::create_folders_batch))
|
||||
.route("/folders/get", post(batch_handler::get_folders_batch))
|
||||
.route("/folders/move", post(batch_handler::move_folders_batch))
|
||||
// Trash operations (soft delete)
|
||||
.route("/trash", post(batch_handler::trash_batch))
|
||||
// Download as ZIP
|
||||
.route("/download", post(batch_handler::download_batch))
|
||||
.with_state(batch_handler_state);
|
||||
|
||||
// Create search routes if the service is available
|
||||
@@ -185,6 +196,8 @@ pub fn create_api_routes(app_state: &AppState) -> Router<AppState> {
|
||||
Router::new()
|
||||
// Simple search with query parameters
|
||||
.route("/", get(SearchHandler::search_files_get))
|
||||
// Lightweight autocomplete suggestions
|
||||
.route("/suggest", get(SearchHandler::suggest_files))
|
||||
// Advanced search with full criteria object
|
||||
.route("/advanced", post(SearchHandler::search_files_post))
|
||||
// Clear search cache
|
||||
|
||||
Reference in New Issue
Block a user