abaddon-ppc/filecache.hpp

80 lines
1.9 KiB
C++
Raw Normal View History

2020-09-10 22:28:42 +00:00
#pragma once
#include <curl/curl.h>
2020-09-10 22:28:42 +00:00
#include <functional>
#include <string>
#include <filesystem>
#include <vector>
#include <unordered_set>
2020-09-10 22:28:42 +00:00
#include <unordered_map>
#include <future>
#include <mutex>
#include "util.hpp"
#include "http.hpp"
2020-09-10 22:28:42 +00:00
class FileCacheWorkerThread {
public:
using callback_type = sigc::slot<void(std::string path)>;
FileCacheWorkerThread();
~FileCacheWorkerThread();
void set_file_path(const std::filesystem::path &path);
void add_image(const std::string &string, callback_type callback);
void stop();
private:
void loop();
bool m_stop = false;
std::thread m_thread;
struct QueueEntry {
std::string URL;
callback_type Callback;
};
std::condition_variable m_cv;
mutable std::mutex m_queue_mutex;
std::queue<QueueEntry> m_queue;
std::unordered_map<CURL *, FILE *> m_curl_file_handles;
std::unordered_map<CURL *, std::string> m_handle_urls;
std::unordered_map<std::string, std::filesystem::path> m_paths;
std::unordered_map<std::string, callback_type> m_callbacks;
int m_running_handles = 0;
std::unordered_set<CURL *> m_handles;
CURLM *m_multi_handle;
std::filesystem::path m_data_path;
};
2020-09-10 22:28:42 +00:00
class Cache {
public:
Cache();
~Cache();
using callback_type = std::function<void(std::string)>;
void GetFileFromURL(std::string url, callback_type cb);
2020-09-30 04:12:38 +00:00
std::string GetPathIfCached(std::string url);
2021-01-20 07:26:04 +00:00
void ClearCache();
2020-09-10 22:28:42 +00:00
private:
void CleanupFutures();
void RespondFromPath(std::filesystem::path path, callback_type cb);
void OnResponse(const std::string &url);
void OnFetchComplete(const std::string &url);
2020-09-10 22:28:42 +00:00
std::unordered_map<std::string, std::vector<callback_type>> m_callbacks;
std::vector<std::future<void>> m_futures;
std::filesystem::path m_tmp_path;
2020-10-27 06:29:02 +00:00
mutable std::mutex m_mutex;
FileCacheWorkerThread m_worker;
2020-09-10 22:28:42 +00:00
};