added .add_file()

This commit is contained in:
P0lunin 2019-09-07 17:45:24 +03:00
parent 88ec897751
commit 2cb6ba9e33
3 changed files with 42 additions and 2 deletions

View file

@ -13,5 +13,5 @@ serde = {version = "1.0.92", features = ["derive"] }
lazy_static = "1.3" lazy_static = "1.3"
apply = "0.2.2" apply = "0.2.2"
derive_more = "0.15.0" derive_more = "0.15.0"
tokio = "0.1"
tokio = "0.1" bytes = "0.4.12"

View file

@ -2,6 +2,7 @@ use reqwest::r#async::multipart::Form;
use serde::Serialize; use serde::Serialize;
use crate::core::types::ParseMode; use crate::core::types::ParseMode;
use crate::core::requests::ChatId; use crate::core::requests::ChatId;
use crate::core::requests::utils;
/// This is a convenient struct that builds `reqwest::r#async::multipart::Form` /// This is a convenient struct that builds `reqwest::r#async::multipart::Form`
/// from scratch. /// 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 { pub fn build(self) -> Form {
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()
}
}

View file

@ -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<Option<Self::Item>, 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
}