Skip to main content

stoat/
file.rs

1use std::path::Path;
2use tokio::fs::File;
3
4use reqwest::Body;
5
6/// A local file ready to be uploaded
7pub struct LocalFile {
8    pub name: String,
9    pub body: Body,
10}
11
12impl LocalFile {
13    /// Creates a local file with a filename and body
14    pub fn new<B: Into<Body>>(name: String, body: B) -> Self {
15        Self {
16            name,
17            body: body.into(),
18        }
19    }
20
21    /// Creates a local file from an existing file
22    ///
23    /// reuses the filename
24    pub async fn from_path<P: AsRef<Path>>(path: P) -> Self {
25        let path = path.as_ref();
26
27        let filename = path
28            .file_name()
29            .expect("File not found.")
30            .to_str()
31            .expect("Invalid filename")
32            .to_string();
33        let file = File::open(path).await.expect("Failed to open file.");
34
35        Self::new(filename, file)
36    }
37
38    /// Marks the file as a spoiler.
39    pub fn spoiler(mut self) -> Self {
40        if !self.is_spoiler() {
41            self.name = format!("SPOILER_{}", &self.name);
42        };
43
44        self
45    }
46
47    /// Returns whether the file is a spoiler
48    pub fn is_spoiler(&self) -> bool {
49        self.name.starts_with("SPOILER_")
50    }
51}