docbox_core/files/
mod.rs

1use mime::Mime;
2use uuid::Uuid;
3
4use crate::utils::file::{get_file_name_ext, get_mime_ext, make_s3_safe};
5
6pub mod delete_file;
7pub mod generated;
8pub mod index_file;
9pub mod purge_expired_presigned_tasks;
10pub mod reprocess_octet_stream_files;
11pub mod update_file;
12pub mod upload_file;
13pub mod upload_file_presigned;
14
15pub fn create_file_key(document_box: &str, name: &str, mime: &Mime, file_key: Uuid) -> String {
16    // Try get file extension from name
17    let file_ext = get_file_name_ext(name)
18        // Fallback to extension from mime type
19        .or_else(|| get_mime_ext(mime).map(|value| value.to_string()))
20        // Fallback to default .bin extension
21        .unwrap_or_else(|| "bin".to_string());
22
23    // Get the file name with the file extension stripped
24    let file_name = name.strip_suffix(&file_ext).unwrap_or(name);
25
26    // Strip unwanted characters from the file name
27    let clean_file_name = make_s3_safe(file_name);
28
29    // Key is composed of the {Unique ID}_{File Name}.{File Ext}
30    let file_key = format!("{file_key}_{clean_file_name}.{file_ext}");
31
32    // Prefix file key with the scope directory
33    format!("{document_box}/{file_key}")
34}
35
36pub fn create_generated_file_key(base_file_key: &str, mime: &Mime) -> String {
37    // Mapped file extensions for the generated type
38    let file_ext = get_mime_ext(mime).unwrap_or("bin");
39
40    // Generate a unique file key
41    let file_key = Uuid::new_v4().to_string();
42
43    // Prefix the file key with the document box scope and a "generated" suffix
44    format!("{base_file_key}_{file_key}.generated.{file_ext}")
45}
46
47#[cfg(test)]
48mod test {
49    use crate::files::create_file_key;
50    use mime::Mime;
51    use uuid::Uuid;
52
53    #[test]
54    fn test_create_file_key_ext_from_mime() {
55        let scope = "scope";
56        let mime: Mime = "image/png".parse().unwrap();
57        let file_key = Uuid::new_v4();
58        let key = create_file_key(scope, "photo", &mime, file_key);
59
60        assert_eq!(key, format!("scope/{file_key}_photo.png"));
61    }
62
63    #[test]
64    fn test_create_file_key_fallback_bin() {
65        let scope = "scope";
66        let mime: Mime = "unknown/unknown".parse().unwrap();
67        let file_key = Uuid::new_v4();
68        let key = create_file_key(scope, "file", &mime, file_key);
69
70        assert_eq!(key, format!("scope/{file_key}_file.bin"));
71    }
72
73    #[test]
74    fn test_create_file_key_strips_special_chars() {
75        let scope = "scope";
76        let mime: Mime = "text/plain".parse().unwrap();
77        let file_key = Uuid::new_v4();
78        let key = create_file_key(scope, "some file$name.txt", &mime, file_key);
79
80        assert_eq!(key, format!("scope/{file_key}_some_filename.txt"));
81    }
82}