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
//! Ruby library to access the web api provided by
//! [open-notify.org](http://open-notify.org/).
//!
//! # Supported
//!
//! * Request list of people in space
//! * Request position of the ISS
//!
//! # Open
//!
//! * Request ISS pass times given a location
//!
//! # Example
//! ```
//! match open_notify_api::astros() {
//!     Ok(astros) => {
//!         println!("People in space {}", astros.people().len());
//!         for person in astros.people().iter() {
//!             println!(" - {}, {}", person.name(), person.craft());
//!         }
//!     },
//!     Err(error_msg) => {
//!         eprintln!("Ups: {:?}", error_msg);
//!     }
//! }
//! ```

extern crate reqwest;
extern crate serde;
extern crate serde_json;

#[macro_use]
extern crate serde_derive;

pub mod error;

/// People are contained in a separate type `Person`
/// to add the information in which craft they are in.
#[derive(Deserialize, Serialize, PartialEq)]
pub struct Person {
    name: String,
    craft: String,
}

impl Person {
    pub fn new(name: &str, craft: &str) -> Person {
        Person {
            name: String::from(name),
            craft: String::from(craft),
        }
    }

    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    pub fn craft(&self) -> &str {
        self.craft.as_str()
    }
}

/// Structure containing astronouts in space.
#[derive(Deserialize, Serialize)]
pub struct Astros {
    message: String,
    #[serde(default)]
    reason: String,
    #[serde(default)]
    number: i32,
    #[serde(default)]
    people: Vec<Person>,
}

impl Astros {
    /// Returns a reference to the list of `People`
    /// in space.
    pub fn people(&self) -> &Vec<Person> {
        &self.people
    }
}

#[derive(Default, Deserialize, Serialize)]
struct IssPosition {
    latitude: f32,
    longitude: f32,
}

/// Structure containing the location of the ISS.
#[derive(Deserialize, Serialize)]
pub struct IssNow {
    message: String,
    #[serde(default)]
    reason: String,
    #[serde(default)]
    timestamp: i64,
    #[serde(default)]
    iss_position: IssPosition,
}

impl IssNow {
    /// Returns the time in form of a unix timestamp
    /// when the latitude and longitude information
    /// was captured.
    pub fn timestamp(&self) -> i64 {
        self.timestamp
    }

    /// Latitude of the ISS
    pub fn latitude(&self) -> f32 {
        self.iss_position.latitude
    }

    /// Longitude of the ISS
    pub fn longitude(&self) -> f32 {
        self.iss_position.longitude
    }
}

/// Fetch astronouts currently in space.
pub fn astros() -> Result<Astros, error::OpenNotificationError> {
    astro_from_json(&reqwest::get("http://api.open-notify.org/astros.json")?.text()?)
}

fn astro_from_json(data: &str) -> Result<Astros, error::OpenNotificationError> {
    let astros: Astros = serde_json::from_str(data)?;

    if astros.number as usize != astros.people.len() {
        return Err(error::OpenNotificationError::Data(String::from(
            "attribute 'number' does not match length of people field",
        )));
    }

    if astros.message != "success" {
        return Err(error::OpenNotificationError::Data(astros.reason));
    }

    Ok(astros)
}

/// Fetch current ISS position.
pub fn iss_now() -> Result<IssNow, error::OpenNotificationError> {
    iss_now_from_json(&reqwest::get("http://api.open-notify.org/iss-now.json")?.text()?)
}

fn iss_now_from_json(data: &str) -> Result<IssNow, error::OpenNotificationError> {
    let iss_now: IssNow = serde_json::from_str(data)?;

    if iss_now.message != "success" {
        return Err(error::OpenNotificationError::Data(iss_now.reason));
    }

    Ok(iss_now)
}

#[derive(Default, Deserialize, Serialize)]
struct IssPassTimesRequest {
    latitude: f32,
    longitude: f32,
    altitude: f32,
    passes: u32,
    datetime: i64,
}

#[derive(Deserialize, Serialize)]
pub struct IssPassTime {
    risetime: i64,
    duration: i64,
}

impl IssPassTime {
    pub fn rise(&self) -> i64 {
        self.risetime
    }

    pub fn duration(&self) -> i64 {
        self.duration
    }
}

/// Structure containing the location of the ISS.
#[derive(Deserialize, Serialize)]
pub struct IssPassTimes {
    message: String,
    #[serde(default)]
    reason: String,
    #[serde(default)]
    request: IssPassTimesRequest,
    #[serde(default)]
    response: Vec<IssPassTime>,
}

impl IssPassTimes {
    pub fn passes(&self) -> &[IssPassTime] {
        &self.response
    }
}

/// Request ISS pass times over a specified location
///
/// # Parameters
/// * `lat` -80 to 80 in degrees
/// * `lon` -180 to 180 in degrees
/// * `alt` 0 to 10000 in meters
/// * `n` 1 to 100; How many passes shall be included in the result.
///
/// # Example
/// ```rust
/// use open_notify_api as ona;
/// if let Ok(reply) = ona::iss_pass_times(52.5, 13.4, 10.0, 5) {
///     assert_eq!(reply.passes().len(), 5);
/// }
/// ```
pub fn iss_pass_times(
    lat: f32,
    lon: f32,
    alt: f32,
    n: u32,
) -> Result<IssPassTimes, error::OpenNotificationError> {
    iss_pass_times_from_json(&reqwest::get(
        format!(
            "http://api.open-notify.org/iss-pass.json?lat={}&lon={}&alt={}&n={}",
            lat, lon, alt, n,
        ).as_str(),
    )?.text()?)
}

fn iss_pass_times_from_json(data: &str) -> Result<IssPassTimes, error::OpenNotificationError> {
    let iss_pass_times: IssPassTimes = serde_json::from_str(data)?;

    if iss_pass_times.message != "success" {
        return Err(error::OpenNotificationError::Data(iss_pass_times.reason));
    }

    Ok(iss_pass_times)
}

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

    #[test]
    fn astro_parse_successful_data() {
        let input_data = r#"{
            "message": "success",
            "number": 6,
            "people": [
            {"name": "Anton Shkaplerov", "craft": "ISS"},
            {"name": "Scott Tingle", "craft": "ISS"},
            {"name": "Norishige Kanai", "craft": "ISS"},
            {"name": "Oleg Artemyev", "craft": "Soyuz MS-08"},
            {"name": "Andrew Feustel", "craft": "Soyuz MS-08"},
            {"name": "Richard Arnold", "craft": "Soyuz MS-08"}]
            }"#;

        let expected_people = vec![
            Person::new("Anton Shkaplerov", "ISS"),
            Person::new("Scott Tingle", "ISS"),
            Person::new("Norishige Kanai", "ISS"),
            Person::new("Oleg Artemyev", "Soyuz MS-08"),
            Person::new("Andrew Feustel", "Soyuz MS-08"),
            Person::new("Richard Arnold", "Soyuz MS-08"),
        ];

        if let Ok(astros) = astro_from_json(input_data) {
            assert_eq!(astros.people().len(), 6);
            for person in expected_people.iter() {
                assert!(astros.people().contains(&person));
            }
        } else {
            assert!(false);
        }
    }

    #[test]
    fn astro_parse_missing_data() {
        let input_data = r#"{
            "message": "success",
            "number": 6,
            "people": [
            {"name": "Anton Shkaplerov", "craft": "ISS"},
            {"name": "Scott Tingle", "craft": "ISS"},
            {"name": "Norishige Kanai", "craft": "ISS"},
            {"name": "Oleg Artemyev" },
            {"name": "Andrew Feustel", "craft": "Soyuz MS-08"},
            {"name": "Richard Arnold", "craft": "Soyuz MS-08"}]
            }"#;

        match astro_from_json(input_data) {
            Err(error::OpenNotificationError::Parsing(_)) => assert!(true),
            Err(_) => assert!(false),
            Ok(_) => assert!(false),
        }
    }

    #[test]
    fn astro_parse_inconsistent_data() {
        let input_data = r#"{
            "message": "success",
            "number": 5,
            "people": [
            {"name": "Anton Shkaplerov", "craft": "ISS"},
            {"name": "Scott Tingle", "craft": "ISS"},
            {"name": "Norishige Kanai", "craft": "ISS"},
            {"name": "Oleg Artemyev", "craft": "Soyuz MS-08"},
            {"name": "Andrew Feustel", "craft": "Soyuz MS-08"},
            {"name": "Richard Arnold", "craft": "Soyuz MS-08"}]
            }"#;

        match astro_from_json(input_data) {
            Err(error::OpenNotificationError::Data(_)) => assert!(true),
            Err(_) => assert!(false),
            Ok(_) => assert!(false),
        }
    }

    #[test]
    fn astro_parse_unsuccessfull_data() {
        let input_data = r#"{
            "message": "failure",
            "reason": "something went wrong"
            }"#;

        use error::OpenNotificationError::Data;
        match astro_from_json(input_data) {
            Err(Data(msg)) => assert_eq!(msg, "something went wrong"),
            Err(_) => assert!(false),
            Ok(_) => assert!(false),
        }
    }

    #[test]
    fn iss_now_parse_successful_data() {
        let input_data = r#"{
            "iss_position": {"longitude": 73.5964, "latitude": -34.6445},
            "message": "success",
            "timestamp": 1521971230}"#;
        if let Ok(iss_now) = iss_now_from_json(input_data) {
            assert_eq!(iss_now.timestamp(), 1521971230);
            assert_eq!(iss_now.latitude(), -34.6445);
            assert_eq!(iss_now.longitude(), 73.5964);
        } else {
            assert!(false);
        }
    }

    #[test]
    fn iss_now_parse_unsuccessfull_data() {
        let input_data = r#"{
            "message": "failure",
            "reason": "something went wrong"
            }"#;

        use error::OpenNotificationError::Data;
        match iss_now_from_json(input_data) {
            Err(Data(msg)) => assert_eq!(msg, "something went wrong"),
            Err(_) => assert!(false),
            Ok(_) => assert!(false),
        }
    }
}