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
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;

mod api;
pub mod errors;
pub mod types;

use errors::OpenstreetmapError;
use quick_xml::de::from_reader;
use quick_xml::se::to_string;
use reqwest::header::CONTENT_TYPE;
use reqwest::StatusCode;
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use url::Url;

pub const DEFAULT_VERSION: &str = "0.6";

#[derive(Debug, Clone)]
pub struct Openstreetmap {
    pub host: String,
    api_version: String,
    credentials: types::Credentials,
    client: reqwest::Client,
}

#[derive(Debug, Clone)]
struct RequestOptions {
    pub use_version: bool,
    pub use_auth: bool,
}

impl RequestOptions {
    pub fn new() -> Self {
        Self {
            use_version: false,
            use_auth: false,
        }
    }
    pub fn with_version(mut self) -> Self {
        self.use_version = true;
        self
    }
    pub fn with_auth(mut self) -> Self {
        self.use_auth = true;
        self
    }
}

impl Openstreetmap {
    pub fn new<T>(host: T, credentials: types::Credentials) -> Self
    where
        T: Into<String>,
    {
        Openstreetmap {
            host: host.into(),
            api_version: DEFAULT_VERSION.into(),
            credentials,
            client: reqwest::Client::new(),
        }
    }

    /// creates a new instance of a Openstreetmap client using a specified reqwest client
    pub fn from_client<H>(host: H, credentials: types::Credentials, client: reqwest::Client) -> Self
    where
        H: Into<String>,
    {
        Openstreetmap {
            host: host.into(),
            api_version: DEFAULT_VERSION.into(),
            credentials,
            client,
        }
    }

    #[inline]
    pub async fn versions(&self) -> Result<Vec<String>, OpenstreetmapError> {
        api::versions::Versions::new(self).get().await
    }

    #[inline]
    pub async fn capabilities(&self) -> Result<types::CapabilitiesAndPolicy, OpenstreetmapError> {
        api::capabilities::Capabilities::new(self).get().await
    }

    #[inline]
    pub async fn map(&self, bbox: &types::BoundingBox) -> Result<types::Map, OpenstreetmapError> {
        api::map::Map::new(self).get(bbox).await
    }

    #[inline]
    pub async fn permissions(&self) -> Result<Vec<types::Permission>, OpenstreetmapError> {
        api::permissions::Permissions::new(self).get().await
    }

    #[inline]
    pub fn changeset(&self) -> api::changeset::Changeset {
        api::changeset::Changeset::new(self)
    }

    #[inline]
    pub fn nodes(&self) -> api::elements::Elements<types::Node> {
        api::elements::Elements::new(self)
    }

    #[inline]
    pub fn ways(&self) -> api::elements::Elements<types::Way> {
        api::elements::Elements::new(self)
    }

    #[inline]
    pub fn relations(&self) -> api::elements::Elements<types::Relation> {
        api::elements::Elements::new(self)
    }

    #[inline]
    pub fn user(&self) -> api::user::User {
        api::user::User::new(self)
    }

    #[inline]
    pub fn notes(&self) -> api::notes::Notes {
        api::notes::Notes::new(self)
    }

    #[inline]
    pub async fn changesets(
        &self,
        query: types::ChangesetQueryParams,
    ) -> Result<Vec<types::Changeset>, OpenstreetmapError> {
        api::changesets::Changesets::new(self).get(query).await
    }

    async fn request<S, D>(
        &self,
        method: reqwest::Method,
        endpoint: &str,
        body: types::RequestBody<S>,
        options: RequestOptions,
    ) -> Result<D, OpenstreetmapError>
    where
        S: Serialize,
        D: DeserializeOwned,
    {
        let mut url = Url::parse(&self.host)?.join("api/")?;

        if options.use_version {
            let version_path = format!("{}/", self.api_version);

            url = url.join(&version_path)?;
        }

        url = url.join(endpoint)?;
        debug!("url -> {:?}", url);

        let mut builder = self.client.request(method, url);

        if options.use_auth {
            builder = match self.credentials {
                types::Credentials::Basic(ref user, ref pass) => {
                    builder.basic_auth(user, Some(pass))
                }
                types::Credentials::None => return Err(OpenstreetmapError::CredentialsNeeded),
            };
        }

        builder = match body {
            types::RequestBody::Xml(payload) => builder
                .body(to_string(&payload)?.into_bytes())
                .header(CONTENT_TYPE, "text/xml"),
            types::RequestBody::Form(payload) => builder.form(&payload),
            types::RequestBody::RawForm(payload) => builder
                .body(payload)
                .header(CONTENT_TYPE, "application/x-www-form-urlencoded"),
            types::RequestBody::None => builder,
        };

        let res = builder.send().await?;

        match res.status() {
            StatusCode::UNAUTHORIZED => Err(OpenstreetmapError::Unauthorized),
            StatusCode::METHOD_NOT_ALLOWED => Err(OpenstreetmapError::MethodNotAllowed),
            StatusCode::NOT_FOUND => Err(OpenstreetmapError::NotFound),
            client_err if client_err.is_client_error() => Err(OpenstreetmapError::Client {
                code: res.status(),
                error: res.text().await?,
            }),
            _ => Ok(from_reader(res.text().await?.as_bytes())?),
        }
    }
}