api: add Message.set_file_from_bytes() API

This commit is contained in:
link2xt
2023-07-08 19:31:13 +00:00
parent 1ba69dbb9b
commit 17a6c88cc7
2 changed files with 27 additions and 13 deletions

View File

@@ -7,6 +7,7 @@ use anyhow::{ensure, format_err, Context as _, Result};
use deltachat_derive::{FromSql, ToSql};
use serde::{Deserialize, Serialize};
use crate::blob::BlobObject;
use crate::chat::{Chat, ChatId};
use crate::config::Config;
use crate::constants::{
@@ -983,6 +984,20 @@ impl Message {
self.param.set_optional(Param::MimeType, filemime);
}
/// Creates a new blob and sets it as a file associated with a message.
pub async fn set_file_from_bytes(
&mut self,
context: &Context,
suggested_name: &str,
data: &[u8],
filemime: Option<&str>,
) -> Result<()> {
let blob = BlobObject::create(context, suggested_name, data).await?;
self.param.set(Param::File, blob.as_name());
self.param.set_optional(Param::MimeType, filemime);
Ok(())
}
/// Set different sender name for a message.
/// This overrides the name set by the `set_config()`-option `displayname`.
pub fn set_override_sender_name(&mut self, name: Option<String>) {

View File

@@ -909,10 +909,8 @@ mod tests {
}
async fn create_webxdc_instance(t: &TestContext, name: &str, bytes: &[u8]) -> Result<Message> {
let file = t.get_blobdir().join(name);
tokio::fs::write(&file, bytes).await?;
let mut instance = Message::new(Viewtype::File);
instance.set_file(file.to_str().unwrap(), None);
instance.set_file_from_bytes(t, name, bytes, None).await?;
Ok(instance)
}
@@ -940,10 +938,10 @@ mod tests {
assert_eq!(instance.chat_id, chat_id);
// sending using bad extension is not working, even when setting Viewtype to webxdc
let file = t.get_blobdir().join("index.html");
tokio::fs::write(&file, b"<html>ola!</html>").await?;
let mut instance = Message::new(Viewtype::Webxdc);
instance.set_file(file.to_str().unwrap(), None);
instance
.set_file_from_bytes(&t, "index.html", b"<html>ola!</html>", None)
.await?;
assert!(send_msg(&t, chat_id, &mut instance).await.is_err());
Ok(())
@@ -967,14 +965,15 @@ mod tests {
assert_eq!(test.viewtype, Viewtype::File);
// sending invalid .xdc as Viewtype::Webxdc should fail already on sending
let file = t.get_blobdir().join("invalid2.xdc");
tokio::fs::write(
&file,
include_bytes!("../test-data/webxdc/invalid-no-zip-but-7z.xdc"),
)
.await?;
let mut instance = Message::new(Viewtype::Webxdc);
instance.set_file(file.to_str().unwrap(), None);
instance
.set_file_from_bytes(
&t,
"invalid2.xdc",
include_bytes!("../test-data/webxdc/invalid-no-zip-but-7z.xdc"),
None,
)
.await?;
assert!(send_msg(&t, chat_id, &mut instance).await.is_err());
Ok(())