blib/lib/OpenSky/API.pm untested

filter: Statementstmt 0.0% 0 / 157 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 27 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 262 CC 23 SCAR 27.2
CC
23
Cov
0%
_get_response
42.0
get_flights_from_interval
20.0
get_flights_by_aircraft
20.0
CRAP 15.2
1 # see also https://github.com/openskynetwork/opensky-api
2  
3 package OpenSky::API;
4  
5 # ABSTRACT: Perl interface to the OpenSky Network API
6  
7 our $VERSION = '0.004';
8 use Moose;
9 use OpenSky::API::Types qw(
10 ArrayRef
11 Bool
12 Dict
13 HashRef
14 InstanceOf
15 Int
16 Latitude
17 Longitude
18 NonEmptyStr
19 Num
20 Optional
21 );
22 use OpenSky::API::States;
23 use OpenSky::API::Flights;
24 use PerlX::Maybe;
25 use Config::INI::Reader;
26 use Carp qw( croak );
27  
28 use Mojo::UserAgent;
29 use Mojo::URL;
30 use Mojo::JSON qw( decode_json );
31 use Type::Params -sigs;
32 use experimental qw( signatures );
33  
34 has config => (
35 is => 'ro',
36 isa => NonEmptyStr,
37 default => sub ($self) { $ENV{HOME} . '/.openskyrc' },
38 );
39  
40 has [qw/debug raw testing/] => (
41 is => 'ro',
42 isa => Bool,
43 default => 0,
44 );
45  
46 has _config_data => (
47 is => 'ro',
48 isa => HashRef,
49 init_arg => undef,
50 lazy => 1,
51 default => sub ($self) {
52 Config::INI::Reader->read_file( $self->config );
53 },
54 );
55  
56 has _ua => (
57 is => 'ro',
58 isa => InstanceOf ['Mojo::UserAgent'],
59 init_arg => undef,
60 default => sub { Mojo::UserAgent->new },
61 );
62  
63 has _username => (
64 is => 'ro',
65 isa => NonEmptyStr,
66 lazy => 1,
67 init_arg => 'username',
68 default => sub ($self) { $ENV{OPENSKY_USERNAME} // $self->_config_data->{opensky}{username} },
69 );
70  
71 has _password => (
72 is => 'ro',
73 isa => NonEmptyStr,
74 lazy => 1,
75 init_arg => 'password',
76 default => sub ($self) { $ENV{OPENSKY_PASSWORD} // $self->_config_data->{opensky}{password} },
77 );
78  
79 has _base_url => (
80 is => 'ro',
81 init_arg => 'base_url',
82 isa => NonEmptyStr,
83 default => sub ($self) {'https://opensky-network.org/api'},
84 );
85  
86 has limit_remaining => (
87 is => 'ro',
88 isa => Int,
89 lazy => 1,
90 writer => '_set_limit_remaining',
91 default => sub ($self) {
92 return 4000 if $self->testing;
93  
94 # per their documentation,
95 # https://openskynetwork.github.io/opensky-api/rest.html#api-credit-usage,
96 # this request should only cost one credit. However, it appears to
97 # cost three.
98 my %params = (
99 lamin => 49.7,
100 lomin => 3.2,
101 lamax => 50.5,
102 lomax => 4.6,
103 );
104 my $route = '/states/all';
105 return $self->_get_response( route => $route, params => \%params, credits => 1 );
106 },
107 );
108  
109 signature_for get_states => (
110 method => 1,
111 named => [
112 time => Optional [Num], { default => 0 },
113 icao24 => Optional [ NonEmptyStr | ArrayRef [NonEmptyStr] ],
114 bbox => Optional [
115 Dict [
116 lamin => Latitude,
117 lomin => Longitude,
118 lamax => Latitude,
119 lomax => Longitude,
120 ],
121 { default => {} },
122 ],
123 extended => Optional [Bool],
124 ],
125 named_to_list => 1,
126 );
127  
128 sub get_states ( $self, $seconds, $icao24, $bbox, $extended ) {
129 my %params = (
130 maybe time => $seconds,
131 maybe icao24 => $icao24,
132 maybe extended => $extended,
133 );
134 if ( keys $bbox->%* ) {
135 $params{$_} = $bbox->{$_} for qw( lamin lomin lamax lomax );
136 }
137  
138 my $route = '/states/all';
139 my $response = $self->_get_response( route => $route, params => \%params, no_auth_required => 1 ) // {
140 time => time - ( $seconds // 0 ),
141 states => [],
142 };
143 if ( $self->raw ) {
144 return $response;
145 }
146 return OpenSky::API::States->new($response);
147 }
148  
149 signature_for get_my_states => (
150 method => 1,
151 named => [
152 time => Optional [Num], { default => 0 },
153 icao24 => Optional [ NonEmptyStr | ArrayRef [NonEmptyStr] ],
154 serials => Optional [ NonEmptyStr | ArrayRef [NonEmptyStr] ],
155 ],
156 named_to_list => 1,
157 );
158  
159 sub get_my_states ( $self, $seconds, $icao24, $serials ) {
160 my %params = (
161 extended => 1,
162 maybe time => $seconds,
163 maybe icao24 => $icao24,
164 maybe serials => $serials,
165 );
166  
167 my $route = '/states/own';
168 my $response = $self->_get_response( route => $route, params => \%params );
169 if ( $self->raw ) {
170 return $response;
171 }
172 return OpenSky::API::States->new($response);
173 }
174  
175 sub get_flights_from_interval ( $self, $begin, $end ) {
176 if ( $begin >= $end ) {
177 croak 'The end time must be greater than or equal to the start time.';
178 }
179 if ( ( $end - $begin ) > 7200 ) {
180 croak 'The time interval must be smaller than two hours.';
181 }
182  
183 my %params = ( begin => $begin, end => $end );
184 my $route = '/flights/all';
185 my $response = $self->_get_response( route => $route, params => \%params ) // [];
186  
187 if ( $self->raw ) {
188 return $response;
189 }
190 return OpenSky::API::Flights->new($response);
191 }
192  
193 sub get_flights_by_aircraft ( $self, $icao24, $begin, $end ) {
194 if ( $begin >= $end ) {
195 croak 'The end time must be greater than or equal to the start time.';
196 }
197 if ( ( $end - $begin ) > 2592 * 1e3 ) {
198 croak 'The time interval must be smaller than 30 days.';
199 }
200  
201 my %params = ( icao24 => $icao24, begin => $begin, end => $end );
202 my $route = '/flights/aircraft';
203 my $response = $self->_get_response( route => $route, params => \%params ) // [];
204  
205 if ( $self->raw ) {
206 return $response;
207 }
208 return OpenSky::API::Flights->new($response);
209 }
210  
211 sub get_arrivals_by_airport ( $self, $airport, $begin, $end ) {
212 if ( $begin >= $end ) {
213 croak 'The end time must be greater than or equal to the start time.';
214 }
215 if ( ( $end - $begin ) > 604800 ) {
216 croak 'The time interval must be smaller than 7 days.';
217 }
218  
219 my %params = ( airport => $airport, begin => $begin, end => $end );
220 my $route = '/flights/arrival';
221 my $response = $self->_get_response( route => $route, params => \%params ) // [];
222  
223 if ( $self->raw ) {
224 return $response;
225 }
226 return OpenSky::API::Flights->new($response);
227 }
228  
229 sub get_departures_by_airport ( $self, $airport, $begin, $end ) {
230 if ( $begin >= $end ) {
231 croak 'The end time must be greater than or equal to the start time.';
232 }
233 if ( ( $end - $begin ) > 604800 ) {
234 croak 'The time interval must be smaller than 7 days.';
235 }
236  
237 my %params = ( airport => $airport, begin => $begin, end => $end );
238 my $route = '/flights/departure';
239 my $response = $self->_get_response( route => $route, params => \%params ) // [];
240  
241 if ( $self->raw ) {
242 return $response;
243 }
244 return OpenSky::API::Flights->new($response);
245 }
246  
247 signature_for _get_response => (
248 method => 1,
249 named => [
250 route => NonEmptyStr,
251 params => Optional [HashRef],
252 credits => Optional [Bool],
253 no_auth_required => Optional [Bool],
254 ],
255 named_to_list => 1,
256 );
257  
258 sub _get_response ( $self, $route, $params, $credits, $no_auth_required ) {
259 my $url = $self->_url( $route, $params, $no_auth_required );
260  
261 my $response = $self->_GET($url);
262 my $remaining = $response->headers->header('X-Rate-Limit-Remaining');
263  
264 $self->_debug( $response->headers->to_string . "\n" );
265  
266 # not all requests cost credits, so we only want to set the limit if
267 # $remaining is defined
268 $self->_set_limit_remaining($remaining) if !$credits && defined $remaining;
269 if ( !$response->is_success ) {
270 if ( $response->code == 404 ) {
271  
272 # this is annoying. If the didn't match any criteria, return a 200
273 # and and empty element. Instead, we get a 404.
274 return;
275 }
276 croak $response->to_string;
277 }
278 return $remaining if $credits;
279 if ( $self->debug ) {
280 $self->_debug( $response->body );
281 }
282 return decode_json( $response->body );
283 }
284  
285 # an easy target to override for testing
286 sub _GET ( $self, $url ) {
287 $self->_debug("GET $url\n");
288 return $self->_ua->get($url)->res;
289 }
290  
291 sub _debug ( $self, $msg ) {
292 return if !$self->debug;
293 say STDERR $msg;
294 }
295  
296 sub _url ( $self, $url, $params = {}, $no_auth_required = 0 ) {
297 my $username = $self->_username;
298 my $password = $self->_password;
299 if ( ( !$username || !$password ) && $no_auth_required ) {
300 return Mojo::URL->new( $self->_base_url . $url )->query($params);
301 }
302 $url = Mojo::URL->new( $self->_base_url . $url )->userinfo( $self->_username . ':' . $self->_password );
303 $url->query($params);
304 return $url;
305 }
306  
307 __PACKAGE__->meta->make_immutable;
308  
309 __END__
310  
311 =pod
312  
313 =encoding UTF-8
314  
315 =head1 NAME
316  
317 OpenSky::API - Perl interface to the OpenSky Network API
318  
319 =head1 VERSION
320  
321 version 0.004
322  
323 =head1 SYNOPSIS
324  
325 use OpenSky::API;
326  
327 my $api = OpenSky::API->new(
328 username => 'username',
329 password => 'password',
330 );
331  
332 my $states = $api->get_states;
333 while ( my $vector = $states->next ) {
334 say $vector->callsign;
335 }
336  
337 =head1 DESCRIPTION
338  
339 This is a Perl interface to the OpenSky Network API. It provides a simple, object-oriented
340 interface, but also allows you to fetch raw results for performance.
341  
342 This is largely based on L<the official Python
343 implementation|https://github.com/openskynetwork/opensky-api/blob/master/python/opensky_api.py>,
344 but with some changes to make it more user-friendly for Perl developers.
345  
346 =head1 CONSTRUCTOR
347  
348 Basic usage:
349  
350 my $open_sky = OpenSky::API->new;
351  
352 This will create an instance of the API object with no authentication. This only allows you access
353 to the C<get_states> method.
354  
355 If you want to use the other methods, you will need to provide a username and password:
356  
357 my $open_sky = OpenSky::API->new(
358 username => 'username',
359 password => 'password',
360 );
361  
362 You can get a username and password by registering for a free account on
363 L<OpenSky Network|https://opensky-network.org>.
364  
365 Alternatively, you can set the C<OPENSKY_USERNAME> and C<OPENSKY_PASSWORD>
366 environment variables, or create a C<.openskyrc> file in your home directory
367 with the following contents:
368  
369 [opensky]
370 username = myusername
371 password = s3cr3t
372  
373 If you'd like that file in another directory, just pass the C<config> argument:
374  
375 my $open_sky = OpenSky::API->new(
376 config => '/path/to/config',
377 );
378  
379 By default, all methods return objects. If you want to get the raw results, you can set the C<raw>
380 attribute in the constructor:
381  
382 my $open_sky = OpenSky::API->new(
383 raw => 1,
384 );
385  
386 If you are debugging why something failed, pass the C<debug> attribute to see
387 a C<STDERR> trace of the requests and responses:
388  
389 my $open_sky = OpenSky::API->new(
390 debug => 1,
391 );
392  
393 =head1 METHODS
394  
395 For more insight to all methods, see L<the OpenSky API
396 documentation|https://openskynetwork.github.io/opensky-api/>.
397  
398 Note a key difference between the Python implementation and this one: the
399 Python implementation returns <None> if results are not found. For this
400 module, you will still receive the iterator, but it won't have any results.
401 This allows you to keep a consistent interface without having to check for
402 C<undef> everywhere.
403  
404 =head2 get_states
405  
406 my $states = $api->get_states;
407  
408 Returns an instance of L<OpenSky::API::States>. if C<< raw => 1 >> was passed
409 to the constructor, this will be the raw data structure instead.
410  
411 This API call can be used to retrieve any state vector of the
412 OpenSky. Please note that rate limits apply for this call. For API calls
413 without rate limitation, see C<get_my_states>.
414  
415 By default, the above fetches all current state vectors.
416  
417 You can (optionally) request state vectors for particular airplanes or times using the following request parameters:
418  
419 my $states = $api->get_states(
420 icao24 => 'abc9f3',
421 time => 1517258400,
422 );
423  
424 Both parameters are optional.
425  
426 =over 4
427  
428 =item * C<icao24>
429  
430 One or more ICAO24 transponder addresses represented by a hex string (e.g. abc9f3). To filter multiple ICAO24 append the property once for each address. If omitted, the state vectors of all aircraft are returned.
431  
432 =item * C<time>
433  
434 A Unix timestamp (seconds since epoch). Only state vectors after this timestamp are returned.
435  
436 =back
437  
438 In addition to that, it is possible to query a certain area defined by a
439 bounding box of WGS84 coordinates. For this purpose, add the following
440 parameters:
441  
442 my $states = $api->get_states(
443 bbox => {
444 lomin => -0.5, # lower bound for the longitude in decimal degrees
445 lamin => 51.25, # lower bound for the latitude in decimal degrees
446 lomax => 0, # upper bound for the longitude in decimal degrees
447 lamax => 51.75, # upper bound for the latitude in decimal degrees
448 },
449 );
450  
451 You can also request the category of aircraft by adding the following request parameter:
452  
453 my $states = $api->get_states(
454 extended => 1,
455 );
456  
457 Any and all of the above parameters can be combined.
458  
459 my $states = $api->get_states(
460 icao24 => 'abc9f3',
461 time => 1517258400,
462 bbox => {
463 lomin => -0.5, # lower bound for the longitude in decimal degrees
464 lamin => 51.25, # lower bound for the latitude in decimal degrees
465 lomax => 0, # upper bound for the longitude in decimal degrees
466 lamax => 51.75, # upper bound for the latitude in decimal degrees
467 },
468 extended => 1,
469 );
470  
471 =head2 get_my_states
472  
473 my $states = $api->get_my_states;
474  
475 Returns an instance of L<OpenSky::API::States>. if C<< raw => 1 >> was passed,
476 this will be the raw data structure instead.
477  
478 This API call can be used to retrieve state vectors for your own
479 sensors without rate limitations. Note that authentication is required for
480 this operation, otherwise you will get a 403 - Forbidden.
481  
482 By default, the above fetches all current state vectors for your states. However, you can also pass
483 arguments to fine-tune this:
484  
485 my $states = $api->get_my_states(
486 time => 1517258400,
487 icao24 => 'abc9f3',
488 serials => [ 1234, 5678 ],
489 );
490  
491 =over 4
492  
493 =item * C<time>
494  
495 The time in seconds since epoch (Unix timestamp to retrieve states for. Current time will be used if omitted.
496  
497 =item * <icao24>
498  
499 One or more ICAO24 transponder addresses represented by a hex string (e.g.
500 abc9f3). To filter multiple ICAO24 append the property once for each address.
501 If omitted, the state vectors of all aircraft are returned.
502  
503 =item * C<serials>
504  
505 Retrieve only states of a subset of your receivers. You can pass this argument
506 several time to filter state of more than one of your receivers. In this case,
507 the API returns all states of aircraft that are visible to at least one of the
508 given receivers.
509  
510 =back
511  
512 =head2 C<get_arrivals_by_airport>
513  
514 my $arrivals = $api->get_arrivals_by_airport('KJFK', $start, $end);
515  
516 Returns an instance of L<OpenSky::API::Flights>. if C<< raw => 1 >> was
517 passed, you will get the raw data structure instead.
518  
519 Positional arguments:
520  
521 =over 4
522  
523 =item * C<airport>
524  
525 The ICAO code of the airport you want to get arrivals for.
526  
527 =item * C<start>
528  
529 The start time in seconds since epoch (Unix timestamp).
530  
531 =item * C<end>
532  
533 The end time in seconds since epoch (Unix timestamp).
534  
535 =back
536  
537 The interval between start and end time must be smaller than seven days.
538  
539 =head2 C<get_departures_by_airport>
540  
541 Identical to C<get_arrivals_by_airport>, but returns departures instead of arrivals.
542  
543 =head2 C<get_flights_by_aircraft>
544  
545 my $flights = $api->get_flights_by_aircraft('abc9f3', $start, $end);
546  
547 Returns an instance of L<OpenSky::API::Flights>. if C<< raw => 1 >> was passed
548 to the constructor, you will get the raw data structure instead.
549  
550 The first argument is the ICAO24 transponder address of the aircraft you want.
551  
552 =head2 C<get_flights_from_interval>
553  
554 my $flights = $api->get_flights_from_interval($start, $end);
555  
556 Returns an instance of L<OpenSky::API::Flights>. if C<< raw => 1 >> was passed
557 to the constructor, you will get the raw data structure instead.
558  
559 =head2 C<limit_remaining>
560  
561 my $limit = $api->limit_remaining;
562  
563 The methods to retrieve state vectors of sensors other than your own are rate
564 limited. As of this writing, this is only C<get_states>. See
565 L<limitations|https://openskynetwork.github.io/opensky-api/rest.html#limitations>
566 for more details.
567  
568 =head1 EXAMPLES
569  
570 Perl Wikipedia, L<OpenSky Network|https://en.wikipedia.org/wiki/OpenSky_Network> is ...
571  
572 The OpenSky Network is a non-profit association based in Switzerland that
573 provides open access of flight tracking control data. It was set up as
574 a research project by several universities and government entities with
575 the goal to improve the security, reliability and efficiency of the
576 airspace. Its main function is to collect, process and store air traffic
577 control data and provide open access to this data to the public. Similar
578 to many existing flight trackers such as Flightradar24 and FlightAware,
579 the OpenSky Network consists of a multitude of sensors (currently around
580 1000, mostly concentrated in Europe and the US), which are connected to
581 the Internet by volunteers, industrial supporters, academic, and
582 governmental organizations. All collected raw data is archived in a
583 large historical database, containing over 23 trillion air traffic control
584 messages (November 2020). The database is primarily used by researchers
585 from different areas to analyze and improve air traffic control
586 technologies and processes
587  
588 =head2 Elon Musk's Jet
589  
590 However, this data can be used to track the movements of certain aircraft. For
591 example, Elon Musk's primary private jet (he has three, but this is the one he
592 mainly uses), has the ICAO24 transponder address C<a835af>. Running the
593 following code ...
594  
595 use OpenSky::API;
596  
597 my $musks_jet = 'a835af';
598 my $openapi = OpenSky::API->new;
599  
600 my $days = 7;
601 my $now = time;
602 my $then = $now - 86400 * 7; # up to 7 days ago
603  
604 my $flight_data = $openapi->get_flights_by_aircraft( $musks_jet, $then, $now );
605 say "Jet $musks_jet has " . $flight_data->count . " flights";
606  
607 As of this writing, that prints out:
608  
609 Jet a835af has 6 flights
610  
611 =head1 ETHICS
612  
613 There are some ethical considerations to be made when using this module. I was
614 ambivalent about writing it, but I decided to do so because I think it's
615 important to be aware of the privacy implications. However, it's also
616 important to be aware of the L<climate
617 implications|https://www.euronews.com/green/2023/03/30/wasteful-luxury-private-jet-pollution-more-than-doubles-in-europe>.
618  
619 Others are using the OpenSky API to model the amount of carbon being released
620 by the aviation industry, while others have used this public data to predict
621 corporate mergers and acquisitions. There are a wealth of reasons why this
622 data is useful, but not all of those reasons are good. Be good.
623  
624 =head1 TODO
625  
626 =over 4
627  
628 =item * Implement rate limits
629  
630 =item * Add a C<is_rate_limited> method to results
631  
632 =item * Add Waypoints and Flight Routes
633  
634 =back
635  
636 =head1 AUTHOR
637  
638 Curtis "Ovid" Poe <curtis.poe@gmail.com>
639  
640 =head1 COPYRIGHT AND LICENSE
641  
642 This software is Copyright (c) 2023 by Curtis "Ovid" Poe.
643  
644 This is free software, licensed under:
645  
646 The Artistic License 2.0 (GPL Compatible)
647  
648 =cut