-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathapi.py
More file actions
563 lines (452 loc) · 20.2 KB
/
Copy pathapi.py
File metadata and controls
563 lines (452 loc) · 20.2 KB
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# -*- coding: utf-8 -*-
import dataclasses
import math
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import quote
from .core import Core, Countries
from .entities.airport import Airport
from .entities.flight import Flight
from .errors import AirportNotFoundError, LoginError
from .flight_tracker_config import FlightTrackerConfig
from .parsers import country_to_slug, parse_airlines_html, parse_airports_json
from .request import APIClient, RetryPolicy
# Some FR24 live-feed backends answer 200 with a well-formed envelope but no
# flight entries -- indistinguishable from a legitimately empty result. The
# "AWSALB" cookie then pins the session to that backend, so dropping it is what
# makes the load balancer re-roll on retry.
FEED_STICKY_COOKIES = ("AWSALB", "AWSALBCORS")
FEED_EMPTY_RETRIES = 4
class FlightRadar24API:
"""
Main class of the FlightRadarAPI
"""
def __init__(
self,
user: Optional[str] = None,
password: Optional[str] = None,
timeout: int = 30,
max_workers: int = 8,
impersonate: Optional[str] = None,
retry: Optional[RetryPolicy] = None,
):
"""
Constructor of the FlightRadar24API class.
:param user: Your email
:param password: Your password
:param timeout: Request timeout in seconds
:param max_workers: Maximum threads used when fetching flight details concurrently
:param impersonate: TLS impersonation profile (curl_cffi). Override when FR24
updates its Cloudflare bot mitigation faster than this library releases.
See ``FlightRadarAPI.request.DEFAULT_IMPERSONATE`` for the current default.
:param retry: Optional :class:`RetryPolicy` applied to transient failures
(``CloudflareError`` and curl_cffi network errors). Defaults to no retry.
"""
self.__flight_tracker_config = FlightTrackerConfig()
self.__login_data: Optional[Dict] = None
client_kwargs: Dict[str, Any] = {"retry": retry}
if impersonate:
client_kwargs["impersonate"] = impersonate
self.__client = APIClient(**client_kwargs)
self.timeout: int = timeout
self.max_workers: int = max_workers
if user is not None and password is not None:
self.login(user, password)
def get_airlines(self) -> List[Dict]:
"""
Return a list with all airlines.
"""
response = self.__client.request(Core.airlines_data_url, headers=Core.html_headers, timeout=self.timeout)
return parse_airlines_html(response.get_bytes_content())
def get_airline_logo(self, iata: str, icao: str) -> Optional[Tuple[bytes, str]]:
"""
Download the logo of an airline from FlightRadar24 and return it as bytes.
"""
iata, icao = iata.upper(), icao.upper()
first_logo_url = Core.airline_logo_url.format(iata, icao)
# Try to get the image by the first URL option.
response = self.__client.request(
first_logo_url, headers=Core.image_headers,
allowed_error_codes=[403, 404], timeout=self.timeout,
)
status_code = response.get_status_code()
if not (400 <= status_code < 500):
return response.get_bytes_content(), first_logo_url.split(".")[-1]
# Get the image by the second airline logo URL.
second_logo_url = Core.alternative_airline_logo_url.format(icao)
response = self.__client.request(
second_logo_url, headers=Core.image_headers,
allowed_error_codes=[403, 404], timeout=self.timeout,
)
status_code = response.get_status_code()
if not (400 <= status_code < 500):
return response.get_bytes_content(), second_logo_url.split(".")[-1]
return None
def get_airport(self, code: str, *, details: bool = False) -> Airport:
"""
Return basic information about a specific airport.
:param code: ICAO or IATA of the airport
:param details: If True, it returns an Airport instance with detailed information.
"""
if not (3 <= len(code) <= 4):
raise ValueError(f"The code '{code}' is invalid. It must be the IATA or ICAO of the airport.")
if details:
airport = Airport()
airport.set_airport_details(self.get_airport_details(code))
return airport
response = self.__client.request(
Core.airport_data_url.format(code),
headers=Core.json_headers, timeout=self.timeout,
)
content = response.get_json_content()
if not content or not content.get("details"):
raise AirportNotFoundError(f"Could not find an airport by the code '{code}'.")
return Airport(info=content["details"])
def get_airport_details(self, code: str, flight_limit: int = 100, page: int = 1) -> Dict:
"""
Return the airport details from FlightRadar24.
:param code: ICAO or IATA of the airport
:param flight_limit: Limit of flights related to the airport
:param page: Page of result to display
"""
if not (3 <= len(code) <= 4):
raise ValueError(f"The code '{code}' is invalid. It must be the IATA or ICAO of the airport.")
request_params: Dict[str, Any] = {"format": "json"}
if self.is_logged_in():
request_params["token"] = self.__client.get_cookie("_frPl")
# Insert the method parameters into the dictionary for the request.
request_params["code"] = code
request_params["limit"] = flight_limit
request_params["page"] = page
# Request details from the FlightRadar24.
response = self.__client.request(
Core.api_airport_data_url,
params=request_params,
headers=Core.json_headers,
allowed_error_codes=[400],
timeout=self.timeout,
)
content = response.get_json_content()
if response.get_status_code() == 400 and content.get("errors"):
errors = content["errors"]["errors"]["parameters"]
if errors.get("limit"):
raise ValueError(errors["limit"]["notBetween"])
raise AirportNotFoundError(f"Could not find an airport by the code '{code}'.", errors)
result = content["result"]["response"]
# Check whether it received data of an airport.
data = result.get("airport", dict()).get("pluginData", dict())
if "details" not in data and len(data.get("runways", [])) == 0 and len(data) <= 3:
raise AirportNotFoundError(f"Could not find an airport by the code '{code}'.")
# Return the airport details.
return result
def get_airport_disruptions(self) -> Dict:
"""
Return airport disruptions.
"""
response = self.__client.request(
Core.airport_disruptions_url,
headers=Core.json_headers, timeout=self.timeout,
)
return response.get_json_content()
def get_airports(
self, countries: Optional[Union[Iterable[Union[Countries, str]], Countries, str]] = None,
) -> List[Airport]:
"""
Return a list with all airports, optionally narrowed to some countries.
:param countries: Country names from the Countries enum, or their slug strings,
as any iterable or a single value. Every country when omitted.
"""
wanted: Optional[List[Union[Countries, str]]] = None
if isinstance(countries, (Countries, str)):
wanted = [countries]
elif countries is not None:
# Materialised: a generator has no len() and is consumed once.
wanted = list(countries)
if wanted is not None and len(wanted) == 0:
return []
response = self.__client.request(
Core.airports_json_url, headers=Core.json_headers, timeout=self.timeout,
)
# get_content(), not get_json_content(): an html body reaches the parser's
# guard; a malformed JSON body still raises. The parser slugifies `wanted`.
return parse_airports_json(response.get_content(), wanted)
def get_bookmarks(self) -> Dict:
"""
Get the bookmarks from the FlightRadar24 account.
"""
if self.__login_data is None:
raise LoginError("You must log in to your account.")
headers = {**Core.json_headers, "accesstoken": self.get_login_data()["accessToken"]}
response = self.__client.request(Core.bookmarks_url, headers=headers, timeout=self.timeout)
return response.get_json_content()
def get_bounds(self, zone: Dict[str, float]) -> str:
"""
Convert coordinate dictionary to a string "y1, y2, x1, x2".
:param zone: Dictionary containing the following keys: tl_y, tl_x, br_y, br_x
"""
return f"{zone['tl_y']},{zone['br_y']},{zone['tl_x']},{zone['br_x']}"
def get_bounds_by_point(self, latitude: float, longitude: float, radius: float) -> str:
"""
Convert a point coordinate and a radius to a string "y1, y2, x1, x2".
:param latitude: Latitude of the point
:param longitude: Longitude of the point
:param radius: Radius in meters to create area around the point
"""
half_side_in_km = abs(radius) / 1000
lat = math.radians(latitude)
lon = math.radians(longitude)
approx_earth_radius = 6371
# Distance from the centre to a corner of the bounding square.
hypotenuse_distance = math.sqrt(2 * (math.pow(half_side_in_km, 2)))
# The two diagonal bearings (in radians) used below are 225° (SW corner,
# yields the min lat/lon) and 45° (NE corner, yields the max lat/lon).
bearing_sw = math.radians(225)
bearing_ne = math.radians(45)
# Destination-point formula along the SW bearing → south-west corner.
lat_min = math.asin(
math.sin(lat) * math.cos(hypotenuse_distance / approx_earth_radius)
+ math.cos(lat)
* math.sin(hypotenuse_distance / approx_earth_radius)
* math.cos(bearing_sw),
)
lon_min = lon + math.atan2(
math.sin(bearing_sw)
* math.sin(hypotenuse_distance / approx_earth_radius)
* math.cos(lat),
math.cos(hypotenuse_distance / approx_earth_radius)
- math.sin(lat) * math.sin(lat_min),
)
# Same formula along the NE bearing → north-east corner.
lat_max = math.asin(
math.sin(lat) * math.cos(hypotenuse_distance / approx_earth_radius)
+ math.cos(lat)
* math.sin(hypotenuse_distance / approx_earth_radius)
* math.cos(bearing_ne),
)
lon_max = lon + math.atan2(
math.sin(bearing_ne)
* math.sin(hypotenuse_distance / approx_earth_radius)
* math.cos(lat),
math.cos(hypotenuse_distance / approx_earth_radius)
- math.sin(lat) * math.sin(lat_max),
)
rad2deg = math.degrees
zone = {
"tl_y": rad2deg(lat_max),
"br_y": rad2deg(lat_min),
"tl_x": rad2deg(lon_min),
"br_x": rad2deg(lon_max)
}
return self.get_bounds(zone)
def get_country_flag(self, country: str) -> Optional[Tuple[bytes, str]]:
"""
Download the flag of a country from FlightRadar24 and return it as bytes.
:param country: Country name
"""
# Same slugifier as the feed, which spells some names "Myanmar (Burma)".
slug = country_to_slug(country)
if not slug:
return None
flag_url = Core.country_flag_url.format(slug)
headers = Core.image_headers.copy()
headers.pop("origin", None) # Does not work for this request.
response = self.__client.request(
flag_url, headers=headers,
allowed_error_codes=[403, 404], timeout=self.timeout,
)
status_code = response.get_status_code()
if not (400 <= status_code < 500):
return response.get_bytes_content(), flag_url.split(".")[-1]
return None
def get_flight_details(self, flight: Flight) -> Dict[Any, Any]:
"""
Return the flight details from Data Live FlightRadar24.
:param flight: A Flight instance
"""
response = self.__client.request_standalone(
Core.flight_data_url.format(flight.id), headers=Core.json_headers, timeout=self.timeout,
)
return response.get_json_content()
def get_flights(
self,
airline: Optional[str] = None,
bounds: Optional[str] = None,
registration: Optional[str] = None,
aircraft_type: Optional[str] = None,
*,
details: bool = False
) -> List[Flight]:
"""
Return a list of flights. See more options at set_flight_tracker_config() method.
:param airline: The airline ICAO. Ex: "DAL"
:param bounds: Coordinates (y1, y2 ,x1, x2). Ex: "75.78,-75.78,-427.56,427.56"
:param registration: Aircraft registration
:param aircraft_type: Aircraft model code. Ex: "B737"
:param details: If True, it returns flights with detailed information
"""
request_params = dataclasses.asdict(self.__flight_tracker_config)
if self.is_logged_in():
request_params["enc"] = self.__client.get_cookie("_frPl")
# Insert the method parameters into the dictionary for the request.
if airline is not None: request_params["airline"] = airline
if bounds is not None: request_params["bounds"] = bounds
if registration is not None: request_params["reg"] = registration
if aircraft_type is not None: request_params["type"] = aircraft_type
flights: List[Flight] = list()
for _ in range(FEED_EMPTY_RETRIES + 1):
# Get all flights from Data Live FlightRadar24.
response = self.__client.request(
Core.real_time_flight_tracker_data_url,
params=request_params,
headers=Core.json_headers,
timeout=self.timeout,
)
content = response.get_json_content()
# Get flights only.
flights = [
Flight(flight_id, flight_info)
for flight_id, flight_info in content.items()
if flight_id[0].isnumeric()
]
# "full_count": 0 means the feed really has nothing to report.
if flights or not content.get("full_count"):
break
for cookie_name in FEED_STICKY_COOKIES:
self.__client.delete_cookie(cookie_name)
if details:
with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
futures = {executor.submit(self.get_flight_details, f): f for f in flights}
for future in as_completed(futures):
futures[future].set_flight_details(future.result())
return flights
def get_flight_tracker_config(self) -> FlightTrackerConfig:
"""
Return a copy of the current config of the Real Time Flight Tracker, used by get_flights() method.
"""
return dataclasses.replace(self.__flight_tracker_config)
def get_history_data(self, flight: Flight, file_type: str, timestamp: int) -> str:
"""
Download historical data of a flight.
:param flight: A Flight instance
:param file_type: Must be "CSV" or "KML"
:param timestamp: A Unix timestamp
"""
if self.__login_data is None:
raise LoginError("You must log in to your account.")
file_type = file_type.lower()
if file_type not in ["csv", "kml"]:
raise ValueError(f"File type '{file_type}' is not supported. Only CSV and KML are supported.")
headers = {**Core.json_headers, "accesstoken": self.get_login_data()["accessToken"]}
response = self.__client.request(
Core.historical_data_url.format(flight.id, file_type, timestamp),
headers=headers,
timeout=self.timeout,
)
return response.get_bytes_content().decode("utf-8")
def get_login_data(self) -> Dict[Any, Any]:
"""
Return the user data.
"""
if self.__login_data is None:
raise LoginError("You must log in to your account.")
return self.__login_data["userData"].copy()
def get_most_tracked(self) -> Dict:
"""
Return the most tracked data.
"""
response = self.__client.request(Core.most_tracked_url, headers=Core.json_headers, timeout=self.timeout)
return response.get_json_content()
def get_volcanic_eruptions(self) -> Dict:
"""
Return boundaries of volcanic eruptions and ash clouds impacting aviation.
"""
response = self.__client.request(
Core.volcanic_eruption_data_url,
headers=Core.json_headers, timeout=self.timeout,
)
return response.get_json_content()
def get_zones(self) -> Dict[str, Any]:
"""
Return all major zones on the globe.
"""
zones = Core.static_zones.copy()
zones.pop("version", None)
return zones
def search(self, query: str, limit: int = 50) -> Dict:
"""
Return the search result.
"""
response = self.__client.request(
Core.search_data_url.format(quote(query), limit),
headers=Core.json_headers, timeout=self.timeout,
)
content = response.get_json_content()
results = content.get("results", [])
stats = content.get("stats", {})
i = 0
data: Dict[str, Any] = {}
for name, count in stats.get("count", {}).items():
data[name] = results[i:i + count]
i += count
return data
def is_logged_in(self) -> bool:
"""
Check if the user is logged into the FlightRadar24 account.
"""
return self.__login_data is not None
def login(self, user: str, password: str) -> None:
"""
Log in to a FlightRadar24 account.
:param user: Your email.
:param password: Your password.
"""
self.__login_data = None
self.__client.clear_cookies()
data = {
"email": user,
"password": password,
"remember": "true",
"type": "web"
}
response = self.__client.request(
Core.user_login_url,
headers=Core.json_headers, data=data, timeout=self.timeout,
)
status_code = response.get_status_code()
content = response.get_json_content()
if not (200 <= status_code < 300) or not content.get("success"):
raise LoginError(content.get("message", "Your email or password is incorrect"))
self.__login_data = {
"userData": content["userData"],
}
def logout(self) -> bool:
"""
Log out of the FlightRadar24 account.
Return a boolean indicating that it successfully logged out of the server.
"""
if self.__login_data is None:
return True
self.__login_data = None
try:
response = self.__client.request(Core.user_logout_url, headers=Core.json_headers, timeout=self.timeout)
return 200 <= response.get_status_code() < 300
finally:
self.__client.clear_cookies()
def set_flight_tracker_config(
self,
flight_tracker_config: Optional[FlightTrackerConfig] = None,
**config: Union[int, str]
) -> None:
"""
Set config for the Real Time Flight Tracker, used by get_flights() method.
"""
if flight_tracker_config is not None:
self.__flight_tracker_config = flight_tracker_config
current_config_dict = dataclasses.asdict(self.__flight_tracker_config)
for key, value in config.items():
value = str(value)
if key not in current_config_dict:
raise KeyError(f"Unknown option: '{key}'")
if not value.isdecimal():
raise TypeError(f"Value must be a number. Got '{value}' for key '{key}'")
setattr(self.__flight_tracker_config, key, value)