Remove the context reference from Message struct

The Message struct had a reference to the context which made a few
APIs a little easier.  However it has surprising consequences a long
way down the line as shown in #335: it means any object which has such
a reference needs to keep open a lock if we want to do this refactor
of no longer having a "closed" Context struct on the Rust API (which
has many benefits which will simply that Context struct and is more
the Rust way - RAII etc).

By refactoring away the context reference on the rust API as done in
here however, we push this behaviour of how these references are
handled back to the C-API pointer behaviour: that is unsafe but just
works in a C-like way.  The resulting complexity in the FFI layer is
also notably less than in the #335 alternative.

As a consequence all APIs which require the context, now explicitly
need to get the context passed in as an argument.  It looks like this
is certainly no downside and maybe even beneficial for further API
refactors.

For this strategy to work out the same should be done to
dc_chatlist_t, dc_chat_t and dc_contact_t.  But this working for
dc_msg_t give a reasonable confidence that this is a good approach.
This commit is contained in:
Floris Bruynooghe
2019-09-09 21:35:08 +02:00
committed by Floris Bruynooghe
parent e73671a6ff
commit a0b5e32f98
9 changed files with 206 additions and 223 deletions

View File

@@ -635,7 +635,7 @@ pub fn get_by_contact_id(context: &Context, contact_id: u32) -> Result<u32, Erro
pub fn prepare_msg<'a>(
context: &'a Context,
chat_id: u32,
msg: &mut Message<'a>,
msg: &mut Message,
) -> Result<u32, Error> {
ensure!(
chat_id > DC_CHAT_ID_LAST_SPECIAL,
@@ -665,13 +665,8 @@ pub fn msgtype_has_file(msgtype: Viewtype) -> bool {
}
}
fn prepare_msg_common<'a>(
context: &'a Context,
chat_id: u32,
msg: &mut Message<'a>,
) -> Result<u32, Error> {
fn prepare_msg_common(context: &Context, chat_id: u32, msg: &mut Message) -> Result<u32, Error> {
msg.id = 0;
msg.context = context;
if msg.type_0 == Viewtype::Text {
// the caller should check if the message text is empty
@@ -787,11 +782,7 @@ pub fn unarchive(context: &Context, chat_id: u32) -> Result<(), Error> {
/// However, this does not imply, the message really reached the recipient -
/// sending may be delayed eg. due to network problems. However, from your
/// view, you're done with the message. Sooner or later it will find its way.
pub fn send_msg<'a>(
context: &'a Context,
chat_id: u32,
msg: &mut Message<'a>,
) -> Result<u32, Error> {
pub fn send_msg(context: &Context, chat_id: u32, msg: &mut Message) -> Result<u32, Error> {
if msg.state != MessageState::OutPreparing {
// automatically prepare normal messages
prepare_msg_common(context, chat_id, msg)?;
@@ -835,7 +826,7 @@ pub fn send_msg<'a>(
}
}
msg.param.remove(Param::PrepForwards);
dc_msg_save_param_to_disk(msg);
dc_msg_save_param_to_disk(context, msg);
}
}
@@ -853,7 +844,7 @@ pub unsafe fn send_text_msg(
chat_id
);
let mut msg = dc_msg_new(context, Viewtype::Text);
let mut msg = dc_msg_new(Viewtype::Text);
msg.text = Some(text_to_send);
send_msg(context, chat_id, &mut msg)
}
@@ -1295,7 +1286,7 @@ pub unsafe fn create_group_chat(
if chat_id != 0 {
if 0 != add_to_chat_contacts_table(context, chat_id, 1) {
let mut draft_msg = dc_msg_new(context, Viewtype::Text);
let mut draft_msg = dc_msg_new(Viewtype::Text);
dc_msg_set_text(&mut draft_msg, draft_txt.as_ptr());
set_draft_raw(context, chat_id, Some(&mut draft_msg));
}
@@ -1340,7 +1331,7 @@ pub fn add_contact_to_chat_ex(
if contact.is_err() || chat_id <= DC_CHAT_ID_LAST_SPECIAL {
return 0;
}
let mut msg = unsafe { dc_msg_new_untyped(context) };
let mut msg = dc_msg_new_untyped();
reset_gossiped_timestamp(context, chat_id);
let contact = contact.unwrap();
@@ -1489,7 +1480,7 @@ pub unsafe fn remove_contact_from_chat(
"Cannot remove special contact"
);
let mut msg = dc_msg_new_untyped(context);
let mut msg = dc_msg_new_untyped();
let mut success = false;
/* we do not check if "contact_id" exists but just delete all records with the id from chats_contacts */
@@ -1588,7 +1579,7 @@ pub unsafe fn set_chat_name(
ensure!(chat_id > DC_CHAT_ID_LAST_SPECIAL, "Invalid chat ID");
let chat = Chat::load_from_db(context, chat_id)?;
let mut msg = dc_msg_new_untyped(context);
let mut msg = dc_msg_new_untyped();
if real_group_exists(context, chat_id) {
if &chat.name == new_name.as_ref() {
@@ -1684,7 +1675,7 @@ pub fn set_chat_profile_image(
chat.param.set(Param::ProfileImage, &new_image_rel);
if chat.update_param().is_ok() {
if chat.is_promoted() {
let mut msg = unsafe { dc_msg_new_untyped(context) };
let mut msg = dc_msg_new_untyped();
msg.param.set_int(Param::Cmd, DC_CMD_GROUPIMAGE_CHANGED);
msg.type_0 = Viewtype::Text;
msg.text = Some(context.stock_system_msg(
@@ -1779,7 +1770,7 @@ pub unsafe fn forward_msgs(
msg.param.set(Param::PrepForwards, new_msg_id.to_string());
}
dc_msg_save_param_to_disk(&mut msg);
dc_msg_save_param_to_disk(context, &mut msg);
msg.param = save_param;
} else {
msg.state = MessageState::OutPending;

View File

@@ -138,7 +138,7 @@ pub unsafe fn dc_initiate_key_transfer(context: &Context) -> *mut libc::c_char {
))
{
if let Ok(chat_id) = chat::create_by_contact_id(context, 1) {
msg = dc_msg_new_untyped(context);
msg = dc_msg_new_untyped();
msg.type_0 = Viewtype::File;
msg.param.set(Param::File, as_str(setup_file_name));
@@ -281,7 +281,7 @@ pub unsafe fn dc_continue_key_transfer(
if msg.is_err()
|| !dc_msg_is_setupmessage(msg.as_ref().unwrap())
|| {
filename = dc_msg_get_file(msg.as_ref().unwrap());
filename = dc_msg_get_file(context, msg.as_ref().unwrap());
filename.is_null()
}
|| *filename.offset(0isize) as libc::c_int == 0i32

View File

@@ -37,7 +37,7 @@ pub struct dc_mimefactory_t<'a> {
pub timestamp: i64,
pub rfc724_mid: *mut libc::c_char,
pub loaded: dc_mimefactory_loaded_t,
pub msg: Message<'a>,
pub msg: Message,
pub chat: Option<Chat<'a>>,
pub increation: libc::c_int,
pub in_reply_to: *mut libc::c_char,
@@ -335,7 +335,10 @@ pub unsafe fn dc_mimefactory_load_mdn<'a>(
}
// TODO should return bool /rtn
pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_int {
pub unsafe fn dc_mimefactory_render(
context: &Context,
factory: &mut dc_mimefactory_t,
) -> libc::c_int {
let subject: *mut mailimf_subject;
let mut ok_to_continue = true;
let imf_fields: *mut mailimf_fields;
@@ -586,7 +589,7 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
}
if 0 != msg.param.get_int(Param::Arg2).unwrap_or_default() & 0x1 {
info!(
msg.context,
context,
"sending secure-join message \'{}\' >>>>>>>>>>>>>>>>>>>>>>>>>",
"vg-member-added",
);
@@ -654,7 +657,7 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
let step = msg.param.get(Param::Arg).unwrap_or_default().strdup();
if strlen(step) > 0 {
info!(
msg.context,
context,
"sending secure-join message \'{}\' >>>>>>>>>>>>>>>>>>>>>>>>>",
as_str(step),
);
@@ -725,12 +728,13 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
}
if let Some(grpimage) = grpimage {
info!(factory.context, "setting group image '{}'", grpimage);
let mut meta = dc_msg_new_untyped(factory.context);
let mut meta = dc_msg_new_untyped();
meta.type_0 = Viewtype::Image;
meta.param.set(Param::File, grpimage);
let mut filename_as_sent = ptr::null_mut();
meta_part = build_body_file(
context,
&meta,
b"group-image\x00" as *const u8 as *const libc::c_char,
&mut filename_as_sent,
@@ -833,7 +837,7 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
/* add attachment part */
if chat::msgtype_has_file(factory.msg.type_0) {
if !is_file_size_okay(&factory.msg) {
if !is_file_size_okay(context, &factory.msg) {
let error: *mut libc::c_char = dc_mprintf(
b"Message exceeds the recommended %i MB.\x00" as *const u8
as *const libc::c_char,
@@ -844,7 +848,7 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
ok_to_continue = false;
} else {
let file_part: *mut mailmime =
build_body_file(&factory.msg, ptr::null(), ptr::null_mut());
build_body_file(context, &factory.msg, ptr::null(), ptr::null_mut());
if !file_part.is_null() {
mailmime_smart_add_part(message, file_part);
parts += 1
@@ -892,12 +896,9 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
mailmime_smart_add_part(message, kml_mime_part);
}
if location::is_sending_locations_to_chat(
factory.msg.context,
factory.msg.chat_id,
) {
if location::is_sending_locations_to_chat(context, factory.msg.chat_id) {
if let Ok((kml_file, last_added_location_id)) =
location::get_kml(factory.msg.context, factory.msg.chat_id)
location::get_kml(context, factory.msg.chat_id)
{
let content_type = mailmime_content_new_with_str(
b"application/vnd.google-earth.kml+xml\x00" as *const u8
@@ -950,7 +951,7 @@ pub unsafe fn dc_mimefactory_render(factory: &mut dc_mimefactory_t) -> libc::c_i
.stock_str(StockMessage::EncryptedMsg)
.into_owned()
} else {
to_string(dc_msg_get_summarytext(&mut factory.msg, 32))
to_string(dc_msg_get_summarytext(context, &mut factory.msg, 32))
};
let p2 = factory
.context
@@ -1134,6 +1135,7 @@ unsafe fn build_body_text(text: *mut libc::c_char) -> *mut mailmime {
#[allow(non_snake_case)]
unsafe fn build_body_file(
context: &Context,
msg: &Message,
mut base_name: *const libc::c_char,
ret_file_name_as_sent: *mut *mut libc::c_char,
@@ -1286,7 +1288,7 @@ unsafe fn build_body_file(
) as *mut libc::c_void,
);
mime_sub = mailmime_new_empty(content, mime_fields);
mailmime_set_body_file(mime_sub, dc_get_abs_path(msg.context, path_filename));
mailmime_set_body_file(mime_sub, dc_get_abs_path(context, path_filename));
if !ret_file_name_as_sent.is_null() {
*ret_file_name_as_sent = dc_strdup(filename_to_send)
}
@@ -1303,10 +1305,10 @@ unsafe fn build_body_file(
/*******************************************************************************
* Render
******************************************************************************/
unsafe fn is_file_size_okay(msg: &Message) -> bool {
unsafe fn is_file_size_okay(context: &Context, msg: &Message) -> bool {
let mut file_size_okay = true;
let path = msg.param.get(Param::File).unwrap_or_default();
let bytes = dc_get_filebytes(msg.context, &path);
let bytes = dc_get_filebytes(context, &path);
if bytes > (49 * 1024 * 1024 / 4 * 3) {
file_size_okay = false;

View File

@@ -677,12 +677,12 @@ pub unsafe fn job_send_msg(context: &Context, msg_id: uint32_t) -> libc::c_int {
mimefactory.msg.param.set_int(Param::Height, height as i32);
}
}
dc_msg_save_param_to_disk(&mut mimefactory.msg);
dc_msg_save_param_to_disk(context, &mut mimefactory.msg);
}
}
}
/* create message */
if 0 == dc_mimefactory_render(&mut mimefactory) {
if 0 == dc_mimefactory_render(context, &mut mimefactory) {
dc_set_msg_failed(context, msg_id, as_opt_str(mimefactory.error));
} else if 0
!= mimefactory
@@ -745,7 +745,7 @@ pub unsafe fn job_send_msg(context: &Context, msg_id: uint32_t) -> libc::c_int {
== 0
{
mimefactory.msg.param.set_int(Param::GuranteeE2ee, 1);
dc_msg_save_param_to_disk(&mut mimefactory.msg);
dc_msg_save_param_to_disk(context, &mut mimefactory.msg);
}
success = add_smtp_job(context, Action::SendMsgToSmtp, &mut mimefactory);
}
@@ -992,7 +992,7 @@ fn connect_to_inbox(context: &Context, inbox: &Imap) -> libc::c_int {
fn send_mdn(context: &Context, msg_id: uint32_t) {
if let Ok(mut mimefactory) = unsafe { dc_mimefactory_load_mdn(context, msg_id) } {
if 0 != unsafe { dc_mimefactory_render(&mut mimefactory) } {
if 0 != unsafe { dc_mimefactory_render(context, &mut mimefactory) } {
add_smtp_job(context, Action::SendMdn, &mut mimefactory);
}
}

View File

@@ -215,7 +215,7 @@ pub fn send_locations_to_chat(context: &Context, chat_id: u32, seconds: i64) {
.is_ok()
{
if 0 != seconds && !is_sending_locations_before {
msg = dc_msg_new(context, Viewtype::Text);
msg = dc_msg_new(Viewtype::Text);
msg.text =
Some(context.stock_system_msg(StockMessage::MsgLocationEnabled, "", "", 0));
msg.param.set_int(Param::Cmd, 8);
@@ -606,7 +606,7 @@ pub fn job_do_DC_JOB_MAYBE_SEND_LOCATIONS(context: &Context, _job: &Job) {
// the easiest way to determine this, is to check for an empty message queue.
// (might not be 100%, however, as positions are sent combined later
// and dc_set_location() is typically called periodically, this is ok)
let mut msg = dc_msg_new(context, Viewtype::Text);
let mut msg = dc_msg_new(Viewtype::Text);
msg.hidden = true;
msg.param.set_int(Param::Cmd, 9);
Some((chat_id, msg))

View File

@@ -137,7 +137,7 @@ impl Lot {
/// approx. max. length returned by dc_msg_get_text()
/// approx. max. length returned by dc_get_msg_info()
#[derive(Clone)]
pub struct Message<'a> {
pub struct Message {
pub id: u32,
pub from_id: u32,
pub to_id: u32,
@@ -150,7 +150,6 @@ pub struct Message<'a> {
pub timestamp_sent: i64,
pub timestamp_rcvd: i64,
pub text: Option<String>,
pub context: &'a Context,
pub rfc724_mid: *mut libc::c_char,
pub in_reply_to: *mut libc::c_char,
pub server_folder: Option<String>,
@@ -270,7 +269,7 @@ pub unsafe fn dc_get_msg_info(context: &Context, msg_id: u32) -> *mut libc::c_ch
_ => {}
}
let p = dc_msg_get_file(&msg);
let p = dc_msg_get_file(context, &msg);
if !p.is_null() && 0 != *p.offset(0isize) as libc::c_int {
ret += &format!(
"\nFile: {}, {}, bytes\n",
@@ -310,11 +309,11 @@ pub unsafe fn dc_get_msg_info(context: &Context, msg_id: u32) -> *mut libc::c_ch
ret.strdup()
}
pub unsafe fn dc_msg_new_untyped<'a>(context: &'a Context) -> Message<'a> {
dc_msg_new(context, Viewtype::Unknown)
pub fn dc_msg_new_untyped() -> Message {
dc_msg_new(Viewtype::Unknown)
}
pub fn dc_msg_new<'a>(context: &'a Context, viewtype: Viewtype) -> Message<'a> {
pub fn dc_msg_new(viewtype: Viewtype) -> Message {
Message {
id: 0,
from_id: 0,
@@ -328,7 +327,6 @@ pub fn dc_msg_new<'a>(context: &'a Context, viewtype: Viewtype) -> Message<'a> {
timestamp_sent: 0,
timestamp_rcvd: 0,
text: None,
context,
rfc724_mid: std::ptr::null_mut(),
in_reply_to: std::ptr::null_mut(),
server_folder: None,
@@ -341,7 +339,7 @@ pub fn dc_msg_new<'a>(context: &'a Context, viewtype: Viewtype) -> Message<'a> {
}
}
impl<'a> Drop for Message<'a> {
impl Drop for Message {
fn drop(&mut self) {
unsafe {
free(self.rfc724_mid.cast());
@@ -380,11 +378,11 @@ pub fn dc_msg_guess_msgtype_from_suffix(path: &Path) -> Option<(Viewtype, &str)>
KNOWN.get(extension).map(|x| *x)
}
pub unsafe fn dc_msg_get_file(msg: &Message) -> *mut libc::c_char {
pub unsafe fn dc_msg_get_file(context: &Context, msg: &Message) -> *mut libc::c_char {
let mut file_abs = ptr::null_mut();
if let Some(file_rel) = msg.param.get(Param::File) {
file_abs = dc_get_abs_path(msg.context, file_rel);
file_abs = dc_get_abs_path(context, file_rel);
}
if !file_abs.is_null() {
file_abs
@@ -440,7 +438,7 @@ pub fn dc_msg_get_timestamp(msg: &Message) -> i64 {
}
}
pub fn dc_msg_load_from_db<'a>(context: &'a Context, id: u32) -> Result<Message<'a>, Error> {
pub fn dc_msg_load_from_db(context: &Context, id: u32) -> Result<Message, Error> {
context.sql.query_row(
"SELECT \
m.id,rfc724_mid,m.mime_in_reply_to,m.server_folder,m.server_uid,m.move_state,m.chat_id, \
@@ -451,8 +449,7 @@ pub fn dc_msg_load_from_db<'a>(context: &'a Context, id: u32) -> Result<Message<
params![id as i32],
|row| {
unsafe {
let mut msg = dc_msg_new_untyped(context);
msg.context = context;
let mut msg = dc_msg_new_untyped();
msg.id = row.get::<_, i32>(0)? as u32;
msg.rfc724_mid = row.get::<_, String>(1)?.strdup();
msg.in_reply_to = match row.get::<_, Option<String>>(2)? {
@@ -643,7 +640,7 @@ pub fn dc_star_msgs(
.is_ok()
}
pub fn dc_get_msg<'a>(context: &'a Context, msg_id: u32) -> Result<Message<'a>, Error> {
pub fn dc_get_msg(context: &Context, msg_id: u32) -> Result<Message, Error> {
dc_msg_load_from_db(context, msg_id)
}
@@ -701,11 +698,10 @@ pub unsafe fn dc_msg_get_filename(msg: &Message) -> *mut libc::c_char {
}
}
pub unsafe fn dc_msg_get_filebytes(msg: &Message) -> uint64_t {
pub fn dc_msg_get_filebytes(context: &Context, msg: &Message) -> uint64_t {
if let Some(file) = msg.param.get(Param::File) {
return dc_get_filebytes(msg.context, &file);
return dc_get_filebytes(context, &file);
}
0
}
@@ -730,14 +726,14 @@ pub fn dc_msg_get_showpadlock(msg: &Message) -> libc::c_int {
0
}
pub unsafe fn dc_msg_get_summary<'a>(msg: &mut Message<'a>, chat: Option<&Chat<'a>>) -> Lot {
pub fn dc_msg_get_summary(context: &Context, msg: &mut Message, chat: Option<&Chat>) -> Lot {
let mut ret = Lot::new();
let chat_loaded: Chat;
let chat = if let Some(chat) = chat {
chat
} else {
if let Ok(chat) = Chat::load_from_db(msg.context, msg.chat_id) {
if let Ok(chat) = Chat::load_from_db(context, msg.chat_id) {
chat_loaded = chat;
&chat_loaded
} else {
@@ -753,12 +749,13 @@ pub unsafe fn dc_msg_get_summary<'a>(msg: &mut Message<'a>, chat: Option<&Chat<'
None
};
ret.fill(msg, chat, contact.as_ref(), msg.context);
ret.fill(msg, chat, contact.as_ref(), context);
ret
}
pub unsafe fn dc_msg_get_summarytext(
context: &Context,
msg: &mut Message,
approx_characters: usize,
) -> *mut libc::c_char {
@@ -767,7 +764,7 @@ pub unsafe fn dc_msg_get_summarytext(
msg.text.as_ref(),
&mut msg.param,
approx_characters,
msg.context,
context,
)
.strdup()
}
@@ -898,7 +895,7 @@ pub fn dc_msg_is_setupmessage(msg: &Message) -> bool {
msg.param.get_int(Param::Cmd) == Some(6)
}
pub unsafe fn dc_msg_get_setupcodebegin(msg: &Message) -> *mut libc::c_char {
pub unsafe fn dc_msg_get_setupcodebegin(context: &Context, msg: &Message) -> *mut libc::c_char {
let mut filename: *mut libc::c_char = ptr::null_mut();
let mut buf: *mut libc::c_char = ptr::null_mut();
let mut buf_bytes: size_t = 0i32 as size_t;
@@ -908,11 +905,11 @@ pub unsafe fn dc_msg_get_setupcodebegin(msg: &Message) -> *mut libc::c_char {
let mut buf_setupcodebegin: *const libc::c_char = ptr::null();
let mut ret: *mut libc::c_char = ptr::null_mut();
if dc_msg_is_setupmessage(msg) {
filename = dc_msg_get_file(msg);
filename = dc_msg_get_file(context, msg);
if !(filename.is_null() || *filename.offset(0isize) as libc::c_int == 0i32) {
if !(0
== dc_read_file(
msg.context,
context,
filename,
&mut buf as *mut *mut libc::c_char as *mut *mut libc::c_void,
&mut buf_bytes,
@@ -977,6 +974,7 @@ pub fn dc_msg_set_duration(msg: &mut Message, duration: libc::c_int) {
}
pub fn dc_msg_latefiling_mediasize(
context: &Context,
msg: &mut Message,
width: libc::c_int,
height: libc::c_int,
@@ -989,20 +987,20 @@ pub fn dc_msg_latefiling_mediasize(
if duration > 0 {
msg.param.set_int(Param::Duration, duration);
}
dc_msg_save_param_to_disk(msg);
dc_msg_save_param_to_disk(context, msg);
}
pub fn dc_msg_save_param_to_disk(msg: &mut Message) -> bool {
pub fn dc_msg_save_param_to_disk(context: &Context, msg: &mut Message) -> bool {
sql::execute(
msg.context,
&msg.context.sql,
context,
&context.sql,
"UPDATE msgs SET param=? WHERE id=?;",
params![msg.param.to_string(), msg.id as i32],
)
.is_ok()
}
pub fn dc_msg_new_load<'a>(context: &'a Context, msg_id: u32) -> Result<Message<'a>, Error> {
pub fn dc_msg_new_load(context: &Context, msg_id: u32) -> Result<Message, Error> {
dc_msg_load_from_db(context, msg_id)
}
@@ -1321,7 +1319,7 @@ mod tests {
let chat = chat::create_by_contact_id(ctx, contact).unwrap();
let mut msg = dc_msg_new(ctx, Viewtype::Text);
let mut msg = dc_msg_new(Viewtype::Text);
let msg_id = chat::prepare_msg(ctx, chat, &mut msg).unwrap();

View File

@@ -274,7 +274,7 @@ fn send_handshake_msg(
fingerprint: Option<String>,
grpid: impl AsRef<str>,
) {
let mut msg = unsafe { dc_msg_new_untyped(context) };
let mut msg = dc_msg_new_untyped();
msg.type_0 = Viewtype::Text;
msg.text = Some(format!("Secure-Join: {}", step));
msg.hidden = true;