DBRIS.pm untested

filter: Statementstmt 0.0% 0 / 261 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 40 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 467 CC 54 SCAR 52.3
CC
54
Cov
0%
new
342.0
get_with_cache_p
306.0
get_with_cache
210.0
CRAP 186.5
1 package Travel::Status::DE::DBRIS;
2  
3 # vim:foldmethod=marker
4  
5 use strict;
6 use warnings;
7 use 5.020;
8 use utf8;
9  
10 use Carp qw(confess);
11 use DateTime;
12 use DateTime::Format::Strptime;
13 use Encode qw(decode encode);
14 use IO::Uncompress::Brotli;
15 use JSON;
16 use LWP::UserAgent;
17 use UUID qw(uuid4);
18  
19 use Travel::Status::DE::DBRIS::Formation;
20 use Travel::Status::DE::DBRIS::JourneyAtStop;
21 use Travel::Status::DE::DBRIS::Journey;
22 use Travel::Status::DE::DBRIS::Location;
23  
24 our $VERSION = '0.39';
25  
26 # bahn.de employs Akamai BMP, whose fingerprinting includes the advertised
27 # TLS options. So we gotta work around that, too.
28 my %tls_options = (
29 SSL_ciphersuites => 'TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256',
30 );
31  
32 # {{{ Constructors
33  
34 sub new {
35 my ( $obj, %conf ) = @_;
36  
37 my $ua = $conf{user_agent};
38  
39 if ( not $ua ) {
40 my %lwp_options = %{ $conf{lwp_options} // { timeout => 20 } };
41 while ( my ( $k, $v ) = each %tls_options ) {
42 $lwp_options{ssl_opts}{$k} = $v;
43 }
44 $ua = LWP::UserAgent->new(%lwp_options);
45 $ua->env_proxy;
46 }
47  
48 my @ua_base = (
49 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.XXXX.YYY Mobile Safari/539.36',
50 'Mozilla/5.0 (Linux; Android 16; SM-S928B/DS) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.XXXX.YYY Mobile Safari/538.35',
51 'Mozilla/5.0 (Linux; Android 15; Pixel 9 Pro Build/AD1A.250418.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/133.0.XXXX.YYY Mobile Safari/537.29',
52 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.XXXX.YYY Mobile Safari/538.34',
53 'Mozilla/5.0 (Linux; Android 16; moto g - 2025 Build/V1VK35.22-13-2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/133.0.XXXX.YYY Mobile Safari/537.31',
54 'Mozilla/5.0 (X11; CrOS x86_64 14542.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.XXXX.YYY Safari/538.32',
55 );
56  
57 my $rand1 = int( rand(1000) );
58 my $rand2 = int( rand(100) );
59 my $ua_str = $ua_base[ int( rand(@ua_base) ) ] =~ s{XXXX}{$rand1}r
60 =~ s{YYY}{$rand2}r;
61  
62 my $self = {
63 cache => $conf{cache},
64 failure_cache => $conf{failure_cache},
65 developer_mode => $conf{developer_mode},
66 messages => [],
67 results => [],
68 station => $conf{station},
69 ua => $ua,
70 header => {
71 'accept' => 'application/json',
72 'accept-encoding' => 'gzip, br',
73 'content-type' => 'application/json; charset=utf-8',
74 'Origin' => 'https://www.bahn.de',
75 'Referer' => 'https://www.bahn.de/buchung/fahrplan/suche',
76 'User-Agent' => $ua_str,
77 'x-correlation-id' => uuid4() . '_' . uuid4(),
78 },
79 };
80  
81 bless( $self, $obj );
82  
83 my $req;
84  
85 if ( my $station = $conf{station} ) {
86 my $dt = $conf{datetime}
87 // DateTime->now( time_zone => 'Europe/Berlin' );
88 my @mots
89 = (
90 qw(ICE EC_IC IR REGIONAL SBAHN BUS SCHIFF UBAHN TRAM ANRUFPFLICHTIG)
91 );
92 if ( $conf{modes_of_transit} ) {
93 @mots = @{ $conf{modes_of_transit} // [] };
94 }
95  
96 # arr → /ankuenfte
97 $req
98 = 'https://www.bahn.de/web/api/reiseloesung/abfahrten'
99 . '?datum='
100 . $dt->strftime('%Y-%m-%d')
101 . '&zeit='
102 . $dt->strftime('%H:%M:00')
103 . '&ortExtId='
104 . $station->{eva}
105 . '&ortId='
106 . $station->{id}
107 . '&mitVias=true&maxVias='
108 . ( $conf{num_vias} // 5 );
109 for my $mot (@mots) {
110 $req .= '&verkehrsmittel[]=' . $mot;
111 }
112 }
113 elsif ( my $gs = $conf{geoSearch} ) {
114 my $lat = $gs->{latitude};
115 my $lon = $gs->{longitude};
116 $req
117 = "https://www.bahn.de/web/api/reiseloesung/orte/nearby?lat=${lat}&long=${lon}&radius=9999&maxNo=100";
118 }
119 elsif ( my $query = $conf{locationSearch} ) {
120 $req
121 = "https://www.bahn.de/web/api/reiseloesung/orte?suchbegriff=${query}&typ=ALL&limit=10";
122 }
123 elsif ( my $journey_id = $conf{journey} ) {
124 my $poly = $conf{with_polyline} ? 'true' : 'false';
125 $journey_id =~ s{[#]}{%23}g;
126 $req
127 = "https://www.bahn.de/web/api/reiseloesung/fahrt?journeyId=${journey_id}&poly=${poly}";
128 }
129 elsif ( my $cf = $conf{formation} ) {
130 my $datetime = $cf->{departure}->clone->set_time_zone('UTC');
131 my $date = $datetime->strftime('%Y-%m-%d');
132 my $time = $datetime->rfc3339 =~ s{(?=Z)}{.000}r;
133 my %param = (
134 administrationId => 80,
135 category => $cf->{train_type},
136 date => $date,
137 evaNumber => $cf->{eva},
138 number => $cf->{train_number},
139 time => $time
140 );
141 $req
142 = 'https://www.bahn.de/web/api/reisebegleitung/wagenreihung/vehicle-sequence?'
143 . join( '&', map { $_ . '=' . $param{$_} } sort keys %param );
144 }
145 else {
146 confess(
147 'station / formation / geoSearch / locationSearch / journey must be specified'
148 );
149 }
150  
151 $self->{strptime_obj} //= DateTime::Format::Strptime->new(
152 pattern => '%Y-%m-%dT%H:%M:%S',
153 time_zone => 'Europe/Berlin',
154 );
155  
156 $self->{strpdate_obj} //= DateTime::Format::Strptime->new(
157 pattern => '%Y-%m-%d',
158 time_zone => 'Europe/Berlin',
159 );
160  
161 my $json = $self->{json} = JSON->new->utf8;
162  
163 if ( $conf{async} ) {
164 $self->{req} = $req;
165 return $self;
166 }
167  
168 if ( $conf{json} ) {
169 $self->{raw_json} = $conf{json};
170 }
171 else {
172 if ( $self->{developer_mode} ) {
173 say "requesting $req";
174 }
175  
176 while ( my ( $key, $value ) = each %{ $self->{header} } ) {
177 $ua->default_header( $key => $value );
178 }
179  
180 my ( $content, $error ) = $self->get_with_cache($req);
181  
182 if ($error) {
183 $self->{errstr} = $error;
184 return $self;
185 }
186  
187 if ( $self->{developer_mode} ) {
188 say decode( 'utf-8', $content );
189 }
190  
191 $self->{raw_json} = $json->decode($content);
192 }
193  
194 if ( $conf{station} ) {
195 $self->parse_stationboard;
196 }
197 elsif ( $conf{journey} ) {
198 $self->parse_journey( id => $conf{journey} );
199 }
200 elsif ( $conf{geoSearch} or $conf{locationSearch} ) {
201 $self->parse_search;
202 }
203 elsif ( $conf{formation} ) {
204 $self->parse_formation( $conf{formation} );
205 }
206  
207 return $self;
208 }
209  
210 sub new_p {
211 my ( $obj, %conf ) = @_;
212 my $promise = $conf{promise}->new;
213  
214 if (
215 not( $conf{station}
216 or $conf{formation}
217 or $conf{geoSearch}
218 or $conf{locationSearch}
219 or $conf{journey} )
220 )
221 {
222 return $promise->reject(
223 'station / geoSearch / locationSearch / journey flag must be passed'
224 );
225 }
226  
227 if ( $conf{user_agent}->can('tls_options') ) {
228 $conf{user_agent}->tls_options( \%tls_options );
229 }
230  
231 my $self = $obj->new( %conf, async => 1 );
232 $self->{promise} = $conf{promise};
233  
234 $self->get_with_cache_p( $self->{req} )->then(
235 sub {
236 my ($content) = @_;
237 $self->{raw_json} = $self->{json}->decode($content);
238  
239 if ( $conf{station} ) {
240 $self->parse_stationboard;
241 }
242 elsif ( $conf{journey} ) {
243 $self->parse_journey( id => $conf{journey} );
244 }
245 elsif ( $conf{geoSearch} or $conf{locationSearch} ) {
246 $self->parse_search;
247 }
248 elsif ( $conf{formation} ) {
249 $self->parse_formation( $conf{formation} );
250 }
251  
252 if ( $self->errstr ) {
253 $promise->reject( $self->errstr, $self );
254 }
255 else {
256 $promise->resolve($self);
257 }
258 return;
259 }
260 )->catch(
261 sub {
262 my ($err) = @_;
263 $promise->reject($err);
264 return;
265 }
266 )->wait;
267  
268 return $promise;
269 }
270  
271 # }}}
272 # {{{ Internal Helpers
273  
274 sub get_with_cache {
275 my ( $self, $url ) = @_;
276 my $cache = $self->{cache};
277 my $failure_cache = $self->{failure_cache};
278  
279 if ( $self->{developer_mode} ) {
280 say "GET $url";
281 }
282  
283 if ($failure_cache) {
284 if ( my $content = $cache->thaw($url) ) {
285 if ( ${$content} =~ s{ ^ n : }{}x ) {
286 if ( $self->{developer_mode} ) {
287 say " cached failure: ${$content}";
288 }
289 return ( undef, ${$content} );
290 }
291 }
292 }
293  
294 if ($cache) {
295 if ( my $content = $cache->thaw($url) ) {
296 if ( $self->{developer_mode} ) {
297 say ' cache hit';
298 }
299 return ( ${$content}, undef );
300 }
301 }
302  
303 if ( $self->{developer_mode} ) {
304 say ' cache miss';
305 }
306  
307 my $reply = $self->{ua}->get($url);
308  
309 if ( $reply->is_error ) {
310 if ( $self->{developer_mode} ) {
311 say ' request failed: ' . $reply->status_line;
312 }
313 if ($failure_cache) {
314 my $err = 'n:' . $reply->status_line;
315 $failure_cache->freeze( $url, \$err );
316 }
317 return ( undef, $reply->status_line );
318 }
319 my $content = $reply->decoded_content;
320  
321 if ($cache) {
322 $cache->freeze( $url, \$content );
323 }
324  
325 return ( $content, undef );
326 }
327  
328 sub get_with_cache_p {
329 my ( $self, $url ) = @_;
330 my $cache = $self->{cache};
331 my $failure_cache = $self->{failure_cache};
332  
333 if ( $self->{developer_mode} ) {
334 say "GET $url";
335 }
336  
337 my $promise = $self->{promise}->new;
338  
339 if ($failure_cache) {
340 if ( my $content = $cache->thaw($url) ) {
341 if ( ${$content} =~ s{ ^ n : }{}x ) {
342 if ( $self->{developer_mode} ) {
343 say " cached failure: ${$content}";
344 }
345 return $promise->reject( ${$content} );
346 }
347 }
348 }
349  
350 if ($cache) {
351 my $content = $cache->thaw($url);
352 if ($content) {
353 if ( $self->{developer_mode} ) {
354 say ' cache hit';
355 }
356 return $promise->resolve( ${$content} );
357 }
358 }
359  
360 if ( $self->{developer_mode} ) {
361 say ' cache miss';
362 }
363  
364 $self->{ua}->get_p( $url => $self->{header} )->then(
365 sub {
366 my ($tx) = @_;
367 if ( my $err = $tx->error ) {
368 if ( $self->{developer_mode} ) {
369 say " request failed: $err";
370 }
371 if ($failure_cache) {
372 my $cached_err = 'n:' . $err;
373 $failure_cache->freeze( $url, \$cached_err );
374 }
375 $promise->reject(
376 "GET $url returned HTTP $err->{code} $err->{message}");
377 return;
378 }
379 my $content = $tx->res->body;
380  
381 if ( $tx->res->headers->content_encoding
382 && $tx->res->headers->content_encoding eq 'br' )
383 {
384 # size (1_000_000) is optional in recent Brotli versions,
385 # but not yet in the one shipped with Debian 13.
386 $content = IO::Uncompress::Brotli::unbro(
387 $tx->res->content->asset->slurp, 1_000_000 );
388 }
389  
390 if ($cache) {
391 $cache->freeze( $url, \$content );
392 }
393 $promise->resolve($content);
394 return;
395 }
396 )->catch(
397 sub {
398 my ($err) = @_;
399 if ( $self->{developer_mode} ) {
400 say " request failed: ${err}";
401 }
402 if ($failure_cache) {
403 my $cached_err = 'n:' . $err;
404 $failure_cache->freeze( $url, \$cached_err );
405 }
406 $promise->reject($err);
407 return;
408 }
409 )->wait;
410  
411 return $promise;
412 }
413  
414 sub parse_journey {
415 my ( $self, %opt ) = @_;
416  
417 $self->{result} = Travel::Status::DE::DBRIS::Journey->new(
418 id => $opt{id},
419 json => $self->{raw_json},
420 strpdate_obj => $self->{strpdate_obj},
421 strptime_obj => $self->{strptime_obj},
422 );
423 }
424  
425 sub parse_search {
426 my ($self) = @_;
427  
428 @{ $self->{results} }
429 = map { Travel::Status::DE::DBRIS::Location->new( json => $_ ) }
430 @{ $self->{raw_json} // [] };
431  
432 return $self;
433 }
434  
435 sub parse_stationboard {
436 my ($self) = @_;
437  
438 # @{$self->{messages}} = map { Travel::Status::DE::DBRIS::Message->new(...) } @{$self->{raw_json}{globalMessages}/[]};
439  
440 @{ $self->{results} } = map {
441 Travel::Status::DE::DBRIS::JourneyAtStop->new(
442 json => $_,
443 strptime_obj => $self->{strptime_obj}
444 )
445 } @{ $self->{raw_json}{entries} // [] };
446  
447 return $self;
448 }
449  
450 sub parse_formation {
451 my ( $self, $conf ) = @_;
452  
453 $self->{result} = Travel::Status::DE::DBRIS::Formation->new(
454 json => $self->{raw_json},
455 train_type => $conf->{train_type}
456 );
457 }
458  
459 # }}}
460 # {{{ Public Functions
461  
462 sub errstr {
463 my ($self) = @_;
464  
465 return $self->{errstr};
466 }
467  
468 sub results {
469 my ($self) = @_;
470 return @{ $self->{results} };
471 }
472  
473 sub result {
474 my ($self) = @_;
475 return $self->{result};
476 }
477  
478 # }}}
479  
480 1;
481  
482 __END__