summaryrefslogtreecommitdiff
path: root/_invitation-mailer/src/main.rs
blob: 369d6fe4908ab127259b1c2e584f7031284032f9 (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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use {
    anyhow::{
        anyhow,
        Context,
        Result,
    },
    chrono::{
        DateTime,
        Local,
        TimeZone,
        Utc,
    },
    getopts::Options,
    ics::{
        escape_text,
        Event,
        ICalendar,
        components::Parameter,
        properties::{
            Attendee,
            Description,
            DtEnd,
            DtStart,
            Location,
            Method,
            Organizer,
            Summary,
        },
    },
    emailmessage::{
        header,
        Message,
        MultiPart,
        SinglePart,
    },
    lettre::{
        address::Envelope,
        SmtpTransport,
        Transport,
        transport::smtp::authentication::Credentials,
    },
    minijinja::{
        Environment,
        context as jinja_context,
    },
    nos::Document,
    std::{
        env::args,
        fs::File,
        io::Read,
    },
    uuid::Uuid,
};

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [options] 'Recipient name <recipient@email.address>'", program);
    print!("{}", opts.usage(&brief));
}

fn to_iso8601(dt: DateTime<Local>) -> String {
    // https://github.com/chronotope/chrono/issues/244
    DateTime::<Utc>::from(dt).format("%Y%m%dT%H%M%SZ").to_string()
}

fn month_number(month: &str) -> Result<u32> {
   match month {
        "January" => Ok(1),
        "February" => Ok(2),
        "March" => Ok(3),
        "April" => Ok(4),
        "May" => Ok(5),
        "June" => Ok(6),
        "July" => Ok(7),
        "August" => Ok(8),
        "September" => Ok(9),
        "October" => Ok(10),
        "November" => Ok(11),
        "December" => Ok(12),
        invalid => Err(anyhow!("Invalid month name: {invalid}")),
    }
}

struct Desc {
    _html: String,
    plain: String,
}

struct HackNight {
    title: String,
    desc: Desc,
    start: DateTime<Local>,
    end: DateTime<Local>,
    location: String,
}

impl HackNight {
    fn new(
        title: String,
        desc: Desc,
        start: DateTime<Local>,
        end: DateTime<Local>,
        location: String,
    ) -> Self {
        Self {
            title,
            desc,
            start,
            end,
            location,
        }
    }

    fn from_html(filename: &str) -> Result<HackNight> {
        let mut file = File::open(filename)?;
        let mut html = String::new();
        File::read_to_string(&mut file, &mut html)?;
        let document = Document::from(&html);
        let event = document.select("article.event").iter().next()
            .ok_or_else(|| anyhow!("Could not find event in html file"))?;

        let year = event.select("p.event-year").text().to_string().parse::<i32>()?;
        let month = month_number(event.select("p.event-month").text().to_string().as_str())?;
        let day = event.select("p.event-day").text().to_string().parse::<u32>()?;

        let timespan = event.select("dl.dl-horizontal > dd").iter().last()
            .ok_or_else(|| anyhow!("No venue timespan found"))?.text().to_string();
        let (start_str, end_str) = timespan.split_once('—')
            .ok_or_else(|| anyhow!("Couldn't split timespan"))?;
        let start_hh = start_str[0..=1].parse::<u32>()?;
        let start_mm = start_str[3..=4].parse::<u32>()?;
        let end_hh: u32 = end_str[0..=1].parse()?;
        let end_mm: u32 = end_str[3..=4].parse()?;

        let description = event.select("div.event-desc");
        let title = event.select("h3.event-desc-header").text().to_string().trim().to_owned();

        let mut title_elem = event.select("h3.event-desc-header");
        title_elem.remove();

        let location = event.select("dl.dl-horizontal > dd > strong").iter().next()
            .ok_or_else(|| anyhow!("No venue location found"))?.text().to_string();
        let mut horizontals = event.select("dl.dl-horizontal");
        horizontals.remove();

        let desc = Desc {
            _html: description.html().to_string(),
            plain: august::convert_unstyled(&description.html().to_string(), 79),
        };

        let start = Local.ymd(year, month, day).and_hms(start_hh, start_mm, 0);
        let end = Local.ymd(year, month, day).and_hms(end_hh, end_mm, 0);

        Ok(HackNight::new(title, desc, start, end, location))
    }

    fn ics<'a>(&'a self, input: &Input) -> Result<ICalendar<'a>> {
        let mut calendar = ICalendar::new("2.0", "-//cph.rs//Hack Night inviter//EN");
        calendar.push(Method::new("REQUEST"));
        let uuid = Uuid::new_v4().to_string();
        let timestamp = to_iso8601(Local::now());

        let mut event = Event::new(uuid, timestamp);

        let mut attendee = Attendee::new(format!("mailto:{}",
            input.recipient_email));
        attendee.add(Parameter::new("RSVP", "TRUE"));
        attendee.add(Parameter::new("CUTYPE", "GROUP"));
        attendee.add(Parameter::new("CN", input.recipient_name.clone()));

        event.push(Organizer::new(format!("mailto:{}", input.organizer_email)));
        event.push(DtStart::new(to_iso8601(self.start)));
        event.push(DtEnd::new(to_iso8601(self.end)));
        event.push(Summary::new(format!("Rust {}", self.title)));
        event.push(Location::new(self.location.clone()));
        event.push(Description::new(escape_text(self.desc.plain.clone())));
        event.push(attendee);

        calendar.add_event(event);

        Ok(calendar)
    }

    fn mail_body(&self, fields: &Input) -> Result<String> {
        let mut file = File::open(fields.template.clone())?;
        let mut contents = String::new();
        File::read_to_string(&mut file, &mut contents)?;
        let mut env = Environment::new();
        env.add_template("plain/text", &contents)?;
        let template = env.get_template("plain/text")?;

        template.render(jinja_context! {
            body => self.desc.plain,
            organizer_email => fields.organizer_email,
        }).context("jinja")
    }

    fn mime_message(&self, input: &Input, body: &str, ics: &ICalendar)
        -> Result<Message<MultiPart<String>>>
    {
        Ok(Message::builder()
            .from(format!("{} <{}>", input.sender_name, input.sender_email).parse()?)
            .to(format!("{} <{}>", input.recipient_name, input.recipient_email).parse()?)
            .subject(format!("Rust {}", &self.title))
            .mime_body(
                MultiPart::mixed()
                .singlepart(
                    SinglePart::quoted_printable()
                    .header(header::ContentType("text/plain; charset=utf8".parse()?))
                    .body(String::from(body))
                )
                .singlepart(
                    SinglePart::base64()
                    .header(header::ContentType("text/calendar; charset=utf8".parse()?))
                    .body(format!("{}", ics))
                )
            )
        )
    }
}

struct Input {
    sender_name: String,
    sender_email: String,
    recipient_name: String,
    recipient_email: String,
    _organizer_name: String,
    organizer_email: String,
    template: String,
}

fn main() -> Result<()> {
    let args: Vec<String> = args().collect();
    let program = args[0].clone();

    let mut opts = Options::new();
    opts.optopt("", "smtp-username", "", "");
    opts.optopt("", "smtp-password", "", "");
    opts.optopt("", "smtp-server", "", "");
    opts.optopt("", "sender-name", "", "Remember to quote spaces");
    opts.optopt("", "sender-email", "", "");
    opts.optopt("", "organizer-name", "", "(Never actually used)");
    opts.optopt("", "organizer-email", "", "");
    opts.optopt("", "jekyll-input-file", "../index.html", "");
    opts.optopt("", "email-template", "email_body.j2", "");
    opts.optflag("h", "help", "Print this help text");
    let matches = opts.parse(&args[1..])?;
    if matches.opt_present("h") {
        print_usage(&program, opts);
        return Ok(());
    }
    let (recipient_name, recipient_email) = if !matches.free.is_empty() {
        matches.free[0].strip_suffix('>')
            .ok_or_else(|| anyhow!("Could not understand recipient argument"))?.split_once(" <")
            .ok_or_else(|| anyhow!("Could not understand recipient argument"))?
    } else {
        print_usage(&program, opts);
        return Ok(());
    };

    let input = Input {
        sender_name: matches.opt_str("sender-name").ok_or_else(|| anyhow!("Missing sender name"))?,
        sender_email: matches.opt_str("sender-email")
            .ok_or_else(|| anyhow!("Missing sender email"))?,
        _organizer_name: matches.opt_str("organizer-name").unwrap_or_default(),
        organizer_email: matches.opt_str("organizer-email")
            .ok_or_else(|| anyhow!("Missing organizer email"))?,
        recipient_name: String::from(recipient_name),
        recipient_email: String::from(recipient_email),
        template: matches.opt_str("email-template")
            .unwrap_or_else(|| String::from("email_body.j2")),
    };
    let hacknight = HackNight::from_html(&matches.opt_str("jekyll-input-file")
        .unwrap_or_else(|| String::from("../index.html")))?;

    let calendar = hacknight.ics(&input)?;
    let body = hacknight.mail_body(&input)?;

    let email = hacknight.mime_message(&input, &body, &calendar)?;

    let creds = Credentials::new(
        matches.opt_str("smtp-username").ok_or_else(|| anyhow!("Missing smtp username"))?,
        matches.opt_str("smtp-password").ok_or_else(|| anyhow!("Missing smtp password"))?,
    );

    // let mailer = SmtpTransport::relay(
    let mailer = SmtpTransport::starttls_relay(
        &matches.opt_str("smtp-server").ok_or_else(|| anyhow!("Missing smtp server"))?
    )?.credentials(creds).build();

    let envelope = Envelope::new(Some(input.sender_email.parse()?),
        vec![input.recipient_email.parse()?])?;
    mailer.send_raw(&envelope, format!("{}", &email).as_bytes()).map(|_| ())
        .context("Failed to send email message")
}