rust_flightplan 1.1.1

Loads a flight plan from SimBrief and decodes it.
Documentation
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
////////////////////////////////////////////////////////////////////////////////////////////////////
// MIT License                                                                                     /
//                                                                                                 /
// Copyright (c) 2024 Rust-FlightPlan Team                                                         /
//                                                                                                 /
// Permission is hereby granted, free of charge, to any person obtaining a copy                    /
// of this software and associated documentation files (the "Software"), to deal                   /
// in the Software without restriction, including without limitation the rights                    /
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell                       /
// copies of the Software, and to permit persons to whom the Software is                           /
// furnished to do so, subject to the following conditions:                                        /
//                                                                                                 /
// The above copyright notice and this permission notice shall be included in all                  /
// copies or substantial portions of the Software.                                                 /
//                                                                                                 /
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR                      /
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,                        /
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE                     /
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER                          /
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,                   /
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE                   /
// SOFTWARE.                                                                                       /
////////////////////////////////////////////////////////////////////////////////////////////////////

use std::error::Error;
use std::{fmt, fs};

use crate::types::{GenericOfp, Ofp};
use regex::Regex;

mod converter;

pub mod types;

static SIMBRIEF_URL: &str = "https://www.simbrief.com/api/xml.fetcher.php?";
static JSON_SUFFIX: &str = "&json=1";
static PLACEHOLDER: &str = "---";

/// Loads the OFP from the `SimBrief` API for a given user ID or username.
/// The `user_id` is used when both variables are given.
///
/// # Arguments
///
/// - `User_id`: A `&str` representing the ID of the user.
/// - `User_name`: A `&str` representing the name of the user.
///
/// # Errors
///
/// Returns an `InvalidArgumentError` if neither `user_name` nor `user_id are` set.
///
/// This method fails if there was an error while sending a request,
/// redirect loop was detected, or redirect limit was exhausted.
///
/// This method fails if the response is not encoded in UTF-8 charset.
///
/// # Returns
///
/// Returns a `Result` containing the loaded `Ofp` if successful,
/// or a `Box<dyn Error>` if an error occurs.
pub async fn load_ofp_online(user_id: &str, user_name: &str) -> Result<Ofp, Box<dyn Error>> {
    let url = build_url(user_id, user_name)?;
    let response = reqwest::get(url).await?;
    let mut content = response.text().await?;
    content = sanitize_ofp(&content);
    serde_json::from_str(&content).map_err(Into::into)
}

pub async fn load_generic_ofp_online(
    user_id: &str,
    user_name: &str,
) -> Result<GenericOfp, Box<dyn Error>> {
    let ofp = load_ofp_online(user_id, user_name).await?;
    Ok(extract_generic_ofp(ofp))
}

pub fn extract_generic_ofp(ofp: Ofp) -> GenericOfp {
    let user_id = ofp.params.user_id;
    let time = ofp.params.time_generated;
    let airac = ofp.params.airac;
    let airline_icao = ofp.general.icao_airline;
    let flight_number = ofp.general.flight_number;
    let callsign = if ofp.atc.is_some() {
        ofp.atc.unwrap().callsign
    } else {
        PLACEHOLDER.to_string()
    };
    let costindex = ofp.general.costindex;
    let initial_altitude = ofp.general.initial_altitude;
    let stepclimb = ofp.general.stepclimb_string;
    let route_distance = ofp.general.route_distance;
    let total_burn = ofp.general.total_burn;
    let route = ofp.general.route;
    let origin_icao = ofp.origin.icao_code;
    let origin_name = ofp.origin.name;
    let origin_plan_rwy = ofp.origin.plan_rwy.unwrap_or("---".to_string());
    let origin_procedure = ofp
        .navlog
        .clone()
        .map_or(PLACEHOLDER.to_string(), |navlog| {
            navlog
                .fixes
                .first()
                .map_or(PLACEHOLDER.to_string(), |fix| fix.via_airway.clone())
        });
    let destination_icao = ofp.destination.icao_code;
    let destination_name = ofp.destination.name;
    let destination_plan_rwy = ofp.destination.plan_rwy.unwrap_or("---".to_string());
    let destination_procedure = ofp
        .navlog
        .clone()
        .map_or(PLACEHOLDER.to_string(), |navlog| {
            navlog
                .fixes
                .last()
                .map_or(PLACEHOLDER.to_string(), |fix| fix.via_airway.clone())
        });

    let mut alternates: Vec<String> = Vec::new();
    if ofp.alternates.is_some() {
        for alternate in ofp.alternates.unwrap() {
            alternates.push(alternate.icao_code);
        }
    }
    if ofp.takeoff_altn.is_some() {
        alternates.push(ofp.takeoff_altn.unwrap().icao_code);
    }
    if ofp.enroute_altn.is_some() {
        alternates.push(ofp.enroute_altn.unwrap().icao_code);
    }

    GenericOfp {
        user_id,
        time,
        airac,
        airline_icao,
        flight_number,
        callsign,
        costindex,
        initial_altitude,
        stepclimb,
        route_distance,
        total_burn,
        route,
        origin_icao,
        origin_name,
        origin_plan_rwy,
        origin_procedure,
        destination_icao,
        destination_name,
        destination_plan_rwy,
        destination_procedure,
        alternates,
    }
}

/// Builds a URL for the given user ID and username.
///
/// # Arguments
///
/// * `user_id` – The user ID.
/// * `user_name` – The username.
///
/// # Returns
///
/// If `user_id` is not empty, it returns a `Result` containing the URL with the user ID.
/// If `user_name` is not empty, it returns a `Result` containing the URL with the username.
/// Otherwise, returns an `Err` containing an `InvalidArgumentError`.
///
/// # Errors
///
/// Returns an ` InvalidArgumentError ` if neither `user_name` nor `user_id` are set.
fn build_url(user_id: &str, user_name: &str) -> Result<String, InvalidArgumentError> {
    if !user_id.is_empty() {
        Ok(format!("{SIMBRIEF_URL}userid={user_id}{JSON_SUFFIX}"))
    } else if !user_name.is_empty() {
        Ok(format!("{SIMBRIEF_URL}username={user_name}{JSON_SUFFIX}"))
    } else {
        Err(InvalidArgumentError::new("user_id and user_name are empty"))
    }
}

/// Loads an `Ofp` object from a `SimBrief` JSON file.
///
/// # Arguments
///
/// * `file_path` – The path to the file to load the `Ofp` object from.
///
/// # Returns
///
/// Returns a `Result` containing the loaded `Ofp` object or an error if loading fails.
///
/// # Errors
///
/// From `fs::read_to_string()`:
/// This function will return an error if `file_path` doesn't already exist.
/// Other errors may also be returned according to `OpenOptions::open`.
///
/// If the contents of the file aren't valid UTF-8, then an error will also be returned.
/// While reading from the file,
/// this function handles `io::ErrorKind::Interrupted` with automatic retries.
/// See `io::Read` documentation for details.
///
/// From `serde_json::from_str()`:
/// This conversion can fail
/// if the structure of the input doesn't match the structure expected by `T`,
/// for example, if `T` is a struct type but the input contains something other than a JSON map.
/// It can also fail if the structure is correct, but
/// `T`'s implementation of Deserialize decides that something is wrong with the data.
/// For example, required struct fields are missing from the JSON map,
/// or some number is too big to fit in the expected primitive type.
pub fn load_ofp_from_file(file_path: &str) -> Result<Ofp, Box<dyn Error>> {
    let mut content = fs::read_to_string(file_path)?;
    content = sanitize_ofp(&content);
    let ofp: Ofp = serde_json::from_str(&content)?;
    Ok(ofp)
}

/// Saves an `Ofp` object to a file in JSON format.
///
/// # Arguments
///
/// * `file_path` – The path of the file to save the `Ofp` object to.
/// * `ofp` – The `Ofp` object to be saved.
///
/// # Returns
///
/// * `Result<String, FileSaveError>` – A result indicating success or failure.
/// If successful, the result will contain
///   the string "Ok".
/// If an error occurs during serialization or file writing, a `FileSaveError` will be returned.
///
/// # Errors
///
/// If the serialization fails or the serialized `Ofp` can't be written to disk,
/// a `FileSaveError` will occur.
pub fn save_ofp_to_file(file_path: &str, ofp: &Ofp) -> Result<(), FileSaveError> {
    let result = serde_json::to_string(ofp);
    match result {
        Ok(content) => match fs::write(file_path, content) {
            Ok(()) => Ok(()),
            Err(_) => Err(FileSaveError::new(
                "Could not write the serialized Ofp to the disk. io::Error",
            )),
        },
        Err(_) => Err(FileSaveError::new("Could not serialize the Ofp")),
    }
}

/// Sanitize the input JSON string by applying various regular expressions to format it properly.
///
/// # Arguments
///
/// * `input` – The input JSON string to be sanitized.
///
/// # Returns
///
/// The sanitized JSON string.
fn sanitize_ofp(input: &str) -> String {
    // adds square brackets if only one sigmet is given.
    let regex_sigmet_open = Regex::new(r#""sigmet":\{"#).unwrap();
    let regex_sigmet_close = Regex::new(r#"}},"text""#).unwrap();
    // adds square brackets if only one alternate metar is given.
    let regex_altn_metar_open = Regex::new(r#""altn_metar":""#).unwrap();
    let regex_altn_metar_close = Regex::new(r#"","altn_taf""#).unwrap();
    // adds square brackets if only one alternate taf is given.
    let regex_altn_taf_open = Regex::new(r#""altn_taf":""#).unwrap();
    let regex_altn_taf_close = Regex::new(r#"","toaltn_metar""#).unwrap();
    // adds square brackets if only one alternate is given.
    let regex_altn_open = Regex::new(r#""alternate":\{"#).unwrap();
    let regex_altn_close = Regex::new(r#"},"takeoff_altn""#).unwrap();
    // removes the alternate tag if it is an empty array.
    let regex_altn_empty = Regex::new(r#""alternate":\[\{}],"#).unwrap();
    // removes the atis tag if it is an empty array.
    let regex_atis_empty = Regex::new(r#","atis":\{}"#).unwrap();
    // adds square brackets if only one atis is given.
    let regex_atis_open = Regex::new(r#""atis":\{"#).unwrap();
    let regex_atis_close = Regex::new(r#"},"notam""#).unwrap();
    // removes the notam tag if it is an empty array.
    let regex_notam_empty = Regex::new(r#","notam":\{}"#).unwrap();
    // adds square brackets if only one notam is given.
    let regex_notam_open = Regex::new(r#""notam":\{"#).unwrap();
    let regex_notam_close = Regex::new(r#""notam_is_obstacle":\{}}},"#).unwrap();
    // adds square brackets if only one fir is given.
    let regex_fir_open = Regex::new(r#""fir":\{"#).unwrap();
    let regex_fir_close0 = Regex::new(r#"}}},\{"ident":"#).unwrap();
    let regex_fir_close1 = Regex::new(r#"}}}]},"etops""#).unwrap();
    // adds square brackets if only one fir_altn is given.
    let regex_fir_altn_open = Regex::new(r#""fir_altn":""#).unwrap();
    let regex_fir_altn_close = Regex::new(r#"","fir_etops""#).unwrap();
    // adds square brackets if only one fir_enroute is given.
    let regex_fir_enroute_open = Regex::new(r#""fir_enroute":""#).unwrap();
    let regex_fir_enroute_close = Regex::new(r#""},"aircraft""#).unwrap();
    // adds square brackets if only one string (normally "NONE") is given for dx_rmk.
    let regex_dx_rmk_open = Regex::new(r#""dx_rmk":""#).unwrap();
    let regex_dx_rmk_close = Regex::new(r#"","sys_rmk"#).unwrap();
    // removes empty objects.
    let regex_empty_open = Regex::new(r#""([^"]*)":\{},"#).unwrap();
    let regex_empty_close = Regex::new(r#","([^"]*)":\{}}"#).unwrap();
    // remove ""impacts":{"zfw_minus_1000":{}},"
    let regex_impacts = Regex::new(r#""impacts":\{"zfw_minus_1000":\{}},"#).unwrap();

    // adds square brackets if only one sigmet is given.
    let temp_sigmet_open = regex_sigmet_open.replace_all(input, "\"sigmet\":[{");
    let temp_sigmet_close = regex_sigmet_close.replace_all(&temp_sigmet_open, "}]},\"text\"");
    // adds square brackets if only one alternate metar is given.
    let temp_altn_metar_open =
        regex_altn_metar_open.replace_all(&temp_sigmet_close, "\"altn_metar\":[\"");
    let temp_altn_metar_close =
        regex_altn_metar_close.replace_all(&temp_altn_metar_open, "\"],\"altn_taf\"");
    // adds square brackets if only one alternate taf is given.
    let temp_altn_taf_open =
        regex_altn_taf_open.replace_all(&temp_altn_metar_close, "\"altn_taf\":[\"");
    let temp_altn_taf_close =
        regex_altn_taf_close.replace_all(&temp_altn_taf_open, "\"],\"toaltn_metar\"");
    // adds square brackets if only one alternate is given.
    let temp_altn_open = regex_altn_open.replace_all(&temp_altn_taf_close, "\"alternate\":[{");
    let temp_altn_close = regex_altn_close.replace_all(&temp_altn_open, "}],\"takeoff_altn\"");
    // removes the alternate tag if it is an empty array.
    let temp_altn_empty = regex_altn_empty.replace_all(&temp_altn_close, "");
    // removes the atis tag if it is an empty array.
    let temp_atis_empty = regex_atis_empty.replace_all(&temp_altn_empty, "");
    // adds square brackets if only one atis is given.
    let temp_atis_open = regex_atis_open.replace_all(&temp_atis_empty, "\"atis\":[{");
    let temp_atis_close = regex_atis_close.replace_all(&temp_atis_open, "}],\"notam\"");
    // removes the notam tag if it is an empty array.
    let temp_notam_empty = regex_notam_empty.replace_all(&temp_atis_close, "");
    // adds square brackets if only one notam is given.
    let temp_notam_open = regex_notam_open.replace_all(&temp_notam_empty, "\"notam\":[{");
    let temp_notam_close =
        regex_notam_close.replace_all(&temp_notam_open, "\"notam_is_obstacle\":{}}]},");
    // adds square brackets if only one fir is given.
    let temp_fir_open = regex_fir_open.replace_all(&temp_notam_close, "\"fir\":[{");
    let temp_fir_close0 = regex_fir_close0.replace_all(&temp_fir_open, "}]}},{\"ident\":");
    let temp_fir_close1 = regex_fir_close1.replace_all(&temp_fir_close0, "}]}}]},\"etops\"");
    // adds square brackets if only one fir_altn is given.
    let temp_fir_altn_open = regex_fir_altn_open.replace_all(&temp_fir_close1, "\"fir_altn\":[\"");
    let temp_fir_altn_close =
        regex_fir_altn_close.replace_all(&temp_fir_altn_open, "\"],\"fir_etops\"");
    // adds square brackets if only one fir_enroute is given.
    let temp_fir_enroute_open =
        regex_fir_enroute_open.replace_all(&temp_fir_altn_close, "\"fir_enroute\":[\"");
    let temp_fir_enroute_close =
        regex_fir_enroute_close.replace_all(&temp_fir_enroute_open, "\"]},\"aircraft\"");
    // adds square brackets if only one string (normally "NONE") is given for dx_rmk.
    let temp_dx_rmk_open = regex_dx_rmk_open.replace_all(&temp_fir_enroute_close, "\"dx_rmk\":[\"");
    let temp_dx_rmk_close = regex_dx_rmk_close.replace_all(&temp_dx_rmk_open, "\"],\"sys_rmk");
    // removes empty objects.
    let temp_empty_open = regex_empty_open.replace_all(&temp_dx_rmk_close, "");
    let temp_empty_close = regex_empty_close.replace_all(&temp_empty_open, "}");
    // remove ""impacts":{"zfw_minus_1000":{}},"
    let temp_impacts = regex_impacts.replace_all(&temp_empty_close, "");
    // temp_impacts.into_owned()
    let result = temp_impacts.into_owned(); // for debugging
    let _ = fs::write("res/test/temp.json", result.clone()); // for debugging
    result // for debugging
}

#[derive(Debug)]
pub struct InvalidArgumentError {
    details: String,
}

impl InvalidArgumentError {
    fn new(msg: &str) -> InvalidArgumentError {
        InvalidArgumentError {
            details: msg.to_string(),
        }
    }
}

impl fmt::Display for InvalidArgumentError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.details)
    }
}

impl Error for InvalidArgumentError {
    fn description(&self) -> &str {
        &self.details
    }
}

#[derive(Debug)]
pub struct FileSaveError {
    details: String,
}

impl FileSaveError {
    fn new(msg: &str) -> FileSaveError {
        FileSaveError {
            details: msg.to_string(),
        }
    }
}

impl fmt::Display for FileSaveError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.details)
    }
}

impl Error for FileSaveError {
    fn description(&self) -> &str {
        &self.details
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use chrono::{DateTime, Utc};

    use crate::types::Ofp;
    use crate::{load_ofp_from_file, load_ofp_online, save_ofp_to_file};
    use tokio_macros::test;

    static FILE_PATH_TEST: &str = "res/test/";

    #[test] // only for local testing
    async fn test_load_ofp_online() {
        let result: Result<Ofp, Box<dyn Error>> = load_ofp_online("353738", "").await;
        assert!(result.is_ok());
        let result: Result<Ofp, Box<dyn Error>> = load_ofp_online("", "greluc").await;
        assert!(result.is_ok());
        // println!("--------------------------------");
        // println!("{}", result.err().unwrap());
        // println!("--------------------------------");
    }

    #[test]
    async fn test_load_ofp_from_file_4alternate_takeoff_enroute_etops() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}EDDFKSFO_XML_1720717760.json", FILE_PATH_TEST));
        assert!(result.is_ok());
        let ofp = result.unwrap();
        assert_eq!(353738u32, ofp.fetch.user_id);
        assert_eq!(
            -7i8,
            ofp.alternates
                .unwrap()
                .first()
                .unwrap()
                .avg_wind_comp
                .unwrap()
        );
        assert_eq!(
            DateTime::<Utc>::from_timestamp(1720719600i64, 0)
                .unwrap()
                .to_utc(),
            ofp.times.sched_out
        );
        // println!("--------------------------------");
        // println!("{}", result.err().unwrap());
        // println!("--------------------------------");
    }

    #[test]
    async fn test_load_ofp_from_file_0alternate() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}EDDFEGLL_XML_1720718078.json", FILE_PATH_TEST));
        assert!(result.is_ok());
    }

    #[test]
    async fn test_load_ofp_from_file_1alternate() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}EDDFLGAV_XML_1720718194.json", FILE_PATH_TEST));
        assert!(result.is_ok());
    }

    #[test]
    async fn test_load_ofp_from_file_4alternate_nonavlog() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}EDDKEDDC_XML_1720852477.json", FILE_PATH_TEST));
        assert!(result.is_ok());
    }

    #[test]
    async fn test_load_ofp_from_file_4alternate_nooptional() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}KLASKSFO_XML_1720853074.json", FILE_PATH_TEST));
        assert!(result.is_ok());
    }

    #[test]
    async fn test_fir_altn_multiple() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}LLBGEDDM_XML_1728041926.json", FILE_PATH_TEST));
        assert!(result.is_ok());
        // println!("--------------------------------");
        // println!("{}", result.err().unwrap());
        // println!("--------------------------------");
    }

    #[test]
    async fn test_load_ofp_from_file_new0() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}LOWWLGKR_XML_1721458468.json", FILE_PATH_TEST));
        assert!(result.is_ok());
    }

    #[test]
    async fn test_load_ofp_from_file_atis_not_issued() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}EDDPEDDF_XML_1722018273.json", FILE_PATH_TEST));
        assert!(result.is_ok());
    }

    #[test]
    async fn test_save_ofp_to_file_4alternate_takeoff_enroute_etops() {
        let result: Result<Ofp, Box<dyn Error>> =
            load_ofp_from_file(&format!("{}EDDFKSFO_XML_1720717760.json", FILE_PATH_TEST));
        assert!(result.is_ok());
        let ofp = result.unwrap();
        let result = save_ofp_to_file("res/test/save.json", &ofp);
        assert!(result.is_ok())
    }
}