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
pub mod err {
    pub use failure::{err_msg as msg, Error};
    pub type Result<T> = std::result::Result<T, Error>;
    pub type BoxedFuture<T> = Box<futures::Future<Item = T, Error = Error>>;
}

use futures::{future::Either as EitherFuture, Future, IntoFuture, Stream};
use serde_derive::{Deserialize, Serialize};

pub struct Client {
    inner: reqwest::r#async::Client,
    base_url: url::Url
}

impl Client {
    pub fn new(url: &str) -> err::Result<Self> {
        Ok(Client { inner: reqwest::r#async::Client::new(), base_url: url.parse()? })
    }
}

pub mod pref {

    use serde_json::json;

    pub trait MetadataPrefix: std::fmt::Debug {
        type MetadataType: std::fmt::Debug;

        fn as_str() -> &'static str;
        fn parse_metadata(node: &roxmltree::Node) -> crate::err::Result<Self::MetadataType>;
    }

    #[derive(Debug)]
    pub struct OaiDc;
    #[derive(Debug)]
    pub struct Xoai;

    impl MetadataPrefix for OaiDc {
        type MetadataType = serde_json::Value;

        fn as_str() -> &'static str { "oai_dc" }

        fn parse_metadata(node: &roxmltree::Node) -> crate::err::Result<Self::MetadataType> {
            let mut map = std::collections::HashMap::new();

            for dc_node in node
                .children()
                .filter(|x| x.has_tag_name("dc"))
                .flat_map(|x| x.children())
                .filter(|x| x.is_element())
            {
                map.entry(String::from(dc_node.tag_name().name()))
                    .or_insert_with(Vec::new)
                    .push(json!(dc_node.text()));
            }

            Ok(json!(map))
        }
    }

    impl MetadataPrefix for Xoai {
        type MetadataType = serde_json::Value;

        fn as_str() -> &'static str { "xoai" }

        fn parse_metadata(_node: &roxmltree::Node) -> crate::err::Result<Self::MetadataType> {
            unimplemented!()
        }
    }

}

pub mod record {

    use chrono::prelude::*;

    #[derive(Debug, Clone)]
    pub struct Header {
        pub identifier: String,
        pub datestamp: DateTime<Utc>,
        pub set_spec: Vec<String>
    }

    #[derive(Debug, Clone)]
    pub struct Record<T> {
        pub header: Header,
        pub metadata: T
    }
}

pub mod list_records {

    use futures::{future::Either as EitherFuture, Future, IntoFuture, Stream};
    use serde_derive::{Deserialize, Serialize};

    use chrono::prelude::*;
    use std::marker::PhantomData;

    use crate::{err, ext::NodeExt, pref, record, Client};

    impl<T: pref::MetadataPrefix> ListRecords<T> {
        fn build(text: String) -> err::Result<ListRecords<T>> {
            let doc = roxmltree::Document::parse(&text)?;

            // for child in doc.root().children() {
            //     println!("{:?}", child.tag_name());
            // }

            let root = doc.root_element();

            let response_date = root
                .children()
                .filter(|x| x.has_tag_name("responseDate"))
                .next()
                .and_then(|x| x.text().and_then(|x| x.parse().ok()))
                .ok_or_else(|| err::msg("No response date"))?;

            let list_records = root
                .children()
                .filter(|x| x.has_tag_name("ListRecords"))
                .next()
                .ok_or_else(|| err::msg("No ListRecords node"))?;

            let resumption_token = list_records
                .children()
                .filter(|x| x.has_tag_name("resumptionToken"))
                .next()
                .and_then(|x| {
                    match (
                        x.text(),
                        x.attribute("completeListSize").and_then(|x| x.parse().ok()),
                        x.attribute("cursor").and_then(|x| x.parse().ok())
                    ) {
                        (value, Some(complete_list_size), Some(cursor)) => Some(ResumptionToken {
                            value: value.map(String::from),
                            complete_list_size,
                            cursor
                        }),
                        _ => None
                    }
                });

            let records = list_records
                .children()
                .filter(|x| x.has_tag_name("record"))
                .flat_map(|x| -> err::Result<record::Record<T::MetadataType>> {
                    let header = x.first("header")?;

                    let header = record::Header {
                        identifier: header
                            .first("identifier")?
                            .text()
                            .ok_or_else(|| err::msg("No identifier"))?
                            .into(),
                        datestamp: header
                            .first("datestamp")?
                            .text()
                            .ok_or_else(|| err::msg("No datestamp"))?
                            .parse()?,
                        set_spec: header
                            .children()
                            .filter(|y| y.has_tag_name("setSpec"))
                            .flat_map(|x| x.text().map(String::from))
                            .collect()
                    };

                    let metadata_node = x.first("metadata")?;

                    let metadata = T::parse_metadata(&metadata_node)?;

                    Ok(record::Record { header, metadata })
                })
                .collect();

            Ok(ListRecords { response_date, records, resumption_token, marker: PhantomData })
        }
    }

    #[derive(Debug)]
    pub struct ResumptionToken {
        value: Option<String>,
        complete_list_size: u64,
        cursor: u64
    }

    #[derive(Debug)]
    pub struct ListRecords<T: pref::MetadataPrefix> {
        response_date: DateTime<Utc>,
        records: Vec<record::Record<T::MetadataType>>,
        resumption_token: Option<ResumptionToken>,
        marker: PhantomData<T>
    }

    impl Client {
        pub fn list_records<T: pref::MetadataPrefix>(
            &self
        ) -> impl Future<Item = ListRecords<T>, Error = err::Error> {
            #[derive(Serialize)]
            struct VerbedParams {
                #[serde(rename = "metadataPrefix")]
                metadata_prefix: &'static str,
                verb: &'static str
            }

            let mut url = self.base_url.clone();

            if let Ok(mut path_segments) = url.path_segments_mut() {
                path_segments.pop_if_empty().push("request");
            } else {
                return EitherFuture::B(futures::future::err(err::msg("Cannot set path")));
            }

            let params = VerbedParams { metadata_prefix: T::as_str(), verb: "ListRecords" };

            if let Ok(query) = serde_urlencoded::to_string(&params) {
                url.set_query(Some(&query));
            } else {
                return EitherFuture::B(futures::future::err(err::msg("Cannot set query")));
            }

            let rt = self
                .inner
                .get(url)
                .send()
                .and_then(|mut res| {
                    let body =
                        std::mem::replace(res.body_mut(), reqwest::r#async::Decoder::empty());
                    body.concat2()
                })
                .from_err()
                .and_then(|body| String::from_utf8(body.to_vec()).into_future().from_err())
                .and_then(|text| ListRecords::<T>::build(text).into_future().from_err());

            EitherFuture::A(rt)
        }
    }
}

mod ext {

    use roxmltree::{ExpandedName, Node};

    pub(crate) trait NodeExt<'a, 'd>: Sized {
        fn first<I: Into<ExpandedName<'a>>>(&self, tag_name: I)
            -> crate::err::Result<Node<'a, 'd>>;
    }

    impl<'a, 'd: 'a> NodeExt<'a, 'd> for Node<'a, 'd> {
        fn first<I: Into<ExpandedName<'a>>>(
            &self,
            tag_name: I
        ) -> crate::err::Result<Node<'a, 'd>>
        {
            let tag_name = tag_name.into();
            self.children()
                .filter(|x| x.has_tag_name(tag_name))
                .next()
                .ok_or_else(|| crate::err::msg(format!("No tag named: {:?}", tag_name)))
        }
    }

}