~matthiasbeyer/imag

ref: 6bc08b60e6e3a99cc9a263713db33061d63dc964 imag/bin/domain/imag-calendar/src/util.rs -rw-r--r-- 6.5 KiB
6bc08b60Matthias Beyer Merge branch 'update-deps' into master 1 year, 3 months ago
                                                                                                    
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
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::collections::BTreeMap;

use clap::ArgMatches;
use vobject::icalendar::ICalendar;
use vobject::icalendar::Event;
use handlebars::Handlebars;
use anyhow::Result;
use anyhow::Error;
use failure::Fail;

use toml_query::read::TomlValueReadTypeExt;
use chrono::NaiveDateTime;

use libimagrt::runtime::Runtime;
use libimagstore::store::FileLockEntry;
use libimagstore::store::Store;
use libimagentryref::reference::fassade::RefFassade;
use libimagentryref::reference::Ref;
use libimagentryref::reference::Config;
use libimagentryref::hasher::default::DefaultHasher;
use crate::libimagcalendar::store::EventStore;

#[derive(Debug)]
pub struct ParsedEventFLE<'a> {
    inner: FileLockEntry<'a>,
    data: ICalendar,
}

impl<'a> ParsedEventFLE<'a> {

    /// Because libimagcalendar only links to the actual calendar data, we need to read the data and
    /// parse it.
    /// With this function, a FileLockEntry can be parsed to a ParsedEventFileLockEntry
    /// (ParsedEventFLE).
    pub fn parse(fle: FileLockEntry<'a>, refconfig: &Config) -> Result<Self> {
        fle.as_ref_with_hasher::<DefaultHasher>()
            .get_path(refconfig)
            .and_then(|p| ::std::fs::read_to_string(p).map_err(|e| Error::from(e.compat())))
            .and_then(|s| ICalendar::build(&s).map_err(|e| Error::from(e.compat())))
            .map(|cal| ParsedEventFLE {
                inner: fle,
                data: cal,
            })
    }

    pub fn get_entry(&self) -> &FileLockEntry<'a> {
        &self.inner
    }

    pub fn get_data(&self) -> &ICalendar {
        &self.data
    }
}

pub fn get_event_print_format<'rc>(config_value_path: &'static str, rt: &Runtime, scmd: &ArgMatches)
    -> Result<Handlebars<'rc>>
{
    scmd.value_of("format")
        .map(String::from)
        .map(Ok)
        .unwrap_or_else(|| {
            rt.config()
                .ok_or_else(|| anyhow!("No configuration file"))?
                .read_string(config_value_path)?
                .ok_or_else(|| anyhow!("Configuration 'contact.list_format' does not exist"))
        })
        .and_then(|fmt| {
            let mut hb = Handlebars::new();
            hb.register_template_string("format", fmt)?;

            hb.register_escape_fn(::handlebars::no_escape);
            ::libimaginteraction::format::register_all_color_helpers(&mut hb);
            ::libimaginteraction::format::register_all_format_helpers(&mut hb);

            Ok(hb)
        })
}

pub fn build_data_object_for_handlebars<'a>(i: usize, event: &Event<'a>)
    -> BTreeMap<&'static str, String>
{
    macro_rules! process_opt {
        ($t:expr, $text:expr) => {
            ($t).map(|obj| obj.into_raw()).unwrap_or_else(|| String::from($text))
        }
    }

    let mut data = BTreeMap::new();

    data.insert("i"           , format!("{}", i));
    data.insert("dtend"       , process_opt!(event.dtend()       , "<no dtend>"));
    data.insert("dtstart"     , process_opt!(event.dtstart()     , "<no dtstart>"));
    data.insert("dtstamp"     , process_opt!(event.dtstamp()     , "<no dtstamp>"));
    data.insert("uid"         , process_opt!(event.uid()         , "<no uid>"));
    data.insert("description" , process_opt!(event.description() , "<no description>"));
    data.insert("summary"     , process_opt!(event.summary()     , "<no summary>"));
    data.insert("url"         , process_opt!(event.url()         , "<no url>"));
    data.insert("location"    , process_opt!(event.location()    , "<no location>"));
    data.insert("class"       , process_opt!(event.class()       , "<no class>"));
    data.insert("categories"  , process_opt!(event.categories()  , "<no categories>"));
    data.insert("transp"      , process_opt!(event.transp()      , "<no transp>"));
    data.insert("rrule"       , process_opt!(event.rrule()       , "<no rrule>"));

    data
}

pub fn kairos_parse(spec: &str) -> Result<NaiveDateTime> {
    match ::kairos::parser::parse(spec).map_err(|e| Error::from(e.compat()))? {
        ::kairos::parser::Parsed::Iterator(_) => {
            trace!("before-filter spec resulted in iterator");
            Err(anyhow!("Not a moment in time: {}", spec))
        }

        ::kairos::parser::Parsed::TimeType(tt) => {
            trace!("before-filter spec resulted in timetype");
            tt.calculate()
                .map_err(|e| Error::from(e.compat()))?
                .get_moment()
                .cloned()
                .ok_or_else(|| anyhow!("Not a moment in time: {}", spec))
        }
    }
}

pub fn find_event_by_id<'a>(store: &'a Store, id: &str, refconfig: &Config) -> Result<Option<ParsedEventFLE<'a>>> {
    if let Some(entry) = store.get_event_by_uid(id)? {
        debug!("Found directly: {} -> {}", id, entry.get_location());
        return ParsedEventFLE::parse(entry, refconfig).map(Some)
    }

    for sid in store.all_events()? {
        let sid = sid?;

        let event = store.get(sid.clone())?.ok_or_else(|| {
            anyhow!("Cannot get {}, which should be there.", sid)
        })?;

        trace!("Checking whether {} is represented by {}", id, event.get_location());
        let parsed = ParsedEventFLE::parse(event, refconfig)?;

        let found = parsed
            .get_data()
            .events()
            .any(|event| {
                let take = event
                    .as_ref()
                    .map(|e| {
                        trace!("Checking whether {:?} starts with {}", e.uid(), id);
                        e.uid().map(|uid| uid.raw().starts_with(id)).unwrap_or(false)
                    })
                    .unwrap_or(false);

                if take {
                    trace!("Seems to be relevant");
                }

                take
            });

        if found {
            return Ok(Some(parsed))
        }
    }

    Ok(None)
}