summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 3c5fc5ff661ec0042b22c7989e1b335f5767b613 (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
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
use chrono::NaiveDateTime;
use clap::{Parser, Subcommand};
use colored::*;
use railway_provider_hafas::client::HafasClient;
use railway_provider_hafas::profile::db::DbProfile;
use serde::Deserialize;

use serde_json::json;
use traveltext::onboard::{choose_api, OnBoardAPI};
use traveltext::{traits::*, travelynx::*, types::*};

use railway_core::{HyperRustlsRequesterBuilder, IntermediateLocation, JourneysOptions, LocationsOptions, Place, ProductsSelection, Provider};

#[derive(Parser)]
struct Cli {
  #[clap(subcommand)]
  command: Command,
  /// print requests that couldn't be parsed to help debugging
  #[clap(long)]
  debug: bool,
  #[clap(default_value = "https://travelynx.de")]
  baseurl: String,
}

#[derive(Subcommand)]
enum Command {
  /// Get current travelynx status
  Status,
  /// Check in to a train using travelynx
  Checkin {
    from: String,
    to: String,
    // TODO: make this optional and guess which train if not given
    #[clap(flatten)]
    train: TrainRef
  },
  /// (If already checked in) change the trip's destination
  To {
    to: String
  },
  /// (If already checked in) change the trip's starting point,
  /// Warning: may lead to doubled entries in your trip history!
  From {
    from: String
  },
  /// Find a (single) trip of a single train via HAFAS.
  /// Mostly intended to ferry trip-data into travelynx 'by hand' if it doesn't know some connection
  Journey {
    /// starting station's name (fuzzy-matched)
    from_name: String,
    /// destination station's name (fuzzy-matched)
    to_name: String,
    /// departure time; takes the next available connection
    time: Option<NaiveDateTime>,
    /// set the dryRun flag to 'true' when importing to travelynx
    #[clap(short = 'd', long = "dry-run")]
    dry_run: bool,
    /// import the found trip into travelynx (needs the token_import config option!)
    #[clap(short = 'i', long = "import")]
    import: bool
  },
  Arewethereyet,
  /// If iceportal.de is available, ask it which train we're in and
  /// check in
  Autocheckin {
    train: String
  },
  /// Undo the last checkin (if any).
  Undo,
  /// Query a train's on-board API
  Query {
    train: String
  }
}

#[derive(Deserialize)]
struct Config {
  token_status: String,
  token_travel: String,
  token_import: Option<String>
}

#[tokio::main]
async fn main() -> Result<(), ureq::Error> {
  let cli = Cli::parse();

  let traveltext = format!(
    "{}{}el{}{}",
    "tr".cyan(),
    "av".bright_magenta(),
    "te".bright_magenta(),
    "xt".cyan()
  );

  let configpath = {
    let mut path = dirs::config_dir().unwrap();
    path.push("traveltext.toml");
    path
  };

  let config: Config = match std::fs::read_to_string(&configpath) {
    Ok(text) => match toml::from_str(&text) {
      Ok(config) => config,
      Err(err) => exit_err(
        &err.to_string(),
        &format!(
          "failed parsing config file {}",
          configpath.to_string_lossy()
        )
      )
    },
    Err(err) => exit_err(
      &err.to_string(),
      &format!("failed reading config at: {}", configpath.to_string_lossy())
    )
  };

  match cli.command {
    Command::Status => {
      let status: Status = exiting_get_request(
        &format!("{}/api/v1/status/{}", cli.baseurl, config.token_status),
        cli.debug
      );

      println!("{}: {}", traveltext, status);
    }
    Command::Arewethereyet => {
      let status: Status = exiting_get_request(
        &format!("{}/api/v1/status/{}", cli.baseurl, config.token_status),
        cli.debug
      );

      match status.to_station {
        None => println!("{}: Fahrt ins {}", traveltext, "Blaue".blue()),
        Some(to) if status.checked_in => {
          let now = chrono::Utc::now();
          let duration = to.real_arrival().map(|dt| *dt - now);
          match duration {
            Some(d) if d < chrono::Duration::zero() => println!(
              "{}: {}",
              traveltext,
              "we should be there already!".green()
            ),
            Some(d) => println!(
              "{}: we'll be there in {} minutes",
              traveltext,
              d.num_minutes()
            ),
            None => println!("{}: I have no idea", traveltext)
          }
        }
        Some(_to) => {
          println!("{}: {}", traveltext, "you're not checked in".red())
        }
      }
    }
    Command::Checkin { from, to, train } => {
      let resp: Response = exiting_post_request(
        &format!("{}/api/v1/travel", cli.baseurl),
        Action::CheckIn {
          train,
          from_station: from,
          to_station: Some(to),
          comment: None,
          token: format!("{}", config.token_travel)
        },
        cli.debug
      );

      println!("{}: {}", traveltext, resp);
    }
    Command::From { from } => {
      println!(
        "{}: {}",
        traveltext,
        "warning: this command may pollute your trip history".red()
      );
      let status: Status = exiting_get_request(
        &format!("{}/api/v1/status/{}", cli.baseurl, config.token_status),
        cli.debug
      );
      match status.train {
        Some(train) => {
          let resp: Response = exiting_post_request(
            &format!("{}/api/v1/travel", cli.baseurl),
            Action::CheckIn {
              train: train.into(),
              to_station: status.to_station.map(|s| s.ds100).flatten(),
              token: config.token_travel,
              comment: None,
              from_station: from
            },
            cli.debug
          );
          println!("{}: {}", traveltext, resp);
        }
        None => {
          println!("{}: {}", traveltext, "not checked in?".red())
        }
      }
    }
    Command::To { to } => {
      let resp: Response = exiting_post_request(
        &format!("{}/api/v1/travel", cli.baseurl),
        Action::CheckOut {
          to_station: to,
          force: false,
          token: config.token_travel,
          comment: None
        },
        cli.debug
      );
      println!("{}: {}", traveltext, resp);
    }
    Command::Undo => {
      let resp: Response = exiting_post_request(
        &format!("{}/api/v1/travel", cli.baseurl),
        Action::Undo {
          token: config.token_travel.to_owned()
        },
        cli.debug
      );

      println!("{}: {}", traveltext, resp);
    }
    Command::Autocheckin { train } => {
      let onboard = match choose_api(&train).request(cli.debug) {
        Ok(resp) => resp,
        Err(e) => exit_err(&e.to_string(), "failed to parse api response")
      };
      let last_stop = onboard.guess_last_station().unwrap();
      let train = onboard.get_train_ref();
      println!(
        "{}: guessing you got onto {} {} in {}, checking in …",
        traveltext,
        train._type,
        train.no,
        last_stop.to_fancy_string()
      );
      let resp: Response = exiting_post_request(
        &format!("{}/api/v1/travel", cli.baseurl),
        Action::CheckIn {
          train,
          from_station: last_stop.name().to_owned(),
          to_station: None,
          comment: None,
          token: format!("{}", config.token_travel)
        },
        cli.debug
      );

      // eprintln!("{:?}", resp);
      println!("{}: {}", traveltext, resp);
    }
    Command::Query { train } => {
      let api: &dyn OnBoardAPI = choose_api(&train);
      match api.request(cli.debug) {
        Ok(resp) => {
          println!(
            "{}: Currently in {}\n",
            traveltext,
            resp.get_train_ref().to_string().green()
          );
          println!(
            "guessing last stop was: {:?}\n",
            resp.guess_last_station().unwrap().name()
          );
          // println!("Stops:\n{}", resp.stops())
        }
        Err(err) => {
          println!("either this tool or the zugportal broke or you're not actually on an ICE\n\
                              (get a response but couldn't parse it)");
        }
      }
    }
    Command::Journey {
      from_name,
      to_name,
      time,
      dry_run,
      import
    } => {
      let c = HafasClient::new(DbProfile, HyperRustlsRequesterBuilder::default());
      let from = &c
        .locations(LocationsOptions {
          query: from_name,
          results: 0,
          // TODO: respect locale set
          language: Some("de".to_string())
        })
        .await
        .unwrap()[0];

      let to = &c
        .locations(LocationsOptions {
          query: to_name,
          results: 0,
          language: None
        })
        .await
        .unwrap()[0];

      let tz_str = iana_time_zone::get_timezone().unwrap();
      let tz: chrono_tz::Tz = tz_str.parse().unwrap();

      let opts = JourneysOptions {
      products: ProductsSelection::all(),
      departure: time.map(|naive| naive.and_local_timezone(tz).unwrap()), //Some(1650536340);
      stopovers: true,
      language: Some("de".to_string()),
        ..JourneysOptions::default()
      };

      let journey = &c
        .journeys(from.clone(), to.clone(), opts)
        .await
        .unwrap()
        .journeys[0]
        .legs[0];

      let stops = journey.intermediate_locations
        .iter()
        .filter_map(|l| match l { IntermediateLocation::Stop(s) => Some(s), _ => None })
        .collect::<Vec<_>>();

      println!("{}: found this trip:", traveltext);

      for stop in &stops {
        match &stop.place {
          Place::Station(station) => {
            println!("{}", station.name.as_ref().unwrap())
          }
          _ => panic!("this train stops somewhere that's not a station??")
        }
        stop.arrival.map(|t| println!("arr: {:?}", t.to_rfc3339()));
        stop.departure.map(|t| println!("dep: {:?}", t.to_rfc3339()));
      }

      if import {
        let travelynx = json!({
          "token": config.token_import.unwrap(),
          "dryRun": dry_run,
          "fromStation":  match &stops[0].place {
            Place::Station (station) => json!({
              "name":station.name,
              "scheduledTime":stops[0].departure.unwrap().timestamp()
            }),
            _ => panic!("this trip lacks a first station?")
          },
          "toStation": match &stops[stops.len()-1].place {
            Place::Station (station) => json!({
              "name": station.name,
              "scheduledTime": stops[stops.len()-1].arrival.unwrap().timestamp()
            }),
            _ => panic!("this trip lacks an end station?")
          },
          "train": match &journey.line {
            Some(line) => json!({
              "type": line.name.as_ref().unwrap().split_ascii_whitespace().next().unwrap(),
              "line": serde_json::Value::Null,
              "no": line.fahrt_nr.as_ref().unwrap()
            }),
            None => panic!("could not find train information")
          },
          "intermediateStops": &stops[1..stops.len()-1]
            .iter()
            .filter_map(|s| match &s.place {
              Place::Station (station) => station.name.as_ref(),
              _ => None
            })
            .collect::<Vec<&String>>()
        });
        if cli.debug {
            println!("{}", serde_json::to_string(&travelynx).unwrap());
        }
        let resp: serde_json::Value = exiting_post_request(
          &format!("{}/api/v1/import", cli.baseurl),
          travelynx,
          cli.debug
        );

        println!("{:?}", resp);
      }
    }
  }
  Ok(())
}

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 exiting_get_request<R: serde::de::DeserializeOwned>(
  uri: &str,
  debug: bool
) -> R {
  match get_request(uri) {
    Ok(obj) => obj,
    Err((err, resp)) => {
      if debug {
        eprintln!("DEBUG: {}", resp);
      }
      exit_err(&err.to_string(), "parsing response failed")
    }
  }
}

fn exiting_post_request<R, P>(uri: &str, payload: P, debug: bool) -> R
where
  P: serde::Serialize,
  R: serde::de::DeserializeOwned
{
  let resp: String = ureq::post(uri)
    .send_json(payload)
    .unwrap_or_else(|err| exit_err(&err.to_string(), "post request failed"))
    .into_string()
    .unwrap_or_else(|err| {
      exit_err(&err.to_string(), "post request response failed")
    });

  match serde_json::from_str::<R>(&resp) {
    Ok(obj) => obj,
    Err(err) => {
      if debug {
        eprintln!("DEBUG: {}", resp);
      }
      exit_err(&err.to_string(), "parsing response failed")
    }
  }
}

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