summaryrefslogtreecommitdiffstats
path: root/src/maillist_view.rs
blob: 00ba7e0d10fba5459709e22bdee15b3a15664bd2 (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
use std::path::PathBuf;

use anyhow::Result;
use anyhow::Context;
use cursive::Cursive;
use cursive::Printer;
use cursive::Rect;
use cursive::View;
use cursive::XY;
use cursive::direction::Direction;
use cursive::view::Selector;
use cursive::event::Event;
use cursive::event::EventResult;
use cursive::views::ResizedView;
use cursive_table_view::TableView;
use cursive_table_view::TableViewItem;
use chrono::naive::NaiveDateTime;

pub struct MaillistView(TableView<MailListingData, MailListingColumn>);

impl MaillistView {
    pub fn create_for(database_path: &PathBuf, query: &str, name: String) -> Result<Self> {
        debug!("Getting '{}' from '{}'", query, database_path.display());

        let items = notmuch::Database::open(database_path, notmuch::DatabaseMode::ReadOnly)
            .context(format!("Opening database {}", database_path.display()))?
            .create_query(query)
            .context("Creating the search query")?
            .search_messages()
            .context(format!("Searching for messages with '{}'", query))?
            .map(|msg| {
                let mail_id = msg.id().to_string();
                let tags    = msg.tags().collect();
                let date    = NaiveDateTime::from_timestamp_opt(msg.date(), 0)
                        .map(|ndt| ndt.to_string())
                        .ok_or_else(|| {
                            error!("Failed to parse timestamp: {}", msg.date());
                            anyhow!("Failed to parse timestamp: {}", msg.date())
                        })
                        .context(format!("Getting the date of message {}", msg.id()))?;

                let from = msg.header("From")
                    .context(format!("Reading Header field 'From' of {}", msg.id()))?
                    .map(|f| f.to_string())
                    .ok_or_else(|| {
                        error!("Failed to get From for {}", msg.id());
                        anyhow!("Failed to get From for {}", msg.id())
                    })
                    .context(format!("Getting the 'From' of message {}", msg.id()))?;

                let to = msg.header("To")
                    .context(format!("Reading Header field 'To' of {}", msg.id()))?
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| {
                        error!("Failed to get 'To:' field for {}, using default ''", msg.id());
                        String::from("")
                    });
                let subject = msg.header("Subject")
                    .context(format!("Reading Header field 'Subject' of {}", msg.id()))?
                    .map(|s| s.to_string())
                    .ok_or_else(|| {
                        error!("Failed to get Subject for {}", msg.id());
                        anyhow!("Failed to get Subject for {}", msg.id())
                    })
                    .context(format!("Getting the subject of message {}", msg.id()))?;

                Ok(MailListingData {
                    mail_id,
                    tags,
                    date,
                    from,
                    to,
                    subject,
                })
            })
            .collect::<Result<Vec<_>>>()
            .context(format!("Creating MaillinglistView for '{}' on {}", query, database_path.display()))?;

        debug!("Found {} entries", items.len());
        let tab = TableView::<MailListingData, MailListingColumn>::new()
                .column(MailListingColumn::Date, "Date", |c| c.width(20))
                .column(MailListingColumn::Tags, "Tags", |c| c.width(20))
                .column(MailListingColumn::From, "From", |c| c)
                .column(MailListingColumn::To, "To", |c| c)
                .column(MailListingColumn::Subject, "Subject", |c| c)
                .default_column(MailListingColumn::Date)
                .items(items)
                .selected_item(0)
                .on_submit(move |siv: &mut Cursive, row: usize, _: usize| {
                    let mail_id = siv.call_on_name(&name, move |table: &mut ResizedView<TableView<MailListingData, MailListingColumn>>| {
                        table.get_inner_mut()
                            .borrow_item(row)
                            .map(|data| data.mail_id.clone())
                    });

                    // use the mail ID to get the whole thread and open it as a table item
                });

        Ok(MaillistView(tab))
    }
}

impl View for MaillistView {
    fn draw(&self, printer: &Printer) {
        self.0.draw(printer)
    }

    fn layout(&mut self, xy: XY<usize>) {
        self.0.layout(xy)
    }

    fn needs_relayout(&self) -> bool {
        self.0.needs_relayout()
    }

    fn required_size(&mut self, constraint: XY<usize>) -> XY<usize> {
        self.0.required_size(constraint)
    }

    fn on_event(&mut self, e: Event) -> EventResult {
        self.0.on_event(e)
    }

    fn call_on_any<'a>(&mut self, s: &Selector, tpl: &'a mut (dyn FnMut(&mut (dyn View + 'static)) + 'a)) {
        self.0.call_on_any(s, tpl);
    }

    fn focus_view(&mut self, s: &Selector) -> Result<(), ()> {
        self.0.focus_view(s)
    }

    fn take_focus(&mut self, source: Direction) -> bool {
        self.0.take_focus(source)
    }

    fn important_area(&self, view_size: XY<usize>) -> Rect {
        self.0.important_area(view_size)
    }

    fn type_name(&self) -> &'static str {
        self.0.type_name()
    }

}

#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum MailListingColumn {
    Date,
    Tags,
    From,
    To,
    Subject,
}

#[derive(Clone, Debug)]
pub struct MailListingData {
    mail_id: String,
    tags: Vec<String>,
    date: String,
    from: String,
    to: String,
    subject: String,
}

impl TableViewItem<MailListingColumn> for MailListingData {

    fn to_column(&self, column: MailListingColumn) -> String {
        match column {
            MailListingColumn::Date    => self.date.clone(),
            MailListingColumn::Tags    => self.tags.join(", "),
            MailListingColumn::From    => self.from.clone(),
            MailListingColumn::To      => self.to.clone(),
            MailListingColumn::Subject => self.subject.clone(),
        }
    }

    fn cmp(&self, other: &Self, column: MailListingColumn) -> std::cmp::Ordering
        where Self: Sized
    {
        match column {
            MailListingColumn::Date    => self.date.cmp(&other.date),
            MailListingColumn::Tags    => self.tags.cmp(&other.tags),
            MailListingColumn::From    => self.from.cmp(&other.from),
            MailListingColumn::To      => self.to.cmp(&other.to),
            MailListingColumn::Subject => self.subject.cmp(&other.subject),
        }
    }

}