2023-11-10 10:59:53 +00:00
|
|
|
"""Get details of upcoming space launches."""
|
|
|
|
|
2023-10-03 13:00:23 +01:00
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import typing
|
|
|
|
from datetime import datetime
|
|
|
|
|
2023-11-05 14:47:17 +00:00
|
|
|
import httpx
|
2023-10-03 13:00:23 +01:00
|
|
|
|
|
|
|
Launch = dict[str, typing.Any]
|
|
|
|
Summary = dict[str, typing.Any]
|
|
|
|
|
|
|
|
|
2023-11-05 14:47:17 +00:00
|
|
|
async def next_launch_api(rocket_dir: str, limit: int = 200) -> list[Launch]:
|
2023-10-03 13:00:23 +01:00
|
|
|
"""Get the next upcoming launches from the API."""
|
|
|
|
now = datetime.now()
|
|
|
|
filename = os.path.join(rocket_dir, now.strftime("%Y-%m-%d_%H:%M:%S.json"))
|
|
|
|
url = "https://ll.thespacedevs.com/2.2.0/launch/upcoming/"
|
|
|
|
|
|
|
|
params: dict[str, str | int] = {"limit": limit}
|
2023-11-05 14:47:17 +00:00
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
r = await client.get(url, params=params)
|
2023-10-03 13:00:23 +01:00
|
|
|
open(filename, "w").write(r.text)
|
|
|
|
data = r.json()
|
|
|
|
return [summarize_launch(launch) for launch in data["results"]]
|
|
|
|
|
|
|
|
|
|
|
|
def filename_timestamp(filename: str) -> tuple[datetime, str] | None:
|
|
|
|
"""Get datetime from filename."""
|
|
|
|
try:
|
|
|
|
ts = datetime.strptime(filename, "%Y-%m-%d_%H:%M:%S.json")
|
|
|
|
except ValueError:
|
|
|
|
return None
|
|
|
|
return (ts, filename)
|
|
|
|
|
|
|
|
|
|
|
|
def format_time(time_str: str, net_precision: str) -> tuple[str, str | None]:
|
|
|
|
"""Format time based on precision."""
|
|
|
|
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
|
|
include_time = False
|
|
|
|
# Format the date based on precision
|
2023-11-23 21:31:29 +00:00
|
|
|
time_format: str | None
|
2023-10-10 06:55:23 +01:00
|
|
|
field2 = None
|
2023-11-23 21:31:29 +00:00
|
|
|
|
|
|
|
match net_precision:
|
|
|
|
case "Year":
|
|
|
|
time_format = "%Y"
|
|
|
|
case "Month":
|
|
|
|
time_format = "%b %Y"
|
|
|
|
case "Week":
|
|
|
|
time_format = "%d %b %Y"
|
|
|
|
field2 = "(Week of)"
|
|
|
|
case "Day" | "Hour" | "Minute":
|
|
|
|
time_format = "%d %b %Y"
|
|
|
|
include_time = net_precision in {"Hour", "Minute"}
|
|
|
|
case "Second":
|
|
|
|
time_format = "%d %b %Y"
|
|
|
|
include_time = True
|
2023-11-25 09:53:04 +00:00
|
|
|
case _ if net_precision and net_precision.startswith("Quarter "):
|
2023-11-23 21:31:29 +00:00
|
|
|
time_format = f"Q{net_precision[-1]} %Y"
|
|
|
|
case _:
|
|
|
|
time_format = None
|
2023-10-03 13:00:23 +01:00
|
|
|
|
2023-10-10 06:55:23 +01:00
|
|
|
if not time_format:
|
|
|
|
return (repr(time_str), repr(net_precision))
|
|
|
|
|
2023-10-03 13:00:23 +01:00
|
|
|
assert time_format
|
|
|
|
|
|
|
|
formatted = dt.strftime(time_format)
|
|
|
|
|
|
|
|
if include_time:
|
|
|
|
return (formatted, dt.strftime("%H:%M"))
|
|
|
|
else:
|
2023-10-10 06:55:23 +01:00
|
|
|
return (formatted, field2)
|
2023-10-03 13:00:23 +01:00
|
|
|
|
|
|
|
|
|
|
|
launch_providers = {
|
|
|
|
"Indian Space Research Organization": "ISRO",
|
|
|
|
"United Launch Alliance": "ULA",
|
|
|
|
"Payload Aerospace S.L.": "Payload Aerospace",
|
|
|
|
"Russian Federal Space Agency (ROSCOSMOS)": "ROSCOSMOS",
|
|
|
|
"China Aerospace Science and Technology Corporation": "CASC",
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-12-23 12:41:15 +00:00
|
|
|
def get_nested(data: dict[str, typing.Any], keys: list[str]) -> typing.Any | None:
|
|
|
|
"""
|
|
|
|
Safely get a nested value from a dictionary.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
data (Dict[str, Any]): The dictionary to search.
|
|
|
|
keys (List[str]): A list of keys for the nested lookup.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Optional[Any]: The retrieved value, or None if any key is missing.
|
|
|
|
"""
|
|
|
|
for key in keys:
|
|
|
|
if data is None or key not in data:
|
|
|
|
return None
|
|
|
|
data = data[key]
|
|
|
|
return data
|
|
|
|
|
|
|
|
|
2023-10-03 13:00:23 +01:00
|
|
|
def summarize_launch(launch: Launch) -> Summary:
|
|
|
|
"""Summarize rocket launch."""
|
2023-12-23 11:36:30 +00:00
|
|
|
try:
|
|
|
|
launch_provider = launch["launch_service_provider"]["name"]
|
|
|
|
launch_provider_abbrev = launch_providers.get(launch_provider)
|
|
|
|
except (TypeError, IndexError):
|
|
|
|
launch_provider = None
|
|
|
|
launch_provider_abbrev = None
|
2023-11-25 09:53:04 +00:00
|
|
|
|
2023-12-23 12:41:15 +00:00
|
|
|
net_precision = typing.cast(str, get_nested(launch, ["net_precision", "name"]))
|
2023-11-25 09:53:04 +00:00
|
|
|
t0_date, t0_time = format_time(launch["net"], net_precision)
|
2023-10-03 13:00:23 +01:00
|
|
|
|
|
|
|
return {
|
2023-12-23 12:41:15 +00:00
|
|
|
"name": launch.get("name"),
|
|
|
|
"status": launch.get("status"),
|
|
|
|
"net": launch.get("net"),
|
2023-11-25 09:53:04 +00:00
|
|
|
"net_precision": net_precision,
|
2023-10-03 13:00:23 +01:00
|
|
|
"t0_date": t0_date,
|
|
|
|
"t0_time": t0_time,
|
2023-12-23 12:41:15 +00:00
|
|
|
"window_start": launch.get("window_start"),
|
|
|
|
"window_end": launch.get("window_end"),
|
2023-10-03 13:00:23 +01:00
|
|
|
"launch_provider": launch_provider,
|
|
|
|
"launch_provider_abbrev": launch_provider_abbrev,
|
2023-12-23 12:41:15 +00:00
|
|
|
"launch_provider_type": get_nested(launch, ["launch_service_provider", "type"]),
|
2023-10-03 14:16:25 +01:00
|
|
|
"rocket": launch["rocket"]["configuration"]["full_name"],
|
2023-12-23 12:41:15 +00:00
|
|
|
"mission": launch.get("mission"),
|
|
|
|
"mission_name": get_nested(launch, ["mission", "name"]),
|
2023-10-03 14:16:25 +01:00
|
|
|
"pad_name": launch["pad"]["name"],
|
|
|
|
"pad_wikipedia_url": launch["pad"]["wiki_url"],
|
2023-10-03 13:00:23 +01:00
|
|
|
"location": launch["pad"]["location"]["name"],
|
|
|
|
"country_code": launch["pad"]["country_code"],
|
2023-12-23 12:41:15 +00:00
|
|
|
"orbit": get_nested(launch, ["mission", "orbit"]),
|
2023-10-03 13:00:23 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-11-05 14:47:17 +00:00
|
|
|
async def get_launches(rocket_dir: str, limit: int = 200) -> list[Summary]:
|
2023-10-03 13:00:23 +01:00
|
|
|
"""Get rocket launches with caching."""
|
|
|
|
now = datetime.now()
|
|
|
|
existing = [x for x in (filename_timestamp(f) for f in os.listdir(rocket_dir)) if x]
|
|
|
|
|
|
|
|
existing.sort(reverse=True)
|
|
|
|
|
|
|
|
if not existing or (now - existing[0][0]).seconds > 3600: # one hour
|
|
|
|
try:
|
2023-11-05 14:47:17 +00:00
|
|
|
return await next_launch_api(rocket_dir, limit=limit)
|
2023-11-10 10:59:53 +00:00
|
|
|
except httpx.ReadTimeout:
|
|
|
|
pass
|
2023-10-03 13:00:23 +01:00
|
|
|
|
|
|
|
f = existing[0][1]
|
|
|
|
|
|
|
|
filename = os.path.join(rocket_dir, f)
|
|
|
|
data = json.load(open(filename))
|
|
|
|
return [summarize_launch(launch) for launch in data["results"]]
|