Pour tout problème contactez-nous par mail : support@froggit.fr | La FAQ :grey_question: | Rejoignez-nous sur le Chat :speech_balloon:

Skip to content
Snippets Groups Projects
static_files.rs 6.13 KiB
Newer Older
  • Learn to ignore specific revisions
  • use crate::env::Env;
    use crate::AppState;
    use std::fs::create_dir_all;
    use std::path::Path;
    
    #[derive(Debug, Clone)]
    pub struct StaticFilesIndex(pub Vec<String>);
    
    impl StaticFilesIndex {
        fn rec_read_dir(root: &Path, files: &mut Vec<String>, strip_from: &Path) {
            for entry in root.read_dir().unwrap() {
                if let Ok(entry) = entry {
                    if entry.path().is_dir() {
                        StaticFilesIndex::rec_read_dir(&entry.path(), files, strip_from);
                    } else {
                        StaticFilesIndex::_push_path(&entry.path(), files, strip_from);
                    }
                }
            }
        }
    
        fn _push_path(path: &Path, files: &mut Vec<String>, strip_from: &Path) {
            let push_path = path.strip_prefix(strip_from).unwrap();
            files.push(push_path.to_str().unwrap().to_owned());
        }
    
        pub fn rebuild(&mut self, env: &Env) {
            let root = env.public_dir.join("assets");
            self.0 = Vec::new();
            StaticFilesIndex::rec_read_dir(&root, &mut self.0, &env.public_dir);
        }
    
        pub fn push_path(&mut self, path: &Path, env: &Env) {
            let strip_from = env.public_dir.join("assets");
            StaticFilesIndex::_push_path(path, &mut self.0, &strip_from);
        }
    }
    
    #[derive(Debug, PartialEq)]
    pub enum UploadType {
        Image,
        Sound,
        Video,
        Doc,
    }
    
    pub struct UploadData {
        pub up_type: UploadType,
        pub filename: String,
    }
    
    pub fn create_dir_if_missing(path: std::path::PathBuf) -> std::path::PathBuf {
        if !path.exists() {
            create_dir_all(&path).unwrap();
        }
    
        path
    }
    
    pub fn get_uploads_dir(app_state: &AppState) -> std::path::PathBuf {
        create_dir_if_missing(app_state.env.public_dir.join("assets/uploads"))
    }
    
    pub fn dirname_from_type(upload_type: &UploadType) -> String {
        match upload_type {
            UploadType::Image => String::from("images"),
            UploadType::Sound => String::from("sounds"),
            UploadType::Video => String::from("videos"),
            UploadType::Doc => String::from("docs"),
        }
    }
    
    pub fn upload_type_from_file_ext(ext: &String) -> UploadType {
        match &ext[..] {
            "webp" | "jpg" | "png" | "jpeg" | "bmp" | "gif" => UploadType::Image,
            "mp3" | "ogg" | "wav" | "opus" => UploadType::Sound,
            "mp4" | "webm" | "ogv" => UploadType::Video,
            _ => UploadType::Doc,
        }
    }
    
    pub fn file_ext(file_name: &String) -> Result<String, String> {
        let parts = file_name.split(".").collect::<Vec<&str>>();
    
        let err_msg = format!("Couldn't get extension from filename : {}", file_name);
    
        if parts.len() < 2 {
            return Err(err_msg);
        }
    
        match parts.last() {
            Some(ext) => Ok(ext.to_string()),
            None => Err(err_msg),
        }
    }
    
    /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*@@
     *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*@@
     *  _______   ______    ______   _______   *@@
     * |__   __@ |  ____@  /  ____@ |__   __@  *@@
     *    |  @   |  @__    \_ @_       |  @    *@@
     *    |  @   |   __@     \  @_     |  @    *@@
     *    |  @   |  @___   ____\  @    |  @    *@@
     *    |__@   |______@  \______@    |__@    *@@
     *                                         *@@
     *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*@@
     *@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*@*/
    
    #[cfg(test)]
    mod test_static_files {
        use super::*;
        use std::{fs::remove_dir_all, path::PathBuf};
    
        #[test]
        fn should_create_missing_directory() {
            let missing_path = PathBuf::from("./some_nested/missing_dir");
            let created_path = create_dir_if_missing(missing_path);
            assert!(created_path.exists());
            remove_dir_all(PathBuf::from("./some_nested")).unwrap();
        }
    
        #[test]
        fn uploads_subdirs_should_be_consistent() {
            assert_eq!(
                upload_type_from_file_ext(&"jpg".to_string()),
                UploadType::Image
            );
            assert_eq!(
                upload_type_from_file_ext(&"jpeg".to_string()),
                UploadType::Image
            );
            assert_eq!(
                upload_type_from_file_ext(&"png".to_string()),
                UploadType::Image
            );
            assert_eq!(
                upload_type_from_file_ext(&"bmp".to_string()),
                UploadType::Image
            );
            assert_eq!(
                upload_type_from_file_ext(&"gif".to_string()),
                UploadType::Image
            );
            assert_eq!(
                upload_type_from_file_ext(&"webp".to_string()),
                UploadType::Image
            );
    
            assert_eq!(
                upload_type_from_file_ext(&"mp3".to_string()),
                UploadType::Sound
            );
            assert_eq!(
                upload_type_from_file_ext(&"ogg".to_string()),
                UploadType::Sound
            );
            assert_eq!(
                upload_type_from_file_ext(&"wav".to_string()),
                UploadType::Sound
            );
            assert_eq!(
                upload_type_from_file_ext(&"opus".to_string()),
                UploadType::Sound
            );
    
            assert_eq!(
                upload_type_from_file_ext(&"mp4".to_string()),
                UploadType::Video
            );
            assert_eq!(
                upload_type_from_file_ext(&"webm".to_string()),
                UploadType::Video
            );
            assert_eq!(
                upload_type_from_file_ext(&"ogv".to_string()),
                UploadType::Video
            );
    
            assert_eq!(
                upload_type_from_file_ext(&"any".to_string()),
                UploadType::Doc
            );
            assert_eq!(
                upload_type_from_file_ext(&"jszaj".to_string()),
                UploadType::Doc
            );
        }
    
        #[test]
        fn should_get_filename_extension() {
            fn valid_ext(ext: Result<String, String>) -> String {
                assert!(ext.is_ok());
                ext.unwrap()
            }
    
            let filename = String::from("somefilename.png");
            let ext = valid_ext(file_ext(&filename));
            assert_eq!(ext, "png");
    
            let filename = String::from("aïe aïe aïe.wav");
            let ext = valid_ext(file_ext(&filename));
            assert_eq!(ext, "wav");
    
            let filename = String::from("salut Ça va.machin.jpg");
            let ext = valid_ext(file_ext(&filename));
            assert_eq!(ext, "jpg");
    
            let filename = String::from("no extension");
            let ext = file_ext(&filename);
            assert!(ext.is_err());
        }
    }