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:
abnvle
2026-05-05 22:41:55 +02:00
parent 8527765bf2
commit d15d7b8f8e
8 changed files with 725 additions and 85 deletions
+1
View File
@@ -17,6 +17,7 @@ pub mod nextcloud_file_id_service;
pub mod nextcloud_login_flow_service; pub mod nextcloud_login_flow_service;
pub mod recent_service; pub mod recent_service;
pub mod search_service; pub mod search_service;
pub mod share_browse_service;
pub mod share_service; pub mod share_service;
pub mod storage_settings_service; pub mod storage_settings_service;
pub mod storage_usage_service; pub mod storage_usage_service;
@@ -0,0 +1,191 @@
//! Share-scoped folder browsing for public folder shares.
use std::sync::Arc;
use uuid::Uuid;
use crate::application::dtos::folder_listing_dto::FolderListingDto;
use crate::application::ports::file_ports::FileRetrievalUseCase;
use crate::application::ports::inbound::FolderUseCase;
use crate::application::services::file_retrieval_service::FileRetrievalService;
use crate::application::services::folder_service::FolderService;
use crate::application::services::share_service::ShareService;
use crate::common::errors::DomainError;
use crate::domain::repositories::folder_repository::FolderRepository;
use crate::infrastructure::repositories::pg::folder_db_repository::FolderDbRepository;
struct ResolvedFolderShare {
root_folder_id: String,
owner_id: Uuid,
display_name: String,
}
pub struct ZipTarget {
pub folder_id: String,
pub display_name: String,
}
pub struct ShareBrowseService {
share_service: Arc<ShareService>,
folder_service: Arc<FolderService>,
file_retrieval: Arc<FileRetrievalService>,
folder_repo: Arc<FolderDbRepository>,
}
impl ShareBrowseService {
pub fn new(
share_service: Arc<ShareService>,
folder_service: Arc<FolderService>,
file_retrieval: Arc<FileRetrievalService>,
folder_repo: Arc<FolderDbRepository>,
) -> Self {
Self {
share_service,
folder_service,
file_retrieval,
folder_repo,
}
}
async fn resolve_folder_share(
&self,
token: &str,
unlock_jwt: Option<&str>,
) -> Result<ResolvedFolderShare, DomainError> {
let share = self
.share_service
.get_shared_link_with_unlock(token, unlock_jwt)
.await?;
if share.item_type != "folder" {
return Err(DomainError::validation_error(
"This endpoint is only valid for folder shares",
));
}
let owner_id = Uuid::parse_str(&share.created_by).map_err(|_| {
DomainError::internal_error(
"Share",
format!("Share has invalid created_by UUID: {}", share.created_by),
)
})?;
let display_name = match share.item_name {
Some(name) => name,
None => self
.folder_service
.get_folder(&share.item_id)
.await
.map(|f| f.name)
.unwrap_or_else(|_| "Shared folder".to_string()),
};
Ok(ResolvedFolderShare {
root_folder_id: share.item_id,
owner_id,
display_name,
})
}
pub async fn list_root(
&self,
token: &str,
unlock_jwt: Option<&str>,
) -> Result<FolderListingDto, DomainError> {
let resolved = self.resolve_folder_share(token, unlock_jwt).await?;
self.list_inner(&resolved.root_folder_id, resolved.owner_id)
.await
}
pub async fn list_subfolder(
&self,
token: &str,
folder_id: &str,
unlock_jwt: Option<&str>,
) -> Result<FolderListingDto, DomainError> {
let resolved = self.resolve_folder_share(token, unlock_jwt).await?;
if !self
.folder_repo
.is_folder_in_subtree(folder_id, &resolved.root_folder_id)
.await?
{
return Err(DomainError::not_found("Folder", folder_id));
}
self.list_inner(folder_id, resolved.owner_id).await
}
pub async fn assert_file_in_share(
&self,
token: &str,
file_id: &str,
unlock_jwt: Option<&str>,
) -> Result<(), DomainError> {
let resolved = self.resolve_folder_share(token, unlock_jwt).await?;
if !self
.folder_repo
.is_file_in_subtree(file_id, &resolved.root_folder_id)
.await?
{
return Err(DomainError::not_found("File", file_id));
}
Ok(())
}
pub async fn resolve_zip_target(
&self,
token: &str,
folder_id: Option<&str>,
unlock_jwt: Option<&str>,
) -> Result<ZipTarget, DomainError> {
let resolved = self.resolve_folder_share(token, unlock_jwt).await?;
let target_folder_id = match folder_id {
None => resolved.root_folder_id.clone(),
Some(id) => {
if !self
.folder_repo
.is_folder_in_subtree(id, &resolved.root_folder_id)
.await?
{
return Err(DomainError::not_found("Folder", id));
}
id.to_string()
}
};
let display_name = if folder_id.is_none() {
resolved.display_name
} else {
self.folder_service
.get_folder(&target_folder_id)
.await
.map(|f| f.name)
.unwrap_or_else(|_| "shared".to_string())
};
Ok(ZipTarget {
folder_id: target_folder_id,
display_name,
})
}
async fn list_inner(
&self,
parent_folder_id: &str,
owner_id: Uuid,
) -> Result<FolderListingDto, DomainError> {
let (folders_res, files_res) = tokio::join!(
self.folder_service
.list_folders_for_owner(Some(parent_folder_id), owner_id),
self.file_retrieval
.list_files_owned(Some(parent_folder_id), owner_id),
);
Ok(FolderListingDto {
folders: folders_res?,
files: files_res?,
})
}
}
+12
View File
@@ -19,6 +19,7 @@ use crate::application::services::nextcloud_file_id_service::NextcloudFileIdServ
use crate::application::services::nextcloud_login_flow_service::NextcloudLoginFlowService; use crate::application::services::nextcloud_login_flow_service::NextcloudLoginFlowService;
use crate::application::services::recent_service::RecentService; use crate::application::services::recent_service::RecentService;
use crate::application::services::search_service::SearchService; use crate::application::services::search_service::SearchService;
use crate::application::services::share_browse_service::ShareBrowseService;
use crate::application::services::share_service::ShareService; use crate::application::services::share_service::ShareService;
use crate::application::services::trash_service::TrashService; use crate::application::services::trash_service::TrashService;
use crate::application::services::{ use crate::application::services::{
@@ -602,6 +603,15 @@ impl AppServiceFactory {
let share_service = self.create_share_service(&repos, &pool); let share_service = self.create_share_service(&repos, &pool);
apps.share_service = share_service.clone(); apps.share_service = share_service.clone();
let share_browse_service = share_service.as_ref().map(|s| {
Arc::new(ShareBrowseService::new(
s.clone(),
apps.folder_service.clone(),
apps.file_retrieval_service.clone(),
repos.folder_repository.clone(),
))
});
// 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<FavoritesService>>; let favorites_service: Option<Arc<FavoritesService>>;
let recent_service: Option<Arc<RecentService>>; let recent_service: Option<Arc<RecentService>>;
@@ -739,6 +749,7 @@ impl AppServiceFactory {
migration_state: Arc::new(tokio::sync::RwLock::new(MigrationState::default())), migration_state: Arc::new(tokio::sync::RwLock::new(MigrationState::default())),
trash_service, trash_service,
share_service, share_service,
share_browse_service,
favorites_service, favorites_service,
recent_service, recent_service,
storage_usage_service, storage_usage_service,
@@ -1047,6 +1058,7 @@ pub struct AppState {
pub migration_state: Arc<tokio::sync::RwLock<MigrationState>>, pub migration_state: Arc<tokio::sync::RwLock<MigrationState>>,
pub trash_service: Option<Arc<TrashService>>, pub trash_service: Option<Arc<TrashService>>,
pub share_service: Option<Arc<ShareService>>, pub share_service: Option<Arc<ShareService>>,
pub share_browse_service: Option<Arc<ShareBrowseService>>,
pub favorites_service: Option<Arc<FavoritesService>>, pub favorites_service: Option<Arc<FavoritesService>>,
pub recent_service: Option<Arc<RecentService>>, pub recent_service: Option<Arc<RecentService>>,
pub storage_usage_service: Option<Arc<StorageUsageService>>, pub storage_usage_service: Option<Arc<StorageUsageService>>,
@@ -190,4 +190,27 @@ pub trait FolderRepository: Send + Sync + 'static {
matched.truncate(limit); matched.truncate(limit);
Ok(matched) Ok(matched)
} }
/// `true` if `candidate_folder_id` is `root_folder_id` itself or any
/// (transitive) descendant. Default impl fails closed so stubs deny
/// access by default.
async fn is_folder_in_subtree(
&self,
candidate_folder_id: &str,
root_folder_id: &str,
) -> Result<bool, DomainError> {
let _ = (candidate_folder_id, root_folder_id);
Ok(false)
}
/// `true` if `file_id`'s parent folder lies within the subtree rooted
/// at `root_folder_id`.
async fn is_file_in_subtree(
&self,
file_id: &str,
root_folder_id: &str,
) -> Result<bool, DomainError> {
let _ = (file_id, root_folder_id);
Ok(false)
}
} }
@@ -965,6 +965,58 @@ impl FolderRepository for FolderDbRepository {
}) })
.collect() .collect()
} }
async fn is_folder_in_subtree(
&self,
candidate_folder_id: &str,
root_folder_id: &str,
) -> Result<bool, DomainError> {
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS (\
SELECT 1 \
FROM storage.folders c, storage.folders r \
WHERE c.id = $1::uuid \
AND r.id = $2::uuid \
AND c.is_trashed = false \
AND r.is_trashed = false \
AND c.lpath <@ r.lpath \
)",
)
.bind(candidate_folder_id)
.bind(root_folder_id)
.fetch_one(self.pool())
.await
.map_err(|e| {
DomainError::internal_error("FolderDb", format!("is_folder_in_subtree: {e}"))
})?;
Ok(exists)
}
async fn is_file_in_subtree(
&self,
file_id: &str,
root_folder_id: &str,
) -> Result<bool, DomainError> {
let exists: bool = sqlx::query_scalar(
"SELECT EXISTS (\
SELECT 1 \
FROM storage.files f \
JOIN storage.folders parent ON f.folder_id = parent.id \
JOIN storage.folders root ON root.id = $2::uuid \
WHERE f.id = $1::uuid \
AND f.is_trashed = false \
AND parent.is_trashed = false \
AND root.is_trashed = false \
AND parent.lpath <@ root.lpath \
)",
)
.bind(file_id)
.bind(root_folder_id)
.fetch_one(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("is_file_in_subtree: {e}")))?;
Ok(exists)
}
} }
// ── Extra helpers for blob-storage bootstrap ── // ── Extra helpers for blob-storage bootstrap ──
+48 -46
View File
@@ -967,56 +967,15 @@ impl FileHandler {
/// Build a Content-Disposition header value. /// Build a Content-Disposition header value.
/// ///
/// Uses RFC 5987 `filename*=UTF-8''<percent-encoded>` to safely handle /// Build a `Content-Disposition` header value for an authenticated download,
/// filenames with quotes, non-ASCII characters, or other special chars. /// honouring the `?inline=true|1` query param. Delegates to the shared
/// A sanitised ASCII `filename=` fallback is included for legacy clients. /// `build_content_disposition` so the share-link path produces identical
/// header values for the same `(name, mime)` pair.
fn content_disposition(name: &str, mime: &str, params: &HashMap<String, String>) -> String { fn content_disposition(name: &str, mime: &str, params: &HashMap<String, String>) -> String {
let force_inline = params let force_inline = params
.get("inline") .get("inline")
.is_some_and(|v| v == "true" || v == "1"); .is_some_and(|v| v == "true" || v == "1");
let disposition = if force_inline build_content_disposition(name, mime, force_inline)
|| mime.starts_with("image/")
|| mime == "application/pdf"
|| mime.starts_with("video/")
|| mime.starts_with("audio/")
{
"inline"
} else {
"attachment"
};
// RFC 5987 percent-encode for filename* (attr-char safe set)
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
// Characters that DON'T need encoding per RFC 5987 attr-char:
// ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." /
// "^" / "_" / "`" / "|" / "~"
const RFC5987_SET: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'!')
.remove(b'#')
.remove(b'$')
.remove(b'&')
.remove(b'+')
.remove(b'-')
.remove(b'.')
.remove(b'^')
.remove(b'_')
.remove(b'`')
.remove(b'|')
.remove(b'~');
let encoded = utf8_percent_encode(name, RFC5987_SET).to_string();
// ASCII fallback: strip anything outside printable ASCII and
// replace '"' and '\\' to prevent header injection.
let ascii_safe: String = name
.chars()
.filter(|c| c.is_ascii_graphic() || *c == ' ')
.map(|c| match c {
'"' | '\\' => '_',
_ => c,
})
.collect();
format!("{disposition}; filename=\"{ascii_safe}\"; filename*=UTF-8''{encoded}")
} }
/// Build a 201 Created JSON response. /// Build a 201 Created JSON response.
@@ -1073,6 +1032,49 @@ pub struct MoveFilePayload {
pub folder_id: Option<String>, pub folder_id: Option<String>,
} }
/// RFC 5987-compliant `Content-Disposition` with both ASCII fallback and
/// `filename*=UTF-8''...` for non-ASCII filenames.
pub(super) fn build_content_disposition(name: &str, mime: &str, force_inline: bool) -> String {
let disposition = if force_inline
|| mime.starts_with("image/")
|| mime == "application/pdf"
|| mime.starts_with("video/")
|| mime.starts_with("audio/")
{
"inline"
} else {
"attachment"
};
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
// RFC 5987 attr-char safe set (no encoding needed for these).
const RFC5987_SET: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'!')
.remove(b'#')
.remove(b'$')
.remove(b'&')
.remove(b'+')
.remove(b'-')
.remove(b'.')
.remove(b'^')
.remove(b'_')
.remove(b'`')
.remove(b'|')
.remove(b'~');
let encoded = utf8_percent_encode(name, RFC5987_SET).to_string();
let ascii_safe: String = name
.chars()
.filter(|c| c.is_ascii_graphic() || *c == ' ')
.map(|c| match c {
'"' | '\\' => '_',
_ => c,
})
.collect();
format!("{disposition}; filename=\"{ascii_safe}\"; filename*=UTF-8''{encoded}")
}
// ── Route handlers (free functions) ────────────────────────────────────────── // ── Route handlers (free functions) ──────────────────────────────────────────
// //
// All annotated route functions live here rather than as methods on FileHandler // All annotated route functions live here rather than as methods on FileHandler
+372 -34
View File
@@ -8,12 +8,15 @@ use axum::{
http::{HeaderMap, StatusCode, header}, http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Response}, response::{IntoResponse, Response},
}; };
use http_range_header::parse_range_header;
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
use utoipa::ToSchema; use utoipa::ToSchema;
use crate::application::services::share_browse_service::ZipTarget;
use crate::application::services::share_service::ShareService; use crate::application::services::share_service::ShareService;
use crate::infrastructure::services::share_unlock_cookie; use crate::infrastructure::services::share_unlock_cookie;
use crate::interfaces::api::handlers::file_handler::build_content_disposition;
use crate::{ use crate::{
application::{ application::{
dtos::share_dto::{CreateShareDto, UpdateShareDto}, dtos::share_dto::{CreateShareDto, UpdateShareDto},
@@ -27,6 +30,7 @@ use crate::{
interfaces::errors::AppError, interfaces::errors::AppError,
interfaces::middleware::auth::AuthUser, interfaces::middleware::auth::AuthUser,
}; };
use tokio_util::io::ReaderStream;
fn unlock_jwt_from_headers(headers: &HeaderMap, share_token: &str) -> Option<String> { fn unlock_jwt_from_headers(headers: &HeaderMap, share_token: &str) -> Option<String> {
headers headers
@@ -370,46 +374,380 @@ pub async fn download_shared_file(
return AppError::bad_request("Download is only supported for file shares").into_response(); 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 retrieval = &state.applications.file_retrieval_service;
let file_id = &share_dto.item_id;
match retrieval.get_file_optimized(file_id, false, true).await { let file_dto = match retrieval.get_file(file_id).await {
Ok((file_dto, content)) => { Ok(d) => d,
let file_name = share_dto.item_name.as_deref().unwrap_or(&file_dto.name); Err(err) => return AppError::from(err).into_response(),
let disposition = format!( };
"attachment; filename=\"{}\"",
file_name.replace('"', "\\\"")
);
let mime = file_dto.mime_type.clone();
match content { let display_name = name_override.unwrap_or(&file_dto.name);
OptimizedFileContent::Bytes { data, .. } => Response::builder() let etag = format!("\"{}-{}\"", file_dto.id, file_dto.modified_at);
.status(StatusCode::OK) let mime = file_dto.mime_type.clone();
.header(header::CONTENT_TYPE, &*mime) let disposition = build_content_disposition(display_name, &mime, false);
.header(header::CONTENT_DISPOSITION, &disposition)
.header(header::CONTENT_LENGTH, data.len()) if let Some(inm) = request_headers.get(header::IF_NONE_MATCH)
.body(Body::from(data)) && 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() .unwrap()
.into_response(), .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(),
} }
} }
}
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(), 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
}
+26 -5
View File
@@ -66,11 +66,32 @@ pub fn create_public_api_routes(app_state: &Arc<AppState>) -> Router<Arc<AppStat
router = router.nest("/s", public_share_router); router = router.nest("/s", public_share_router);
// Download endpoint uses full AppState (needs FileRetrievalService) // AppState-backed share endpoints (download, contents, file, zip)
router = router.route( router = router
"/s/{token}/download", .route(
get(share_handler::download_shared_file), "/s/{token}/download",
); get(share_handler::download_shared_file),
)
.route(
"/s/{token}/contents",
get(share_handler::list_share_contents_root),
)
.route(
"/s/{token}/contents/{folder_id}",
get(share_handler::list_share_contents_subfolder),
)
.route(
"/s/{token}/file/{file_id}",
get(share_handler::download_share_file_in_folder),
)
.route(
"/s/{token}/zip",
get(share_handler::download_share_zip_root),
)
.route(
"/s/{token}/zip/{folder_id}",
get(share_handler::download_share_zip_subfolder),
);
} }
// i18n routes — no auth required (localization should be available before login) // i18n routes — no auth required (localization should be available before login)