feat(share): public folder browsing API + range support + zip
Five new public endpoints under /api/s/{token}/...:
GET /contents
GET /contents/{folder_id}
GET /file/{file_id}
GET /zip
GET /zip/{folder_id}
All honour the unlock cookie from /verify, so password-protected
folder shares work end-to-end.
Folder/file IDs are validated against the share subtree via a single
ltree containment query (O(log N) on the existing GiST index).
Out-of-scope IDs return 404.
download_shared_file refactored to a Range/304/206/416-aware
serve_share_file helper, shared with the new /file/{file_id}
endpoint. content_disposition extracted from FileHandler so RFC 5987
formatting is identical across auth and share download paths.
This commit is contained in:
@@ -8,12 +8,15 @@ use axum::{
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http_range_header::parse_range_header;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::application::services::share_browse_service::ZipTarget;
|
||||
use crate::application::services::share_service::ShareService;
|
||||
use crate::infrastructure::services::share_unlock_cookie;
|
||||
use crate::interfaces::api::handlers::file_handler::build_content_disposition;
|
||||
use crate::{
|
||||
application::{
|
||||
dtos::share_dto::{CreateShareDto, UpdateShareDto},
|
||||
@@ -27,6 +30,7 @@ use crate::{
|
||||
interfaces::errors::AppError,
|
||||
interfaces::middleware::auth::AuthUser,
|
||||
};
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
fn unlock_jwt_from_headers(headers: &HeaderMap, share_token: &str) -> Option<String> {
|
||||
headers
|
||||
@@ -370,46 +374,380 @@ pub async fn download_shared_file(
|
||||
return AppError::bad_request("Download is only supported for file shares").into_response();
|
||||
}
|
||||
|
||||
// 4. Retrieve file content via the internal (no-ownership-check) API
|
||||
// 4. Stream the file with full Range / 304 / 416 / 206 support.
|
||||
serve_share_file(
|
||||
&state,
|
||||
&share_dto.item_id,
|
||||
share_dto.item_name.as_deref(),
|
||||
&headers,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stream a file for a public share. Honours `If-None-Match` (304),
|
||||
/// `Range` (206 / 416), and falls back to a 200 via `get_file_optimized`.
|
||||
async fn serve_share_file(
|
||||
state: &Arc<AppState>,
|
||||
file_id: &str,
|
||||
name_override: Option<&str>,
|
||||
request_headers: &HeaderMap,
|
||||
) -> Response {
|
||||
let retrieval = &state.applications.file_retrieval_service;
|
||||
let file_id = &share_dto.item_id;
|
||||
|
||||
match retrieval.get_file_optimized(file_id, false, true).await {
|
||||
Ok((file_dto, content)) => {
|
||||
let file_name = share_dto.item_name.as_deref().unwrap_or(&file_dto.name);
|
||||
let disposition = format!(
|
||||
"attachment; filename=\"{}\"",
|
||||
file_name.replace('"', "\\\"")
|
||||
);
|
||||
let mime = file_dto.mime_type.clone();
|
||||
let file_dto = match retrieval.get_file(file_id).await {
|
||||
Ok(d) => d,
|
||||
Err(err) => return AppError::from(err).into_response(),
|
||||
};
|
||||
|
||||
match content {
|
||||
OptimizedFileContent::Bytes { data, .. } => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, data.len())
|
||||
.body(Body::from(data))
|
||||
let display_name = name_override.unwrap_or(&file_dto.name);
|
||||
let etag = format!("\"{}-{}\"", file_dto.id, file_dto.modified_at);
|
||||
let mime = file_dto.mime_type.clone();
|
||||
let disposition = build_content_disposition(display_name, &mime, false);
|
||||
|
||||
if let Some(inm) = request_headers.get(header::IF_NONE_MATCH)
|
||||
&& let Ok(client_etag) = inm.to_str()
|
||||
&& (client_etag == etag || client_etag == "*")
|
||||
{
|
||||
return Response::builder()
|
||||
.status(StatusCode::NOT_MODIFIED)
|
||||
.header(header::ETAG, &etag)
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
.into_response();
|
||||
}
|
||||
|
||||
if let Some(range_hdr) = request_headers.get(header::RANGE)
|
||||
&& let Ok(range_str) = range_hdr.to_str()
|
||||
&& let Ok(ranges) = parse_range_header(range_str)
|
||||
{
|
||||
match ranges.validate(file_dto.size) {
|
||||
Ok(valid_ranges) => {
|
||||
if let Some(range) = valid_ranges.first() {
|
||||
let start = *range.start();
|
||||
let end = *range.end();
|
||||
let length = end - start + 1;
|
||||
|
||||
match retrieval
|
||||
.get_file_range_stream(file_id, start, Some(end + 1))
|
||||
.await
|
||||
{
|
||||
Ok(stream) => {
|
||||
return Response::builder()
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, length)
|
||||
.header(
|
||||
header::CONTENT_RANGE,
|
||||
format!("bytes {}-{}/{}", start, end, file_dto.size),
|
||||
)
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::ETAG, &etag)
|
||||
.body(Body::from_stream(Box::into_pin(stream)))
|
||||
.unwrap()
|
||||
.into_response();
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!("share range stream error: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
return Response::builder()
|
||||
.status(StatusCode::RANGE_NOT_SATISFIABLE)
|
||||
.header(header::CONTENT_RANGE, format!("bytes */{}", file_dto.size))
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
.into_response(),
|
||||
OptimizedFileContent::Mmap(mmap_data) => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, mmap_data.len())
|
||||
.body(Body::from(mmap_data))
|
||||
.unwrap()
|
||||
.into_response(),
|
||||
OptimizedFileContent::Stream(stream) => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, file_dto.size)
|
||||
.body(Body::from_stream(stream))
|
||||
.unwrap()
|
||||
.into_response(),
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match retrieval.get_file_optimized(file_id, false, true).await {
|
||||
Ok((_, content)) => match content {
|
||||
OptimizedFileContent::Bytes { data, .. } => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, data.len())
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::ETAG, &etag)
|
||||
.body(Body::from(data))
|
||||
.unwrap()
|
||||
.into_response(),
|
||||
OptimizedFileContent::Mmap(mmap_data) => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, mmap_data.len())
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::ETAG, &etag)
|
||||
.body(Body::from(mmap_data))
|
||||
.unwrap()
|
||||
.into_response(),
|
||||
OptimizedFileContent::Stream(stream) => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, file_dto.size)
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::ETAG, &etag)
|
||||
.body(Body::from_stream(stream))
|
||||
.unwrap()
|
||||
.into_response(),
|
||||
},
|
||||
Err(err) => AppError::from(err).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public folder browsing endpoints ──────────────────────────────────────
|
||||
|
||||
fn sharing_disabled_response() -> Response {
|
||||
AppError::new(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"Sharing is disabled",
|
||||
"Disabled",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn share_browse_error_response(err: crate::common::errors::DomainError) -> Response {
|
||||
if err.kind == ErrorKind::AccessDenied {
|
||||
if err.message.contains("password") {
|
||||
return (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(json!({
|
||||
"error": "Password required",
|
||||
"requiresPassword": true
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
if err.message.contains("expired") {
|
||||
return AppError::new(StatusCode::GONE, err.message, "Expired").into_response();
|
||||
}
|
||||
}
|
||||
AppError::from(err).into_response()
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/s/{token}/contents",
|
||||
params(("token" = String, Path, description = "Share token")),
|
||||
responses(
|
||||
(status = 200, description = "Folder contents (sub-folders + files)"),
|
||||
(status = 400, description = "Share is not a folder share"),
|
||||
(status = 401, description = "Password required"),
|
||||
(status = 410, description = "Share expired"),
|
||||
(status = 503, description = "Sharing disabled")
|
||||
),
|
||||
tag = "shares"
|
||||
)]
|
||||
pub async fn list_share_contents_root(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(token): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
let Some(browse) = state.share_browse_service.clone() else {
|
||||
return sharing_disabled_response();
|
||||
};
|
||||
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
|
||||
|
||||
match browse.list_root(&token, unlock_jwt.as_deref()).await {
|
||||
Ok(listing) => (StatusCode::OK, Json(listing)).into_response(),
|
||||
Err(err) => share_browse_error_response(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/s/{token}/contents/{folder_id}",
|
||||
params(
|
||||
("token" = String, Path, description = "Share token"),
|
||||
("folder_id" = String, Path, description = "Subfolder ID (must be inside the share)")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Subfolder contents"),
|
||||
(status = 400, description = "Share is not a folder share"),
|
||||
(status = 401, description = "Password required"),
|
||||
(status = 404, description = "Subfolder not found or not in share scope"),
|
||||
(status = 410, description = "Share expired")
|
||||
),
|
||||
tag = "shares"
|
||||
)]
|
||||
pub async fn list_share_contents_subfolder(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path((token, folder_id)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
let Some(browse) = state.share_browse_service.clone() else {
|
||||
return sharing_disabled_response();
|
||||
};
|
||||
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
|
||||
|
||||
match browse
|
||||
.list_subfolder(&token, &folder_id, unlock_jwt.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(listing) => (StatusCode::OK, Json(listing)).into_response(),
|
||||
Err(err) => share_browse_error_response(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/s/{token}/file/{file_id}",
|
||||
params(
|
||||
("token" = String, Path, description = "Share token"),
|
||||
("file_id" = String, Path, description = "File ID (must be inside the share)")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "File content (or 206 for Range request)"),
|
||||
(status = 206, description = "Partial Content"),
|
||||
(status = 304, description = "Not Modified"),
|
||||
(status = 401, description = "Password required"),
|
||||
(status = 404, description = "File not found or not in share scope"),
|
||||
(status = 410, description = "Share expired"),
|
||||
(status = 416, description = "Range not satisfiable")
|
||||
),
|
||||
tag = "shares"
|
||||
)]
|
||||
pub async fn download_share_file_in_folder(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path((token, file_id)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
let Some(browse) = state.share_browse_service.clone() else {
|
||||
return sharing_disabled_response();
|
||||
};
|
||||
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
|
||||
|
||||
if let Err(err) = browse
|
||||
.assert_file_in_share(&token, &file_id, unlock_jwt.as_deref())
|
||||
.await
|
||||
{
|
||||
return share_browse_error_response(err);
|
||||
}
|
||||
|
||||
serve_share_file(&state, &file_id, None, &headers).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/s/{token}/zip",
|
||||
params(("token" = String, Path, description = "Share token")),
|
||||
responses(
|
||||
(status = 200, description = "ZIP archive of the shared folder"),
|
||||
(status = 400, description = "Share is not a folder share"),
|
||||
(status = 401, description = "Password required"),
|
||||
(status = 410, description = "Share expired"),
|
||||
(status = 503, description = "Sharing or ZIP service disabled")
|
||||
),
|
||||
tag = "shares"
|
||||
)]
|
||||
pub async fn download_share_zip_root(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(token): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
serve_share_zip(state, token, None, headers).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/s/{token}/zip/{folder_id}",
|
||||
params(
|
||||
("token" = String, Path, description = "Share token"),
|
||||
("folder_id" = String, Path, description = "Subfolder ID (must be inside the share)")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "ZIP archive of the subfolder"),
|
||||
(status = 401, description = "Password required"),
|
||||
(status = 404, description = "Subfolder not found or not in share scope"),
|
||||
(status = 410, description = "Share expired")
|
||||
),
|
||||
tag = "shares"
|
||||
)]
|
||||
pub async fn download_share_zip_subfolder(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path((token, folder_id)): Path<(String, String)>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
serve_share_zip(state, token, Some(folder_id), headers).await
|
||||
}
|
||||
|
||||
async fn serve_share_zip(
|
||||
state: Arc<AppState>,
|
||||
token: String,
|
||||
folder_id: Option<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let Some(browse) = state.share_browse_service.clone() else {
|
||||
return sharing_disabled_response();
|
||||
};
|
||||
let zip_service = match &state.core.zip_service {
|
||||
Some(svc) => svc,
|
||||
None => {
|
||||
return AppError::new(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"ZIP service not initialized",
|
||||
"Disabled",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
let unlock_jwt = unlock_jwt_from_headers(&headers, &token);
|
||||
|
||||
let target: ZipTarget = match browse
|
||||
.resolve_zip_target(&token, folder_id.as_deref(), unlock_jwt.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(t) => t,
|
||||
Err(err) => return share_browse_error_response(err),
|
||||
};
|
||||
|
||||
let temp_file = match zip_service
|
||||
.create_folder_zip(&target.folder_id, &target.display_name)
|
||||
.await
|
||||
{
|
||||
Ok(f) => f,
|
||||
Err(err) => {
|
||||
tracing::error!("share zip: create_folder_zip failed: {}", err);
|
||||
return AppError::internal_error(format!("ZIP creation failed: {}", err))
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
|
||||
let file_size = match temp_file.as_file().metadata() {
|
||||
Ok(m) => m.len(),
|
||||
Err(e) => {
|
||||
tracing::error!("share zip: temp metadata failed: {}", e);
|
||||
return AppError::internal_error("ZIP creation failed").into_response();
|
||||
}
|
||||
};
|
||||
|
||||
// Reuse the existing fd: split off the std::File and the TempPath.
|
||||
let (std_file, temp_path) = temp_file.into_parts();
|
||||
let tokio_file = tokio::fs::File::from_std(std_file);
|
||||
let stream = ReaderStream::new(tokio_file);
|
||||
let body = Body::from_stream(stream);
|
||||
|
||||
let disposition = build_content_disposition(
|
||||
&format!("{}.zip", target.display_name),
|
||||
"application/zip",
|
||||
false,
|
||||
);
|
||||
|
||||
let mut response = Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, "application/zip")
|
||||
.header(header::CONTENT_DISPOSITION, disposition)
|
||||
.header(header::CONTENT_LENGTH, file_size)
|
||||
.body(body)
|
||||
.unwrap();
|
||||
|
||||
// Keep TempPath alive until the body finishes streaming.
|
||||
response.extensions_mut().insert(Arc::new(temp_path));
|
||||
response
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user