summaryrefslogtreecommitdiffstats
path: root/lib/entry/libimagentryurl/src/iter.rs
blob: f899cb38b2754466b764f03aeefff954c99807e4 (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
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2019 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
//

//! Iterator helpers for external linking stuff
//!
//! Contains also helpers to filter iterators for external/internal links
//!
//!
//! # Warning
//!
//! This module uses `internal::Link` as link type, so we operate on _store ids_ here.
//!
//! Not to confuse with `external::Link` which is a real `FileLockEntry` under the hood.
//!

use libimagentrylink::link::Link;
use libimagentrylink::iter::LinkIter;
use libimagstore::store::Store;

use failure::Fallible as Result;
use failure::ResultExt;
use failure::Error;
use url::Url;

/// Helper for building `OnlyUrlIter` and `NoUrlIter`
///
/// The boolean value defines, how to interpret the `is_external_link_storeid()` return value
/// (here as "pred"):
///
/// ```ignore
///     pred | bool | xor | take?
///     ---- | ---- | --- | ----
///        0 |    0 |   0 |   1
///        0 |    1 |   1 |   0
///        1 |    0 |   1 |   0
///        1 |    1 |   0 |   1
/// ```
///
/// If `bool` says "take if return value is false", we take the element if the `pred` returns
/// false... and so on.
///
/// As we can see, the operator between these two operants is `!(a ^ b)`.
pub struct UrlFilterIter(LinkIter, bool);

impl Iterator for UrlFilterIter {
    type Item = Link;

    fn next(&mut self) -> Option<Self::Item> {
        use crate::util::is_external_link_storeid;

        while let Some(elem) = self.0.next() {
            trace!("Check whether is external: {:?}", elem);
            if !(self.1 ^ is_external_link_storeid(&elem)) {
                trace!("Is external id: {:?}", elem);
                return Some(elem);
            }
        }
        None
    }
}

/// Helper trait to be implemented on `LinkIter` to select or deselect all external links
///
/// # See also
///
/// Also see `OnlyUrlIter` and `NoUrlIter` and the helper traits/functions
/// `OnlyInteralLinks`/`only_links()` and `OnlyUrlLinks`/`only_urls()`.
pub trait SelectUrl {
    fn select_urls(self, b: bool) -> UrlFilterIter;
}

impl SelectUrl for LinkIter {
    fn select_urls(self, b: bool) -> UrlFilterIter {
        UrlFilterIter(self, b)
    }
}


pub struct OnlyUrlIter(UrlFilterIter);

impl OnlyUrlIter {
    pub fn new(li: LinkIter) -> OnlyUrlIter {
        OnlyUrlIter(UrlFilterIter(li, true))
    }

    pub fn urls(self, store: &Store) -> UrlIter<'_> {
        UrlIter(self, store)
    }
}

impl Iterator for OnlyUrlIter {
    type Item = Link;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub struct NoUrlIter(UrlFilterIter);

impl NoUrlIter {
    pub fn new(li: LinkIter) -> NoUrlIter {
        NoUrlIter(UrlFilterIter(li, false))
    }
}

impl Iterator for NoUrlIter {
    type Item = Link;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

pub trait OnlyUrlLinks : Sized {
    fn only_urls(self) -> OnlyUrlIter ;

    fn no_links(self) -> OnlyUrlIter {
        self.only_urls()
    }
}

impl OnlyUrlLinks for LinkIter {
    fn only_urls(self) -> OnlyUrlIter {
        OnlyUrlIter::new(self)
    }
}

pub trait OnlyInternalLinks : Sized {
    fn only_links(self) -> NoUrlIter;

    fn no_urls(self) -> NoUrlIter {
        self.only_links()
    }
}

impl OnlyInternalLinks for LinkIter {
    fn only_links(self) -> NoUrlIter {
        NoUrlIter::new(self)
    }
}

pub struct UrlIter<'a>(OnlyUrlIter, &'a Store);

impl<'a> Iterator for UrlIter<'a> {
    type Item = Result<Url>;

    fn next(&mut self) -> Option<Self::Item> {
        use crate::link::Link;

        loop {
            let next = self.0
                .next()
                .map(|id| {
                    debug!("Retrieving entry for id: '{:?}'", id);
                    self.1
                        .retrieve(id.clone())
                        .with_context(|e| format!("Retrieving entry for id: '{:?}' failed: {}", id, e))
                        .map_err(From::from)
                        .and_then(|f| {
                            debug!("Store::retrieve({:?}) succeeded", id);
                            debug!("getting uri link from file now");
                            f.get_url()
                                .context("Error happened while getting link URI from FLE")
                                .with_context(|e| format!("URL -> Err = {:?}", e))
                                .map_err(Error::from)
                        })
                });

            match next {
                Some(Ok(Some(link))) => return Some(Ok(link)),
                Some(Ok(None))       => continue,
                Some(Err(e))         => return Some(Err(e)),
                None                 => return None
            }
        }
    }

}