summaryrefslogtreecommitdiffstats
path: root/src/views/maillist.rs
blob: 303efe6b2d8bad4cbfa38cf2351e540054e38257 (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
use std::path::PathBuf;
use std::rc::Rc;

use anyhow::Context;
use anyhow::Result;
use chrono::naive::NaiveDateTime;
use cursive::Cursive;
use cursive::view::SizeConstraint;
use cursive::views::ResizedView;
use cursive_table_view::TableView;
use cursive_table_view::TableViewItem;
use getset::Getters;
use notmuch::Message;
use notmuch::MessageOwner;

use crate::views::mail::MailView;
use crate::runtime::Runtime;

pub struct MaillistView {
    rt: Rc<Runtime>,
    view: ResizedView<TableView<MailListingData, MailListingColumn>>,
}

impl MaillistView {
    pub fn for_query(rt: Rc<Runtime>, query: &str) -> Result<impl cursive::view::View> {
        debug!("Getting '{}' from '{}'", query, rt.config().notmuch_database_path().display());

        fn get_header_field_save<'o, O: MessageOwner + 'o>(msg: &Message<'o, O>, field: &str) -> String {
            match msg.header(field) {
                Err(e) => {
                    error!("Failed getting '{}' of '{}': {}", field, msg.id(), e);
                    String::from("---")
                },

                Ok(None) => format!("No Value for {}", field),
                Ok(Some(f)) => f.to_string(),
            }
        }

        let items = rt.database()
            .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 filename = msg.filename();
                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    = get_header_field_save(&msg, "From");
                let to      = get_header_field_save(&msg, "To");
                let subject = get_header_field_save(&msg, "Subject");

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

        debug!("Found {} entries", items.len());
        let mailviewrt = rt.clone();
        let view = 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| {
                    debug!("Submit: row = {}", row);
                    let (mail_id, filename) = siv.call_on_name(crate::views::main::MAIN_VIEW_NAME, move |main: &mut crate::views::main::MainView| {
                        debug!("Got main view.");
                        main.get_current_mux()
                            .map(|mux| {
                                debug!("Got mux view.");
                                if let Some(ml) = mux.downcast_ref::<MaillistView>() {
                                    debug!("Got table, finding item now.");
                                    ml.view
                                        .get_inner()
                                        .borrow_item(row)
                                        .map(|data| {
                                            debug!("Found item: {:?}", data);
                                            (data.mail_id.clone(), data.filename.clone())
                                        })
                                } else {
                                    debug!("Did not find table.");
                                    unimplemented!()
                                }
                            })
                    })
                    .unwrap()
                    .unwrap()
                    .unwrap();

                    debug!("Showing mail {}", mail_id);
                    let mv = MailView::create_for(mailviewrt.clone(), mail_id, filename).unwrap();

                    siv.call_on_name(crate::views::main::MAIN_VIEW_NAME , move |main: &mut crate::views::main::MainView| {
                        main.get_current_tab_mut()
                            .map(|tab: &mut crate::tabs::Tab| {
                                let foc = tab.mux().focus();
                                tab.mux_mut().add_right_of(mv, foc);
                            })
                    });

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

        Ok({
            MaillistView {
                rt,
                view: ResizedView::new(SizeConstraint::Full, SizeConstraint::Full, view)
            }
        })
    }
}

impl cursive::view::ViewWrapper for MaillistView {
    type V = ResizedView<TableView<MailListingData, MailListingColumn>>;

    fn with_view<F, R>(&self, f: F) -> Option<R>
        where F: FnOnce(&Self::V) -> R
    {
        Some(f(&self.view))
    }

    fn with_view_mut<F, R>(&mut self, f: F) -> Option<R>
        where F: FnOnce(&mut Self::V) -> R
    {
        Some(f(&mut self.view))
    }
}

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

#[derive(Clone, Debug, Getters)]
pub struct MailListingData {
    #[getset(get = "pub")]
    mail_id: String,

    #[getset(get = "pub")]
    filename: PathBuf,

    #[getset(get = "pub")]
    tags: Vec<String>,

    #[getset(get = "pub")]
    date: String,

    #[getset(get = "pub")]
    from: String,

    #[getset(get = "pub")]
    to: String,

    #[getset(get = "pub")]
    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),
        }
    }

}