config.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "config.h"
  2. #include <QDebug>
  3. namespace Config {
  4. std::map<std::string, std::string> configuration;
  5. bool configValid = false;
  6. bool configInitialized = false;
  7. std::string configPath = "configGUI.txt";
  8. std::vector<std::string> configKeys = {"Autofill-IP", "Default-IP", "Autofill-Username", "Default-Username", "CLI-Path", "Keyfile-Path"};
  9. } // namespace Config
  10. void Config::setupDefaultConfig() {
  11. configuration.clear();
  12. for (std::string s : configKeys)
  13. configuration.insert(std::pair<std::string, std::string>(s, ""));
  14. setValue(configKeys[0], "0");
  15. setValue(configKeys[1], "0.0.0.0");
  16. setValue(configKeys[2], "0");
  17. setValue(configKeys[3], "user");
  18. configInitialized = true;
  19. configValid = true;
  20. }
  21. bool Config::checkConfig() {
  22. if (!configValid || configuration.size() != configKeys.size())
  23. return false;
  24. std::string autofill_ip = getValue("Autofill-IP");
  25. if (autofill_ip != "0" && autofill_ip != "1")
  26. return false;
  27. std::string autofill_user = getValue("Autofill-Username");
  28. if (autofill_user != "0" && autofill_user != "1")
  29. return false;
  30. return true;
  31. }
  32. bool Config::loadFile() {
  33. std::string line;
  34. if (!configInitialized)
  35. setupDefaultConfig();
  36. std::ifstream ifile(configPath);
  37. if (ifile.is_open()) {
  38. while (getline(ifile, line)) {
  39. std::stringstream ss(line);
  40. std::string segment;
  41. std::vector<std::string> v;
  42. while (getline(ss, segment, '=')) {
  43. v.push_back(segment);
  44. }
  45. if (v.size() != 2) {
  46. // One line doesn't have the format *=*
  47. configValid = false;
  48. } else {
  49. configuration[v.at(0)] = v.at(1);
  50. }
  51. }
  52. configValid = true;
  53. return true;
  54. }
  55. return false;
  56. }
  57. void Config::saveFile() {
  58. std::ofstream file;
  59. if (!configInitialized)
  60. setupDefaultConfig();
  61. file.open(configPath);
  62. for (auto const &x : configuration) {
  63. file << x.first << "=" << x.second << std::endl;
  64. }
  65. file.close();
  66. }
  67. std::string Config::getValue(const std::string &key) {
  68. auto it = configuration.find(key);
  69. if (it == configuration.end()) {
  70. return "";
  71. } else {
  72. return it->second;
  73. }
  74. }
  75. void Config::setValue(const std::string &key, const std::string &value) {
  76. auto it = configuration.find(key);
  77. if (it == configuration.end()) {
  78. configuration.insert(std::pair<std::string, std::string>(key, value));
  79. } else {
  80. it->second = value;
  81. }
  82. }