forked from CPP-Final-Project/Chat_Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfigService.h
115 lines (90 loc) · 3.15 KB
/
ConfigService.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#pragma once
#include <QEnableSharedFromThis>
#include <QObject>
#include <QFile>
#include <QJsonParseError>
#include <QJsonObject>
#include <plog/Log.h>
#include "UserItem.h"
class ConfigData{
public:
static ConfigData getConfig() {
ConfigData config;
return config;
}
void saveConfig(const QString& nickname_, const QString& password_) {
QFile config_file;
QJsonObject config_json;
QJsonParseError jsonError;
if (config_file.open(QIODevice::WriteOnly | QFile::Text))
{
QJsonObject json;
QJsonObject user;
json["ServerAddress"] = config_server_adress;
json["ServerPort"] = config_server_port;
user["Nickname"] = nickname_;
user["Password"] = password_;
json["User"] = user;
config_json = json;
config_file.write(QJsonDocument(config_json).toJson());
}
else
{
qDebug() << "Error configuration file cannot be opened.";
}
config_file.close();
};
auto getConfNickname() const { return config_user_nickname; };
auto setConfNickanme(const QString& var_) { config_user_nickname = var_; };
auto getConfPassword() const { return config_user_password; };
auto setConfPassword(const QString& var_) { config_user_password = var_; };
auto getConfPort() { return config_server_port; };
auto getConfServer() { return config_server_adress; };
private:
explicit ConfigData()
{
QFile config_file;
QJsonParseError jsonError;
QJsonDocument config_file_doc;
config_file.setFileName(CONFIG_FILE_PATH);
if (config_file.open(QIODevice::ReadOnly | QFile::Text))
{
config_file_doc = QJsonDocument::fromJson(QByteArray(config_file.readAll()), &jsonError);
config_file.close();
if (jsonError.error == QJsonParseError::NoError)
{
QJsonObject config_json = config_file_doc.object();
if (const QJsonValue v = config_file_doc["User"]["Nickname"]; v.isString())
config_user_nickname = v.toString();
else
{
config_user_nickname = "";
PLOGE << "Error nickname reading";
}
if (const QJsonValue v = config_file_doc["User"]["Password"]; v.isString())
config_user_password = v.toString();
else
{
config_user_password = "";
PLOGE << "Error password reading";
}
}
else
{
PLOGE << "Error config file read: " << jsonError.error;
}
}
else
{
PLOGW << "Configuration file can't be open (not exist)";
}
};
private:
private:
const QString CONFIG_FILE_PATH = "./config.json";
const QString config_server_adress = "127.0.0.1";
const quint16 config_server_port = 5555;
QString config_user_nickname;
QString config_user_password;
void loadConfig() {}
};