summaryrefslogtreecommitdiff
path: root/src/onboard/mod.rs
blob: b6717e818d60e13df8a248c8dc5dcf0e91714915 (plain)
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
use crate::traits::IsStation;
use crate::travelynx::TrainRef;
use crate::types::Trip;
use serde::de::DeserializeOwned;

pub mod iceportal;
pub mod zugportal;

pub fn choose_api(name: &str) -> &dyn OnBoardAPI {
  match name {
    "iceportal" => &iceportal::Iceportal {} as &dyn OnBoardAPI,
    "zugportal" => &zugportal::Zugportal {} as &dyn OnBoardAPI,
    _ => panic!("no such API known")
  }
}

pub trait OnBoardAPI {
  fn apiurl(&self) -> &'static str;

  fn request(
    &self,
    debug: bool
  ) -> Result<Box<dyn OnBoardInfo>, serde_json::Error>;
}

pub fn request<Api, I>(
  api: &Api,
  debug: bool
) -> Result<Box<dyn OnBoardInfo>, serde_json::Error>
where
  Api: OnBoardAPI,
  I: OnBoardInfo + DeserializeOwned + 'static
{
  let url: &'static str = api.apiurl();
  match get_request::<I>(url) {
    Ok(resp) => Ok(Box::new(resp)),
    Err((err, resp)) => {
      if debug {
        eprintln!("{:?}\n\nError was:{:?}", resp, err);
      }
      Err(err)
    }
  }
}

pub trait OnBoardInfo {
  fn guess_last_station(&self) -> Option<&dyn IsStation>;

  fn get_train_ref(&self) -> TrainRef;

  fn stops<'a>(&'a self) -> Trip<'a>;
}

fn get_request<R>(uri: &str) -> Result<R, (serde_json::Error, String)>
where
  R: serde::de::DeserializeOwned
{
  let resp: String = ureq::get(uri)
    .call()
    .unwrap_or_else(|err| exit_err(&err.to_string(), "get request failed"))
    .into_string()
    .unwrap_or_else(|err| {
      exit_err(&err.to_string(), "get request response failed")
    });

  match serde_json::from_str::<R>(&resp) {
    Ok(obj) => Ok(obj),
    Err(err) => Err((err, resp))
  }
}

fn exit_err(msg: &str, scope: &str) -> ! {
  eprintln!("{}: {}", scope, msg);
  std::process::exit(1)
}