aboutsummaryrefslogtreecommitdiffstats
path: root/filamento/src/files.rs
blob: dcc9cd2e83d11e57c8eef5c5d41f8a85a2469aa9 (plain) (blame)
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
use std::{
    collections::HashMap,
    convert::Infallible,
    error::Error,
    path::{Path, PathBuf},
    sync::Arc,
};

use tokio::io;
use tokio::sync::Mutex;

#[cfg(not(target_arch = "wasm32"))]
pub trait FileStore {
    type Err: Clone + Send + Error;

    fn is_stored(
        &self,
        name: &str,
    ) -> impl std::future::Future<Output = Result<bool, Self::Err>> + std::marker::Send;
    fn store(
        &self,
        name: &str,
        data: &[u8],
    ) -> impl std::future::Future<Output = Result<(), Self::Err>> + std::marker::Send;
    fn delete(
        &self,
        name: &str,
    ) -> impl std::future::Future<Output = Result<(), Self::Err>> + std::marker::Send;
}

#[cfg(target_arch = "wasm32")]
pub trait FileStore {
    type Err: Clone + Send + Error;

    fn is_stored(&self, name: &str) -> impl std::future::Future<Output = Result<bool, Self::Err>>;
    fn store(
        &self,
        name: &str,
        data: &[u8],
    ) -> impl std::future::Future<Output = Result<(), Self::Err>>;
    fn delete(&self, name: &str) -> impl std::future::Future<Output = Result<(), Self::Err>>;
}

#[derive(Clone, Debug)]
pub struct FilesMem {
    files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
}

impl FilesMem {
    pub fn new() -> Self {
        Self {
            files: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub async fn get_file(&self, name: impl AsRef<str>) -> Option<Vec<u8>> {
        let name = name.as_ref();
        self.files.lock().await.get(name).cloned()
    }
}

#[cfg(all(feature = "opfs", target_arch = "wasm32"))]
pub mod opfs;

#[cfg(all(feature = "opfs", target_arch = "wasm32"))]
pub use opfs::FilesOPFS;

impl FileStore for FilesMem {
    type Err = Infallible;

    async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> {
        Ok(self.files.lock().await.contains_key(name))
    }

    async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> {
        self.files
            .lock()
            .await
            .insert(name.to_string(), data.to_owned());

        Ok(())
    }

    async fn delete(&self, name: &str) -> Result<(), Self::Err> {
        self.files.lock().await.remove(name);
        Ok(())
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Debug)]
pub struct Files {
    root: PathBuf,
}

#[cfg(not(target_arch = "wasm32"))]
impl Files {
    pub fn new(root: impl AsRef<Path>) -> Self {
        let root = root.as_ref();
        let root = root.into();
        Self { root }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl FileStore for Files {
    type Err = Arc<io::Error>;

    async fn is_stored(&self, name: &str) -> Result<bool, Self::Err> {
        tracing::debug!("checking if {} is stored", name);
        // TODO: is this secure ;-;
        let name = name.replace("/", "").replace(".", "");
        let res = tokio::fs::try_exists(self.root.join(name))
            .await
            .map_err(|err| Arc::new(err));
        tracing::debug!("file check res: {:?}", res);
        res
    }

    async fn store(&self, name: &str, data: &[u8]) -> Result<(), Self::Err> {
        tracing::debug!("storing {} is stored", name);
        let name = name.replace("/", "").replace(".", "");
        let res = tokio::fs::write(self.root.join(name), data)
            .await
            .map_err(|err| Arc::new(err));
        tracing::debug!("file store res: {:?}", res);
        res
    }

    async fn delete(&self, name: &str) -> Result<(), Self::Err> {
        tracing::debug!("deleting {}", name);
        let name = name.replace("/", "").replace(".", "");
        let res = tokio::fs::remove_file(self.root.join(name))
            .await
            .map_err(|err| Arc::new(err));
        tracing::debug!("file delete res: {:?}", res);
        res
    }
}