summaryrefslogtreecommitdiff
path: root/melib/src/addressbook.rs
blob: 42867d08a0418257ac8cfeedd946889a88983967 (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
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
/*
 * meli - addressbook module
 *
 * Copyright 2019 Manos Pitsidianakis
 *
 * This file is part of meli.
 *
 * meli is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * meli 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with meli. If not, see <http://www.gnu.org/licenses/>.
 */

#[cfg(feature = "vcard")]
pub mod vcard;

pub mod mutt;

use crate::datetime::{self, UnixTimestamp};
use crate::parsec::Parser;
use std::collections::HashMap;
use uuid::Uuid;

use std::ops::Deref;

#[derive(Hash, Debug, PartialEq, Eq, Clone, Copy, Deserialize, Serialize)]
#[serde(from = "String")]
#[serde(into = "String")]
pub enum CardId {
    Uuid(Uuid),
    Hash(u64),
}

impl Into<String> for CardId {
    fn into(self) -> String {
        match self {
            CardId::Uuid(u) => u.to_string(),
            CardId::Hash(u) => u.to_string(),
        }
    }
}

impl From<String> for CardId {
    fn from(s: String) -> CardId {
        if let Ok(u) = uuid::Uuid::parse_str(s.as_str()) {
            CardId::Uuid(u)
        } else {
            use std::str::FromStr;
            CardId::Hash(u64::from_str(&s).unwrap())
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct AddressBook {
    display_name: String,
    created: UnixTimestamp,
    last_edited: UnixTimestamp,
    pub cards: HashMap<CardId, Card>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Card {
    id: CardId,
    title: String,
    name: String,
    additionalname: String,
    name_prefix: String,
    name_suffix: String,
    //address
    birthday: Option<UnixTimestamp>,
    email: String,
    url: String,
    key: String,

    color: u8,
    last_edited: UnixTimestamp,
    extra_properties: HashMap<String, String>,

    /// If true, we can't make any changes because we do not manage this resource.
    external_resource: bool,
}

impl AddressBook {
    pub fn new(display_name: String) -> AddressBook {
        AddressBook {
            display_name,
            created: datetime::now(),
            last_edited: datetime::now(),
            cards: HashMap::default(),
        }
    }

    pub fn with_account(s: &crate::conf::AccountSettings) -> AddressBook {
        let mut ret = AddressBook::new(s.name.clone());
        if let Some(mutt_alias_file) = s.extra.get("mutt_alias_file").map(String::as_str) {
            match std::fs::read_to_string(std::path::Path::new(mutt_alias_file))
                .map_err(|err| err.to_string())
                .and_then(|contents| {
                    contents
                        .lines()
                        .map(|line| mutt::parse_mutt_contact().parse(line).map(|(_, c)| c))
                        .collect::<Result<Vec<Card>, &str>>()
                        .map_err(|err| err.to_string())
                }) {
                Ok(cards) => {
                    for c in cards {
                        ret.add_card(c);
                    }
                }
                Err(err) => {
                    crate::log(
                        format!(
                            "Could not load mutt alias file {:?}: {}",
                            mutt_alias_file, err
                        ),
                        crate::WARN,
                    );
                }
            }
        }
        #[cfg(feature = "vcard")]
        if let Some(vcard_path) = s.vcard_folder() {
            match vcard::load_cards(std::path::Path::new(vcard_path)) {
                Ok(cards) => {
                    for c in cards {
                        ret.add_card(c);
                    }
                }
                Err(err) => {
                    crate::log(
                        format!("Could not load vcards from {:?}: {}", vcard_path, err),
                        crate::WARN,
                    );
                }
            }
        }
        ret
    }

    pub fn add_card(&mut self, card: Card) {
        self.cards.insert(card.id, card);
    }
    pub fn remove_card(&mut self, card_id: CardId) {
        self.cards.remove(&card_id);
    }
    pub fn card_exists(&self, card_id: CardId) -> bool {
        self.cards.contains_key(&card_id)
    }
    pub fn search(&self, term: &str) -> Vec<String> {
        self.cards
            .values()
            .filter(|c| c.email.contains(term))
            .map(|c| format!("{} <{}>", &c.name, &c.email))
            .collect()
    }
}

impl Deref for AddressBook {
    type Target = HashMap<CardId, Card>;

    fn deref(&self) -> &HashMap<CardId, Card> {
        &self.cards
    }
}

impl Card {
    pub fn new() -> Card {
        Card {
            id: CardId::Uuid(Uuid::new_v4()),
            title: String::new(),
            name: String::new(),
            additionalname: String::new(),
            name_prefix: String::new(),
            name_suffix: String::new(),
            //address
            birthday: None,
            email: String::new(),
            url: String::new(),
            key: String::new(),

            last_edited: datetime::now(),
            external_resource: false,
            extra_properties: HashMap::default(),
            color: 0,
        }
    }

    pub fn id(&self) -> &CardId {
        &self.id
    }

    pub fn title(&self) -> &str {
        self.title.as_str()
    }
    pub fn name(&self) -> &str {
        self.name.as_str()
    }
    pub fn additionalname(&self) -> &str {
        self.additionalname.as_str()
    }
    pub fn name_prefix(&self) -> &str {
        self.name_prefix.as_str()
    }
    pub fn name_suffix(&self) -> &str {
        self.name_suffix.as_str()
    }
    pub fn email(&self) -> &str {
        self.email.as_str()
    }
    pub fn url(&self) -> &str {
        self.url.as_str()
    }
    pub fn key(&self) -> &str {
        self.key.as_str()
    }
    pub fn last_edited(&self) -> String {
        datetime::timestamp_to_string(self.last_edited, None, false)
    }

    pub fn set_id(&mut self, new_val: CardId) -> &mut Self {
        self.id = new_val;
        self
    }

    pub fn set_title(&mut self, new: String) -> &mut Self {
        self.title = new;
        self
    }

    pub fn set_name(&mut self, new: String) -> &mut Self {
        self.name = new;
        self
    }

    pub fn set_additionalname(&mut self, new: String) -> &mut Self {
        self.additionalname = new;
        self
    }

    pub fn set_name_prefix(&mut self, new: String) -> &mut Self {
        self.name_prefix = new;
        self
    }

    pub fn set_name_suffix(&mut self, new: String) -> &mut Self {
        self.name_suffix = new;
        self
    }

    pub fn set_email(&mut self, new: String) -> &mut Self {
        self.email = new;
        self
    }

    pub fn set_url(&mut self, new: String) -> &mut Self {
        self.url = new;
        self
    }

    pub fn set_key(&mut self, new: String) -> &mut Self {
        self.key = new;
        self
    }

    pub fn set_extra_property(&mut self, key: &str, value: String) -> &mut Self {
        self.extra_properties.insert(key.to_string(), value);
        self
    }

    pub fn extra_property(&self, key: &str) -> Option<&str> {
        self.extra_properties.get(key).map(String::as_str)
    }

    pub fn extra_properties(&self) -> &HashMap<String, String> {
        &self.extra_properties
    }

    pub fn set_external_resource(&mut self, new_val: bool) -> &mut Self {
        self.external_resource = new_val;
        self
    }

    pub fn external_resource(&self) -> bool {
        self.external_resource
    }
}

impl From<HashMap<String, String>> for Card {
    fn from(mut map: HashMap<String, String>) -> Card {
        let mut card = Card::new();
        if let Some(val) = map.remove("TITLE") {
            card.title = val;
        }
        if let Some(val) = map.remove("NAME") {
            card.name = val;
        }
        if let Some(val) = map.remove("ADDITIONAL NAME") {
            card.additionalname = val;
        }
        if let Some(val) = map.remove("NAME PREFIX") {
            card.name_prefix = val;
        }
        if let Some(val) = map.remove("NAME SUFFIX") {
            card.name_suffix = val;
        }

        if let Some(val) = map.remove("E-MAIL") {
            card.email = val;
        }
        if let Some(val) = map.remove("URL") {
            card.url = val;
        }
        if let Some(val) = map.remove("KEY") {
            card.key = val;
        }
        card.extra_properties = map;
        card
    }
}

impl Default for Card {
    fn default() -> Self {
        Self::new()
    }
}