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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::raw::*;
use crate::Result;

/// A layer that can automatically set `Content-Type` based on the file extension in the path.
///
/// # MimeGuess
///
/// This layer uses [mime_guess](https://crates.io/crates/mime_guess) to automatically
/// set `Content-Type` based on the file extension in the operation path.
///
/// However, please note that this layer will not overwrite the `content_type` you manually set,
/// nor will it overwrite the `content_type` provided by backend services.
///
/// A simple example is that for object storage backends, when you call `stat`, the backend will
/// provide `content_type` information, and `mime_guess` will not be called, but will use
/// the `content_type` provided by the backend.
///
/// But if you use the [Fs](../services/struct.Fs.html) backend to call `stat`, the backend will
/// not provide `content_type` information, and our `mime_guess` will be called to provide you with
/// appropriate `content_type` information.
///
/// Another thing to note is that using this layer does not necessarily mean that the result will 100%
/// contain `content_type` information. If the extension of your path is custom or an uncommon type,
/// the returned result will still not contain `content_type` information (the specific condition here is
/// when [mime_guess::from_path::first_raw](https://docs.rs/mime_guess/latest/mime_guess/struct.MimeGuess.html#method.first_raw)
/// returns `None`).
///
/// # Examples
///
/// ```no_run
/// # use opendal::layers::MimeGuessLayer;
/// # use opendal::services;
/// # use opendal::Operator;
/// # use opendal::Result;
/// # use opendal::Scheme;
///
/// # fn main() -> Result<()> {
/// let _ = Operator::new(services::Memory::default())?
///     .layer(MimeGuessLayer::default())
///     .finish();
/// Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct MimeGuessLayer {}

impl<A: Access> Layer<A> for MimeGuessLayer {
    type LayeredAccess = MimeGuessAccessor<A>;

    fn layer(&self, inner: A) -> Self::LayeredAccess {
        MimeGuessAccessor(inner)
    }
}

#[derive(Clone, Debug)]
pub struct MimeGuessAccessor<A: Access>(A);

fn mime_from_path(path: &str) -> Option<&str> {
    mime_guess::from_path(path).first_raw()
}

fn opwrite_with_mime(path: &str, op: OpWrite) -> OpWrite {
    if op.content_type().is_some() {
        return op;
    }

    if let Some(mime) = mime_from_path(path) {
        return op.with_content_type(mime);
    }

    op
}

fn rpstat_with_mime(path: &str, rp: RpStat) -> RpStat {
    rp.map_metadata(|metadata| {
        if metadata.content_type().is_some() {
            return metadata;
        }

        if let Some(mime) = mime_from_path(path) {
            return metadata.with_content_type(mime.into());
        }

        metadata
    })
}

impl<A: Access> LayeredAccess for MimeGuessAccessor<A> {
    type Inner = A;
    type Reader = A::Reader;
    type BlockingReader = A::BlockingReader;
    type Writer = A::Writer;
    type BlockingWriter = A::BlockingWriter;
    type Lister = A::Lister;
    type BlockingLister = A::BlockingLister;

    fn inner(&self) -> &Self::Inner {
        &self.0
    }

    async fn write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::Writer)> {
        self.inner()
            .write(path, opwrite_with_mime(path, args))
            .await
    }

    fn blocking_write(&self, path: &str, args: OpWrite) -> Result<(RpWrite, Self::BlockingWriter)> {
        self.inner()
            .blocking_write(path, opwrite_with_mime(path, args))
    }

    async fn stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
        self.inner()
            .stat(path, args)
            .await
            .map(|rp| rpstat_with_mime(path, rp))
    }

    fn blocking_stat(&self, path: &str, args: OpStat) -> Result<RpStat> {
        self.inner()
            .blocking_stat(path, args)
            .map(|rp| rpstat_with_mime(path, rp))
    }

    async fn read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::Reader)> {
        self.inner().read(path, args).await
    }

    async fn list(&self, path: &str, args: OpList) -> Result<(RpList, Self::Lister)> {
        self.inner().list(path, args).await
    }

    fn blocking_read(&self, path: &str, args: OpRead) -> Result<(RpRead, Self::BlockingReader)> {
        self.inner().blocking_read(path, args)
    }

    fn blocking_list(&self, path: &str, args: OpList) -> Result<(RpList, Self::BlockingLister)> {
        self.inner().blocking_list(path, args)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::services::Memory;
    use crate::Metadata;
    use crate::Operator;
    use futures::TryStreamExt;

    const DATA: &str = "<html>test</html>";
    const CUSTOM: &str = "text/custom";
    const HTML: &str = "text/html";

    #[tokio::test]
    async fn test_async() {
        let op = Operator::new(Memory::default())
            .unwrap()
            .layer(MimeGuessLayer::default())
            .finish();

        op.write("test0.html", DATA).await.unwrap();
        assert_eq!(
            op.stat("test0.html").await.unwrap().content_type(),
            Some(HTML)
        );

        op.write("test1.asdfghjkl", DATA).await.unwrap();
        assert_eq!(
            op.stat("test1.asdfghjkl").await.unwrap().content_type(),
            None
        );

        op.write_with("test2.html", DATA)
            .content_type(CUSTOM)
            .await
            .unwrap();
        assert_eq!(
            op.stat("test2.html").await.unwrap().content_type(),
            Some(CUSTOM)
        );

        let entries: Vec<Metadata> = op
            .lister_with("")
            .await
            .unwrap()
            .and_then(|entry| {
                let op = op.clone();
                async move { op.stat(entry.path()).await }
            })
            .try_collect()
            .await
            .unwrap();
        assert_eq!(entries[0].content_type(), Some(HTML));
        assert_eq!(entries[1].content_type(), None);
        assert_eq!(entries[2].content_type(), Some(CUSTOM));
    }

    #[test]
    fn test_blocking() {
        let op = Operator::new(Memory::default())
            .unwrap()
            .layer(MimeGuessLayer::default())
            .finish()
            .blocking();

        op.write("test0.html", DATA).unwrap();
        assert_eq!(op.stat("test0.html").unwrap().content_type(), Some(HTML));

        op.write("test1.asdfghjkl", DATA).unwrap();
        assert_eq!(op.stat("test1.asdfghjkl").unwrap().content_type(), None);

        op.write_with("test2.html", DATA)
            .content_type(CUSTOM)
            .call()
            .unwrap();
        assert_eq!(op.stat("test2.html").unwrap().content_type(), Some(CUSTOM));

        let entries: Vec<Metadata> = op
            .lister_with("")
            .call()
            .unwrap()
            .map(|entry| {
                let op = op.clone();
                op.stat(entry.unwrap().path()).unwrap()
            })
            .collect();
        assert_eq!(entries[0].content_type(), Some(HTML));
        assert_eq!(entries[1].content_type(), None);
        assert_eq!(entries[2].content_type(), Some(CUSTOM));
    }
}