27namespace fs = std::filesystem;
42 static const std::regex re{R
"((\d+(?:\.\d+)?)\s*%)"};
47 static const std::regex re{R
"((\d+(?:\.\d+)?)\s*([kMG])?/s)"};
52 static const std::regex re{R
"((\d+(?:\.\d+)?)\s*([kMG])?B?/s)"};
57 static const std::regex re{R
"(content-length:\s*(\d+))", std::regex::icase};
68 [](
const std::shared_ptr<std::future<void>>& fu)
70 return fu->wait_for(std::chrono::seconds(0)) ==
71 std::future_status::ready;
91 const auto startsWithCI = [&url](
const char* prefix)
93 const size_t n = std::strlen(prefix);
96 for (
size_t i = 0; i < n; ++i)
98 if (std::tolower(
static_cast<unsigned char>(url[i])) != prefix[i])
103 return startsWithCI(
"http://") || startsWithCI(
"https://");
111std::atomic<bool> FileDownloadService::cancelled_{
false};
112std::atomic<bool> FileDownloadService::downloading_{
false};
113std::mutex FileDownloadService::downloadMutex_;
122 std::lock_guard<std::mutex> lock(downloadMutex_);
130 fs::path parentDir = fs::path(request.
localPath).parent_path();
131 if (!parentDir.empty() && !fs::exists(parentDir))
134 fs::create_directories(parentDir, ec);
137 result.
errorMessage =
"Failed to create directory: " + parentDir.string();
139 downloading_ =
false;
145 uint64_t existingSize = 0;
148 std::error_code fileSizeEc;
149 existingSize = fs::file_size(request.
localPath, fileSizeEc);
152 Logger::info(
"FileDownload: Found existing file ({} bytes), attempting resume",
159 if (!isHttpUrl(request.
url))
161 result.
errorMessage =
"Refusing non-http(s) download URL: " + request.
url;
163 downloading_ =
false;
168 std::ostringstream cmd;
169 cmd <<
"curl -L --fail --connect-timeout 30 ";
173 cmd <<
"--progress-bar ";
178 cmd <<
"-C " << existingSize <<
" ";
182 cmd <<
"--proto =https --max-redirs 10 ";
185 for (
const auto& [key, value] : request.
headers)
207 request.
headers.empty() ?
"none" :
"redacted");
210 FILE* rawPipe = popen(cmd.str().c_str(),
"r");
215 downloading_ =
false;
219 std::array<char, 256> buffer;
220 std::string currentLine;
224 auto lastProgressUpdate = std::chrono::steady_clock::now();
225 const auto progressInterval = std::chrono::milliseconds(100);
232 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), rawPipe) !=
nullptr)
239 downloading_ =
false;
243 std::error_code removeEc;
249 currentLine = buffer.data();
254 if (currentLine.find(
'%') != std::string::npos)
258 if (std::regex_search(currentLine, match, kPercentRegex()))
263 std::max(0, std::min(100,
static_cast<int>(std::stof(match[1].str()))));
272 if (std::regex_search(currentLine, match, kSpeedRegex()))
276 double speed = std::stod(match[1].str());
277 std::string unit = match[2].str();
278 if (unit ==
"k" || unit ==
"K")
280 else if (unit ==
"M")
281 speed *= 1024 * 1024;
282 else if (unit ==
"G")
283 speed *= 1024 * 1024 * 1024;
293 auto now = std::chrono::steady_clock::now();
294 if (progressCallback && (now - lastProgressUpdate) >= progressInterval)
296 progressCallback(progress);
297 lastProgressUpdate = now;
302 int status = pclose(rawPipe);
303 downloading_ =
false;
309 result.
errorMessage =
"Failed to wait for curl process";
310 Logger::error(
"FileDownload: pclose failed: {}", strerror(errno));
316 if (WIFEXITED(status))
318 exitCode = WEXITSTATUS(status);
320 else if (WIFSIGNALED(status))
322 exitCode = 128 + WTERMSIG(status);
336 result.
errorMessage =
"HTTP error (file not found or access denied)";
342 result.
errorMessage =
"Range request not supported (resume failed)";
348 result.
errorMessage =
"curl failed with exit code " + std::to_string(exitCode);
369 std::error_code sizeEc;
376 result.
errorMessage =
"file_size failed: " + sizeEc.message();
378 std::error_code rmEc;
387 std::error_code rmEc;
399 Logger::info(
"FileDownload: Checksum verified successfully");
415 if (progressCallback)
420 progressCallback(progress);
426std::vector<DownloadResult>
430 std::vector<DownloadResult> results;
431 results.reserve(requests.size());
433 uint64_t totalSize = 0;
434 uint64_t downloadedSize = 0;
437 for (
const auto& req : requests)
444 for (
const auto& request : requests)
450 results.push_back(cancelled);
457 if (progressCallback)
460 batchProg.
statusMessage =
"Downloading file " + std::to_string(fileIndex + 1) +
461 " of " + std::to_string(requests.size());
466 batchProg.
bytesDownloaded = downloadedSize + fileProgress.bytesDownloaded;
471 progressCallback(batchProg);
476 results.push_back(result);
498 std::make_shared<std::future<void>>(std::async(std::launch::async,
499 [request, onComplete, onProgress]()
506 storeFuture(std::move(future));
510 const std::vector<DownloadRequest>& requests,
511 const std::function<
void(std::vector<DownloadResult>)>& onComplete,
515 std::make_shared<std::future<void>>(std::async(std::launch::async,
516 [requests, onComplete, onProgress]()
523 storeFuture(std::move(future));
546 const std::string& type)
549 if (calculated.empty())
555 std::string expectedLower = expected;
556 std::string calculatedLower = calculated;
557 std::transform(expectedLower.begin(), expectedLower.end(), expectedLower.begin(),
558 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
559 std::transform(calculatedLower.begin(), calculatedLower.end(), calculatedLower.begin(),
560 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
562 return expectedLower == calculatedLower;
566 const std::string& type)
574 command =
"md5sum " + escapedPath +
" 2>/dev/null";
576 else if (type ==
"sha256")
578 command =
"sha256sum " + escapedPath +
" 2>/dev/null";
580 else if (type ==
"sha1")
582 command =
"sha1sum " + escapedPath +
" 2>/dev/null";
586 Logger::error(
"FileDownload: Unknown checksum type: {}", type);
590 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(),
"r"), pclose);
593 Logger::error(
"FileDownload: Failed to run checksum command");
597 std::array<char, 256> buffer;
604 if (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe.get()) !=
nullptr)
606 result = buffer.data();
610 size_t spacePos = result.find(
' ');
611 if (spacePos != std::string::npos)
613 result = result.substr(0, spacePos);
617 while (!result.empty() && std::isspace(
static_cast<unsigned char>(result.back())))
630 std::string command =
"curl -sI -L --connect-timeout 10 --proto =https --max-redirs 10 -- " +
632 " 2>/dev/null | grep -i content-length | tail -1";
634 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(),
"r"), pclose);
640 std::array<char, 256> buffer;
642 if (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe.get()) !=
nullptr)
644 result = buffer.data();
649 if (std::regex_search(result, match, kContentLengthRegex()))
653 return std::stoull(match[1].str());
669 std::string command =
670 "curl -sI -L --connect-timeout 10 --max-time 15 --proto =https --max-redirs 10 "
671 "-o /dev/null -w \"%{http_code}\" -- " +
674 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(),
"r"), pclose);
680 std::array<char, 16> buffer;
682 if (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe.get()) !=
nullptr)
684 result = buffer.data();
690 int statusCode = std::stoi(result);
691 return statusCode >= 200 && statusCode < 300;
703DownloadProgress FileDownloadService::parseProgressOutput(
const std::string& line,
704 const std::string& filename)
714 if (std::regex_search(line, match, kPercentRegex()))
718 progress.
percentComplete =
static_cast<int>(std::stof(match[1].str()));
730 double speed = std::stod(match[1].str());
731 std::string unit = match.size() > 2 ? match[2].str() :
"";
732 if (unit ==
"k" || unit ==
"K")
734 else if (unit ==
"M")
735 speed *= 1024 * 1024;
736 else if (unit ==
"G")
737 speed *= 1024 * 1024 * 1024;
748std::string FileDownloadService::buildCurlCommand(
const DownloadRequest& request,
bool withProgress)
750 std::ostringstream cmd;
751 cmd <<
"curl -L --fail --connect-timeout 30 ";
752 cmd <<
"--proto =https --max-redirs 10 ";
757 cmd <<
"--progress-bar ";
764 for (
const auto& [key, value] : request.
headers)
static DownloadResult download(const DownloadRequest &request, const ProgressCallback &progressCallback=nullptr)
Download a file with optional progress tracking.
static void downloadBatchAsync(const std::vector< DownloadRequest > &requests, const std::function< void(std::vector< DownloadResult >)> &onComplete, const ProgressCallback &onProgress=nullptr)
Download multiple files asynchronously.
static std::vector< DownloadResult > downloadBatch(const std::vector< DownloadRequest > &requests, ProgressCallback progressCallback=nullptr)
Download multiple files sequentially.
static bool isDownloading()
Check if a download is currently in progress.
static std::string calculateChecksum(const std::string &filePath, const std::string &type)
Calculate file checksum.
static void cancel()
Cancel the current download operation.
std::function< void(const DownloadResult &)> CompletionCallback
static bool isUrlAccessible(const std::string &url)
Check if URL is accessible.
static uint64_t getRemoteFileSize(const std::string &url)
Get file size from URL without downloading.
static bool verifyChecksum(const std::string &filePath, const std::string &expected, const std::string &type)
Verify file checksum.
static void downloadAsync(const DownloadRequest &request, const CompletionCallback &onComplete, const ProgressCallback &onProgress=nullptr)
Download a file asynchronously.
std::function< void(const DownloadProgress &)> ProgressCallback
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
bool isHttpUrl(const std::string &url)
const std::regex & kSpeedRegexWithB()
const std::regex & kContentLengthRegex()
const std::regex & kPercentRegex()
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
void storeFuture(std::shared_ptr< std::future< void > > f)
const std::regex & kSpeedRegex()
Progress information for downloads.
std::string statusMessage
std::string currentFile
Current file being processed.
std::string expectedChecksum
std::map< std::string, std::string > headers