diff options
author | saturneric <[email protected]> | 2023-11-07 07:18:06 +0000 |
---|---|---|
committer | saturneric <[email protected]> | 2023-11-07 07:18:06 +0000 |
commit | 3ad7fecdb6458fdd6f146bed19fe643c7f93e905 (patch) | |
tree | 522f7a5dd0389ad0771d01a50ea49ef646940894 /src | |
parent | refactor: improve the code structure of core (diff) | |
download | GpgFrontend-3ad7fecdb6458fdd6f146bed19fe643c7f93e905.tar.gz GpgFrontend-3ad7fecdb6458fdd6f146bed19fe643c7f93e905.zip |
refactor: remove CommonUtils at core
Diffstat (limited to 'src')
41 files changed, 720 insertions, 584 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 324b3b25..bb8cdf77 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -27,12 +27,12 @@ aux_source_directory(./function/basic CORE_SOURCE) aux_source_directory(./function/result_analyse CORE_SOURCE) aux_source_directory(./function/gpg CORE_SOURCE) -aux_source_directory(./function/aes CORE_SOURCE) aux_source_directory(./function CORE_SOURCE) aux_source_directory(./thread CORE_SOURCE) aux_source_directory(./model CORE_SOURCE) aux_source_directory(./common CORE_SOURCE) aux_source_directory(./module CORE_SOURCE) +aux_source_directory(./utils/aes CORE_SOURCE) aux_source_directory(./utils CORE_SOURCE) aux_source_directory(. CORE_SOURCE) diff --git a/src/core/common/CoreCommonUtil.h b/src/core/common/CoreCommonUtil.h deleted file mode 100644 index e41254c9..00000000 --- a/src/core/common/CoreCommonUtil.h +++ /dev/null @@ -1,84 +0,0 @@ -/**
- * Copyright (C) 2021 Saturneric <[email protected]>
- *
- * This file is part of GpgFrontend.
- *
- * GpgFrontend is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * GpgFrontend is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
- *
- * The initial version of the source code is inherited from
- * the gpg4usb project, which is under GPL-3.0-or-later.
- *
- * All the source code of GpgFrontend was modified and released by
- * Saturneric <[email protected]> starting on May 12, 2021.
- *
- * SPDX-License-Identifier: GPL-3.0-or-later
- *
- */
-
-#pragma once
-
-#include "core/GpgFrontendCore.h"
-
-namespace GpgFrontend {
-
-class GPGFRONTEND_CORE_EXPORT CoreCommonUtil : public QObject {
- Q_OBJECT
- public:
- /**
- * @brief Construct a new Core Common Util object
- *
- */
- static CoreCommonUtil *GetInstance();
-
- /**
- * @brief
- *
- */
- CoreCommonUtil() = default;
-
- /**
- * @brief set a temp cache under a certain key
- *
- */
- void SetTempCacheValue(const std::string &, const std::string &);
-
- /**
- * @brief after get the temp cache, its value will be imediately ease in
- * storage
- *
- * @return std::string
- */
- std::string GetTempCacheValue(const std::string &);
-
- /**
- * @brief imediately ease temp cache in storage
- *
- * @return std::string
- */
- void ResetTempCacheValue(const std::string &);
-
- signals:
-
- /**
- * @brief
- *
- */
- void SignalGnupgNotInstall();
-
- private:
- static std::unique_ptr<CoreCommonUtil> instance_; ///<
- std::map<std::string, std::string> temp_cache_; //<
-};
-
-} // namespace GpgFrontend
diff --git a/src/core/function/ArchiveFileOperator.cpp b/src/core/function/ArchiveFileOperator.cpp index 27d18803..18920e75 100644 --- a/src/core/function/ArchiveFileOperator.cpp +++ b/src/core/function/ArchiveFileOperator.cpp @@ -39,7 +39,7 @@ struct ArchiveStruct { std::string name; }; -int copy_data(struct archive *ar, struct archive *aw) { +auto copy_data(struct archive *ar, struct archive *aw) -> int { int r; const void *buff; size_t size; @@ -112,8 +112,9 @@ void GpgFrontend::ArchiveFileOperator::CreateArchive( auto u8_filename = relative_archive_path.u8string(); - if (!u8_filename.empty() && u8_filename == u8"-") + if (!u8_filename.empty() && u8_filename == u8"-") { throw std::runtime_error("cannot write to stdout"); + } #ifdef WINDOWS archive_write_open_filename_w(a, relative_archive_path.wstring().c_str()); diff --git a/src/core/function/ArchiveFileOperator.h b/src/core/function/ArchiveFileOperator.h index e4bf2011..7cbe644c 100644 --- a/src/core/function/ArchiveFileOperator.h +++ b/src/core/function/ArchiveFileOperator.h @@ -35,13 +35,32 @@ namespace GpgFrontend { class GPGFRONTEND_CORE_EXPORT ArchiveFileOperator { public: + /** + * @brief + * + * @param archive_path + */ static void ListArchive(const std::filesystem::path &archive_path); + /** + * @brief Create a Archive object + * + * @param base_path + * @param archive_path + * @param compress + * @param files + */ static void CreateArchive(const std::filesystem::path &base_path, const std::filesystem::path &archive_path, int compress, const std::vector<std::filesystem::path> &files); + /** + * @brief + * + * @param archive_path + * @param base_path + */ static void ExtractArchive(const std::filesystem::path &archive_path, const std::filesystem::path &base_path); }; diff --git a/src/core/function/CacheManager.cpp b/src/core/function/CacheManager.cpp index 8445c648..161f9a0c 100644 --- a/src/core/function/CacheManager.cpp +++ b/src/core/function/CacheManager.cpp @@ -30,116 +30,238 @@ #include <algorithm> #include <boost/format.hpp> +#include <shared_mutex> +#include <utility> #include "function/DataObjectOperator.h" -GpgFrontend::CacheManager::CacheManager(int channel) - : SingletonFunctionObject<CacheManager>(channel), - m_timer_(new QTimer(this)) { - connect(m_timer_, &QTimer::timeout, this, &CacheManager::flush_cache_storage); - m_timer_->start(15000); +namespace GpgFrontend { - load_all_cache_storage(); -} +template <typename Key, typename Value> +class ThreadSafeMap { + public: + using MapType = std::map<Key, Value>; + using IteratorType = typename MapType::iterator; -void GpgFrontend::CacheManager::SaveCache(std::string key, - const nlohmann::json& value, - bool flush) { - auto data_object_key = get_data_object_key(key); - cache_storage_.insert(key, value); + void insert(const Key& key, const Value& value) { + std::unique_lock lock(mutex_); + map_[key] = value; + } - if (std::find(key_storage_.begin(), key_storage_.end(), key) == - key_storage_.end()) { - SPDLOG_DEBUG("register new key of cache", key); - key_storage_.push_back(key); + auto get(const Key& key) -> std::optional<Value> { + std::shared_lock lock(mutex_); + auto it = map_.find(key); + if (it != map_.end()) { + return it->second; + } + return std::nullopt; } - if (flush) { - flush_cache_storage(); + auto exists(const Key& key) -> bool { + std::shared_lock lock(mutex_); + return map_.count(key) > 0; } -} -nlohmann::json GpgFrontend::CacheManager::LoadCache(std::string key) { - auto data_object_key = get_data_object_key(key); + auto begin() -> IteratorType { return map_mirror_.begin(); } + + auto end() -> IteratorType { return map_mirror_.end(); } - if (!cache_storage_.exists(key)) { - cache_storage_.insert(key, load_cache_storage(key, {})); + auto mirror() -> ThreadSafeMap& { + std::shared_lock lock(mutex_); + map_mirror_ = map_; + return *this; } - auto cache = cache_storage_.get(key); - if (cache) - return *cache; - else - return {}; -} + auto remove(std::string key) -> bool { + std::unique_lock lock(mutex_); + auto it = map_.find(key); + if (it != map_.end()) { + map_.erase(it); + return true; + } + return false; + } + + private: + MapType map_mirror_; + MapType map_; + mutable std::shared_mutex mutex_; +}; -nlohmann::json GpgFrontend::CacheManager::LoadCache( - std::string key, nlohmann::json default_value) { - auto data_object_key = get_data_object_key(key); - if (!cache_storage_.exists(key)) { - cache_storage_.insert(key, load_cache_storage(key, default_value)); +class CacheManager::Impl : public SingletonFunctionObject<CacheManager::Impl> { + public: + Impl(CacheManager* parent, int channel) + : SingletonFunctionObject<CacheManager::Impl>(channel), + parent_(parent), + m_timer_(new QTimer(parent)) { + connect(m_timer_, &QTimer::timeout, parent_, + [this]() { flush_cache_storage(); }); + m_timer_->start(15000); + + load_all_cache_storage(); } - auto cache = cache_storage_.get(key); - if (cache) - return *cache; - else - return {}; -} + void SaveCache(std::string key, const nlohmann::json& value, bool flush) { + auto data_object_key = get_data_object_key(key); + cache_storage_.insert(key, value); -std::string GpgFrontend::CacheManager::get_data_object_key(std::string key) { - return (boost::format("__cache_data_%1%") % key).str(); -} + if (std::find(key_storage_.begin(), key_storage_.end(), key) == + key_storage_.end()) { + SPDLOG_DEBUG("register new key of cache", key); + key_storage_.push_back(key); + } + + if (flush) { + flush_cache_storage(); + } + } -nlohmann::json GpgFrontend::CacheManager::load_cache_storage( - std::string key, nlohmann::json default_value) { - auto data_object_key = get_data_object_key(key); - auto stored_data = - GpgFrontend::DataObjectOperator::GetInstance().GetDataObject( - data_object_key); + auto LoadCache(const std::string& key) -> nlohmann::json { + auto data_object_key = get_data_object_key(key); - if (stored_data.has_value()) { - return stored_data.value(); - } else { - return default_value; + if (!cache_storage_.exists(key)) { + cache_storage_.insert(key, load_cache_storage(key, {})); + } + + auto cache = cache_storage_.get(key); + if (cache) { + return *cache; + } + return {}; } -} -void GpgFrontend::CacheManager::flush_cache_storage() { - for (auto cache : cache_storage_.mirror()) { - auto key = get_data_object_key(cache.first); - SPDLOG_DEBUG("save cache into filesystem, key {}, value size: {}", key, - cache.second.size()); - GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(key, - cache.second); + auto LoadCache(const std::string& key, nlohmann::json default_value) + -> nlohmann::json { + auto data_object_key = get_data_object_key(key); + if (!cache_storage_.exists(key)) { + cache_storage_.insert(key, + load_cache_storage(key, std::move(default_value))); + } + + auto cache = cache_storage_.get(key); + if (cache) { + return *cache; + } + return {}; } - GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(drk_key_, - key_storage_); -} -void GpgFrontend::CacheManager::register_cache_key(std::string key) {} + auto ResetCache(const std::string& key) -> bool { + auto data_object_key = get_data_object_key(key); + return cache_storage_.remove(key); + } -void GpgFrontend::CacheManager::load_all_cache_storage() { - SPDLOG_DEBUG("start to load all cache from file system"); - auto stored_data = - GpgFrontend::DataObjectOperator::GetInstance().GetDataObject(drk_key_); + private: + CacheManager* parent_; + ThreadSafeMap<std::string, nlohmann::json> cache_storage_; + nlohmann::json key_storage_; + QTimer* m_timer_; + const std::string drk_key_ = "__cache_manage_data_register_key_list"; - // get cache data list from file system - nlohmann::json registered_key_list; - if (stored_data.has_value()) { - registered_key_list = std::move(stored_data.value()); + /** + * @brief Get the data object key object + * + * @param key + * @return std::string + */ + static auto get_data_object_key(std::string key) -> std::string { + return (boost::format("__cache_data_%1%") % key).str(); } - if (!registered_key_list.is_array()) { - GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj( - drk_key_, nlohmann::json::array()); - SPDLOG_ERROR("drk_key_ is not an array, abort."); - return; + /** + * @brief + * + * @param key + * @param default_value + * @return nlohmann::json + */ + static auto load_cache_storage(std::string key, nlohmann::json default_value) + -> nlohmann::json { + auto data_object_key = get_data_object_key(std::move(key)); + auto stored_data = + GpgFrontend::DataObjectOperator::GetInstance().GetDataObject( + data_object_key); + + if (stored_data.has_value()) { + return stored_data.value(); + } + return default_value; } - for (auto key : registered_key_list) { - load_cache_storage(key, {}); + /** + * @brief + * + */ + void load_all_cache_storage() { + SPDLOG_DEBUG("start to load all cache from file system"); + auto stored_data = + GpgFrontend::DataObjectOperator::GetInstance().GetDataObject(drk_key_); + + // get cache data list from file system + nlohmann::json registered_key_list; + if (stored_data.has_value()) { + registered_key_list = std::move(stored_data.value()); + } + + if (!registered_key_list.is_array()) { + GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj( + drk_key_, nlohmann::json::array()); + SPDLOG_ERROR("drk_key_ is not an array, abort."); + return; + } + + for (const auto& key : registered_key_list) { + load_cache_storage(key, {}); + } + + key_storage_ = registered_key_list; + } + + /** + * @brief + * + */ + void flush_cache_storage() { + for (const auto& cache : cache_storage_.mirror()) { + auto key = get_data_object_key(cache.first); + SPDLOG_DEBUG("save cache into filesystem, key {}, value size: {}", key, + cache.second.size()); + GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(key, + cache.second); + } + GpgFrontend::DataObjectOperator::GetInstance().SaveDataObj(drk_key_, + key_storage_); } - key_storage_ = registered_key_list; -}
\ No newline at end of file + /** + * @brief + * + * @param key + */ + void register_cache_key(const std::string& key) {} +}; + +CacheManager::CacheManager(int channel) + : SingletonFunctionObject<CacheManager>(channel), + p_(std::make_unique<Impl>(this, channel)) {} + +CacheManager::~CacheManager() = default; + +void CacheManager::SaveCache(std::string key, const nlohmann::json& value, + bool flush) { + p_->SaveCache(std::move(key), value, flush); +} + +auto CacheManager::LoadCache(std::string key) -> nlohmann::json { + return p_->LoadCache(key); +} + +auto CacheManager::LoadCache(std::string key, nlohmann::json default_value) + -> nlohmann::json { + return p_->LoadCache(key, std::move(default_value)); +} + +auto CacheManager::ResetCache(std::string key) -> bool { + return p_->ResetCache(key); +} + +} // namespace GpgFrontend diff --git a/src/core/function/CacheManager.h b/src/core/function/CacheManager.h index 2126decb..49db494e 100644 --- a/src/core/function/CacheManager.h +++ b/src/core/function/CacheManager.h @@ -29,84 +29,34 @@ #pragma once #include <nlohmann/json.hpp> -#include <optional> -#include <shared_mutex> #include "core/function/basic/GpgFunctionObject.h" namespace GpgFrontend { -template <typename Key, typename Value> -class ThreadSafeMap { - public: - using MapType = std::map<Key, Value>; - using IteratorType = typename MapType::iterator; - - void insert(const Key& key, const Value& value) { - std::unique_lock lock(mutex_); - map_[key] = value; - } - - std::optional<Value> get(const Key& key) { - std::shared_lock lock(mutex_); - auto it = map_.find(key); - if (it != map_.end()) { - return it->second; - } - return std::nullopt; - } - - bool exists(const Key& key) { - std::shared_lock lock(mutex_); - return map_.count(key) > 0; - } - - IteratorType begin() { return map_mirror_.begin(); } - - IteratorType end() { return map_mirror_.end(); } - - ThreadSafeMap& mirror() { - std::shared_lock lock(mutex_); - map_mirror_ = map_; - return *this; - } - - private: - MapType map_mirror_; - MapType map_; - mutable std::shared_mutex mutex_; -}; - class GPGFRONTEND_CORE_EXPORT CacheManager : public QObject, public SingletonFunctionObject<CacheManager> { Q_OBJECT public: - CacheManager(int channel = SingletonFunctionObject::GetDefaultChannel()); + explicit CacheManager( + int channel = SingletonFunctionObject::GetDefaultChannel()); + + ~CacheManager() override; void SaveCache(std::string key, const nlohmann::json& value, bool flush = false); - nlohmann::json LoadCache(std::string key); + auto LoadCache(std::string key) -> nlohmann::json; - nlohmann::json LoadCache(std::string key, nlohmann::json default_value); - - private: - std::string get_data_object_key(std::string key); + auto LoadCache(std::string key, nlohmann::json default_value) + -> nlohmann::json; - nlohmann::json load_cache_storage(std::string key, - nlohmann::json default_value); + auto ResetCache(std::string key) -> bool; - void load_all_cache_storage(); - - void flush_cache_storage(); - - void register_cache_key(std::string key); - - ThreadSafeMap<std::string, nlohmann::json> cache_storage_; - nlohmann::json key_storage_; - QTimer* m_timer_; - const std::string drk_key_ = "__cache_manage_data_register_key_list"; + private: + class Impl; + std::unique_ptr<Impl> p_; }; } // namespace GpgFrontend diff --git a/src/core/function/CharsetOperator.cpp b/src/core/function/CharsetOperator.cpp index 28dcec11..8623428d 100644 --- a/src/core/function/CharsetOperator.cpp +++ b/src/core/function/CharsetOperator.cpp @@ -35,14 +35,16 @@ #include <cstddef> -GpgFrontend::CharsetOperator::CharsetInfo GpgFrontend::CharsetOperator::Detect( - const std::string &buffer) { +namespace GpgFrontend { + +auto CharsetOperator::Detect(const std::string &buffer) + -> CharsetOperator::CharsetInfo { const UCharsetMatch *ucm; UErrorCode status = U_ZERO_ERROR; UCharsetDetector *csd = ucsdet_open(&status); status = U_ZERO_ERROR; - if (U_FAILURE(status)) { + if (U_FAILURE(status) != 0) { SPDLOG_ERROR("failed to open charset detector: {}", u_errorName(status)); return {"unknown", "unknown", 0}; } @@ -51,7 +53,7 @@ GpgFrontend::CharsetOperator::CharsetInfo GpgFrontend::CharsetOperator::Detect( status = U_ZERO_ERROR; ucsdet_setText(csd, buffer.data(), buffer.size(), &status); - if (U_FAILURE(status)) { + if (U_FAILURE(status) != 0) { SPDLOG_ERROR("failed to set text to charset detector: {}", u_errorName(status)); return {"unknown", "unknown", 0}; @@ -60,37 +62,37 @@ GpgFrontend::CharsetOperator::CharsetInfo GpgFrontend::CharsetOperator::Detect( status = U_ZERO_ERROR; ucm = ucsdet_detect(csd, &status); - if (U_FAILURE(status)) return {"unknown", "unknown", 0}; + if (U_FAILURE(status) != 0) return {"unknown", "unknown", 0}; status = U_ZERO_ERROR; const char *name = ucsdet_getName(ucm, &status); - if (U_FAILURE(status)) return {"unknown", "unknown", 0}; + if (U_FAILURE(status) != 0) return {"unknown", "unknown", 0}; status = U_ZERO_ERROR; int confidence = ucsdet_getConfidence(ucm, &status); - if (U_FAILURE(status)) return {name, "unknown", 0}; + if (U_FAILURE(status) != 0) return {name, "unknown", 0}; status = U_ZERO_ERROR; const char *language = ucsdet_getLanguage(ucm, &status); - if (U_FAILURE(status)) return {name, "unknown", confidence}; + if (U_FAILURE(status) != 0) return {name, "unknown", confidence}; SPDLOG_DEBUG("Detected charset: {} {} {}", name, language, confidence); return {name, language, confidence}; } -bool GpgFrontend::CharsetOperator::Convert2Utf8(const std::string &buffer, - std::string &out_buffer, - std::string from_charset_name) { +auto CharsetOperator::Convert2Utf8(const std::string &buffer, + std::string &out_buffer, + std::string from_charset_name) -> bool { UErrorCode status = U_ZERO_ERROR; const auto from_encode = std::string("utf-8"); - const auto to_encode = from_charset_name; + const auto &to_encode = from_charset_name; SPDLOG_DEBUG("Converting buffer: {}", buffer.size()); // test if the charset is supported UConverter *conv = ucnv_open(from_encode.c_str(), &status); ucnv_close(conv); - if (U_FAILURE(status)) { + if (U_FAILURE(status) != 0) { SPDLOG_ERROR("failed to open converter: {}, from encode: {}", u_errorName(status), from_encode); return false; @@ -99,14 +101,15 @@ bool GpgFrontend::CharsetOperator::Convert2Utf8(const std::string &buffer, // test if the charset is supported conv = ucnv_open(to_encode.c_str(), &status); ucnv_close(conv); - if (U_FAILURE(status)) { + if (U_FAILURE(status) != 0) { SPDLOG_ERROR("failed to open converter: {}, to encode: {}", u_errorName(status), to_encode); return false; } status = U_ZERO_ERROR; - int32_t target_limit = 0, target_capacity = 0; + int32_t target_limit = 0; + int32_t target_capacity = 0; target_capacity = ucnv_convert(from_encode.c_str(), to_encode.c_str(), nullptr, @@ -120,11 +123,13 @@ bool GpgFrontend::CharsetOperator::Convert2Utf8(const std::string &buffer, out_buffer.size(), buffer.data(), buffer.size(), &status); } - if (U_FAILURE(status)) { + if (U_FAILURE(status) != 0) { SPDLOG_ERROR("failed to convert to utf-8: {}", u_errorName(status)); return false; } SPDLOG_DEBUG("converted buffer: {} bytes", out_buffer.size()); return true; -}
\ No newline at end of file +} + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/CharsetOperator.h b/src/core/function/CharsetOperator.h index 42d6ed4e..c7092797 100644 --- a/src/core/function/CharsetOperator.h +++ b/src/core/function/CharsetOperator.h @@ -36,9 +36,9 @@ class GPGFRONTEND_CORE_EXPORT CharsetOperator { public: using CharsetInfo = std::tuple<std::string, std::string, int>; - static CharsetInfo Detect(const std::string &buffer); + static auto Detect(const std::string &buffer) -> CharsetInfo; - static bool Convert2Utf8(const std::string &buffer, std::string &out_buffer, - std::string from_charset_name); + static auto Convert2Utf8(const std::string &buffer, std::string &out_buffer, + std::string from_charset_name) -> bool; }; } // namespace GpgFrontend diff --git a/src/core/function/CoreSignalStation.cpp b/src/core/function/CoreSignalStation.cpp index 9b1d919c..8cb84743 100644 --- a/src/core/function/CoreSignalStation.cpp +++ b/src/core/function/CoreSignalStation.cpp @@ -29,11 +29,12 @@ #include "core/function/CoreSignalStation.h" std::unique_ptr<GpgFrontend::CoreSignalStation> - GpgFrontend::CoreSignalStation::_instance = nullptr; + GpgFrontend::CoreSignalStation::instance = nullptr; -GpgFrontend::CoreSignalStation* GpgFrontend::CoreSignalStation::GetInstance() { - if (_instance == nullptr) { - _instance = std::make_unique<CoreSignalStation>(); +auto GpgFrontend::CoreSignalStation::GetInstance() + -> GpgFrontend::CoreSignalStation* { + if (instance == nullptr) { + instance = std::make_unique<CoreSignalStation>(); } - return _instance.get(); + return instance.get(); } diff --git a/src/core/function/CoreSignalStation.h b/src/core/function/CoreSignalStation.h index 1a48c14c..31134609 100644 --- a/src/core/function/CoreSignalStation.h +++ b/src/core/function/CoreSignalStation.h @@ -38,7 +38,7 @@ namespace GpgFrontend { */ class GPGFRONTEND_CORE_EXPORT CoreSignalStation : public QObject { Q_OBJECT - static std::unique_ptr<CoreSignalStation> _instance; + static std::unique_ptr<CoreSignalStation> instance; public: /** @@ -46,7 +46,7 @@ class GPGFRONTEND_CORE_EXPORT CoreSignalStation : public QObject { * * @return SignalStation* */ - static CoreSignalStation* GetInstance(); + static auto GetInstance() -> CoreSignalStation*; signals: @@ -61,6 +61,12 @@ class GPGFRONTEND_CORE_EXPORT CoreSignalStation : public QObject { * */ void SignalNeedUserInputPassphrase(); + + /** + * @brief + * + */ + void SignalGnupgNotInstall(); }; } // namespace GpgFrontend diff --git a/src/core/function/DataObjectOperator.cpp b/src/core/function/DataObjectOperator.cpp index 2fb794c5..a55fe79a 100644 --- a/src/core/function/DataObjectOperator.cpp +++ b/src/core/function/DataObjectOperator.cpp @@ -35,7 +35,9 @@ #include "core/function/PassphraseGenerator.h" #include "core/utils/IOUtils.h" -void GpgFrontend::DataObjectOperator::init_app_secure_key() { +namespace GpgFrontend { + +void DataObjectOperator::init_app_secure_key() { SPDLOG_DEBUG("initializing application secure key"); WriteFileStd(app_secure_key_path_, PassphraseGenerator::GetInstance().Generate(256)); @@ -44,7 +46,7 @@ void GpgFrontend::DataObjectOperator::init_app_secure_key() { std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); } -GpgFrontend::DataObjectOperator::DataObjectOperator(int channel) +DataObjectOperator::DataObjectOperator(int channel) : SingletonFunctionObject<DataObjectOperator>(channel) { if (!is_directory(app_secure_path_)) create_directory(app_secure_path_); @@ -65,11 +67,12 @@ GpgFrontend::DataObjectOperator::DataObjectOperator(int channel) if (!exists(app_data_objs_path_)) create_directory(app_data_objs_path_); } -std::string GpgFrontend::DataObjectOperator::SaveDataObj( - const std::string& _key, const nlohmann::json& value) { - std::string _hash_obj_key = {}; +auto DataObjectOperator::SaveDataObj(const std::string& _key, + const nlohmann::json& value) + -> std::string { + std::string hash_obj_key = {}; if (_key.empty()) { - _hash_obj_key = + hash_obj_key = QCryptographicHash::hash( hash_key_ + QByteArray::fromStdString( PassphraseGenerator::GetInstance().Generate(32) + @@ -79,39 +82,39 @@ std::string GpgFrontend::DataObjectOperator::SaveDataObj( .toHex() .toStdString(); } else { - _hash_obj_key = + hash_obj_key = QCryptographicHash::hash(hash_key_ + QByteArray::fromStdString(_key), QCryptographicHash::Sha256) .toHex() .toStdString(); } - const auto obj_path = app_data_objs_path_ / _hash_obj_key; + const auto obj_path = app_data_objs_path_ / hash_obj_key; QAESEncryption encryption(QAESEncryption::AES_256, QAESEncryption::ECB, QAESEncryption::Padding::ISO); auto encoded = encryption.encode(QByteArray::fromStdString(to_string(value)), hash_key_); - SPDLOG_DEBUG("saving data object {} to {} , size: {} bytes", _hash_obj_key, + SPDLOG_DEBUG("saving data object {} to {} , size: {} bytes", hash_obj_key, obj_path.u8string(), encoded.size()); WriteFileStd(obj_path.u8string(), encoded.toStdString()); - return _key.empty() ? _hash_obj_key : std::string(); + return _key.empty() ? hash_obj_key : std::string(); } -std::optional<nlohmann::json> GpgFrontend::DataObjectOperator::GetDataObject( - const std::string& _key) { +auto DataObjectOperator::GetDataObject(const std::string& _key) + -> std::optional<nlohmann::json> { try { SPDLOG_DEBUG("get data object {}", _key); - auto _hash_obj_key = + auto hash_obj_key = QCryptographicHash::hash(hash_key_ + QByteArray::fromStdString(_key), QCryptographicHash::Sha256) .toHex() .toStdString(); - const auto obj_path = app_data_objs_path_ / _hash_obj_key; + const auto obj_path = app_data_objs_path_ / hash_obj_key; if (!std::filesystem::exists(obj_path)) { SPDLOG_ERROR("data object not found :{}", _key); @@ -145,13 +148,13 @@ std::optional<nlohmann::json> GpgFrontend::DataObjectOperator::GetDataObject( } } -std::optional<nlohmann::json> -GpgFrontend::DataObjectOperator::GetDataObjectByRef(const std::string& _ref) { +auto DataObjectOperator::GetDataObjectByRef(const std::string& _ref) + -> std::optional<nlohmann::json> { if (_ref.size() != 64) return {}; try { - const auto& _hash_obj_key = _ref; - const auto obj_path = app_data_objs_path_ / _hash_obj_key; + const auto& hash_obj_key = _ref; + const auto obj_path = app_data_objs_path_ / hash_obj_key; if (!std::filesystem::exists(obj_path)) return {}; @@ -170,3 +173,4 @@ GpgFrontend::DataObjectOperator::GetDataObjectByRef(const std::string& _ref) { return {}; } } +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/DataObjectOperator.h b/src/core/function/DataObjectOperator.h index b30bce83..06455211 100644 --- a/src/core/function/DataObjectOperator.h +++ b/src/core/function/DataObjectOperator.h @@ -48,11 +48,13 @@ class GPGFRONTEND_CORE_EXPORT DataObjectOperator explicit DataObjectOperator( int channel = SingletonFunctionObject::GetDefaultChannel()); - std::string SaveDataObj(const std::string &_key, const nlohmann::json &value); + auto SaveDataObj(const std::string &_key, const nlohmann::json &value) + -> std::string; - std::optional<nlohmann::json> GetDataObject(const std::string &_key); + auto GetDataObject(const std::string &_key) -> std::optional<nlohmann::json>; - std::optional<nlohmann::json> GetDataObjectByRef(const std::string &_ref); + auto GetDataObjectByRef(const std::string &_ref) + -> std::optional<nlohmann::json>; private: /** diff --git a/src/core/function/GlobalSettingStation.cpp b/src/core/function/GlobalSettingStation.cpp index 5a6852f7..5dc10dc1 100644 --- a/src/core/function/GlobalSettingStation.cpp +++ b/src/core/function/GlobalSettingStation.cpp @@ -28,21 +28,20 @@ #include "GlobalSettingStation.h" -#include "GpgFrontendBuildInstallInfo.h" +#include "core/utils/FilesystemUtils.h" #include "core/utils/IOUtils.h" namespace GpgFrontend { -class GlobalSettingStation::Impl { +class GlobalSettingStation::Impl + : SingletonFunctionObject<GlobalSettingStation::Impl> { public: /** * @brief Construct a new Global Setting Station object * */ - explicit Impl(int channel) noexcept { - using namespace std::filesystem; - using namespace libconfig; - + explicit Impl(int channel) noexcept + : SingletonFunctionObject<GlobalSettingStation::Impl>(channel) { SPDLOG_INFO("app path: {}", app_path_.u8string()); SPDLOG_INFO("app configure path: {}", app_configure_path_.u8string()); SPDLOG_INFO("app data path: {}", app_data_path_.u8string()); @@ -54,8 +53,9 @@ class GlobalSettingStation::Impl { SPDLOG_INFO("app data objects files total size: {}", GetDataObjectsFilesSize()); - if (!is_directory(app_configure_path_)) + if (!is_directory(app_configure_path_)) { create_directory(app_configure_path_); + } if (!is_directory(app_data_path_)) create_directory(app_data_path_); if (!is_directory(app_log_path_)) create_directory(app_log_path_); if (!is_directory(config_dir_path_)) create_directory(config_dir_path_); @@ -66,7 +66,7 @@ class GlobalSettingStation::Impl { SPDLOG_DEBUG("user interface configuration successfully written to {}", main_config_path_.u8string()); - } catch (const FileIOException &fioex) { + } catch (const libconfig::FileIOException &fioex) { SPDLOG_DEBUG( "i/o error while writing UserInterface configuration file {}", main_config_path_.u8string()); @@ -76,31 +76,34 @@ class GlobalSettingStation::Impl { this->ui_cfg_.readFile(main_config_path_.u8string().c_str()); SPDLOG_DEBUG("user interface configuration successfully read from {}", main_config_path_.u8string()); - } catch (const FileIOException &fioex) { + } catch (const libconfig::FileIOException &fioex) { SPDLOG_ERROR("i/o error while reading UserInterface configure file"); - } catch (const ParseException &pex) { + } catch (const libconfig::ParseException &pex) { SPDLOG_ERROR("parse error at {} : {} - {}", pex.getFile(), pex.getLine(), pex.getError()); } } } - libconfig::Setting &GetMainSettings() noexcept { return ui_cfg_.getRoot(); } + auto GetMainSettings() noexcept -> libconfig::Setting & { + return ui_cfg_.getRoot(); + } - std::string GetLogFilesSize() const { - return get_human_readable_size( - get_files_size_at_path(app_log_path_, "*.log")); + [[nodiscard]] auto GetLogFilesSize() const -> std::string { + return GetHumanFriendlyFileSize(GetFileSizeByPath(app_log_path_, "*.log")); } - std::string GetDataObjectsFilesSize() const { - return get_human_readable_size( - get_files_size_at_path(app_data_objs_path_, "*")); + [[nodiscard]] auto GetDataObjectsFilesSize() const -> std::string { + return GetHumanFriendlyFileSize( + GetFileSizeByPath(app_data_objs_path_, "*")); } - void ClearAllLogFiles() const { delete_all_files(app_log_path_, "*.log"); } + void ClearAllLogFiles() const { + DeleteAllFilesByPattern(app_log_path_, "*.log"); + } void ClearAllDataObjects() const { - delete_all_files(app_data_objs_path_, "*"); + DeleteAllFilesByPattern(app_data_objs_path_, "*"); } /** @@ -109,7 +112,7 @@ class GlobalSettingStation::Impl { * @return libconfig::Setting& */ template <typename T> - T LookupSettings(std::string path, T default_value) noexcept { + auto LookupSettings(std::string path, T default_value) noexcept -> T { T value = default_value; try { value = static_cast<T>(GetMainSettings().lookup(path)); @@ -124,9 +127,11 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetAppDir() const { return app_path_; } + [[nodiscard]] auto GetAppDir() const -> std::filesystem::path { + return app_path_; + } - [[nodiscard]] std::filesystem::path GetAppDataPath() const { + [[nodiscard]] auto GetAppDataPath() const -> std::filesystem::path { return app_data_path_; } @@ -135,7 +140,7 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetLogDir() const { + [[nodiscard]] auto GetLogDir() const -> std::filesystem::path { return app_log_path_; } @@ -144,7 +149,7 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetStandaloneDatabaseDir() const { + [[nodiscard]] auto GetStandaloneDatabaseDir() const -> std::filesystem::path { auto db_path = app_configure_path_ / "db"; if (!std::filesystem::exists(db_path)) { std::filesystem::create_directory(db_path); @@ -152,7 +157,7 @@ class GlobalSettingStation::Impl { return db_path; } - [[nodiscard]] std::filesystem::path GetAppConfigPath() const { + [[nodiscard]] auto GetAppConfigPath() const -> std::filesystem::path { return app_configure_path_; } @@ -161,7 +166,7 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetStandaloneGpgBinDir() const { + [[nodiscard]] auto GetStandaloneGpgBinDir() const -> std::filesystem::path { return app_resource_path_ / "gpg1.4" / "gpg"; } @@ -170,7 +175,7 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetLocaleDir() const { + [[nodiscard]] auto GetLocaleDir() const -> std::filesystem::path { return app_locale_path_; } @@ -179,7 +184,7 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetResourceDir() const { + [[nodiscard]] auto GetResourceDir() const -> std::filesystem::path { return app_resource_path_; } @@ -188,7 +193,7 @@ class GlobalSettingStation::Impl { * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetCertsDir() const { + [[nodiscard]] auto GetCertsDir() const -> std::filesystem::path { return app_resource_path_ / "certs"; } @@ -197,13 +202,12 @@ class GlobalSettingStation::Impl { * */ void SyncSettings() noexcept { - using namespace libconfig; try { ui_cfg_.writeFile(main_config_path_.u8string().c_str()); SPDLOG_DEBUG("updated ui configuration successfully written to {}", main_config_path_.u8string()); - } catch (const FileIOException &fioex) { + } catch (const libconfig::FileIOException &fioex) { SPDLOG_ERROR("i/o error while writing ui configuration file: {}", main_config_path_.u8string()); } @@ -254,61 +258,6 @@ class GlobalSettingStation::Impl { * */ void init_app_secure_key() {} - - /** - * @brief - * - */ - int64_t get_files_size_at_path(std::filesystem::path path, - std::string filename_pattern) const { - auto dir = QDir(QString::fromStdString(path.u8string())); - QFileInfoList fileList = dir.entryInfoList( - QStringList() << QString::fromStdString(filename_pattern), QDir::Files); - qint64 totalSize = 0; - - for (const QFileInfo &fileInfo : fileList) { - totalSize += fileInfo.size(); - } - return totalSize; - } - - /** - * @brief - * - */ - std::string get_human_readable_size(int64_t size) const { - double num = size; - QStringList list; - list << "KB" - << "MB" - << "GB" - << "TB"; - - QStringListIterator i(list); - QString unit("bytes"); - - while (num >= 1024.0 && i.hasNext()) { - unit = i.next(); - num /= 1024.0; - } - return (QString().setNum(num, 'f', 2) + " " + unit).toStdString(); - } - - /** - * @brief - * - */ - void delete_all_files(std::filesystem::path path, - std::string filename_pattern) const { - auto dir = QDir(QString::fromStdString(path.u8string())); - - QStringList logFiles = dir.entryList( - QStringList() << QString::fromStdString(filename_pattern), QDir::Files); - - for (const auto &file : logFiles) { - QFile::remove(dir.absoluteFilePath(file)); - } - } }; GlobalSettingStation::GlobalSettingStation(int channel) noexcept @@ -319,51 +268,54 @@ GlobalSettingStation::~GlobalSettingStation() noexcept = default; void GlobalSettingStation::SyncSettings() noexcept { p_->SyncSettings(); } -libconfig::Setting &GlobalSettingStation::GetMainSettings() noexcept { +auto GlobalSettingStation::GetMainSettings() noexcept -> libconfig::Setting & { return p_->GetMainSettings(); } -std::filesystem::path GlobalSettingStation::GetAppDir() const { +auto GlobalSettingStation::GetAppDir() const -> std::filesystem::path { return p_->GetAppDir(); } -std::filesystem::path GlobalSettingStation::GetAppDataPath() const { +auto GlobalSettingStation::GetAppDataPath() const -> std::filesystem::path { return p_->GetAppDataPath(); } -[[nodiscard]] std::filesystem::path GlobalSettingStation::GetLogDir() const { +[[nodiscard]] auto GlobalSettingStation::GetLogDir() const + -> std::filesystem::path { return p_->GetLogDir(); } -std::filesystem::path GlobalSettingStation::GetStandaloneDatabaseDir() const { +auto GlobalSettingStation::GetStandaloneDatabaseDir() const + -> std::filesystem::path { return p_->GetStandaloneDatabaseDir(); } -std::filesystem::path GlobalSettingStation::GetAppConfigPath() const { +auto GlobalSettingStation::GetAppConfigPath() const -> std::filesystem::path { return p_->GetAppConfigPath(); } -std::filesystem::path GlobalSettingStation::GetStandaloneGpgBinDir() const { +auto GlobalSettingStation::GetStandaloneGpgBinDir() const + -> std::filesystem::path { return p_->GetStandaloneGpgBinDir(); } -std::filesystem::path GlobalSettingStation::GetLocaleDir() const { +auto GlobalSettingStation::GetLocaleDir() const -> std::filesystem::path { return p_->GetLocaleDir(); } -std::filesystem::path GlobalSettingStation::GetResourceDir() const { +auto GlobalSettingStation::GetResourceDir() const -> std::filesystem::path { return p_->GetResourceDir(); } -std::filesystem::path GlobalSettingStation::GetCertsDir() const { +auto GlobalSettingStation::GetCertsDir() const -> std::filesystem::path { return p_->GetCertsDir(); } -std::string GlobalSettingStation::GetLogFilesSize() const { +auto GlobalSettingStation::GetLogFilesSize() const -> std::string { return p_->GetLogFilesSize(); } -std::string GlobalSettingStation::GetDataObjectsFilesSize() const { +auto GlobalSettingStation::GetDataObjectsFilesSize() const -> std::string { return p_->GetDataObjectsFilesSize(); } diff --git a/src/core/function/GlobalSettingStation.h b/src/core/function/GlobalSettingStation.h index fc0197be..18f42db1 100644 --- a/src/core/function/GlobalSettingStation.h +++ b/src/core/function/GlobalSettingStation.h @@ -62,71 +62,79 @@ class GPGFRONTEND_CORE_EXPORT GlobalSettingStation * * @return libconfig::Setting& */ - libconfig::Setting &GetMainSettings() noexcept; + auto GetMainSettings() noexcept -> libconfig::Setting &; /** * @brief Get the App Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetAppDir() const; + [[nodiscard]] auto GetAppDir() const -> std::filesystem::path; /** * @brief Gets the application data directory. * @return Path to the application data directory. */ - [[nodiscard]] std::filesystem::path GetAppDataPath() const; + [[nodiscard]] auto GetAppDataPath() const -> std::filesystem::path; /** * @brief Get the Log Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetLogDir() const; + [[nodiscard]] auto GetLogDir() const -> std::filesystem::path; /** * @brief Get the Standalone Database Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetStandaloneDatabaseDir() const; + [[nodiscard]] auto GetStandaloneDatabaseDir() const -> std::filesystem::path; - [[nodiscard]] std::filesystem::path GetAppConfigPath() const; + [[nodiscard]] auto GetAppConfigPath() const -> std::filesystem::path; /** * @brief Get the Standalone Gpg Bin Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetStandaloneGpgBinDir() const; + [[nodiscard]] auto GetStandaloneGpgBinDir() const -> std::filesystem::path; /** * @brief Get the Locale Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetLocaleDir() const; + [[nodiscard]] auto GetLocaleDir() const -> std::filesystem::path; /** * @brief Get the Resource Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetResourceDir() const; + [[nodiscard]] auto GetResourceDir() const -> std::filesystem::path; /** * @brief Get the Certs Dir object * * @return std::filesystem::path */ - [[nodiscard]] std::filesystem::path GetCertsDir() const; + [[nodiscard]] auto GetCertsDir() const -> std::filesystem::path; - [[nodiscard]] std::string GetLogFilesSize() const; + [[nodiscard]] auto GetLogFilesSize() const -> std::string; - [[nodiscard]] std::string GetDataObjectsFilesSize() const; + [[nodiscard]] auto GetDataObjectsFilesSize() const -> std::string; + /** + * @brief clear all log files + * + */ void ClearAllLogFiles() const; + /** + * @brief clear all data objects + * + */ void ClearAllDataObjects() const; /** @@ -142,7 +150,7 @@ class GPGFRONTEND_CORE_EXPORT GlobalSettingStation * @return The setting value. */ template <typename T> - T LookupSettings(std::string path, T default_value) noexcept { + auto LookupSettings(std::string path, T default_value) noexcept -> T { T value = default_value; try { value = static_cast<T>(GetMainSettings().lookup(path)); diff --git a/src/core/function/KeyPackageOperator.cpp b/src/core/function/KeyPackageOperator.cpp index 3beaad32..6452c91e 100644 --- a/src/core/function/KeyPackageOperator.cpp +++ b/src/core/function/KeyPackageOperator.cpp @@ -40,17 +40,17 @@ namespace GpgFrontend { -bool KeyPackageOperator::GeneratePassphrase( - const std::filesystem::path& phrase_path, std::string& phrase) { +auto KeyPackageOperator::GeneratePassphrase( + const std::filesystem::path& phrase_path, std::string& phrase) -> bool { phrase = PassphraseGenerator::GetInstance().Generate(256); SPDLOG_DEBUG("generated passphrase: {} bytes", phrase.size()); return WriteFileStd(phrase_path, phrase); } -bool KeyPackageOperator::GenerateKeyPackage( +auto KeyPackageOperator::GenerateKeyPackage( const std::filesystem::path& key_package_path, const std::string& key_package_name, KeyIdArgsListPtr& key_ids, - std::string& phrase, bool secret) { + std::string& phrase, bool secret) -> bool { SPDLOG_DEBUG("generating key package: {}", key_package_name); ByteArrayPtr key_export_data = nullptr; @@ -72,10 +72,10 @@ bool KeyPackageOperator::GenerateKeyPackage( return WriteFileStd(key_package_path, encoded.toStdString()); } -bool KeyPackageOperator::ImportKeyPackage( +auto KeyPackageOperator::ImportKeyPackage( const std::filesystem::path& key_package_path, - const std::filesystem::path& phrase_path, - GpgFrontend::GpgImportInformation& import_info) { + const std::filesystem::path& phrase_path, GpgImportInformation& import_info) + -> bool { SPDLOG_DEBUG("importing key package: {]", key_package_path.u8string()); std::string encrypted_data; @@ -116,7 +116,7 @@ bool KeyPackageOperator::ImportKeyPackage( return true; } -std::string KeyPackageOperator::GenerateKeyPackageName() { +auto KeyPackageOperator::GenerateKeyPackageName() -> std::string { return generate_key_package_name(); } @@ -125,7 +125,7 @@ std::string KeyPackageOperator::GenerateKeyPackageName() { * * @return std::string key package name */ -std::string KeyPackageOperator::generate_key_package_name() { +auto KeyPackageOperator::generate_key_package_name() -> std::string { std::random_device rd_; ///< Random device auto mt_ = std::mt19937(rd_()); ///< Mersenne twister diff --git a/src/core/function/KeyPackageOperator.h b/src/core/function/KeyPackageOperator.h index 7d194028..26939271 100644 --- a/src/core/function/KeyPackageOperator.h +++ b/src/core/function/KeyPackageOperator.h @@ -28,7 +28,6 @@ #pragma once -#include "core/GpgFrontendCore.h" #include "core/function/gpg/GpgKeyImportExporter.h" namespace GpgFrontend { @@ -47,15 +46,15 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { * @return true if passphrase was generated and saved * @return false if passphrase was not generated and saved */ - static bool GeneratePassphrase(const std::filesystem::path &phrase_path, - std::string &phrase); + static auto GeneratePassphrase(const std::filesystem::path &phrase_path, + std::string &phrase) -> bool; /** * @brief generate the name of the key package * * @return std::string name of the key package */ - static std::string GenerateKeyPackageName(); + static auto GenerateKeyPackageName() -> std::string; /** * @brief generate key package @@ -68,10 +67,10 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { * @return true if key package was generated * @return false if key package was not generated */ - static bool GenerateKeyPackage(const std::filesystem::path &key_package_path, + static auto GenerateKeyPackage(const std::filesystem::path &key_package_path, const std::string &key_package_name, KeyIdArgsListPtr &key_ids, std::string &phrase, - bool secret); + bool secret) -> bool; /** * @brief import key package @@ -82,9 +81,10 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { * @return true if key package was imported * @return false if key package was not imported */ - static bool ImportKeyPackage(const std::filesystem::path &key_package_path, + static auto ImportKeyPackage(const std::filesystem::path &key_package_path, const std::filesystem::path &phrase_path, - GpgFrontend::GpgImportInformation &import_info); + GpgFrontend::GpgImportInformation &import_info) + -> bool; private: /** @@ -92,6 +92,6 @@ class GPGFRONTEND_CORE_EXPORT KeyPackageOperator { * * @return std::string key package name */ - static std::string generate_key_package_name(); + static auto generate_key_package_name() -> std::string; }; } // namespace GpgFrontend diff --git a/src/core/function/PassphraseGenerator.cpp b/src/core/function/PassphraseGenerator.cpp index 261f1606..6d0db65d 100644 --- a/src/core/function/PassphraseGenerator.cpp +++ b/src/core/function/PassphraseGenerator.cpp @@ -32,11 +32,11 @@ namespace GpgFrontend { -std::string PassphraseGenerator::Generate(int len) { +auto PassphraseGenerator::Generate(int len) -> std::string { std::uniform_int_distribution<int> dist(999, 99999); auto file_string = boost::format("KeyPackage_%1%") % dist(mt_); - static const char alphanum[] = + static const char kAlphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; @@ -44,7 +44,7 @@ std::string PassphraseGenerator::Generate(int len) { tmp_str.reserve(len); for (int i = 0; i < len; ++i) { - tmp_str += alphanum[dist(mt_) % (sizeof(alphanum) - 1)]; + tmp_str += kAlphanum[dist(mt_) % (sizeof(kAlphanum) - 1)]; } return tmp_str; } diff --git a/src/core/function/PassphraseGenerator.h b/src/core/function/PassphraseGenerator.h index d4bb7809..19ecbb08 100644 --- a/src/core/function/PassphraseGenerator.h +++ b/src/core/function/PassphraseGenerator.h @@ -28,7 +28,6 @@ #pragma once -#include "core/GpgFrontendCore.h" #include "core/function/basic/GpgFunctionObject.h" namespace GpgFrontend { @@ -56,8 +55,9 @@ class GPGFRONTEND_CORE_EXPORT PassphraseGenerator * @param len length of the passphrase * @return std::string passphrase */ - std::string Generate(int len); + auto Generate(int len) -> std::string; + private: std::random_device rd_; ///< Random device std::mt19937 mt_ = std::mt19937(rd_()); ///< Mersenne twister }; diff --git a/src/core/function/gpg/GpgContext.cpp b/src/core/function/gpg/GpgContext.cpp index 3df684ea..fe8dc5cd 100644 --- a/src/core/function/gpg/GpgContext.cpp +++ b/src/core/function/gpg/GpgContext.cpp @@ -32,7 +32,6 @@ #include <gpgme.h> #include <unistd.h> -#include "core/common/CoreCommonUtil.h" #include "core/function/CoreSignalStation.h" #include "core/function/basic/GpgFunctionObject.h" #include "core/function/gpg/GpgCommandExecutor.h" @@ -40,6 +39,7 @@ #include "core/module/ModuleManager.h" #include "core/thread/Task.h" #include "core/thread/TaskRunnerGetter.h" +#include "core/utils/CacheUtils.h" #include "core/utils/CommonUtils.h" #include "core/utils/GpgUtils.h" @@ -251,8 +251,7 @@ class GpgContext::Impl : public SingletonFunctionObject<GpgContext::Impl> { return gpgme_error_from_errno(GPG_ERR_CANCELED); } - std::string passphrase = - CoreCommonUtil::GetInstance()->GetTempCacheValue("__key_passphrase"); + std::string passphrase = GetTempCacheValue("__key_passphrase"); // no pawword is an error situation if (passphrase.empty()) { // user input passphrase diff --git a/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp b/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp index 4426d3b9..9273c850 100644 --- a/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgDecryptResultAnalyse.cpp @@ -35,7 +35,7 @@ GpgFrontend::GpgDecryptResultAnalyse::GpgDecryptResultAnalyse( GpgError m_error, GpgDecrResult m_result) : error_(m_error), result_(std::move(m_result)) {} -void GpgFrontend::GpgDecryptResultAnalyse::do_analyse() { +void GpgFrontend::GpgDecryptResultAnalyse::doAnalyse() { stream_ << "[#] " << _("Decrypt Operation"); if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { @@ -43,7 +43,7 @@ void GpgFrontend::GpgDecryptResultAnalyse::do_analyse() { } else { stream_ << "[" << _("Failed") << "] " << gpgme_strerror(error_) << std::endl; - set_status(-1); + setStatus(-1); if (result_ != nullptr && result_->unsupported_algorithm != nullptr) { stream_ << "------------>" << std::endl; stream_ << _("Unsupported Algo") << ": " << result_->unsupported_algorithm @@ -61,7 +61,7 @@ void GpgFrontend::GpgDecryptResultAnalyse::do_analyse() { stream_ << _("MIME") << ": " << _("true") << std::endl; } - auto recipient = result_->recipients; + auto *recipient = result_->recipients; if (recipient != nullptr) stream_ << _("Recipient(s)") << ": " << std::endl; while (recipient != nullptr) { print_recipient(stream_, recipient); @@ -87,7 +87,7 @@ void GpgFrontend::GpgDecryptResultAnalyse::print_recipient( } } else { stream << "<" << _("Unknown") << ">"; - set_status(0); + setStatus(0); } stream << std::endl; diff --git a/src/core/function/result_analyse/GpgDecryptResultAnalyse.h b/src/core/function/result_analyse/GpgDecryptResultAnalyse.h index de339ba0..55b9afee 100644 --- a/src/core/function/result_analyse/GpgDecryptResultAnalyse.h +++ b/src/core/function/result_analyse/GpgDecryptResultAnalyse.h @@ -29,7 +29,6 @@ #pragma once #include "GpgResultAnalyse.h" -#include "core/GpgConstants.h" namespace GpgFrontend { @@ -53,7 +52,7 @@ class GPGFRONTEND_CORE_EXPORT GpgDecryptResultAnalyse * @brief * */ - void do_analyse() final; + void doAnalyse() final; private: /** diff --git a/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp b/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp index 684fff07..9f523330 100644 --- a/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgEncryptResultAnalyse.cpp @@ -32,24 +32,24 @@ GpgFrontend::GpgEncryptResultAnalyse::GpgEncryptResultAnalyse( GpgError error, GpgEncrResult result) : error_(error), result_(std::move(result)) {} -void GpgFrontend::GpgEncryptResultAnalyse::do_analyse() { +void GpgFrontend::GpgEncryptResultAnalyse::doAnalyse() { SPDLOG_DEBUG("start encrypt result analyse"); stream_ << "[#] " << _("Encrypt Operation") << " "; - if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) + if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { stream_ << "[" << _("Success") << "]" << std::endl; - else { + } else { stream_ << "[" << _("Failed") << "] " << gpgme_strerror(error_) << std::endl; - set_status(-1); + setStatus(-1); } - if (!~status_) { + if ((~status_) == 0) { stream_ << "------------>" << std::endl; if (result_ != nullptr) { stream_ << _("Invalid Recipients") << ": " << std::endl; - auto inv_reci = result_->invalid_recipients; + auto *inv_reci = result_->invalid_recipients; while (inv_reci != nullptr) { stream_ << _("Fingerprint") << ": " << inv_reci->fpr << std::endl; stream_ << _("Reason") << ": " << gpgme_strerror(inv_reci->reason) diff --git a/src/core/function/result_analyse/GpgEncryptResultAnalyse.h b/src/core/function/result_analyse/GpgEncryptResultAnalyse.h index 7c976c17..13f0a3b6 100644 --- a/src/core/function/result_analyse/GpgEncryptResultAnalyse.h +++ b/src/core/function/result_analyse/GpgEncryptResultAnalyse.h @@ -29,7 +29,6 @@ #pragma once #include "GpgResultAnalyse.h" -#include "core/GpgConstants.h" namespace GpgFrontend { /** @@ -52,7 +51,7 @@ class GPGFRONTEND_CORE_EXPORT GpgEncryptResultAnalyse * @brief * */ - void do_analyse() final; + void doAnalyse() final; private: GpgError error_; ///< diff --git a/src/core/function/result_analyse/GpgResultAnalyse.cpp b/src/core/function/result_analyse/GpgResultAnalyse.cpp index a5b38a6b..87027560 100644 --- a/src/core/function/result_analyse/GpgResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgResultAnalyse.cpp @@ -28,19 +28,20 @@ #include "GpgResultAnalyse.h" -const std::string GpgFrontend::GpgResultAnalyse::GetResultReport() const { +auto GpgFrontend::GpgResultAnalyse::GetResultReport() const + -> const std::string { return stream_.str(); } -int GpgFrontend::GpgResultAnalyse::GetStatus() const { return status_; } +auto GpgFrontend::GpgResultAnalyse::GetStatus() const -> int { return status_; } -void GpgFrontend::GpgResultAnalyse::set_status(int m_status) { +void GpgFrontend::GpgResultAnalyse::setStatus(int m_status) { if (m_status < status_) status_ = m_status; } void GpgFrontend::GpgResultAnalyse::Analyse() { if (!analysed_) { - do_analyse(); + doAnalyse(); analysed_ = true; } } diff --git a/src/core/function/result_analyse/GpgResultAnalyse.h b/src/core/function/result_analyse/GpgResultAnalyse.h index de4551c1..b95eb2f0 100644 --- a/src/core/function/result_analyse/GpgResultAnalyse.h +++ b/src/core/function/result_analyse/GpgResultAnalyse.h @@ -52,14 +52,14 @@ class GPGFRONTEND_CORE_EXPORT GpgResultAnalyse { * * @return const std::string */ - [[nodiscard]] const std::string GetResultReport() const; + [[nodiscard]] auto GetResultReport() const -> const std::string; /** * @brief Get the Status object * * @return int */ - [[nodiscard]] int GetStatus() const; + [[nodiscard]] auto GetStatus() const -> int; /** * @brief @@ -72,14 +72,14 @@ class GPGFRONTEND_CORE_EXPORT GpgResultAnalyse { * @brief * */ - virtual void do_analyse() = 0; + virtual void doAnalyse() = 0; /** * @brief Set the status object * * @param m_status */ - void set_status(int m_status); + void setStatus(int m_status); std::stringstream stream_; ///< int status_ = 1; ///< diff --git a/src/core/function/result_analyse/GpgSignResultAnalyse.cpp b/src/core/function/result_analyse/GpgSignResultAnalyse.cpp index a33836bb..5925ced9 100644 --- a/src/core/function/result_analyse/GpgSignResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgSignResultAnalyse.cpp @@ -34,24 +34,24 @@ GpgFrontend::GpgSignResultAnalyse::GpgSignResultAnalyse(GpgError error, GpgSignResult result) : error_(error), result_(std::move(result)) {} -void GpgFrontend::GpgSignResultAnalyse::do_analyse() { +void GpgFrontend::GpgSignResultAnalyse::doAnalyse() { SPDLOG_DEBUG("start sign result analyse"); stream_ << "[#] " << _("Sign Operation") << " "; - if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) + if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { stream_ << "[" << _("Success") << "]" << std::endl; - else { + } else { stream_ << "[" << _("Failed") << "] " << gpgme_strerror(error_) << std::endl; - set_status(-1); + setStatus(-1); } if (result_ != nullptr && (result_->signatures != nullptr || result_->invalid_signers != nullptr)) { SPDLOG_DEBUG("sign result analyse getting result"); stream_ << "------------>" << std::endl; - auto new_sign = result_->signatures; + auto *new_sign = result_->signatures; while (new_sign != nullptr) { stream_ << "[>]" << _("New Signature") << ": " << std::endl; @@ -59,20 +59,21 @@ void GpgFrontend::GpgSignResultAnalyse::do_analyse() { SPDLOG_DEBUG("signers fingerprint: ", new_sign->fpr); stream_ << " " << _("Sign Mode") << ": "; - if (new_sign->type == GPGME_SIG_MODE_NORMAL) + if (new_sign->type == GPGME_SIG_MODE_NORMAL) { stream_ << _("Normal"); - else if (new_sign->type == GPGME_SIG_MODE_CLEAR) + } else if (new_sign->type == GPGME_SIG_MODE_CLEAR) { stream_ << _("Clear"); - else if (new_sign->type == GPGME_SIG_MODE_DETACH) + } else if (new_sign->type == GPGME_SIG_MODE_DETACH) { stream_ << _("Detach"); + } stream_ << std::endl; - auto singerKey = + auto singer_key = GpgFrontend::GpgKeyGetter::GetInstance().GetKey(new_sign->fpr); - if (singerKey.IsGood()) { + if (singer_key.IsGood()) { stream_ << " " << _("Signer") << ": " - << singerKey.GetUIDs()->front().GetUID() << std::endl; + << singer_key.GetUIDs()->front().GetUID() << std::endl; } else { stream_ << " " << _("Signer") << ": " << "<unknown>" << std::endl; @@ -94,13 +95,14 @@ void GpgFrontend::GpgSignResultAnalyse::do_analyse() { SPDLOG_DEBUG("sign result analyse getting invalid signer"); - auto invalid_signer = result_->invalid_signers; + auto *invalid_signer = result_->invalid_signers; - if (invalid_signer != nullptr) + if (invalid_signer != nullptr) { stream_ << _("Invalid Signers") << ": " << std::endl; + } while (invalid_signer != nullptr) { - set_status(0); + setStatus(0); stream_ << "[>] " << _("Signer") << ": " << std::endl; stream_ << " " << _("Fingerprint") << ": " << invalid_signer->fpr << std::endl; diff --git a/src/core/function/result_analyse/GpgSignResultAnalyse.h b/src/core/function/result_analyse/GpgSignResultAnalyse.h index 549b8563..a6c23362 100644 --- a/src/core/function/result_analyse/GpgSignResultAnalyse.h +++ b/src/core/function/result_analyse/GpgSignResultAnalyse.h @@ -51,7 +51,7 @@ class GPGFRONTEND_CORE_EXPORT GpgSignResultAnalyse : public GpgResultAnalyse { * @brief * */ - void do_analyse(); + void doAnalyse() override; private: GpgError error_; ///< diff --git a/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp b/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp index b9947cd7..fd80c6bb 100644 --- a/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp +++ b/src/core/function/result_analyse/GpgVerifyResultAnalyse.cpp @@ -39,22 +39,22 @@ GpgFrontend::GpgVerifyResultAnalyse::GpgVerifyResultAnalyse( GpgError error, GpgVerifyResult result) : error_(error), result_(std::move(result)) {} -void GpgFrontend::GpgVerifyResultAnalyse::do_analyse() { +void GpgFrontend::GpgVerifyResultAnalyse::doAnalyse() { SPDLOG_DEBUG("started"); stream_ << "[#] " << _("Verify Operation") << " "; - if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) + if (gpgme_err_code(error_) == GPG_ERR_NO_ERROR) { stream_ << "[" << _("Success") << "]" << std::endl; - else { + } else { stream_ << "[" << _("Failed") << "] " << gpgme_strerror(error_) << std::endl; - set_status(-1); + setStatus(-1); } if (result_ != nullptr && result_->signatures != nullptr) { stream_ << "------------>" << std::endl; - auto sign = result_->signatures; + auto *sign = result_->signatures; stream_ << "[>] " << _("Signed On") << "(" << _("UTC") << ")" << " " @@ -64,87 +64,87 @@ void GpgFrontend::GpgVerifyResultAnalyse::do_analyse() { stream_ << std::endl << "[>] " << _("Signatures List") << ":" << std::endl; - bool canContinue = true; + bool can_continue = true; int count = 1; - while (sign && canContinue) { + while ((sign != nullptr) && can_continue) { stream_ << boost::format(_("Signature [%1%]:")) % count++ << std::endl; switch (gpg_err_code(sign->status)) { case GPG_ERR_BAD_SIGNATURE: stream_ << _("A Bad Signature.") << std::endl; print_signer(stream_, sign); stream_ << _("This Signature is invalid.") << std::endl; - canContinue = false; - set_status(-1); + can_continue = false; + setStatus(-1); break; case GPG_ERR_NO_ERROR: stream_ << _("A") << " "; - if (sign->summary & GPGME_SIGSUM_GREEN) { + if ((sign->summary & GPGME_SIGSUM_GREEN) != 0) { stream_ << _("Good") << " "; } - if (sign->summary & GPGME_SIGSUM_RED) { + if ((sign->summary & GPGME_SIGSUM_RED) != 0) { stream_ << _("Bad") << " "; } - if (sign->summary & GPGME_SIGSUM_SIG_EXPIRED) { + if ((sign->summary & GPGME_SIGSUM_SIG_EXPIRED) != 0) { stream_ << _("Expired") << " "; } - if (sign->summary & GPGME_SIGSUM_KEY_MISSING) { + if ((sign->summary & GPGME_SIGSUM_KEY_MISSING) != 0) { stream_ << _("Missing Key's") << " "; } - if (sign->summary & GPGME_SIGSUM_KEY_REVOKED) { + if ((sign->summary & GPGME_SIGSUM_KEY_REVOKED) != 0) { stream_ << _("Revoked Key's") << " "; } - if (sign->summary & GPGME_SIGSUM_KEY_EXPIRED) { + if ((sign->summary & GPGME_SIGSUM_KEY_EXPIRED) != 0) { stream_ << _("Expired Key's") << " "; } - if (sign->summary & GPGME_SIGSUM_CRL_MISSING) { + if ((sign->summary & GPGME_SIGSUM_CRL_MISSING) != 0) { stream_ << _("Missing CRL's") << " "; } - if (sign->summary & GPGME_SIGSUM_VALID) { + if ((sign->summary & GPGME_SIGSUM_VALID) != 0) { stream_ << _("Signature Fully Valid.") << std::endl; } else { stream_ << _("Signature Not Fully Valid.") << std::endl; stream_ << _("(May used a subkey to sign)") << std::endl; } - if (!(sign->status & GPGME_SIGSUM_KEY_MISSING)) { - if (!print_signer(stream_, sign)) set_status(0); + if ((sign->status & GPGME_SIGSUM_KEY_MISSING) == 0U) { + if (!print_signer(stream_, sign)) setStatus(0); } else { stream_ << _("Key is NOT present with ID 0x") << sign->fpr << std::endl; } - set_status(1); + setStatus(1); break; case GPG_ERR_NO_PUBKEY: stream_ << _("A signature could NOT be verified due to a Missing Key") << std::endl; - set_status(-2); + setStatus(-2); break; case GPG_ERR_CERT_REVOKED: stream_ << _("A signature is valid but the key used to verify the " "signature has been revoked") << std::endl; if (!print_signer(stream_, sign)) { - set_status(0); + setStatus(0); } - set_status(-1); + setStatus(-1); break; case GPG_ERR_SIG_EXPIRED: stream_ << _("A signature is valid but expired") << std::endl; if (!print_signer(stream_, sign)) { - set_status(0); + setStatus(0); } - set_status(-1); + setStatus(-1); break; case GPG_ERR_KEY_EXPIRED: stream_ << _("A signature is valid but the key used to " "verify the signature has expired.") << std::endl; if (!print_signer(stream_, sign)) { - set_status(0); + setStatus(0); } break; case GPG_ERR_GENERAL: @@ -152,13 +152,13 @@ void GpgFrontend::GpgVerifyResultAnalyse::do_analyse() { "the signature verification.") << std::endl; status_ = -1; - canContinue = false; + can_continue = false; break; default: auto fpr = std::string(sign->fpr); stream_ << _("Error for key with fingerprint") << " " << GpgFrontend::BeautifyFingerprint(fpr); - set_status(-1); + setStatus(-1); } stream_ << std::endl; sign = sign->next; @@ -169,48 +169,53 @@ void GpgFrontend::GpgVerifyResultAnalyse::do_analyse() { << "[>] " << _("Could not find information that can be used for verification.") << std::endl; - set_status(0); + setStatus(0); return; } } -bool GpgFrontend::GpgVerifyResultAnalyse::print_signer( - std::stringstream &stream, gpgme_signature_t sign) { - bool keyFound = true; +auto GpgFrontend::GpgVerifyResultAnalyse::print_signer( + std::stringstream &stream, gpgme_signature_t sign) -> bool { + bool key_found = true; auto key = GpgFrontend::GpgKeyGetter::GetInstance().GetKey(sign->fpr); if (!key.IsGood()) { stream << " " << _("Signed By") << ": " << "<" << _("Unknown") << ">" << std::endl; - set_status(0); - keyFound = false; + setStatus(0); + key_found = false; } else { stream << " " << _("Signed By") << ": " << key.GetUIDs()->front().GetUID() << std::endl; } - if (sign->pubkey_algo) + if (sign->pubkey_algo != 0U) { stream << " " << _("Public Key Algo") << ": " << gpgme_pubkey_algo_name(sign->pubkey_algo) << std::endl; - if (sign->hash_algo) + } + if (sign->hash_algo != 0U) { stream << " " << _("Hash Algo") << ": " << gpgme_hash_algo_name(sign->hash_algo) << std::endl; - if (sign->timestamp) + } + if (sign->timestamp != 0U) { stream << " " << _("Date") << "(" << _("UTC") << ")" << ": " << boost::posix_time::to_iso_extended_string( boost::posix_time::from_time_t(sign->timestamp)) << std::endl; + } stream << std::endl; - return keyFound; + return key_found; } -gpgme_signature_t GpgFrontend::GpgVerifyResultAnalyse::GetSignatures() const { - if (result_) +auto GpgFrontend::GpgVerifyResultAnalyse::GetSignatures() const + -> gpgme_signature_t { + if (result_) { return result_->signatures; - else - return nullptr; + } + return nullptr; } -GpgFrontend::GpgVerifyResult -GpgFrontend::GpgVerifyResultAnalyse::TakeChargeOfResult() { + +auto GpgFrontend::GpgVerifyResultAnalyse::TakeChargeOfResult() + -> GpgFrontend::GpgVerifyResult { return std::move(result_); } diff --git a/src/core/function/result_analyse/GpgVerifyResultAnalyse.h b/src/core/function/result_analyse/GpgVerifyResultAnalyse.h index 88361110..9b6051b2 100644 --- a/src/core/function/result_analyse/GpgVerifyResultAnalyse.h +++ b/src/core/function/result_analyse/GpgVerifyResultAnalyse.h @@ -30,7 +30,6 @@ #include "GpgResultAnalyse.h" - namespace GpgFrontend { /** * @brief @@ -51,21 +50,21 @@ class GPGFRONTEND_CORE_EXPORT GpgVerifyResultAnalyse : public GpgResultAnalyse { * * @return gpgme_signature_t */ - gpgme_signature_t GetSignatures() const; + auto GetSignatures() const -> gpgme_signature_t; /** * @brief * * @return GpgVerifyResult */ - GpgVerifyResult TakeChargeOfResult(); + auto TakeChargeOfResult() -> GpgVerifyResult; - private: + protected: /** * @brief * */ - void do_analyse(); + void doAnalyse() final; private: /** @@ -76,7 +75,7 @@ class GPGFRONTEND_CORE_EXPORT GpgVerifyResultAnalyse : public GpgResultAnalyse { * @return true * @return false */ - bool print_signer(std::stringstream &stream, gpgme_signature_t sign); + auto print_signer(std::stringstream &stream, gpgme_signature_t sign) -> bool; GpgError error_; ///< GpgVerifyResult result_; ///< diff --git a/src/core/thread/CtxCheckTask.cpp b/src/core/thread/CtxCheckTask.cpp index 4ca3978d..3c24ca79 100644 --- a/src/core/thread/CtxCheckTask.cpp +++ b/src/core/thread/CtxCheckTask.cpp @@ -29,18 +29,20 @@ #include "core/thread/CtxCheckTask.h" #include "core/GpgCoreInit.h" -#include "core/common/CoreCommonUtil.h" +#include "core/function/CoreSignalStation.h" #include "core/function/gpg/GpgContext.h" #include "core/function/gpg/GpgKeyGetter.h" #include "thread/Task.h" -GpgFrontend::Thread::CoreInitTask::CoreInitTask() : Task("ctx_check_task") { +namespace GpgFrontend { + +Thread::CoreInitTask::CoreInitTask() : Task("ctx_check_task") { connect(this, &CoreInitTask::SignalGnupgNotInstall, - CoreCommonUtil::GetInstance(), - &CoreCommonUtil::SignalGnupgNotInstall); + CoreSignalStation::GetInstance(), + &CoreSignalStation::SignalGnupgNotInstall); } -void GpgFrontend::Thread::CoreInitTask::Run() { +void Thread::CoreInitTask::Run() { // Init GpgFrontend Core InitGpgFrontendCore(); @@ -49,8 +51,10 @@ void GpgFrontend::Thread::CoreInitTask::Run() { emit SignalGnupgNotInstall(); } // Try flushing key cache - else - GpgFrontend::GpgKeyGetter::GetInstance().FlushKeyCache(); + else { + GpgKeyGetter::GetInstance().FlushKeyCache(); + } SPDLOG_DEBUG("ctx check task runnable done"); } +} // namespace GpgFrontend diff --git a/src/core/utils/CacheUtils.cpp b/src/core/utils/CacheUtils.cpp new file mode 100644 index 00000000..32c7ac66 --- /dev/null +++ b/src/core/utils/CacheUtils.cpp @@ -0,0 +1,50 @@ +/** + * Copyright (C) 2021 Saturneric <[email protected]> + * + * This file is part of GpgFrontend. + * + * GpgFrontend is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GpgFrontend is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. + * + * The initial version of the source code is inherited from + * the gpg4usb project, which is under GPL-3.0-or-later. + * + * All the source code of GpgFrontend was modified and released by + * Saturneric <[email protected]> starting on May 12, 2021. + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#include "CacheUtils.h" + +#include "core/function/CacheManager.h" + +namespace GpgFrontend { + +void SetTempCacheValue(const std::string& key, const std::string& value) { + nlohmann::json cache_json = value; + CacheManager::GetInstance().SaveCache(key, cache_json); +} + +auto GetTempCacheValue(const std::string& key) -> std::string { + nlohmann::json cache_json = ""; + cache_json = CacheManager::GetInstance().LoadCache(key, cache_json); + return cache_json.template get<std::string>(); +} + +void ResetTempCacheValue(const std::string& key) { + CacheManager::GetInstance().ResetCache(key); +} + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/common/CoreCommonUtil.cpp b/src/core/utils/CacheUtils.h index 4d966211..018618e8 100644 --- a/src/core/common/CoreCommonUtil.cpp +++ b/src/core/utils/CacheUtils.h @@ -1,58 +1,56 @@ -/**
- * Copyright (C) 2021 Saturneric <[email protected]>
- *
- * This file is part of GpgFrontend.
- *
- * GpgFrontend is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * GpgFrontend is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
- *
- * The initial version of the source code is inherited from
- * the gpg4usb project, which is under GPL-3.0-or-later.
- *
- * All the source code of GpgFrontend was modified and released by
- * Saturneric <[email protected]> starting on May 12, 2021.
- *
- * SPDX-License-Identifier: GPL-3.0-or-later
- *
- */
-
-#include "CoreCommonUtil.h"
-
-namespace GpgFrontend {
-
-std::unique_ptr<CoreCommonUtil> CoreCommonUtil::instance_ = nullptr; ///<
-
-CoreCommonUtil* CoreCommonUtil::GetInstance() {
- if (instance_ == nullptr) {
- instance_ = std::make_unique<CoreCommonUtil>();
- }
- return instance_.get();
-}
-
-void CoreCommonUtil::SetTempCacheValue(const std::string& key,
- const std::string& value) {
- temp_cache_[key] = value;
-}
-
-std::string CoreCommonUtil::GetTempCacheValue(const std::string& key) {
- std::string temp_cache_value;
- std::swap(temp_cache_value, temp_cache_[key]);
- return temp_cache_value;
-}
-
-void CoreCommonUtil::ResetTempCacheValue(const std::string& key) {
- std::string temp_cache_value;
- std::swap(temp_cache_value, temp_cache_[key]);
-}
-
-} // namespace GpgFrontend
+/** + * Copyright (C) 2021 Saturneric <[email protected]> + * + * This file is part of GpgFrontend. + * + * GpgFrontend is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * GpgFrontend is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GpgFrontend. If not, see <https://www.gnu.org/licenses/>. + * + * The initial version of the source code is inherited from + * the gpg4usb project, which is under GPL-3.0-or-later. + * + * All the source code of GpgFrontend was modified and released by + * Saturneric <[email protected]> starting on May 12, 2021. + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#pragma once + +namespace GpgFrontend { + +/** + * @brief set a temp cache under a certain key + * + */ +void GPGFRONTEND_CORE_EXPORT SetTempCacheValue(const std::string &, + const std::string &); + +/** + * @brief after get the temp cache, its value will be imediately ease in + * storage + * + * @return std::string + */ +auto GPGFRONTEND_CORE_EXPORT GetTempCacheValue(const std::string &) + -> std::string; + +/** + * @brief imediately ease temp cache in storage + * + * @return std::string + */ +void GPGFRONTEND_CORE_EXPORT ResetTempCacheValue(const std::string &); + +} // namespace GpgFrontend diff --git a/src/core/utils/FilesystemUtils.cpp b/src/core/utils/FilesystemUtils.cpp index edf86297..84c8caf4 100644 --- a/src/core/utils/FilesystemUtils.cpp +++ b/src/core/utils/FilesystemUtils.cpp @@ -30,7 +30,7 @@ namespace GpgFrontend { -auto GetOnlyFileNameWithPath(const std::string& path) -> std::string { +auto GetOnlyFileNameWithPath(const std::string &path) -> std::string { // Create a path object from given string std::filesystem::path path_obj(path); // Check if file name in the path object has extension @@ -42,7 +42,7 @@ auto GetOnlyFileNameWithPath(const std::string& path) -> std::string { return {}; } -auto GetFileExtension(const std::string& path) -> std::string { +auto GetFileExtension(const std::string &path) -> std::string { // Create a path object from given string std::filesystem::path path_obj(path); @@ -55,4 +55,59 @@ auto GetFileExtension(const std::string& path) -> std::string { return {}; } +/** + * @brief + * + */ +auto GetFileSizeByPath(const std::filesystem::path &path, + const std::string &filename_pattern) -> int64_t { + auto dir = QDir(QString::fromStdString(path.u8string())); + QFileInfoList file_list = dir.entryInfoList( + QStringList() << QString::fromStdString(filename_pattern), QDir::Files); + qint64 total_size = 0; + + for (const QFileInfo &file_info : file_list) { + total_size += file_info.size(); + } + return total_size; +} + +/** + * @brief + * + */ +auto GetHumanFriendlyFileSize(int64_t size) -> std::string { + auto num = static_cast<double>(size); + QStringList list; + list << "KB" + << "MB" + << "GB" + << "TB"; + + QStringListIterator i(list); + QString unit("bytes"); + + while (num >= 1024.0 && i.hasNext()) { + unit = i.next(); + num /= 1024.0; + } + return (QString().setNum(num, 'f', 2) + " " + unit).toStdString(); +} + +/** + * @brief + * + */ +void DeleteAllFilesByPattern(const std::filesystem::path &path, + const std::string &filename_pattern) { + auto dir = QDir(QString::fromStdString(path.u8string())); + + QStringList log_files = dir.entryList( + QStringList() << QString::fromStdString(filename_pattern), QDir::Files); + + for (const auto &file : log_files) { + QFile::remove(dir.absoluteFilePath(file)); + } +} + } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/FilesystemUtils.h b/src/core/utils/FilesystemUtils.h index 23b73b2b..e38078a5 100644 --- a/src/core/utils/FilesystemUtils.h +++ b/src/core/utils/FilesystemUtils.h @@ -28,13 +28,16 @@ #pragma once +namespace GpgFrontend { + /** * @brief Get the file extension object * * @param path * @return std::string */ -auto GetFileExtension(const std::string& path) -> std::string; +auto GPGFRONTEND_CORE_EXPORT GetFileExtension(const std::string& path) + -> std::string; /** * @brief Get the only file name with path object @@ -42,4 +45,36 @@ auto GetFileExtension(const std::string& path) -> std::string; * @param path * @return std::string */ -auto GetOnlyFileNameWithPath(const std::string& path) -> std::string;
\ No newline at end of file +auto GPGFRONTEND_CORE_EXPORT GetOnlyFileNameWithPath(const std::string& path) + -> std::string; + +/** + * @brief Get the File Size By Path object + * + * @param path The path of the file + * @param filename_pattern The pattern of the file name, e.g. "*.txt" + * @return int64_t + */ +auto GPGFRONTEND_CORE_EXPORT GetFileSizeByPath( + const std::filesystem::path& path, const std::string& filename_pattern) + -> int64_t; + +/** + * @brief Get the Human Readable File Size object + * + * @param size + * @return std::string + */ +auto GPGFRONTEND_CORE_EXPORT GetHumanFriendlyFileSize(int64_t size) + -> std::string; + +/** + * @brief + * + * @param path + * @param filename_pattern + */ +void GPGFRONTEND_CORE_EXPORT DeleteAllFilesByPattern( + const std::filesystem::path& path, const std::string& filename_pattern); + +} // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/utils/GpgUtils.h b/src/core/utils/GpgUtils.h index 201c7320..a617ba11 100644 --- a/src/core/utils/GpgUtils.h +++ b/src/core/utils/GpgUtils.h @@ -128,6 +128,6 @@ auto GPGFRONTEND_CORE_EXPORT CheckGpgError2ErrCode( * @param text * @return int */ -auto TextIsSigned(BypeArrayRef text) -> int; +auto GPGFRONTEND_CORE_EXPORT TextIsSigned(BypeArrayRef text) -> int; } // namespace GpgFrontend
\ No newline at end of file diff --git a/src/core/function/aes/aes_ssl.h b/src/core/utils/aes/aes_ssl.h index 5c3ac935..5c3ac935 100644 --- a/src/core/function/aes/aes_ssl.h +++ b/src/core/utils/aes/aes_ssl.h diff --git a/src/core/function/aes/aes_ssl_cbc.cpp b/src/core/utils/aes/aes_ssl_cbc.cpp index 3aa80ef5..3aa80ef5 100644 --- a/src/core/function/aes/aes_ssl_cbc.cpp +++ b/src/core/utils/aes/aes_ssl_cbc.cpp diff --git a/src/ui/UserInterfaceUtils.cpp b/src/ui/UserInterfaceUtils.cpp index d2ff0e7b..eb6b6d58 100644 --- a/src/ui/UserInterfaceUtils.cpp +++ b/src/ui/UserInterfaceUtils.cpp @@ -34,7 +34,6 @@ #include <vector> #include "core/GpgConstants.h" -#include "core/common/CoreCommonUtil.h" #include "core/function/CacheManager.h" #include "core/function/CoreSignalStation.h" #include "core/function/GlobalSettingStation.h" @@ -155,8 +154,9 @@ CommonUtils *CommonUtils::GetInstance() { } CommonUtils::CommonUtils() : QWidget(nullptr) { - connect(CoreCommonUtil::GetInstance(), &CoreCommonUtil::SignalGnupgNotInstall, - this, &CommonUtils::SignalGnupgNotInstall); + connect(CoreSignalStation::GetInstance(), + &CoreSignalStation::SignalGnupgNotInstall, this, + &CommonUtils::SignalGnupgNotInstall); connect(this, &CommonUtils::SignalKeyStatusUpdated, SignalStation::GetInstance(), &SignalStation::SignalKeyDatabaseRefresh); diff --git a/src/ui/dialog/key_generate/KeygenDialog.cpp b/src/ui/dialog/key_generate/KeygenDialog.cpp index 7d29036f..0fd7b6c4 100644 --- a/src/ui/dialog/key_generate/KeygenDialog.cpp +++ b/src/ui/dialog/key_generate/KeygenDialog.cpp @@ -30,9 +30,9 @@ #include <qobject.h> -#include "core/common/CoreCommonUtil.h" #include "core/function/GlobalSettingStation.h" #include "core/function/gpg/GpgKeyOpera.h" +#include "core/utils/CacheUtils.h" #include "dialog/WaitingDialog.h" #include "ui/SignalStation.h" @@ -141,8 +141,8 @@ void KeyGenDialog::slot_key_gen_accept() { } if (!use_pinentry_ && !gen_key_info_->IsNoPassPhrase()) { - CoreCommonUtil::GetInstance()->SetTempCacheValue( - "__key_passphrase", this->passphrase_edit_->text().toStdString()); + SetTempCacheValue("__key_passphrase", + this->passphrase_edit_->text().toStdString()); } GpgGenKeyResult result; @@ -162,7 +162,7 @@ void KeyGenDialog::slot_key_gen_accept() { dialog->close(); if (!use_pinentry_ && !gen_key_info_->IsNoPassPhrase()) { - CoreCommonUtil::GetInstance()->ResetTempCacheValue("__key_passphrase"); + ResetTempCacheValue("__key_passphrase"); } SPDLOG_DEBUG("generate done"); diff --git a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp index d3f3510d..fcc84d19 100644 --- a/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp +++ b/src/ui/dialog/key_generate/SubkeyGenerateDialog.cpp @@ -31,10 +31,10 @@ #include <cassert> #include <cstddef> -#include "core/common/CoreCommonUtil.h" #include "core/function/GlobalSettingStation.h" #include "core/function/gpg/GpgKeyGetter.h" #include "core/function/gpg/GpgKeyOpera.h" +#include "core/utils/CacheUtils.h" #include "core/utils/GpgUtils.h" #include "ui/SignalStation.h" #include "ui/dialog/WaitingDialog.h" @@ -294,8 +294,8 @@ void SubkeyGenerateDialog::slot_key_gen_accept() { } if (!use_pinentry_ && !gen_key_info_->IsNoPassPhrase()) { - CoreCommonUtil::GetInstance()->SetTempCacheValue( - "__key_passphrase", this->passphrase_edit_->text().toStdString()); + SetTempCacheValue("__key_passphrase", + this->passphrase_edit_->text().toStdString()); } GpgError error; @@ -315,7 +315,7 @@ void SubkeyGenerateDialog::slot_key_gen_accept() { waiting_dialog->close(); if (!use_pinentry_ && !gen_key_info_->IsNoPassPhrase()) { - CoreCommonUtil::GetInstance()->ResetTempCacheValue("__key_passphrase"); + ResetTempCacheValue("__key_passphrase"); } if (CheckGpgError(error) == GPG_ERR_NO_ERROR) { diff --git a/src/ui/widgets/TextEdit.cpp b/src/ui/widgets/TextEdit.cpp index 9c53b311..f27bab7c 100644 --- a/src/ui/widgets/TextEdit.cpp +++ b/src/ui/widgets/TextEdit.cpp @@ -482,7 +482,11 @@ void TextEdit::SlotPrint() { if (dlg->exec() != QDialog::Accepted) { return; } - document->print(&printer); + if (document != nullptr) { + document->print(&printer); + } else { + QMessageBox::warning(this, _("Warning"), _("No document to print")); + } // statusBar()->showMessage(_("Ready"), 2000); #endif |