stately-files 0.5.0

File upload and relative path management for stately
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use std::path::{Path, PathBuf};

use axum::body::Body;
use axum::extract::{Multipart, Query, State};
use axum::http::header;
use axum::response::{Json, Response};
use tokio::fs::{self, File};
use tokio::io::AsyncWriteExt;
use tokio_util::io::ReaderStream;

use super::error::{Error, Result};
use super::path::VersionedPath;
use super::request::{FileDownloadQuery, FileListQuery, FileSaveRequest};
use super::response::{FileEntryType, FileInfo, FileListResponse, FileUploadResponse, FileVersion};
use super::state::FileState;
use super::utils;
use crate::settings::{Dirs, IGNORE_FILES, UPLOAD_DIR, VERSION_DIR};

// TODO: Remove - notes
//   * Upload is for managed files, add handler for uploading *anywhere*

/// Upload a file to the data directory
///
/// Files are stored in a versioned structure:
/// `data/uploads/{name}/{uuid}`
///
/// This allows automatic versioning without conflicts.
///
/// # Errors
/// - `Error::BadRequest` if the file name is invalid
/// - `Error::Internal` if the file could not be saved
#[utoipa::path(
    post,
    path = "/upload",
    request_body(content = String, content_type = "multipart/form-data"),
    responses(
        (status = 200, description = "File uploaded successfully", body = FileUploadResponse),
        (status = 400, description = "Bad request", body = stately::ApiError),
        (status = 500, description = "Internal server error", body = stately::ApiError)
    ),
    tag = "files"
)]
pub async fn upload(
    State(state): State<FileState>,
    mut multipart: Multipart,
) -> Result<Json<FileUploadResponse>> {
    let mut file_name: Option<String> = None;
    let mut file_data: Option<Vec<u8>> = None;

    // Parse multipart form data
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|_e| Error::BadRequest("Invalid multipart data".to_string()))?
    {
        match field.name().unwrap_or("") {
            "file" => {
                file_name = field.file_name().map(ToString::to_string);
                file_data = Some(
                    field
                        .bytes()
                        .await
                        .map_err(|e| Error::BadRequest(format!("Failed to read file data: {e:?}")))?
                        .to_vec(),
                );
            }
            "name" => {
                file_name =
                    Some(field.text().await.map_err(|e| {
                        Error::BadRequest(format!("Failed to read name field: {e:?}"))
                    })?);
            }
            _ => {}
        }
    }

    let Some(data) = file_data else {
        return Err(Error::BadRequest("No file provided".to_string()));
    };

    // Sanitize filename - remove path separators and dangerous characters
    let sanitized_name =
        utils::sanitize_filename(&file_name.unwrap_or_else(|| "unnamed".to_string()));

    save(&sanitized_name, &data, state.base.as_ref()).await
}

/// Save file content directly (without multipart upload)
///
/// This endpoint allows saving file content from a text input.
///
/// # Errors
/// - `Error::BadRequest` if the file name is invalid
/// - `Error::Internal` if the file could not be saved
#[utoipa::path(
    post,
    path = "/save",
    request_body = FileSaveRequest,
    responses(
        (status = 200, description = "File saved successfully", body = FileUploadResponse),
        (status = 400, description = "Bad request", body = stately::ApiError),
        (status = 500, description = "Internal server error", body = stately::ApiError)
    ),
    tag = "files"
)]
pub async fn save_file(
    State(state): State<FileState>,
    Json(request): Json<FileSaveRequest>,
) -> Result<Json<FileUploadResponse>> {
    let name = request.name.unwrap_or_else(|| "unnamed.txt".to_string());
    let sanitized_name = utils::sanitize_filename(&name);
    save(&sanitized_name, request.content.as_bytes(), state.base.as_ref()).await
}

/// List files and directories
///
/// Lists all files and directories in the specified path (or root data directory if no path
/// specified). Returns both files and directories with a flag indicating which is which.
///
/// Versioned files are stored as: `{filename}/__versions__/{uuid}`
/// The UI is responsible for aggregating versions for display.
///
/// # Errors
/// - `Error::BadRequest` if the path is invalid
/// - `Error::Internal` if the files could not be listed
#[utoipa::path(
    get,
    path = "/list",
    params(FileListQuery),
    responses(
        (status = 200, description = "Files and directories listed successfully", body = FileListResponse),
        (status = 400, description = "Bad request", body = stately::ApiError),
        (status = 500, description = "Internal server error", body = stately::ApiError)
    ),
    tag = "files"
)]
pub async fn list_files(
    State(state): State<FileState>,
    Query(params): Query<FileListQuery>,
) -> Result<Json<FileListResponse>> {
    let base_dir = state.base.as_ref().unwrap_or(Dirs::get()).data.clone().join(UPLOAD_DIR);

    let target_dir = if let Some(path) = params.path {
        // Sanitize and resolve the path
        let sanitized = utils::sanitize_path(&path);
        base_dir.join(sanitized)

    // Default to root data directory if no path specified
    } else {
        base_dir
    };

    // Ensure the directory exists
    if !target_dir.exists() {
        return Ok(Json(FileListResponse { files: vec![] }));
    }

    Ok(Json(FileListResponse { files: collect_files(target_dir).await? }))
}

async fn collect_files(target_dir: impl AsRef<Path>) -> Result<Vec<FileInfo>> {
    let mut files = Vec::new();

    // PASS 1: Collect all entries
    let mut entries_vec = Vec::new();
    let mut entries = fs::read_dir(target_dir.as_ref())
        .await
        .map_err(utils::map_file_err("Failed to read directory"))?;

    while let Some(entry) = entries
        .next_entry()
        .await
        .map_err(utils::map_file_err("Failed to read directory entry"))?
    {
        entries_vec.push(entry);
    }

    // PASS 2: Classify and process each entry
    for (name, entry) in entries_vec
        .into_iter()
        .map(|e| (e.file_name().to_string_lossy().to_string(), e))
        .filter(|(name, _)| !IGNORE_FILES.iter().any(|i| name.starts_with(i)))
    {
        let metadata =
            entry.metadata().await.map_err(utils::map_file_err("Failed to read file metadata"))?;

        let path = entry.path();
        // info!("Found entry: {name} (file: {}, dir: {})", metadata.is_file(), metadata.is_dir());

        if metadata.is_file() {
            // Regular file
            let size = metadata.len();
            let created = utils::get_created_time(&metadata);
            let modified = utils::get_modified_time(&metadata);
            // info!("Adding file: {name} (size: {size} bytes)");
            files.push(FileInfo {
                name,
                size,
                entry_type: FileEntryType::File,
                created,
                modified,
                versions: None,
            });
        } else if metadata.is_dir() {
            // Check if versioned file (has __versions__ subdirectory)
            let versions_path = path.join(VERSION_DIR);

            if fs::try_exists(&versions_path).await.unwrap_or(false) {
                // info!("Found versioned file: {name}");

                // Read all versions
                let mut versions = Vec::new();
                let mut versions_dir = fs::read_dir(&versions_path)
                    .await
                    .map_err(utils::map_file_err("Failed to read version dir"))?;
                while let Some(version_entry) = versions_dir
                    .next_entry()
                    .await
                    .map_err(utils::map_file_err("Failed to get entry for version"))?
                {
                    let version_meta = version_entry
                        .metadata()
                        .await
                        .map_err(utils::map_file_err("Failed to get metadata for version"))?;
                    if version_meta.is_file() {
                        versions.push(FileVersion {
                            uuid:    version_entry.file_name().to_string_lossy().to_string(),
                            size:    version_meta.len(),
                            created: utils::get_created_time(&version_meta),
                        });
                    }
                }
                // info!("Adding versioned file: {name} ({} versions)", versions.len());

                // Sort newest first (UUID v7 is time-sortable)
                versions.sort_by(|a, b| b.uuid.cmp(&a.uuid));

                // Initialize FileInfo for updates
                let mut version = FileInfo {
                    name,
                    size: 0,
                    entry_type: FileEntryType::VersionedFile,
                    created: None,
                    modified: None,
                    versions: None,
                };

                // Calculate metadata from versions
                if !versions.is_empty() {
                    version.size = versions.first().map_or(0, |v| v.size);
                    version.modified = versions.first().and_then(|v| v.created);
                    version.created = versions.last().and_then(|v| v.created);
                    version.versions = Some(versions);
                }

                files.push(version);
            } else {
                // Regular directory
                // info!("Adding directory: {name}");
                files.push(FileInfo {
                    name,
                    size: 0,
                    entry_type: FileEntryType::Directory,
                    created: None,
                    modified: None,
                    versions: None,
                });
            }
        }
    }

    // Sort by name
    files.sort_by(|a, b| b.name.cmp(&a.name));

    Ok(files)
}

/// Save file with UUID-based versioning
///
/// Files are stored as: uploads/{name}/__versions__/{uuid}
async fn save(name: &str, data: &[u8], base: Option<&Dirs>) -> Result<Json<FileUploadResponse>> {
    let (uuid, file_dir, file_path) = utils::create_versioned_filepath(name, base);

    // Create directory if it doesn't exist
    fs::create_dir_all(&file_dir)
        .await
        .map_err(utils::map_file_err("Failed to create upload directory"))?;

    // Write file
    let mut file =
        File::create(&file_path).await.map_err(utils::map_file_err("Failed to create file"))?;
    file.write_all(data).await.map_err(utils::map_file_err("Failed to write file"))?;
    file.flush().await.map_err(utils::map_file_err("Failed to flush file"))?;

    Ok(Json(FileUploadResponse {
        uuid:      uuid.to_string(),
        success:   true,
        path:      name.to_string(),
        full_path: file_path.to_string_lossy().to_string(),
    }))
}

// ================================================================================================
// Download handlers
// ================================================================================================

/// Download a file from the cache directory
///
/// Returns the raw file content with appropriate Content-Type header.
/// No version resolution is performed - the path is used directly.
///
/// # Errors
/// - `Error::NotFound` if the file does not exist
/// - `Error::Internal` if the file could not be read
#[utoipa::path(
    get,
    path = "/file/cache/{path}",
    params(
        ("path" = String, Path, description = "Path to file relative to cache directory")
    ),
    responses(
        (status = 200, description = "File content", content_type = "application/octet-stream"),
        (status = 404, description = "File not found", body = stately::ApiError),
        (status = 500, description = "Internal server error", body = stately::ApiError)
    ),
    tag = "files"
)]
pub async fn download_cache(
    State(state): State<FileState>,
    axum::extract::Path(path): axum::extract::Path<String>,
) -> Result<Response<Body>> {
    let base = state.base.as_ref().unwrap_or(Dirs::get());
    let sanitized = utils::sanitize_path(&path);
    let file_path = base.cache.join(sanitized);

    stream_file(file_path).await
}

/// Download a file from the data directory
///
/// Returns the raw file content with appropriate Content-Type header.
/// No version resolution is performed - the path is used directly.
///
/// # Errors
/// - `Error::NotFound` if the file does not exist
/// - `Error::Internal` if the file could not be read
#[utoipa::path(
    get,
    path = "/file/data/{path}",
    params(
        ("path" = String, Path, description = "Path to file relative to data directory")
    ),
    responses(
        (status = 200, description = "File content", content_type = "application/octet-stream"),
        (status = 404, description = "File not found", body = stately::ApiError),
        (status = 500, description = "Internal server error", body = stately::ApiError)
    ),
    tag = "files"
)]
pub async fn download_data(
    State(state): State<FileState>,
    axum::extract::Path(path): axum::extract::Path<String>,
) -> Result<Response<Body>> {
    let base = state.base.as_ref().unwrap_or(Dirs::get());
    let sanitized = utils::sanitize_path(&path);
    let file_path = base.data.join(sanitized);

    stream_file(file_path).await
}

/// Download a file from the uploads directory
///
/// Returns the raw file content with appropriate Content-Type header.
/// Automatically resolves to the latest version unless a specific version UUID is provided.
///
/// # Errors
/// - `Error::NotFound` if the file does not exist
/// - `Error::Internal` if the file could not be read
#[utoipa::path(
    get,
    path = "/file/upload/{path}",
    params(
        ("path" = String, Path, description = "Path to versioned file relative to uploads directory"),
        FileDownloadQuery
    ),
    responses(
        (status = 200, description = "File content", content_type = "application/octet-stream"),
        (status = 404, description = "File not found", body = stately::ApiError),
        (status = 500, description = "Internal server error", body = stately::ApiError)
    ),
    tag = "files"
)]
pub async fn download_upload(
    State(state): State<FileState>,
    axum::extract::Path(path): axum::extract::Path<String>,
    Query(params): Query<FileDownloadQuery>,
) -> Result<Response<Body>> {
    let base = state.base.as_ref().unwrap_or(Dirs::get());
    let sanitized = utils::sanitize_path(&path);
    let uploads_dir = base.data.join(UPLOAD_DIR);

    let file_path = if let Some(version) = params.version {
        // Specific version requested
        uploads_dir.join(&sanitized).join(VERSION_DIR).join(version)
    } else {
        // Resolve to latest version
        let versioned = VersionedPath::new(sanitized.to_string_lossy().to_string());
        versioned.resolve(&uploads_dir).map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                Error::NotFound(format!("File not found: {path}"))
            } else {
                Error::Internal(format!("Failed to resolve file: {e}"))
            }
        })?
    };

    stream_file(file_path).await
}

/// Stream a file as an HTTP response with appropriate headers
///
/// # Errors
/// - Returns an error if the file does not exist or is not a file.
pub async fn stream_file(file_path: PathBuf) -> Result<Response<Body>> {
    // Check if file exists
    if !file_path.exists() {
        return Err(Error::NotFound(format!("File not found: {}", file_path.display())));
    }

    // Ensure it's a file, not a directory
    let metadata = fs::metadata(&file_path)
        .await
        .map_err(utils::map_file_err("Failed to read file metadata"))?;

    if !metadata.is_file() {
        return Err(Error::BadRequest(format!("Path is not a file: {}", file_path.display())));
    }

    // Determine content type from extension
    let content_type = mime_guess::from_path(&file_path).first_or_octet_stream().to_string();

    // Open file for streaming
    let file = File::open(&file_path).await.map_err(utils::map_file_err("Failed to open file"))?;

    // Create a stream from the file
    let stream = ReaderStream::new(file);
    let body = Body::from_stream(stream);

    // Extract filename for Content-Disposition header
    let filename = file_path.file_name().and_then(|n| n.to_str()).unwrap_or("download");

    // Build response with headers
    let response = Response::builder()
        .header(header::CONTENT_TYPE, content_type)
        .header(header::CONTENT_LENGTH, metadata.len())
        .header(header::CONTENT_DISPOSITION, format!("attachment; filename=\"{filename}\""))
        .body(body)
        .map_err(|e| Error::Internal(format!("Failed to build response: {e}")))?;

    Ok(response)
}