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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Copyright 2017 Telefónica Germany Next GmbH. See the COPYRIGHT file at
// the top-level directory of this distribution
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use reqwest::{self, header};
use serde::de::DeserializeOwned;
use uuid::Uuid;

use endpoints::GeenyApi;
use errors::*;
use models::*;

/// Interface for Geeny Things Mangager APIs
///
/// `ThingsApi` is an interface for interacting with the Geeny Things Manager API.
/// The full specification of these APIs may be found in the
/// [API Specification](https://labs.geeny.io/things/docs/).
///
/// An explanation of what each of these Geeny items are (e.g. `ThingTypes`,
/// `MessageTypes`) may be found in the
/// [Geeny Glossary](https://confluence.geeny.io/display/EXTDOC/Geeny+ThingTypes+MessageTypes)
#[derive(Debug, Serialize, Deserialize, Clone, Hash)]
pub struct ThingsApi(GeenyApi);

impl Default for ThingsApi {
    /// Create a ThingsApi handle for the Production Things Manager
    ///
    /// # Example
    ///
    /// ```rust
    /// use geeny_api::ThingsApi;
    ///
    /// let api = ThingsApi::default();
    /// ```
    fn default() -> Self {
        Self::new("https://labs.geeny.io".into(), 443)
    }
}

impl ThingsApi {
    /// Create a new Things API handle
    ///
    /// If it is not necessary to set a custom host or port, the `default()`
    /// method may be used instead.
    ///
    /// # Example
    ///
    /// ```rust
    /// use geeny_api::ThingsApi;
    ///
    /// let api = ThingsApi::new("https://labs.geeny.io".into(), 443);
    /// ```
    pub fn new(host: String, port: u16) -> Self {
        ThingsApi(GeenyApi {
            host: host,
            port: port,
        })
    }

    /// Define a new MessageType on the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// use geeny_api::ThingsApi;
    /// use geeny_api::models::*;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     // Define a new MessageType to create
    ///     let mt_request = MessageTypeRequest {
    ///         name: "New MessageType".into(),
    ///         description: "Cool Test Message Type".into(),
    ///         media_type: "application/json".into(),
    ///         tags: vec![
    ///             "IoT".into(),
    ///             "Test".into(),
    ///             "Geeny".into(),
    ///         ],
    ///     };
    ///
    ///     let mt = api.create_message_type(&token, &mt_request).unwrap();
    /// }
    /// ```
    pub fn create_message_type(
        &self,
        token: &str,
        req: &MessageTypeRequest,
    ) -> Result<MessageType> {
        let client = reqwest::Client::new()?;

        let mut resp = client
            .post(&self.0.endpoint("/things/api/v1/messageTypes"))
            .json(req)
            .header(header::Authorization(format!("JWT {}", token)))
            .send()?;

        Ok(resp.json().chain_err(|| "Failed to deserialize")?)
    }

    /// Define a new ThingType on the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// extern crate uuid;
    /// use geeny_api::ThingsApi;
    /// use geeny_api::models::*;
    /// use uuid::Uuid;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     // Define a new ThingType to create
    ///     let tt_request = ThingTypeRequest {
    ///         name: "New ThingType".into(),
    ///         resources: vec![
    ///             Resource {
    ///                 uri: "demo/send/path".into(),
    ///                 method: ResourceMethod::Pub,
    ///                 message_type: Uuid::nil(), // 'id' field from `MessageType` struct
    ///             },
    ///             Resource {
    ///                 uri: "demo/receive/path".into(),
    ///                 method: ResourceMethod::Sub,
    ///                 message_type: Uuid::nil(), // 'id' field from `MessageType` struct
    ///             },
    ///         ],
    ///     };
    ///
    ///     let tt = api.create_thing_type(&token, &tt_request).unwrap();
    /// }
    /// ```
    pub fn create_thing_type(&self, token: &str, req: &ThingTypeRequest) -> Result<ThingType> {
        let client = reqwest::Client::new()?;

        let mut resp = client
            .post(&self.0.endpoint("/things/api/v1/thingTypes"))
            .json(req)
            .header(header::Authorization(format!("JWT {}", token)))
            .send()?;

        Ok(resp.json().chain_err(|| "Failed to deserialize")?)
    }

    /// Create a new instance of a Thing on the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// extern crate uuid;
    /// use geeny_api::ThingsApi;
    /// use geeny_api::models::*;
    /// use uuid::Uuid;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     // Define a new ThingType to create
    ///     let t_request = ThingRequest {
    ///         name: "New Thing".into(),
    ///
    ///         // Serial Number must be unique across all instances of...
    ///         serial_number: "ABCD12345".into(),
    ///
    ///         // ...this thing_type, from the `id` field of `ThingType` struct
    ///         thing_type: Uuid::nil(),
    ///     };
    ///
    ///     let thing = api.create_thing(&token, &t_request).unwrap();
    /// }
    /// ```
    pub fn create_thing(&self, token: &str, req: &ThingRequest) -> Result<Thing> {
        let client = reqwest::Client::new()?;

        let mut resp = client
            .post(&self.0.endpoint("/things/api/v1/things"))
            .json(req)
            .header(header::Authorization(format!("JWT {}", token)))
            .send()?;

        Ok(resp.json().chain_err(|| "Failed to deserialize")?)
    }

    /// Delete a specific Thing from the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// extern crate uuid;
    /// use geeny_api::ThingsApi;
    /// use uuid::Uuid;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     let thing = api.delete_thing(&token, &Uuid::nil()).unwrap();
    /// }
    /// ```
    pub fn delete_thing(&self, token: &str, id: &Uuid) -> Result<Thing> {
        let client = reqwest::Client::new()?;

        let mut resp = client
            .delete(
                &self.0
                    .endpoint(&format!("/things/api/v1/things/{}", id.hyphenated())),
            )
            .header(header::Authorization(format!("JWT {}", token)))
            .send()?;

        Ok(resp.json().chain_err(|| "Failed to deserialize")?)
    }

    /// Get all publicly visible ThingTypes from the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// use geeny_api::ThingsApi;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     let all_thing_types = api.get_thing_types(&token).unwrap();
    ///
    ///     for tt in all_thing_types {
    ///         println!("{:?}", tt);
    ///     }
    /// }
    /// ```
    pub fn get_thing_types(&self, token: &str) -> Result<Vec<ThingType>> {
        get_all(&self.0, token, "/things/api/v1/thingTypes")
    }

    /// Get all publicly visible MessageTypes from the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// use geeny_api::ThingsApi;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     let all_message_types = api.get_message_types(&token).unwrap();
    ///
    ///     for mt in all_message_types {
    ///         println!("{:?}", mt);
    ///     }
    /// }
    /// ```
    pub fn get_message_types(&self, token: &str) -> Result<Vec<MessageType>> {
        get_all(&self.0, token, "/things/api/v1/messageTypes")
    }

    /// Get all Things from the current account from the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// use geeny_api::ThingsApi;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     let all_things = api.get_things(&token).unwrap();
    ///
    ///     for thing in all_things {
    ///         println!("{:?}", thing);
    ///     }
    /// }
    /// ```
    pub fn get_things(&self, token: &str) -> Result<Vec<Thing>> {
        get_all(&self.0, token, "/things/api/v1/things")
    }

    /// Get all Resources for a given ThingType from the Geeny Cloud
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// extern crate uuid;
    /// use geeny_api::ThingsApi;
    /// use uuid::Uuid;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     let resources = api.get_thing_type_resources(
    ///         &token,
    ///         &Uuid::nil() // from `id` field of `ThingType` struct
    ///     ).unwrap();
    ///
    ///     for resource in resources {
    ///         println!("{:?}", resource);
    ///     }
    /// }
    /// ```
    pub fn get_thing_type_resources(&self, token: &str, ttid: &Uuid) -> Result<Vec<Resource>> {
        get_all(
            &self.0,
            token,
            &format!("/things/api/v1/thingTypes/{}/resources", ttid.hyphenated()),
        )
    }

    /// Obtain a specific Thing from the current account from the Geeny Cloud
    /// by the Thing's serial number
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// extern crate geeny_api;
    /// use geeny_api::ThingsApi;
    ///
    /// fn main() {
    ///     let api = ThingsApi::default();
    ///     let token = "...".to_string(); // from ConnectApi
    ///
    ///     let thing = api.get_thing_by_serial(
    ///         &token,
    ///         "ABCD12345"
    ///     ).unwrap();
    /// }
    /// ```
    pub fn get_thing_by_serial(&self, token: &str, serial: &str) -> Result<Option<Thing>> {
        // TODO - filter server side to only get matching devices
        let things = self.get_things(token)?;
        let found = things.iter().find(|i| i.serial_number == serial);

        let thing = match found {
            Some(t) => Some(t.to_owned()),
            None => None,
        };

        Ok(thing)
    }
}

/// Generic method to get all T's from a given endpoint, following a standard
/// "paging" approach
fn get_all<T>(api: &GeenyApi, token: &str, endpoint: &str) -> Result<Vec<T>>
where
    T: DeserializeOwned,
{
    let mut response = vec![];

    loop {
        let url = format!("{}?offset={}", endpoint, response.len());
        let client = reqwest::Client::new()?;

        let mut resp = client
            .get(&api.endpoint(&url))
            .header(header::Authorization(format!("JWT {}", token)))
            .send()?;

        let mut data_resp = resp.json::<GenericResponse<T>>()
            .chain_err(|| "Failed to deserialize")?;

        // Move all of the items from response into retval
        let len = data_resp.data.len();
        response.append(&mut data_resp.data);

        // If the response was not "full", we are done
        if len != data_resp.meta.limit {
            break;
        }
    }

    Ok(response)
}

#[cfg(test)]
mod test {
    use super::*;
    use serde_json;
    use models::*;

    #[test]
    fn serialize_test() {
        let api = ThingsApi::default();
        let s = serde_json::to_string(&api).unwrap();

        assert_eq!(s, "{\"host\":\"https://labs.geeny.io\",\"port\":443}");
    }

    #[test]
    fn deserialize_test() {
        let api = ThingsApi::default();
        let de_api: ThingsApi = serde_json::from_str(
            r#"
            {
                "host": "https://labs.geeny.io",
                "port": 443
            }
        "#,
        ).unwrap();

        assert_eq!(api.0.host, de_api.0.host);
        assert_eq!(api.0.port, de_api.0.port);
    }

    #[ignore]
    #[test]
    fn basic_test() {
        let token = get_token();
        let api = ThingsApi::default();

        assert!(api.get_things(&token).is_ok());
    }

    fn get_token() -> String {
        use std::env;
        use endpoints::connect::ConnectApi;

        let user = env::var("TEST_USER").unwrap();
        let pass = env::var("TEST_PASSWORD").unwrap();

        let api = ConnectApi::default();
        let req = AuthLoginRequest {
            email: user,
            password: pass,
        };

        api.login(&req).unwrap().token
    }
}