| 468 | } |
| 469 | |
| 470 | std::string DownloadAndCacheFile(const std::string& uri) { |
| 471 | const std::vector<std::string> parts = StringSplit(uri, ";"); |
| 472 | THROW_CHECK_EQ(parts.size(), 3) |
| 473 | << "Invalid URI format. Expected: <url>;<name>;<sha256>"; |
| 474 | |
| 475 | const std::string& url = parts[0]; |
| 476 | THROW_CHECK(!url.empty()); |
| 477 | const std::string& name = parts[1]; |
| 478 | THROW_CHECK(!name.empty()); |
| 479 | const std::string& sha256 = parts[2]; |
| 480 | THROW_CHECK_EQ(sha256.size(), 64); |
| 481 | |
| 482 | std::filesystem::path download_cache_dir; |
| 483 | if (download_cache_dir_overwrite.has_value()) { |
| 484 | download_cache_dir = *download_cache_dir_overwrite; |
| 485 | } else { |
| 486 | const std::optional<std::filesystem::path> home_dir = HomeDir(); |
| 487 | THROW_CHECK(home_dir.has_value()); |
| 488 | download_cache_dir = *home_dir / ".cache" / "colmap"; |
| 489 | } |
| 490 | |
| 491 | if (!std::filesystem::exists(download_cache_dir)) { |
| 492 | VLOG(2) << "Creating download cache directory: " << download_cache_dir; |
| 493 | THROW_CHECK(std::filesystem::create_directories(download_cache_dir)); |
| 494 | } |
| 495 | |
| 496 | const auto path = download_cache_dir / (sha256 + "-" + name); |
| 497 | |
| 498 | if (std::filesystem::exists(path)) { |
| 499 | VLOG(2) << "File already downloaded. Skipping download."; |
| 500 | std::vector<char> blob; |
| 501 | ReadBinaryBlob(path.string(), &blob); |
| 502 | THROW_CHECK_EQ(ComputeSHA256({blob.data(), blob.size()}), sha256) |
| 503 | << "The cached file does not match the expected SHA256"; |
| 504 | } else { |
| 505 | LOG(INFO) << "Downloading file from: " << url; |
| 506 | const std::optional<std::string> blob = DownloadFile(url); |
| 507 | THROW_CHECK(blob.has_value()) << "Failed to download file"; |
| 508 | THROW_CHECK_EQ(ComputeSHA256({blob->data(), blob->size()}), sha256) |
| 509 | << "The downloaded file does not match the expected SHA256"; |
| 510 | LOG(INFO) << "Caching file at: " << path; |
| 511 | WriteBinaryBlob(path.string(), {blob->data(), blob->size()}); |
| 512 | } |
| 513 | |
| 514 | return path.string(); |
| 515 | } |
| 516 | |
| 517 | void OverwriteDownloadCacheDir(std::filesystem::path path) { |
| 518 | download_cache_dir_overwrite = std::move(path); |
no test coverage detected