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