diff --git a/Cargo.toml b/Cargo.toml index f9f76f12..fba1a67f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,5 +13,5 @@ serde = {version = "1.0.92", features = ["derive"] } lazy_static = "1.3" apply = "0.2.2" derive_more = "0.15.0" - -tokio = "0.1" \ No newline at end of file +tokio = "0.1" +bytes = "0.4.12" \ No newline at end of file diff --git a/src/core/requests/form_builder.rs b/src/core/requests/form_builder.rs index 8b530025..8311a754 100644 --- a/src/core/requests/form_builder.rs +++ b/src/core/requests/form_builder.rs @@ -2,6 +2,7 @@ use reqwest::r#async::multipart::Form; use serde::Serialize; use crate::core::types::ParseMode; use crate::core::requests::ChatId; +use crate::core::requests::utils; /// This is a convenient struct that builds `reqwest::r#async::multipart::Form` /// from scratch. @@ -37,6 +38,12 @@ impl FormBuilder { } } + pub fn add_file(self, name: &str, path_to_file: &String) -> Self { + Self { + form: self.form.part(name.to_owned(), utils::file_to_part(path_to_file)) + } + } + pub fn build(self) -> Form { self.form } @@ -85,3 +92,9 @@ impl ToFormValue for ChatId { } } } + +impl ToFormValue for String { + fn to_form_value(&self) -> String { + self.to_owned() + } +} diff --git a/src/core/requests/utils.rs b/src/core/requests/utils.rs new file mode 100644 index 00000000..e0419a70 --- /dev/null +++ b/src/core/requests/utils.rs @@ -0,0 +1,27 @@ +use tokio::codec::FramedRead; +use std::fs::File; +use bytes::{Bytes, BytesMut}; +use tokio::prelude::*; +use reqwest::r#async::multipart::Part; + +struct FileDecoder; + +impl tokio::codec::Decoder for FileDecoder { + type Item = Bytes; + type Error = std::io::Error; + + fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { + if src.is_empty() { + return Ok(None) + } + Ok(Some(src.take().freeze())) + } +} + +pub fn file_to_part(path_to_file: &String) -> Part { + let file = tokio::fs::File::open(path_to_file.clone()) + .map(|file| FramedRead::new(file, FileDecoder)) + .flatten_stream(); + let part = Part::stream(file).file_name("file"); + part +} \ No newline at end of file