HAFAS.pm untested

filter: Statementstmt 0.0% 0 / 285 Branchbran 0.0% 0 / 96 Conditioncond 0.0% 0 / 66 MC/DCmcdc 0.0% 0 / 40 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 534 CC 49 SCAR 44.0
CC
49
Cov
0%
new
272.0
mot_mask
72.0
post_with_cache
72.0
CRAP 81.3
1 package Travel::Routing::DE::HAFAS;
2  
3 # vim:foldmethod=marker
4  
5 use strict;
6 use warnings;
7 use 5.014;
8 use utf8;
9  
10 use Carp qw(confess);
11 use DateTime;
12 use DateTime::Format::Strptime;
13 use Digest::MD5 qw(md5_hex);
14 use Encode qw(decode encode);
15 use JSON;
16 use LWP::UserAgent;
17 use Travel::Routing::DE::HAFAS::Connection;
18 use Travel::Status::DE::HAFAS;
19 use Travel::Status::DE::HAFAS::Location;
20 use Travel::Status::DE::HAFAS::Message;
21  
22 our $VERSION = '0.11';
23  
24 # {{{ Endpoint Definition
25  
26 my %hafas_instance
27 = map { $_->{shortname} => $_ } Travel::Status::DE::HAFAS->get_services;
28  
29 # }}}
30 # {{{ Constructors
31  
32 sub new {
33 my ( $obj, %conf ) = @_;
34 my $service = $conf{service};
35  
36 my $ua = $conf{user_agent};
37  
38 if ( not $ua ) {
39 my %lwp_options = %{ $conf{lwp_options} // { timeout => 10 } };
40 $ua = LWP::UserAgent->new(%lwp_options);
41 $ua->env_proxy;
42 }
43  
44 if ( not( $conf{from_stop} and $conf{to_stop} ) ) {
45 confess('from_stop and to_stop must be specified');
46 }
47  
48 if ( not defined $service ) {
49 confess("The service option is mandatory");
50 }
51  
52 if ( defined $service and not exists $hafas_instance{$service} ) {
53 confess("The service '$service' is not supported");
54 }
55  
56 my $now = DateTime->now( time_zone => 'Europe/Berlin' );
57 my $self = {
58 active_service => $service,
59 cache => $conf{cache},
60 developer_mode => $conf{developer_mode},
61 exclusive_mots => $conf{exclusive_mots},
62 excluded_mots => $conf{excluded_mots},
63 messages => [],
64 results => [],
65 from_stop => $conf{from_stop},
66 via_stops => $conf{via_stops} // [],
67 to_stop => $conf{to_stop},
68 ua => $ua,
69 now => $now,
70 };
71  
72 bless( $self, $obj );
73  
74 my $req;
75  
76 my $date = ( $conf{datetime} // $now )->strftime('%Y%m%d');
77 my $time = ( $conf{datetime} // $now )->strftime('%H%M%S');
78 my $outFrwd = $conf{arrival} ? \0 : undef;
79  
80 my @via_locs = map { $self->stop_to_hafas($_) } @{ $self->{via_stops} };
81  
82 $req = {
83 svcReqL => [
84 {
85 meth => 'TripSearch',
86 req => {
87 depLocL => [ $self->stop_to_hafas( $self->{from_stop} ) ],
88 arrLocL => [ $self->stop_to_hafas( $self->{to_stop} ) ],
89 numF => 6,
90 maxChg => $conf{max_change},
91 minChgTime => $conf{min_change_time},
92 outFrwd => $outFrwd,
93 viaLocL => @via_locs
94 ? [ map { { loc => $_ } } @via_locs ]
95 : undef,
96 trfReq => {
97 cType => 'PK',
98 tvlrProf => [ { type => 'E' } ],
99 },
100 outDate => $date,
101 outTime => $time,
102 jnyFltrL => [
103 {
104 type => "PROD",
105 mode => "INC",
106 value => $self->mot_mask
107 }
108 ]
109 },
110 },
111 ],
112 %{ $hafas_instance{$service}{request} }
113 };
114  
115 if ( $conf{language} ) {
116 $req->{lang} = $conf{language};
117 }
118  
119 $self->{strptime_obj} //= DateTime::Format::Strptime->new(
120 pattern => '%Y%m%dT%H%M%S',
121 time_zone => 'Europe/Berlin',
122 );
123  
124 my $json = $self->{json} = JSON->new->utf8;
125  
126 # The JSON request is the cache key, so if we have a cache we must ensure
127 # that JSON serialization is deterministic.
128 if ( $self->{cache} ) {
129 $json->canonical;
130 }
131  
132 $req = $json->encode($req);
133 $self->{post} = $req;
134  
135 my $url = $conf{url} // $hafas_instance{$service}{mgate};
136  
137 if ( my $salt = $hafas_instance{$service}{salt} ) {
138 if ( $hafas_instance{$service}{micmac} ) {
139 my $mic = md5_hex( $self->{post} );
140 my $mac = md5_hex( $mic . $salt );
141 $url .= "?mic=$mic&mac=$mac";
142 }
143 else {
144 $url .= '?checksum=' . md5_hex( $self->{post} . $salt );
145 }
146 }
147  
148 if ( $conf{async} ) {
149 $self->{url} = $url;
150 return $self;
151 }
152  
153 if ( $conf{json} ) {
154 $self->{raw_json} = $conf{json};
155 }
156 else {
157 if ( $self->{developer_mode} ) {
158 say "requesting $req from $url";
159 }
160  
161 my ( $content, $error ) = $self->post_with_cache($url);
162  
163 if ($error) {
164 $self->{errstr} = $error;
165 return $self;
166 }
167  
168 if ( $self->{developer_mode} ) {
169 say decode( 'utf-8', $content );
170 }
171  
172 $self->{raw_json} = $json->decode($content);
173 }
174  
175 $self->check_mgate;
176 $self->parse_trips;
177  
178 return $self;
179 }
180  
181 sub new_p {
182 my ( $obj, %conf ) = @_;
183 my $promise = $conf{promise}->new;
184  
185 if ( not( $conf{from_stop} and $conf{to_stop} ) ) {
186 confess('from_stop and to_stop must be specified');
187 return $promise->reject('from_stop and to_stop must be specified');
188 }
189  
190 my $self = $obj->new( %conf, async => 1 );
191 $self->{promise} = $conf{promise};
192  
193 $self->post_with_cache_p( $self->{url} )->then(
194 sub {
195 my ($content) = @_;
196 $self->{raw_json} = $self->{json}->decode($content);
197 $self->check_mgate;
198 $self->parse_trips;
199 if ( $self->errstr ) {
200 $promise->reject( $self->errstr, $self );
201 }
202 else {
203 $promise->resolve($self);
204 }
205 return;
206 }
207 )->catch(
208 sub {
209 my ($err) = @_;
210 $promise->reject($err);
211 return;
212 }
213 )->wait;
214  
215 return $promise;
216 }
217  
218 # }}}
219 # {{{ Internal Helpers
220  
221 sub mot_mask {
222 my ($self) = @_;
223  
224 my $service = $self->{active_service};
225 my $mot_mask = 2**@{ $hafas_instance{$service}{productbits} } - 1;
226  
227 my %mot_pos;
228 for my $i ( 0 .. $#{ $hafas_instance{$service}{productbits} } ) {
229 if ( ref( $hafas_instance{$service}{productbits}[$i] ) eq 'ARRAY' ) {
230 $mot_pos{ $hafas_instance{$service}{productbits}[$i][0] } = $i;
231 }
232 else {
233 $mot_pos{ $hafas_instance{$service}{productbits}[$i] } = $i;
234 }
235 }
236  
237 if ( my @mots = @{ $self->{exclusive_mots} // [] } ) {
238 $mot_mask = 0;
239 for my $mot (@mots) {
240 if ( exists $mot_pos{$mot} ) {
241 $mot_mask |= 1 << $mot_pos{$mot};
242 }
243 elsif ( $mot =~ m{ ^ \d+ $ }x ) {
244 $mot_mask |= 1 << $mot;
245 }
246 }
247 }
248  
249 if ( my @mots = @{ $self->{excluded_mots} // [] } ) {
250 for my $mot (@mots) {
251 if ( exists $mot_pos{$mot} ) {
252 $mot_mask &= ~( 1 << $mot_pos{$mot} );
253 }
254 elsif ( $mot =~ m{ ^ \d+ $ }x ) {
255 $mot_mask &= ~( 1 << $mot );
256 }
257 }
258 }
259  
260 return $mot_mask;
261 }
262  
263 sub stop_to_hafas {
264 my ( $self, $stop ) = @_;
265  
266 if ( $stop =~ m{ ^ [0-9]+ $ }x ) {
267 return { lid => 'A=1@L=' . $stop . '@' };
268 }
269 else {
270 return { lid => 'A=1@O=' . $stop . '@' };
271 }
272 }
273  
274 sub post_with_cache {
275 my ( $self, $url ) = @_;
276 my $cache = $self->{cache};
277  
278 if ( $self->{developer_mode} ) {
279 say "POST $url";
280 }
281  
282 if ($cache) {
283 my $content = $cache->thaw( $self->{post} );
284 if ($content) {
285 if ( $self->{developer_mode} ) {
286 say ' cache hit';
287 }
288 return ( ${$content}, undef );
289 }
290 }
291  
292 if ( $self->{developer_mode} ) {
293 say ' cache miss';
294 }
295  
296 my $reply = $self->{ua}->post(
297 $url,
298 'Content-Type' => 'application/json',
299 Content => $self->{post}
300 );
301  
302 if ( $reply->is_error ) {
303 return ( undef, $reply->status_line );
304 }
305 my $content = $reply->content;
306  
307 if ($cache) {
308 $cache->freeze( $self->{post}, \$content );
309 }
310  
311 return ( $content, undef );
312 }
313  
314 sub post_with_cache_p {
315 my ( $self, $url ) = @_;
316 my $cache = $self->{cache};
317  
318 if ( $self->{developer_mode} ) {
319 say "POST $url";
320 }
321  
322 my $promise = $self->{promise}->new;
323  
324 if ($cache) {
325 my $content = $cache->thaw( $self->{post} );
326 if ($content) {
327 if ( $self->{developer_mode} ) {
328 say ' cache hit';
329 }
330 return $promise->resolve( ${$content} );
331 }
332 }
333  
334 if ( $self->{developer_mode} ) {
335 say ' cache miss';
336 }
337  
338 $self->{ua}->post_p( $url, $self->{post} )->then(
339 sub {
340 my ($tx) = @_;
341 if ( my $err = $tx->error ) {
342 $promise->reject(
343 "POST $url returned HTTP $err->{code} $err->{message}");
344 return;
345 }
346 my $content = $tx->res->body;
347 if ($cache) {
348 $cache->freeze( $self->{post}, \$content );
349 }
350 $promise->resolve($content);
351 return;
352 }
353 )->catch(
354 sub {
355 my ($err) = @_;
356 $promise->reject($err);
357 return;
358 }
359 )->wait;
360  
361 return $promise;
362 }
363  
364 sub check_mgate {
365 my ($self) = @_;
366  
367 if ( $self->{raw_json}{err} and $self->{raw_json}{err} ne 'OK' ) {
368 $self->{errstr} = $self->{raw_json}{errTxt}
369 // 'error code is ' . $self->{raw_json}{err};
370 $self->{errcode} = $self->{raw_json}{err};
371 }
372 elsif ( defined $self->{raw_json}{cInfo}{code}
373 and $self->{raw_json}{cInfo}{code} ne 'OK'
374 and $self->{raw_json}{cInfo}{code} ne 'VH' )
375 {
376 $self->{errstr} = 'cInfo code is ' . $self->{raw_json}{cInfo}{code};
377 $self->{errcode} = $self->{raw_json}{cInfo}{code};
378 }
379 elsif ( @{ $self->{raw_json}{svcResL} // [] } == 0 ) {
380 $self->{errstr} = 'svcResL is empty';
381 }
382 elsif ( $self->{raw_json}{svcResL}[0]{err} ne 'OK' ) {
383 $self->{errstr}
384 = 'svcResL[0].err is ' . $self->{raw_json}{svcResL}[0]{err};
385 $self->{errcode} = $self->{raw_json}{svcResL}[0]{err};
386 }
387  
388 return $self;
389 }
390  
391 sub parse_trips {
392 my ($self) = @_;
393  
394 my $common = $self->{raw_json}{svcResL}[0]{res}{common};
395  
396 my @locL = map { Travel::Status::DE::HAFAS::Location->new( loc => $_ ) }
397 @{ $common->{locL} // [] };
398  
399 my @prodL = map {
400 Travel::Status::DE::HAFAS::Product->new(
401 common => $common,
402 product => $_
403 )
404 } @{ $common->{prodL} // [] };
405  
406 my @conL = @{ $self->{raw_json}{svcResL}[0]{res}{outConL} // [] };
407 for my $con (@conL) {
408 push(
409 @{ $self->{results} },
410 Travel::Routing::DE::HAFAS::Connection->new(
411 common => $self->{raw_json}{svcResL}[0]{res}{common},
412 locL => \@locL,
413 prodL => \@prodL,
414 connection => $con,
415 hafas => $self,
416 )
417 );
418 }
419 }
420  
421 sub add_message {
422 my ( $self, $json, $is_him ) = @_;
423  
424 my $text = $json->{txtN};
425 my $code = $json->{code};
426  
427 if ($is_him) {
428 $text = $json->{text};
429 $code = $json->{hid};
430 }
431  
432 # Some backends use remL for operator information. We don't want that.
433 if ( $code eq 'OPERATOR' ) {
434 return;
435 }
436  
437 for my $message ( @{ $self->{messages} } ) {
438 if (
439 (
440 not( defined $code and defined $message->{code} )
441 or $code eq $message->{code}
442 )
443 and ( not( defined $text and defined $message->{text} )
444 or $text eq $message->{text} )
445 )
446 {
447 $message->{ref_count}++;
448 return $message;
449 }
450 }
451  
452 my $message = Travel::Status::DE::HAFAS::Message->new(
453 json => $json,
454 ref_count => 1,
455 );
456 push( @{ $self->{messages} }, $message );
457 return $message;
458 }
459  
460 # }}}
461 # {{{ Public Functions
462  
463 sub errcode {
464 my ($self) = @_;
465  
466 return $self->{errcode};
467 }
468  
469 sub errstr {
470 my ($self) = @_;
471  
472 return $self->{errstr};
473 }
474  
475 sub messages {
476 my ($self) = @_;
477 return @{ $self->{messages} };
478 }
479  
480 sub connections {
481 my ($self) = @_;
482 return @{ $self->{results} };
483 }
484  
485 # static
486 sub get_services {
487 my @services;
488 for my $service ( sort keys %hafas_instance ) {
489 my %desc = %{ $hafas_instance{$service} };
490 $desc{shortname} = $service;
491 push( @services, \%desc );
492 }
493 return @services;
494 }
495  
496 # static
497 sub get_service {
498 my ($service) = @_;
499  
500 if ( defined $service and exists $hafas_instance{$service} ) {
501 return $hafas_instance{$service};
502 }
503 return;
504 }
505  
506 sub get_active_service {
507 my ($self) = @_;
508  
509 if ( defined $self->{active_service} ) {
510 return $hafas_instance{ $self->{active_service} };
511 }
512 return;
513 }
514  
515 # }}}
516  
517 1;
518  
519 __END__