From d7389c222094b852265c8d8007875d6a255b36e4 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Mon, 11 Nov 2024 04:26:07 +0300 Subject: [PATCH] add Network.getTotalUpload, getTotalDownload --- src/network/Network.cpp | 29 +++++++++++++++++++++++++++++ src/network/Network.hpp | 5 +++++ test/network/curltest.cpp | 2 ++ 3 files changed, 36 insertions(+) diff --git a/src/network/Network.cpp b/src/network/Network.cpp index bdd2a2acb..b91e51df6 100644 --- a/src/network/Network.cpp +++ b/src/network/Network.cpp @@ -19,6 +19,9 @@ size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) { class CurlHttp : public Http { CURL* curl; + + size_t totalUpload = 0; + size_t totalDownload = 0; public: CurlHttp(CURL* curl) : curl(curl) { } @@ -33,9 +36,27 @@ class CurlHttp : public Http { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); CURLcode res = curl_easy_perform(curl); + if (res == CURLE_OK) { + long size; + if (!curl_easy_getinfo(curl, CURLINFO_REQUEST_SIZE, &size)) { + totalUpload += size; + } + if (!curl_easy_getinfo(curl, CURLINFO_HEADER_SIZE, &size)) { + totalDownload += size; + } + totalDownload += buffer.size(); + } callback(res, std::move(buffer)); } + size_t getTotalUpload() const override { + return totalUpload; + } + + size_t getTotalDownload() const override { + return totalDownload; + } + static std::unique_ptr create() { if (auto curl = curl_easy_init()) { return std::make_unique(curl); @@ -54,6 +75,14 @@ void Network::httpGet(const std::string& url, const OnResponse& callback) { http->get(url, callback); } +size_t Network::getTotalUpload() const { + return http->getTotalUpload(); +} + +size_t Network::getTotalDownload() const { + return http->getTotalDownload(); +} + std::unique_ptr Network::create(const NetworkSettings& settings) { auto http = CurlHttp::create(); return std::make_unique(std::move(http)); diff --git a/src/network/Network.hpp b/src/network/Network.hpp index 2e92a302b..c3a131dae 100644 --- a/src/network/Network.hpp +++ b/src/network/Network.hpp @@ -16,6 +16,8 @@ namespace network { virtual ~Http() {} virtual void get(const std::string& url, const OnResponse& callback) = 0; + virtual size_t getTotalUpload() const = 0; + virtual size_t getTotalDownload() const = 0; }; class Network { @@ -26,6 +28,9 @@ namespace network { void httpGet(const std::string& url, const OnResponse& callback); + size_t getTotalUpload() const; + size_t getTotalDownload() const; + static std::unique_ptr create(const NetworkSettings& settings); }; } diff --git a/test/network/curltest.cpp b/test/network/curltest.cpp index ea4924be7..ade222428 100644 --- a/test/network/curltest.cpp +++ b/test/network/curltest.cpp @@ -15,4 +15,6 @@ TEST(curltest, curltest) { std::cout << value << std::endl; } ); + std::cout << "upload: " << network->getTotalUpload() << " B" << std::endl; + std::cout << "download: " << network->getTotalDownload() << " B" << std::endl; }