Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to attach files formed from bytes #182

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions examples/api_trait_implementation.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use frankenstein::ErrorResponse;
use frankenstein::FileUploadForm;
use frankenstein::SendMessageParams;
use frankenstein::TelegramApi;
use isahc::{prelude::*, Request};
use std::path::PathBuf;

static TOKEN: &str = "TOKEN";
static BASE_API_URL: &str = "https://api.telegram.org/bot";
Expand Down Expand Up @@ -106,7 +106,7 @@ impl TelegramApi for Api {
&self,
_method: &str,
_params: T1,
_files: Vec<(&str, PathBuf)>,
_files: Vec<FileUploadForm>,
) -> Result<T2, Error> {
let error = HttpError {
code: 500,
Expand Down
39 changes: 22 additions & 17 deletions src/api/async_telegram_api_impl.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use super::Error;
use super::HttpError;
use crate::api_params::FileUpload;
use crate::api_params::FileUploadForm;
use crate::api_traits::AsyncTelegramApi;
use crate::api_traits::ErrorResponse;
use async_trait::async_trait;
use reqwest::multipart;
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
use tokio::fs::File;
use typed_builder::TypedBuilder;
Expand Down Expand Up @@ -133,21 +134,11 @@ impl AsyncTelegramApi for AsyncApi {
&self,
method: &str,
params: T1,
files: Vec<(&str, PathBuf)>,
files: Vec<FileUploadForm>,
) -> Result<T2, Self::Error> {
let json_string = Self::encode_params(&params)?;
let json_struct: Value = serde_json::from_str(&json_string).unwrap();
let file_keys: Vec<&str> = files.iter().map(|(key, _)| *key).collect();
let files_with_paths: Vec<(String, &str, String)> = files
.iter()
.map(|(key, path)| {
(
(*key).to_string(),
path.to_str().unwrap(),
path.file_name().unwrap().to_str().unwrap().to_string(),
)
})
.collect();
let file_keys: Vec<&str> = files.iter().map(|(key, _)| key.as_str()).collect();

let mut form = multipart::Form::new();
for (key, val) in json_struct.as_object().unwrap() {
Expand All @@ -161,11 +152,25 @@ impl AsyncTelegramApi for AsyncApi {
}
}

for (parameter_name, file_path, file_name) in files_with_paths {
let file = File::open(file_path).await?;
for (parameter_name, file) in files {
match file {
FileUpload::InputFile(input_file) => {
let file_path = input_file.path;
let file = File::open(&file_path).await?;
let file_name = file_path.file_name().unwrap().to_str().unwrap().to_string();

let part = multipart::Part::stream(file).file_name(file_name);
form = form.part(parameter_name, part);
let part = multipart::Part::stream(file).file_name(file_name);
form = form.part(parameter_name, part);
}
FileUpload::InputBuf(input_buf) => {
let buf = input_buf.data.clone();
let file_name = input_buf.file_name.clone();

let part = multipart::Part::stream(buf).file_name(file_name);
form = form.part(parameter_name, part);
}
FileUpload::String(_) => continue,
}
}

let url = format!("{}/{method}", self.api_url);
Expand Down
38 changes: 23 additions & 15 deletions src/api/telegram_api_impl.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use super::Error;
use super::HttpError;
use crate::api_params::FileUpload;
use crate::api_params::FileUploadForm;
use crate::api_traits::ErrorResponse;
use crate::api_traits::TelegramApi;
use multipart::client::lazy::Multipart;
use serde_json::Value;
use std::path::PathBuf;
use std::time::Duration;
use typed_builder::TypedBuilder;
use ureq::Response;
Expand Down Expand Up @@ -123,15 +124,11 @@ impl TelegramApi for Api {
&self,
method: &str,
params: T1,
files: Vec<(&str, PathBuf)>,
files: Vec<FileUploadForm>,
) -> Result<T2, Error> {
let json_string = Self::encode_params(&params)?;
let json_struct: Value = serde_json::from_str(&json_string).unwrap();
let file_keys: Vec<&str> = files.iter().map(|(key, _)| *key).collect();
let files_with_names: Vec<(&str, Option<&str>, PathBuf)> = files
.iter()
.map(|(key, path)| (*key, path.file_name().unwrap().to_str(), path.clone()))
.collect();
let file_keys: Vec<&str> = files.iter().map(|(key, _)| key.as_str()).collect();

let mut form = Multipart::new();
for (key, val) in json_struct.as_object().unwrap() {
Expand All @@ -145,15 +142,26 @@ impl TelegramApi for Api {
}
}

for (parameter_name, file_name, file_path) in files_with_names {
let file = std::fs::File::open(&file_path).unwrap();
let file_extension = file_path
.extension()
.and_then(std::ffi::OsStr::to_str)
.unwrap_or("");
let mime = mime_guess::from_ext(file_extension).first_or_octet_stream();
for (parameter_name, file) in &files {
match file {
FileUpload::InputFile(input_file) => {
let file = std::fs::File::open(&input_file.path).unwrap();
let file_name = input_file.path.file_name().unwrap().to_str();
let file_extension =
input_file.path.extension().unwrap().to_str().unwrap_or("");
let mime = mime_guess::from_ext(file_extension).first_or_octet_stream();

form.add_stream(parameter_name, file, file_name, Some(mime));
form.add_stream(parameter_name, file, file_name, Some(mime));
}
FileUpload::InputBuf(input_buf) => {
let file = std::io::Cursor::<Vec<u8>>::new(input_buf.data.clone());
let file_extension = input_buf.file_name.rsplit_once('.').unwrap_or(("", "")).1;
let mime = mime_guess::from_ext(file_extension).first_or_octet_stream();

form.add_stream(parameter_name, file, Some(&input_buf.file_name), Some(mime));
}
FileUpload::String(_) => continue,
}
}

let url = format!("{}/{method}", self.api_url);
Expand Down
43 changes: 43 additions & 0 deletions src/api_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,22 @@ use typed_builder::TypedBuilder as Builder;
#[serde(untagged)]
pub enum FileUpload {
InputFile(InputFile),
InputBuf(InputBuf),
String(String),
}

pub type FileUploadForm = (String, FileUpload);

impl FileUpload {
pub fn to_form_with_key(&self, key: &str) -> FileUploadForm {
(key.to_string(), self.clone())
}

pub fn is_input(&self) -> bool {
matches!(self, FileUpload::InputFile(_) | FileUpload::InputBuf(_))
}
}

impl From<PathBuf> for FileUpload {
fn from(path: PathBuf) -> Self {
let input_file = InputFile { path };
Expand All @@ -36,12 +49,36 @@ impl From<PathBuf> for FileUpload {
}
}

impl From<(String, Vec<u8>)> for FileUpload {
fn from((file_name, data): (String, Vec<u8>)) -> Self {
Self::InputBuf(InputBuf { file_name, data })
}
}

impl From<InputFile> for FileUpload {
fn from(file: InputFile) -> Self {
Self::InputFile(file)
}
}

impl From<&InputFile> for FileUpload {
fn from(file: &InputFile) -> Self {
Self::InputFile(file.clone())
}
}

impl From<InputBuf> for FileUpload {
fn from(input: InputBuf) -> Self {
Self::InputBuf(input)
}
}

impl From<&InputBuf> for FileUpload {
fn from(input: &InputBuf) -> Self {
Self::InputBuf(input.clone())
}
}

impl From<String> for FileUpload {
fn from(file: String) -> Self {
Self::String(file)
Expand Down Expand Up @@ -220,6 +257,12 @@ pub struct InputFile {
pub path: PathBuf,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Builder)]
pub struct InputBuf {
pub file_name: String,
pub data: Vec<u8>,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of providing Vec. what do you think about using generic AsRef<[u8]>

in this case it will be more flexible.

Copy link
Author

@akahan akahan Aug 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I also support this idea. I'll work on it.

}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Builder)]
pub struct GetUpdatesParams {
#[serde(skip_serializing_if = "Option::is_none")]
Expand Down
Loading