summaryrefslogtreecommitdiffstats
path: root/bin/domain/imag-mail/src/new.rs
blob: 4af5a11a1ba471e22afe0cf2c66aa6db3e1ffeb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::path::PathBuf;
use std::collections::BTreeMap;

use failure::Fallible as Result;
use failure::err_msg;
use toml_query::read::TomlValueReadExt;
use clap::ArgMatches;
use resiter::IterInnerOkOrElse;
use resiter::AndThen;
use resiter::Filter;
use resiter::Map;
use chrono::Local;
use email_format::Email;
use email_format::rfc5322::Parsable;
use handlebars::Handlebars;
use failure::Error;

use libimagmail::mail::Mail;
use libimagmail::store::MailStore;
use libimagmail::notmuch::connection::NotmuchConnection;
use libimagrt::runtime::Runtime;
use libimagstore::storeid::StoreId;
use libimagstore::iter::get::StoreIdGetIteratorExtension;
use libimagentryedit::edit::edit_in_tmpfile;
use libimaginteraction::format::HandlebarsData;

use crate::config::MailConfig;

fn sid_value_of(scmd: &ArgMatches, s: &str) -> Option<Result<StoreId>> {
    scmd.value_of(s).map(String::from).map(PathBuf::from).map(StoreId::new)
}

pub fn new(rt: &Runtime) -> Result<()> {
    let config             = rt.config()
        .ok_or_else(|| err_msg("Configuration missing"))?
        .read_partial::<MailConfig>()?
        .ok_or_else(|| err_msg("Configuration for \"mail\" missing"))?;

    let scmd               = rt.cli().subcommand_matches("new").unwrap(); // safe by main()
    let notmuch_path       = config.get_notmuch_database_path_or_cli(rt);
    debug!("notmuch path: {:?}", notmuch_path);
    let notmuch_connection = NotmuchConnection::open(notmuch_path)?;
    let store              = rt.store().with_connection(&notmuch_connection);

    let bcc = sid_value_of(&scmd, "bcc").transpose()?;
    let cc  = sid_value_of(&scmd, "cc").transpose()?;
    let to  = sid_value_of(&scmd, "to")
        .map(|r| r.map(|e| Some(vec![e])))
        .unwrap_or_else(|| rt.ids::<crate::ui::PathProvider>())?
        .ok_or_else(|| err_msg("No ids supplied"))?;
    let subject = scmd.value_of("subject").map(String::from);

    let in_reply_to = scmd.value_of("in-reply-to")
        .map(String::from)
        .map(|s| {
            match StoreId::new(PathBuf::from(&s))
                .and_then(|sid| store.get(sid))?
            {
                Some(fle) => Ok(Some(fle)),
                None      => store.get_mail_by_id(&s),
            }
        })
        .transpose()?
        .flatten();

    let notmuch_path       = config.get_notmuch_database_path_or_cli(rt);
    debug!("notmuch path: {:?}", notmuch_path);

    let written_message_id = mk_processed_template(rt, &scmd, &config)
        .and_then(|msg| edit_message_validated(rt, msg))
        .and_then(|msg| {
            // Write message to maildir and return message id
            maildir::Maildir::from(config.get_outgoing_maildir().to_path_buf())
                .store_new(&msg.as_bytes())
                .map_err(Error::from)
        })?;

    //
    // Writing the valid message to the outgoing maildir
    //

    info!("Stored: {}", written_message_id);
    debug!("Stored: {} in {}", written_message_id, config.get_outgoing_maildir().display());

    Ok(())
}

pub fn reply_to(rt: &Runtime) -> Result<()> {
    let config             = rt.config()
        .ok_or_else(|| err_msg("Configuration missing"))?
        .read_partial::<MailConfig>()?
        .ok_or_else(|| err_msg("Configuration for \"mail\" missing"))?;

    let scmd  = rt.cli().subcommand_matches("reply-to").unwrap(); // safe by main()
    let store = rt.store();

    let in_reply_to = sid_value_of(&scmd, "in-reply-to")
        .map(|r| r.map(|e| Some(vec![e])))
        .unwrap_or_else(|| rt.ids::<crate::ui::PathProvider>())?
        .ok_or_else(|| err_msg("No ids supplied"))?
        .into_iter()
        .map(Ok)
        .into_get_iter(rt.store())
        .map_inner_ok_or_else(|| err_msg("Did not find one entry"))
        .and_then_ok(|m| m.is_mail().map(|b| (b, m)))
        .filter_ok(|tpl| tpl.0)
        .map_ok(|tpl| tpl.1);

    unimplemented!()
}

fn mk_processed_template(rt: &Runtime, scmd: &ArgMatches, config: &MailConfig) -> Result<String> {
    debug!("Processing the template for the mail...");
    let mut hb_data = BTreeMap::new();

    hb_data.insert(String::from("message_id"), HandlebarsData::Str(generate_message_id(config)?));
    hb_data.insert(String::from("date"), HandlebarsData::Str({
        scmd.value_of("date")
            .map(String::from)
            .unwrap_or_else(|| {
                Local::now().to_rfc2822()
            })
    }));

    hb_data.insert(String::from("from"), HandlebarsData::Str({
        scmd.value_of("from")
            .map(String::from)
            .unwrap_or_else(|| {
                config.get_from_address().clone()
            })
    }));

    fn parse_recipient_data(scmd: &ArgMatches,
                            hb_data: &mut BTreeMap<String, HandlebarsData>,
                            primary_field: &str,
                            fail_if_absent: bool,
                            name_field: &str,
                            has_field: &str)
        -> Result<()>
    {
        let to = match scmd.value_of(primary_field).map(String::from) {
            Some(to) => to,
            None => if fail_if_absent {
                return Err(format_err!("Missing value for field field: '{}'", primary_field))
            } else {
                return Ok(())
            },
        };

        // Assume it is string for now
        // TODO: Check whether `to` is a StoreId (here)

        let (addr, _) = email_format::rfc5322::types::NameAddr::parse(to.as_bytes())?;
        let has_field_val = if let Some(display_name) = addr.display_name {
            hb_data.insert(String::from(name_field), HandlebarsData::Str(format!("{}", display_name).trim().to_string()));
            true
        } else {
            false
        };

        hb_data.insert(String::from(has_field), HandlebarsData::Bool(has_field_val));
        hb_data.insert(String::from(primary_field), HandlebarsData::Str(to));
        Ok(())
    };


    // parse "to" data, whether it is StoreId or String, also set to_name and has_to_name if there is a name present for the "to" data
    parse_recipient_data(&scmd, &mut hb_data, "to", true, "to_name", "has_to_name")?;
    parse_recipient_data(&scmd, &mut hb_data, "cc", false, "cc_name", "has_cc_name")?;
    parse_recipient_data(&scmd, &mut hb_data, "bcc", false, "bcc_name", "has_bcc_name")?;

    if let Some(in_reply_to) = scmd.value_of("in-reply-to").map(String::from) {
        hb_data.insert(String::from("is_in_reply_to") , HandlebarsData::Bool(true));
        hb_data.insert(String::from("in_reply_to") , HandlebarsData::Str(in_reply_to));
    } else {
        hb_data.insert(String::from("is_in_reply_to") , HandlebarsData::Bool(false));
    }

    hb_data.insert(String::from("subject"), HandlebarsData::Str({
        scmd.value_of("subject")
            .map(String::from)
            .unwrap_or_else(|| String::new())
    }));

    let template = if *config.get_edit_headers() {
        debug!("Template with header header editing");
        config.get_header_template()
    } else {
        debug!("Template without header editing");
        config.get_default_template()
    };

    process_template(template, &hb_data)
}

///
/// Editing the text and validating it
///
fn edit_message_validated(rt: &Runtime, mut msg: String) -> Result<String> {
    edit_in_tmpfile(&rt, &mut msg)?;

    let (mail, remainder) = Email::parse(&msg.as_bytes())?;
    debug!("Parsed: {}", mail);
    debug!("Remainder: {:?}", remainder);

    if remainder