use std::fs; use std::path::PathBuf; use sqlx::PgPool; use uuid::Uuid; use crate::{ dto::FileResponse, error::{ApiError, ApiResult}, models::{File, Role, User}, pam, repositories::FileRepository, }; const FILE_NAME_MAX_LEN: usize = 100; const FILES_PER_PAGE: i64 = 10; const MAX_UPLOAD_SIZE: usize = 1024 * 1024; pub async fn upload( pool: &PgPool, user: User, workspace_id: Uuid, name: String, data: Vec, is_public: bool, ) -> ApiResult { ensure_participant(&user, workspace_id)?; let name = sanitize_name(name)?; let file_id = Uuid::new_v4(); let filename = format!("{workspace_id}/{file_id}"); let file = write_and_create( pool, &name, &filename, &user, Some(workspace_id), data, is_public, ) .await?; Ok(file_response(file)) } pub async fn upload_personal( pool: &PgPool, user: User, name: String, data: Vec, is_public: bool, ) -> ApiResult { let name = sanitize_name(name)?; let file_id = Uuid::new_v4(); let filename = format!("users/{}/{file_id}", user.id); let file = write_and_create(pool, &name, &filename, &user, None, data, is_public).await?; Ok(file_response(file)) } pub async fn list( pool: &PgPool, user: User, workspace_id: Uuid, page: Option, ) -> ApiResult> { ensure_participant(&user, workspace_id)?; let page = page.unwrap_or(1).max(1) as i64; let offset = (page - 1) * FILES_PER_PAGE; Ok( FileRepository::list_for_workspace(pool, workspace_id, FILES_PER_PAGE, offset) .await? .into_iter() .map(file_response) .collect(), ) } pub async fn list_personal( pool: &PgPool, user: User, page: Option, ) -> ApiResult> { let page = page.unwrap_or(1).max(1) as i64; let offset = (page - 1) * FILES_PER_PAGE; let mut responses: Vec = FileRepository::list_personal(pool, user.id, FILES_PER_PAGE, offset) .await? .into_iter() .map(file_response) .collect(); let mut seen: std::collections::HashSet = responses.iter().map(|file| file.id).collect(); for (workspace_id, granted_file) in pam::memberships::grants_for(&user.username) { let files = match granted_file.as_deref() { Some(name) => { FileRepository::find_by_workspace_and_name(pool, workspace_id, name, FILES_PER_PAGE) .await? } None => { FileRepository::list_for_workspace(pool, workspace_id, FILES_PER_PAGE, 0).await? } }; for file in files { if seen.insert(file.id) { let mut response = file_response(file); response.shared = true; responses.push(response); } } } Ok(responses) } pub async fn list_public(pool: &PgPool, page: Option) -> ApiResult> { let page = page.unwrap_or(1).max(1) as i64; let offset = (page - 1) * FILES_PER_PAGE; Ok(FileRepository::list_public(pool, FILES_PER_PAGE, offset) .await? .into_iter() .map(file_response) .collect()) } pub async fn download(pool: &PgPool, user: User, file_id: Uuid) -> ApiResult<(String, Vec)> { let file = FileRepository::get(pool, file_id).await?; ensure_access(&user, &file)?; let path = storage_dir().join(&file.filename); let data = fs::read(&path).map_err(|_| ApiError::NotFound)?; Ok((file.name, data)) } pub async fn delete(pool: &PgPool, user: User, file_id: Uuid) -> ApiResult<()> { let file = FileRepository::get(pool, file_id).await?; ensure_access(&user, &file)?; let allowed = match file.workspace_id { None => file.owner_id == user.id, Some(workspace_id) => { file.owner_id == user.id || (user.workspace_id == Some(workspace_id) && user.role == Role::WorkspaceAdmin) } }; if !allowed { return Err(ApiError::Forbidden); } FileRepository::delete(pool, file_id).await?; let _ = fs::remove_file(storage_dir().join(&file.filename)); Ok(()) } fn ensure_participant(user: &User, workspace_id: Uuid) -> ApiResult<()> { if user.workspace_id == Some(workspace_id) { Ok(()) } else { Err(ApiError::Forbidden) } } fn ensure_access(user: &User, file: &File) -> ApiResult<()> { if file.is_public { return Ok(()); } match file.workspace_id { None => { if file.owner_id == user.id { Ok(()) } else { Err(ApiError::Forbidden) } } Some(workspace_id) => pam::ffi::authorize_file(&user.username, workspace_id, &file.name), } } fn sanitize_name(name: String) -> ApiResult { let name = name.trim().to_string(); if name.is_empty() { return Err(ApiError::BadRequest( "file name must not be empty".to_string(), )); } if name.len() > FILE_NAME_MAX_LEN { return Err(ApiError::BadRequest(format!( "file name must be at most {FILE_NAME_MAX_LEN} characters" ))); } if name.chars().any(|c| c.is_control()) { return Err(ApiError::BadRequest( "file name must not contain control characters".to_string(), )); } Ok(name) } #[allow(clippy::too_many_arguments)] async fn write_and_create( pool: &PgPool, name: &str, filename: &str, owner: &User, workspace_id: Option, data: Vec, is_public: bool, ) -> ApiResult { if data.len() > MAX_UPLOAD_SIZE { return Err(ApiError::BadRequest(format!( "file must be at most {MAX_UPLOAD_SIZE} bytes" ))); } let path = storage_dir().join(filename); if let Some(parent) = path.parent() { fs::create_dir_all(parent).map_err(|err| { println!( "[file-upload] failed to create storage directory {}: {err}", parent.display() ); ApiError::Async })?; } fs::write(&path, &data).map_err(|err| { println!("[file-upload] failed to write {}: {err}", path.display()); ApiError::Async })?; let mut file = FileRepository::create( pool, name, filename, owner.id, workspace_id, data.len() as i64, is_public, ) .await; match file { Ok(ref mut created) => created.owner = owner.username.clone(), Err(err) => { if let Err(cleanup_err) = fs::remove_file(&path) { println!( "[file-upload] failed to clean up {}: {cleanup_err}", path.display() ); } return Err(err); } } file } fn storage_dir() -> PathBuf { std::env::var("PAMSAVE_STORAGE_DIR") .unwrap_or_else(|_| "./storage".to_string()) .into() } fn file_response(file: File) -> FileResponse { FileResponse { id: file.id, name: file.name, size: file.size, is_public: file.is_public, owner: file.owner, created_at: file.created_at, shared: false, } }