summaryrefslogtreecommitdiff
path: root/bin/dbris-m
blob: bf75a29c873aa709dfd5374b227a239dd97c8c79 (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
#!perl
use strict;
use warnings;
use 5.020;

our $VERSION = '0.01';

use utf8;
use DateTime;
use Encode qw(decode);
use JSON;
use Getopt::Long qw(:config no_ignore_case);
use List::Util   qw(max);
use Travel::Status::DE::DBRIS;

my $developer_mode;
my $show_jid;
my $use_cache = 1;
my $cache;
my ( $json_output, $raw_json_output );

my @output;

binmode( STDOUT, ':encoding(utf-8)' );
for my $arg (@ARGV) {
	$arg = decode( 'UTF-8', $arg );
}

my $output_bold  = -t STDOUT ? "\033[1m" : q{};
my $output_reset = -t STDOUT ? "\033[0m" : q{};

GetOptions(
	'h|help'     => sub { show_help(0) },
	'j|with-jid' => \$show_jid,
	'V|version'  => \&show_version,
	'cache!'     => \$use_cache,
	'devmode'    => \$developer_mode,
	'json'       => \$json_output,
	'raw-json'   => \$raw_json_output,

) or show_help(1);

if ($use_cache) {
	my $cache_path = ( $ENV{XDG_CACHE_HOME} // "$ENV{HOME}/.cache" )
	  . '/Travel-Status-DE-DBRIS';
	eval {
		require Cache::File;
		$cache = Cache::File->new(
			cache_root      => $cache_path,
			default_expires => '90 seconds',
			lock_level      => Cache::File::LOCK_LOCAL(),
		);
	};
	if ($@) {
		$cache = undef;
	}
}

my %opt = (
	cache          => $cache,
	station        => shift || show_help(1),
	developer_mode => $developer_mode,
);

if ( $opt{station} =~ m{ ^ (?<lat> [0-9.]+ ) : (?<lon> [0-9].+ ) $ }x ) {
	$opt{geoSearch} = {
		latitude  => $+{lat},
		longitude => $+{lon},
	};
	delete $opt{station};
}
elsif ( $opt{station} =~ m{ ^ [?] (?<query> .*) $ }x ) {
	$opt{locationSearch} = $+{query};
	delete $opt{station};
}
elsif ( $opt{station} =~ m{[|]} ) {
	$opt{journey} = $opt{station};
	delete $opt{station};
}
elsif ( $opt{station} !~ m{ ^ \d+ $ }x ) {
	my $status
	  = Travel::Status::DE::DBRIS->new( locationSearch => $opt{station} );
	for my $result ( $status->results ) {
		if ( defined $result->eva ) {
			$opt{station} = $result;
			last;
		}
	}
}

my $status = Travel::Status::DE::DBRIS->new(%opt);

sub show_help {
	my ($code) = @_;

	print "Usage: db-ris-m <station|lat:lon>\n" . "See also: man dbris-m\n";

	exit $code;
}

sub show_version {
	say "dbris-m version ${VERSION}";

	exit 0;
}

sub spacer {
	my ($len) = @_;
	return ( $len % 2 ? q { } : q{} ) . ( q{ ·} x ( $len / 2 ) );
}

sub display_occupancy {
	my ($occupancy) = @_;

	if ( not $occupancy ) {
		return q{ };
	}
	if ( $occupancy == 1 ) {
		return q{.};
	}
	if ( $occupancy == 2 ) {
		return q{o};
	}
	if ( $occupancy == 3 ) {
		return q{*};
	}
	if ( $occupancy == 4 ) {
		return q{!};
	}
	return q{?};
}

sub format_delay {
	my ( $delay, $len ) = @_;
	if ( $delay and $len ) {
		return sprintf( "(%+${len}d)", $delay );
	}
	return q{};
}

if ( my $err = $status->errstr ) {
	say STDERR "Request error: ${err}";
	exit 2;
}

if ($raw_json_output) {
	say JSON->new->convert_blessed->encode( $status->{raw_json} );
	exit 0;
}

if ($json_output) {
	if ( $opt{journey} ) {
		say JSON->new->convert_blessed->encode( $status->result );
	}
	else {
		say JSON->new->convert_blessed->encode( [ $status->results ] );
	}
	exit 0;
}

if ( $opt{station} ) {
	my $max_line = max map { length( $_->line ) } $status->results;
	my $max_dest
	  = max map { length( $_->destination // q{} ) } $status->results;
	my $max_delay = max map { length( $_->delay // q{} ) } $status->results;
	my $max_platform
	  = max map { length( $_->rt_platform // $_->platform // q{} ) }
	  $status->results;

	$max_delay += 1;

	for my $result ( $status->results ) {
		printf(
			"%s  %s  %${max_line}s  %${max_dest}s  %${max_platform}s\n",
			$result->is_cancelled ? '--:--' : $result->dep->strftime('%H:%M'),
			$result->delay
			? sprintf( "(%+${max_delay}d)", $result->delay )
			: q{ } x ( $max_delay + 2 ),
			$result->line,
			$result->destination // $result->via_last // q{???},
			$result->rt_platform // $result->platform // q{}
		);
		if ($show_jid) {
			say $result->id =~ s{ }{}gr;
		}
		for my $message ( $result->messages ) {
			say $message->{text};
		}
		if ( $show_jid or scalar $result->messages ) {
			say q{};
		}
	}
}
elsif ( $opt{journey} ) {
	my $trip = $status->result;

	my $max_name     = max map { length( $_->name ) } $trip->route;
	my $max_platform = max map { length( $_->platform // q{} ) } $trip->route;

	my $mark_stop = 0;
	my $now       = DateTime->now( time_zone => 'Europe/Berlin' );
	for my $i ( reverse 1 .. ( scalar $trip->route // 0 ) ) {
		my $stop = ( $trip->route )[ $i - 1 ];
		if (
			not $stop->is_cancelled
			and (  $stop->dep and $now <= $stop->dep
				or $stop->arr and $now <= $stop->arr )
		  )
		{
			$mark_stop = $stop;
		}
	}

	printf( "%s am %s\n\n", $trip->train, $trip->day->strftime('%d.%m.%Y') );

	for my $stop ( $trip->route ) {
		if ( $stop == $mark_stop ) {
			print($output_bold);
		}
		if ( $stop->is_cancelled ) {
			print('    --:--    ');
		}
		elsif ( $stop->arr and $stop->dep ) {
			printf( '%s → %s',
				$stop->arr->strftime('%H:%M'),
				$stop->dep->strftime('%H:%M'),
			);
		}
		elsif ( $stop->dep ) {
			printf( '        %s', $stop->dep->strftime('%H:%M') );
		}
		elsif ( $stop->arr ) {
			printf( '%s        ', $stop->arr->strftime('%H:%M') );
		}
		else {
			print('             ');
		}
		printf( "  %-${max_name}s  %${max_platform}s\n",
			$stop->name, $stop->platform // q{} );
		if ( $stop == $mark_stop ) {
			print($output_reset);
		}
	}
	if ( $trip->attributes ) {
		say q{};
	}
	for my $attr ( $trip->attributes ) {
		say $attr->{value};
	}
	if ( $trip->messages ) {
		say q{};
	}
	for my $message ( $trip->messages ) {
		say $message->{text};
	}
}
elsif ( $opt{geoSearch} ) {
	for my $result ( $status->results ) {
		if ( defined $result->eva ) {
			printf( "%8d  %s\n", $result->eva, $result->name );
		}
	}
}
elsif ( $opt{locationSearch} ) {
	for my $result ( $status->results ) {
		if ( defined $result->eva ) {
			printf( "%8d  %s\n", $result->eva, $result->name );
		}
	}
}

__END__

=head1 NAME

dbris-m - Interface to bahn.de / bahnhof.de RIS::*-based departure monitors

=head1 SYNOPSIS

B<dbris-m> I<station>

B<dbris-m> B<?>I<query>|I<lat>B<:>I<lon>

=head1 VERSION

version 0.01

=head1 DESCRIPTION

dbris-m is an interface to the public transport services operated by
Deutsche Bahn on bahn.de and bahnhof.de.

It can serve as an arrival/departure monitor, request details about a specific
trip/journey, and look up public transport stops by name or geolocation.
The operating mode depends on the contents of its non-option argument.

=head2 Departure Monitor (I<station>)

Show departures at I<station>. I<station> may be given as a station name or
station ID.  For each departure, B<dbris-m> shows

=over

=item * estimated departure time,

=item * delay, if known,

=item * trip name, number, or line,

=item * direction / destination, and

=item * platform, if known.

=back

=head2 Location Search (B<?>I<query>|I<lat>B<:>I<lon>)

List stations that match I<query> or that are located in the vicinity of
I<lat>B<:>I<lon> geocoordinates with station ID and name.

=head1 OPTIONS

Values in brackets indicate options that only apply to the corresponding
operating mode(s).

=over

=item B<--json>

Print result(s) as JSON and exit. This is a dump of internal data structures
and not guaranteed to remain stable between minor versions. Please use the
Travel::Status::DE::DBRIS(3pm) module if you need a proper API.

=item B<--no-cache>

If the Cache::File module is available, server replies are cached in
F<~/.cache/Travel-Status-DE-DBRIS> (or a path relative to C<$XDG_CACHE_HOME>,
if set) for 90 seconds. Use this option to disable caching. You can also use
B<--cache> to re-enable it.

=item B<--raw-json>

Print unprocessed API response as JSON and exit.
Useful for debugging and development purposes.

=item B<-V>, B<--version>

Show version information and exit.

=back

=head1 EXIT STATUS

0 upon success, 1 upon internal error, 2 upon backend error.

=head1 CONFIGURATION

None.

=head1 DEPENDENCIES

=over

=item * Class::Accessor(3pm)

=item * DateTime(3pm)

=item * LWP::UserAgent(3pm)

=back

=head1 BUGS AND LIMITATIONS

=over

=item * This module is very much work-in-progress

=item * At the moment, there is no way of getting journey IDs from the
departure monitor, and thus no way to get departure details.

=back

=head1 AUTHOR

Copyright (C) 2024 by Birte Kristina Friesel E<lt>derf@finalrewind.orgE<gt>

=head1 LICENSE

This program is licensed under the same terms as Perl itself.