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
|
use clap::{Parser, Subcommand};
use colored::*;
use serde::Deserialize;
use traveltext::onboard::{choose_api, OnBoardAPI};
use traveltext::{traits::*, travelynx::*, types::*};
#[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,
/// API token to use in requests
token: Option<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
Destination {
to: String
},
Station {
station: String
},
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
}
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::Destination { 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::Station { station } => {
// let c = HafasClient::new(DbProfile, HyperRustlsRequester::new());
// println!("{:#?}", c.suggestions("München Hbf", None).await.unwrap());
}
}
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)
}
|