#include "imagestore.h" #include #include #include #include #include Magick::Image imagestore::get(std::string key, std::string url) const { std::lock_guard lock(mutex_); std::string filename = path_ + "/" + key; Magick::Image pic; if (std::ifstream(filename)) { pic.read(filename); } else { // This is to avoid getting rate limited. std::this_thread::sleep_for(std::chrono::milliseconds(50)); std::ostringstream imgbuf; curl::curl_ios imgios(imgbuf); curl::curl_easy imghandle(imgios); imghandle.add(url.c_str()); imghandle.add(30); imghandle.add(300); imghandle.perform(); if (imghandle.get_info().get() != 200) { throw std::runtime_error("Could not download image"); } std::string content_type = imghandle.get_info().get(); if (content_type.substr(0, 6) != "image/") { throw std::runtime_error("Could not download image"); } std::string imgstr = imgbuf.str(); Magick::Blob img(imgstr.c_str(), imgstr.length()); try { pic.read(img); } catch (const Magick::ErrorOption& e) { // Occurs when the the data downloaded from the server is malformed std::cout << "Magick: " << e.what() << std::endl; throw std::runtime_error("Could not download image"); } pic.write(filename); } return pic; } void imagestore::cleanup() const { std::lock_guard lock(mutex_); for (const auto& entry : std::filesystem::directory_iterator(path_)) { std::filesystem::remove_all(entry); } }