diff --git a/modules/space/horizonsfile.cpp b/modules/space/horizonsfile.cpp index 03e5841274..6a13d79cb0 100644 --- a/modules/space/horizonsfile.cpp +++ b/modules/space/horizonsfile.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -167,6 +168,44 @@ std::string constructHorizonsUrl(HorizonsType type, const std::string& target, return url; } +json sendHorizonsRequest(const std::string& url, std::filesystem::path filePath) { + // Set up HTTP request and download result + auto download = std::make_unique( + url, + filePath, + HttpFileDownload::Overwrite::Yes + ); + + HttpFileDownload* dl = download.get(); + dl->start(); + + bool failed = false; + dl->wait(); + if (!dl->hasSucceeded()) { + LERROR(fmt::format("Error downloading horizons file with URL {}", dl->url())); + failed = true; + } + + if (failed) { + dl->cancel(); + } + + // Read the entire file into a string + constexpr auto read_size = std::size_t(4096); + std::ifstream stream = std::ifstream(filePath.string().data()); + stream.exceptions(std::ios_base::badbit); + + std::string answer; + std::string buf = std::string(read_size, '\0'); + while (stream.read(&buf[0], read_size)) { + answer.append(buf, 0, stream.gcount()); + } + answer.append(buf, 0, stream.gcount()); + + // convert to a json object + return json::parse(answer); +} + HorizonsResultCode isValidHorizonsAnswer(const json& answer) { // Signature, source and version if (auto signature = answer.find("signature"); signature != answer.end()) { diff --git a/modules/space/horizonsfile.h b/modules/space/horizonsfile.h index 8995eb779b..d67b4d61c5 100644 --- a/modules/space/horizonsfile.h +++ b/modules/space/horizonsfile.h @@ -127,6 +127,7 @@ std::string constructHorizonsUrl(HorizonsType type, const std::string& target, const std::string& observer, const std::string& startTime, const std::string& stopTime, const std::string& stepSize, const std::string& unit); +nlohmann::json sendHorizonsRequest(const std::string& url, std::filesystem::path filePath); HorizonsResultCode isValidHorizonsAnswer(const nlohmann::json& answer); HorizonsResultCode isValidHorizonsFile(std::filesystem::path file); HorizonsResult readHorizonsFile(std::filesystem::path file);