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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/*
 * This file is part of mailpot
 *
 * Copyright 2020 - Manos Pitsidianakis
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

use std::borrow::Cow;

use super::*;
use crate::mail::ListRequest;

impl Connection {
    /// Insert a mailing list post into the database.
    pub fn insert_post(&self, list_pk: i64, message: &[u8], env: &Envelope) -> Result<i64> {
        let from_ = env.from();
        let address = if from_.is_empty() {
            String::new()
        } else {
            from_[0].get_email()
        };
        let datetime: std::borrow::Cow<'_, str> = if env.timestamp != 0 {
            melib::datetime::timestamp_to_string(
                env.timestamp,
                Some(melib::datetime::RFC3339_FMT_WITH_TIME),
                true,
            )
            .into()
        } else {
            env.date.as_str().into()
        };
        let message_id = env.message_id_display();
        let mut stmt = self.connection.prepare(
            "INSERT OR REPLACE INTO post(list, address, message_id, message, datetime, timestamp) \
             VALUES(?, ?, ?, ?, ?, ?) RETURNING pk;",
        )?;
        let pk = stmt.query_row(
            rusqlite::params![
                &list_pk,
                &address,
                &message_id,
                &message,
                &datetime,
                &env.timestamp
            ],
            |row| {
                let pk: i64 = row.get("pk")?;
                Ok(pk)
            },
        )?;

        trace!(
            "insert_post list_pk {}, from {:?} message_id {:?} post_pk {}.",
            list_pk,
            address,
            message_id,
            pk
        );
        Ok(pk)
    }

    /// Process a new mailing list post.
    pub fn post(&mut self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        let result = self.inner_post(env, raw, _dry_run);
        if let Err(err) = result {
            return match self.insert_to_error_queue(None, env, raw, err.to_string()) {
                Ok(idx) => {
                    log::info!(
                        "Inserted mail from {:?} into error_queue at index {}",
                        env.from(),
                        idx
                    );
                    Err(err)
                }
                Err(err2) => {
                    log::error!(
                        "Could not insert mail from {:?} into error_queue: {err2}",
                        env.from(),
                    );

                    Err(err.chain_err(|| err2))
                }
            };
        }
        result
    }

    fn inner_post(&mut self, env: &Envelope, raw: &[u8], _dry_run: bool) -> Result<()> {
        trace!("Received envelope to post: {:#?}", &env);
        let tos = env.to().to_vec();
        if tos.is_empty() {
            return Err("Envelope To: field is empty!".into());
        }
        if env.from().is_empty() {
            return Err("Envelope From: field is empty!".into());
        }
        let mut lists = self.lists()?;
        if lists.is_empty() {
            return Err("No active mailing lists found.".into());
        }
        let prev_list_len = lists.len();
        for t in &tos {
            if let Some((addr, subaddr)) = t.subaddress("+") {
                lists.retain(|list| {
                    if !addr.contains_address(&list.address()) {
                        return true;
                    }
                    if let Err(err) = ListRequest::try_from((subaddr.as_str(), env))
                        .and_then(|req| self.request(list, req, env, raw))
                    {
                        info!("Processing request returned error: {}", err);
                    }
                    false
                });
                if lists.len() != prev_list_len {
                    // Was request, handled above.
                    return Ok(());
                }
            }
        }

        lists.retain(|list| {
            trace!(
                "Is post related to list {}? {}",
                &list,
                tos.iter().any(|a| a.contains_address(&list.address()))
            );

            tos.iter().any(|a| a.contains_address(&list.address()))
        });
        if lists.is_empty() {
            return Err(format!(
                "No relevant mailing list found for these addresses: {:?}",
                tos
            )
            .into());
        }

        trace!("Configuration is {:#?}", &self.conf);
        use crate::mail::{ListContext, Post, PostAction};
        for mut list in lists {
            trace!("Examining list {}", list.display_name());
            let filters = self.list_filters(&list);
            let subscriptions = self.list_subscriptions(list.pk)?;
            let owners = self.list_owners(list.pk)?;
            trace!("List subscriptions {:#?}", &subscriptions);
            let mut list_ctx = ListContext {
                post_policy: self.list_post_policy(list.pk)?,
                subscription_policy: self.list_subscription_policy(list.pk)?,
                list_owners: &owners,
                list: &mut list,
                subscriptions: &subscriptions,
                scheduled_jobs: vec![],
            };
            let mut post = Post {
                from: env.from()[0].clone(),
                bytes: raw.to_vec(),
                to: env.to().to_vec(),
                action: PostAction::Hold,
            };
            let result = filters
                .into_iter()
                .fold(Ok((&mut post, &mut list_ctx)), |p, f| {
                    p.and_then(|(p, c)| f.feed(p, c))
                });
            trace!("result {:#?}", result);

            let Post { bytes, action, .. } = post;
            trace!("Action is {:#?}", action);
            let post_env = melib::Envelope::from_bytes(&bytes, None)?;
            match action {
                PostAction::Accept => {
                    let _post_pk = self.insert_post(list_ctx.list.pk, &bytes, &post_env)?;
                    trace!("post_pk is {:#?}", _post_pk);
                    for job in list_ctx.scheduled_jobs.iter() {
                        trace!("job is {:#?}", &job);
                        if let crate::mail::MailJob::Send { recipients } = job {
                            trace!("recipients: {:?}", &recipients);
                            if recipients.is_empty() {
                                trace!("list has no recipients");
                            }
                            for recipient in recipients {
                                let mut env = post_env.clone();
                                env.set_to(melib::smallvec::smallvec![recipient.clone()]);
                                self.insert_to_queue(QueueEntry::new(
                                    Queue::Out,
                                    Some(list.pk),
                                    Some(Cow::Owned(env)),
                                    &bytes,
                                    None,
                                )?)?;
                            }
                        }
                    }
                }
                PostAction::Reject { reason } => {
                    log::info!("PostAction::Reject {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was rejected.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Reject {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    return Err(PostRejected(reason).into());
                }
                PostAction::Defer { reason } => {
                    trace!("PostAction::Defer {{ reason: {} }}", reason);
                    for f in env.from() {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list: &list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("Your post to {} was deferred.", list.id),
                                    details => &reason,
                                },
                                queue: Queue::Out,
                                comment: format!("PostAction::Defer {{ reason: {} }}", reason)
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Deferred,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some(format!("PostAction::Defer {{ reason: {} }}", reason)),
                    )?)?;
                    return Err(PostRejected(reason).into());
                }
                PostAction::Hold => {
                    trace!("PostAction::Hold");
                    self.insert_to_queue(QueueEntry::new(
                        Queue::Hold,
                        Some(list.pk),
                        Some(Cow::Borrowed(&post_env)),
                        &bytes,
                        Some("PostAction::Hold".to_string()),
                    )?)?;
                    return Err(PostRejected("Hold".into()).into());
                }
            }
        }

        Ok(())
    }

    /// Process a new mailing list request.
    pub fn request(
        &mut self,
        list: &DbVal<MailingList>,
        request: ListRequest,
        env: &Envelope,
        raw: &[u8],
    ) -> Result<()> {
        let post_policy = self.list_post_policy(list.pk)?;
        match request {
            ListRequest::Help => {
                // [ref:TODO] add test for this
                trace!(
                    "help action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let subscription_policy = self.list_subscription_policy(list.pk)?;
                let subject = format!("Help for {}", list.name);
                let details = list
                    .generate_help_email(post_policy.as_deref(), subscription_policy.as_deref());
                for f in env.from() {
                    self.send_reply_with_list_template(
                        TemplateRenderContext {
                            template: Template::GENERIC_HELP,
                            default_fn: Some(Template::default_generic_help),
                            list,
                            context: minijinja::context! {
                                list => &list,
                                subject => &subject,
                                details => &details,
                            },
                            queue: Queue::Out,
                            comment: "Help request".into(),
                        },
                        std::iter::once(Cow::Borrowed(f)),
                    )?;
                }
            }
            ListRequest::Subscribe => {
                trace!(
                    "subscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                let approval_needed = post_policy
                    .as_ref()
                    .map(|p| p.approval_needed)
                    .unwrap_or(false);
                for f in env.from() {
                    let email_from = f.get_email();
                    if self
                        .list_subscription_by_address(list.pk, &email_from)
                        .is_ok()
                    {
                        /* send error notice to e-mail sender */
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    subject => format!("You are already subscribed to {}.", list.id),
                                    details => "No action has been taken since you are already subscribed to the list.",
                                },
                                queue: Queue::Out,
                                comment: format!("Address {} is already subscribed to list {}", f, list.id).into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                        continue;
                    }

                    let subscription = ListSubscription {
                        pk: 0,
                        list: list.pk,
                        address: f.get_email(),
                        account: None,
                        name: f.get_display_name(),
                        digest: false,
                        hide_address: false,
                        receive_duplicates: true,
                        receive_own_posts: false,
                        receive_confirmation: true,
                        enabled: !approval_needed,
                        verified: true,
                    };
                    if approval_needed {
                        match self.add_candidate_subscription(list.pk, subscription) {
                            Ok(v) => {
                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER,
                                        default_fn: Some(
                                            Template::default_subscription_request_owner,
                                        ),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            candidate => &v,
                                        },
                                        queue: Queue::Out,
                                        comment: Template::SUBSCRIPTION_REQUEST_NOTICE_OWNER.into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                            Err(err) => {
                                log::error!(
                                    "Could not create candidate subscription for {f:?}: {err}"
                                );
                                /* send error notice to e-mail sender */
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::GENERIC_FAILURE,
                                        default_fn: Some(Template::default_generic_failure),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    std::iter::once(Cow::Borrowed(f)),
                                )?;

                                /* send error details to list owners */

                                let list_owners = self.list_owners(list.pk)?;
                                self.send_reply_with_list_template(
                                    TemplateRenderContext {
                                        template: Template::ADMIN_NOTICE,
                                        default_fn: Some(Template::default_admin_notice),
                                        list,
                                        context: minijinja::context! {
                                            list => &list,
                                            details => err.to_string(),
                                        },
                                        queue: Queue::Out,
                                        comment: format!(
                                            "Could not create candidate subscription for {f:?}: \
                                             {err}"
                                        )
                                        .into(),
                                    },
                                    list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                                )?;
                            }
                        }
                    } else if let Err(err) = self.add_subscription(list.pk, subscription) {
                        log::error!("Could not create subscription for {f:?}: {err}");

                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not create subscription for {f:?}: {err}")
                                    .into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        log::trace!(
                            "Added subscription to list {list:?} for address {f:?}, sending \
                             confirmation."
                        );
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::SUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_subscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::SUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Unsubscribe => {
                trace!(
                    "unsubscribe action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                for f in env.from() {
                    if let Err(err) = self.remove_subscription(list.pk, &f.get_email()) {
                        log::error!("Could not unsubscribe {f:?}: {err}");
                        /* send error notice to e-mail sender */

                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::GENERIC_FAILURE,
                                default_fn: Some(Template::default_generic_failure),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;

                        /* send error details to list owners */

                        let list_owners = self.list_owners(list.pk)?;
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::ADMIN_NOTICE,
                                default_fn: Some(Template::default_admin_notice),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                    details => err.to_string(),
                                },
                                queue: Queue::Out,
                                comment: format!("Could not unsubscribe {f:?}: {err}").into(),
                            },
                            list_owners.iter().map(|owner| Cow::Owned(owner.address())),
                        )?;
                    } else {
                        self.send_reply_with_list_template(
                            TemplateRenderContext {
                                template: Template::UNSUBSCRIPTION_CONFIRMATION,
                                default_fn: Some(Template::default_unsubscription_confirmation),
                                list,
                                context: minijinja::context! {
                                    list => &list,
                                },
                                queue: Queue::Out,
                                comment: Template::UNSUBSCRIPTION_CONFIRMATION.into(),
                            },
                            std::iter::once(Cow::Borrowed(f)),
                        )?;
                    }
                }
            }
            ListRequest::Other(ref req) if req == "owner" => {
                trace!(
                    "list-owner mail action for addresses {:?} in list {}",
                    env.from(),
                    list
                );
                return Err("list-owner emails are not implemented yet.".into());
                //FIXME: mail to list-owner
                /*
                for _owner in self.list_owners(list.pk)? {
                        self.insert_to_queue(
                            Queue::Out,
                            Some(list.pk),
                            None,
                            draft.finalise()?.as_bytes(),
                            "list-owner-forward".to_string(),
                        )?;
                }
                */
            }
            ListRequest::Other(ref req) if req.trim().eq_ignore_ascii_case("password") => {
                trace!(
                    "list-request password set action for addresses {:?} in list {list}",
                    env.from(),
                );
                let body = env.body_bytes(raw);
                let password = body.text();
                // TODO: validate SSH public key with `ssh-keygen`.
                for f in env.from() {
                    let email_from = f.get_email();
                    if let Ok(sub) = self.list_subscription_by_address(list.pk, &email_from) {
                        match self.account_by_address(&email_from)? {
                            Some(_acc) => {
                                let changeset = AccountChangeset {
                                    address: email_from.clone(),
                                    name: None,
                                    public_key: None,
                                    password: Some(password.clone()),
                                    enabled: None,
                                };
                                self.update_account(changeset)?;
                            }
                            None => {
                                // Create new account.
                                self.add_account(Account {
                                    pk: 0,
                                    name: sub.name.clone(),
                                    address: sub.address.clone(),
                                    public_key: None,
                                    password: password.clone(),
                                    enabled: sub.enabled,
                                })?;
                            }
                        }
                    }
                }
            }
            ListRequest::RetrieveMessages(ref message_ids) => {
                trace!(
                    "retrieve messages {message_ids:?} action for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::RetrieveArchive(ref from, ref to) => {
                trace!(
                    "retrieve archive action from {from:?} to {to:?} for addresses {:?} in list \
                     {list}",
                    env.from(),
                );
                return Err("message retrievals are not implemented yet.".into());
            }
            ListRequest::ChangeSetting(ref setting, ref toggle) => {
                trace!(
                    "change setting {setting}, request with value {toggle:?} for addresses {:?} \
                     in list {list}",
                    env.from(),
                );
                return Err("setting digest options via e-mail is not implemented yet.".into());
            }
            ListRequest::Other(ref req) => {
                trace!(
                    "unknown request action {req} for addresses {:?} in list {list}",
                    env.from(),
                );
                return Err(format!("Unknown request {req}.").into());
            }
        }
        Ok(())
    }

    /// Fetch all year and month values for which at least one post exists in
    /// `yyyy-mm` format.
    pub fn months(&self, list_pk: i64) -> Result<Vec<String>> {
        let mut stmt = self.connection.prepare(
            "SELECT DISTINCT strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') FROM post \
             WHERE list = ?;",
        )?;
        let months_iter = stmt.query_map([list_pk], |row| {
            let val: String = row.get(0)?;
            Ok(val)
        })?;

        let mut ret = vec![];
        for month in months_iter {
            let month = month?;
            ret.push(month);
        }
        Ok(ret)
    }

    /// Find a post by its `Message-ID` email header.
    pub fn list_post_by_message_id(
        &self,
        list_pk: i64,
        message_id: &str,
    ) -> Result<Option<DbVal<Post>>> {
        let mut stmt = self.connection.prepare(
            "SELECT *, strftime('%Y-%m', CAST(timestamp AS INTEGER), 'unixepoch') AS month_year \
             FROM post WHERE list = ? AND message_id = ?;",
        )?;
        let ret = stmt
            .query_row(rusqlite::params![&list_pk, &message_id], |row| {
                let pk = row.get("pk")?;
                Ok(DbVal(
                    Post {
                        pk,
                        list: row.get("list")?,
                        envelope_from: row.get("envelope_from")?,
                        address: row.get("address")?,
                        message_id: row.get("message_id")?,
                        message: row.get("message")?,
                        timestamp: row.get("timestamp")?,
                        datetime: row.get("datetime")?,
                        month_year: row.get("month_year")?,
                    },
                    pk,
                ))
            })
            .optional()?;

        Ok(ret)
    }

    /// Helper function to send a template reply.
    pub fn send_reply_with_list_template<'ctx, F: Fn() -> Template>(
        &self,
        render_context: TemplateRenderContext<'ctx, F>,
        recipients: impl Iterator<Item = Cow<'ctx, melib::Address>>,
    ) -> Result<()> {
        let TemplateRenderContext {
            template,
            default_fn,
            list,
            context,
            queue,
            comment,
        } = render_context;

        let post_policy = self.list_post_policy(list.pk)?;
        let subscription_policy = self.list_subscription_policy(list.pk)?;

        let templ = self
            .fetch_template(template, Some(list.pk))?
            .map(DbVal::into_inner)
            .or_else(|| default_fn.map(|f| f()))
            .ok_or_else(|| -> crate::Error {
                format!("Template with name {template:?} was not found.").into()
            })?;

        let mut draft = templ.render(context)?;
        draft.headers.insert(
            melib::HeaderName::new_unchecked("From"),
            list.request_subaddr(),
        );
        for addr in recipients {
            let mut draft = draft.clone();
            draft
                .headers
                .insert(melib::HeaderName::new_unchecked("To"), addr.to_string());
            list.insert_headers(
                &mut draft,
                post_policy.as_deref(),
                subscription_policy.as_deref(),
            );
            self.insert_to_queue(QueueEntry::new(
                queue,
                Some(list.pk),
                None,
                draft.finalise()?.as_bytes(),
                Some(comment.to_string()),
            )?)?;
        }
        Ok(())
    }
}

/// Helper type for [`Connection::send_reply_with_list_template`].
#[derive(Debug)]
pub struct TemplateRenderContext<'ctx, F: Fn() -> Template> {
    /// Template name.
    pub template: &'ctx str,
    /// If template is not found, call a function that returns one.
    pub default_fn: Option<F>,
    /// The pertinent list.
    pub list: &'ctx DbVal<MailingList>,
    /// [`minijinja`]'s template context.
    pub context: minijinja::value::Value,
    /// Destination queue in the database.
    pub queue: Queue,
    /// Comment for the queue entry in the database.
    pub comment: Cow<'static, str>,
}