Compare commits
41 Commits
e06170dd59
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d92d3179f | |||
| 0feaf09d83 | |||
| ceaf6b5fbd | |||
| 760c778c3b | |||
| b1f7fbff8b | |||
| b76523ec75 | |||
| 178850e0bc | |||
| 0a2b0d840b | |||
| 54d537dc9b | |||
| a9a4b39da1 | |||
| 5b62f9461b | |||
| 5530aff2f3 | |||
| c1ee2135df | |||
| a6648b7d1e | |||
| dbfaee27dc | |||
| f392efb54f | |||
| 057bd244bd | |||
| c9d67ff2cc | |||
| 13dc22de9f | |||
| e68b446407 | |||
| 6fc3ffc537 | |||
| f694e0e5ed | |||
| becde8c794 | |||
| 1db5d9022a | |||
| cf55adc34e | |||
| 5318390749 | |||
| b6c49dda20 | |||
| 7ae10e6ed7 | |||
| 6adf18caeb | |||
| d4ff1ffb61 | |||
| ba482e6e17 | |||
| db1ecbece0 | |||
| 63fe96fb2e | |||
| bedf8084d3 | |||
| 2a152daa70 | |||
| 08c2e3a093 | |||
| bc96a805f8 | |||
| e29cd0aebf | |||
| e1bc779791 | |||
| caffa1c18a | |||
| c15e5425a7 |
@ -1,7 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
set(TARGET_APP "GenericCore")
|
||||
project(${TARGET_APP} VERSION 0.1.0 LANGUAGES CXX)
|
||||
project(${TARGET_APP} VERSION 0.3.0 LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
@ -11,6 +11,8 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core LinguistTools)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools Gui)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Test)
|
||||
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Network)
|
||||
|
||||
configure_file(CoreConfig.h.in CoreConfig.h)
|
||||
|
||||
@ -31,14 +33,19 @@ add_library(${TARGET_APP} STATIC
|
||||
data/filehandler.h data/filehandler.cpp
|
||||
model/metadata.h
|
||||
formats/csvparser.h formats/csvparser.cpp
|
||||
model/generalsortfiltermodel.h model/generalsortfiltermodel.cpp
|
||||
network/servercommunicator.h network/servercommunicator.cpp
|
||||
network/apiroutes.h
|
||||
# 3rd party libraries
|
||||
../3rdParty/rapidcsv/src/rapidcsv.h
|
||||
model/generalsortfiltermodel.h model/generalsortfiltermodel.cpp
|
||||
utils/messagehandler.h
|
||||
)
|
||||
|
||||
include_directories(${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui)
|
||||
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Test)
|
||||
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Network)
|
||||
|
||||
target_compile_definitions(${TARGET_APP} PRIVATE ${TARGET_APP}_LIBRARY)
|
||||
|
||||
|
||||
@ -45,6 +45,7 @@ QList<ModelItemValues> FileHandler::getItemValuesFromCSVFile(const QString& file
|
||||
QFile file;
|
||||
file.setFileName(filePath);
|
||||
if (file.exists()) {
|
||||
// TODO inform UI on CSV import errors
|
||||
result = CsvParser::getItemsFromCSVFile(filePath);
|
||||
}
|
||||
return result;
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class QJsonDocument;
|
||||
class QString;
|
||||
|
||||
@ -40,4 +40,48 @@ void SettingsHandler::saveSettings(QVariantMap settingMap, QString group) {
|
||||
settings.sync();
|
||||
}
|
||||
|
||||
void SettingsHandler::deleteSettings(QStringList keys, QString group) {
|
||||
qInfo() << "deleting settings...";
|
||||
|
||||
QSettings settings;
|
||||
if (!group.isEmpty()) {
|
||||
qDebug() << "starting group:" << group;
|
||||
settings.beginGroup(group);
|
||||
}
|
||||
|
||||
foreach (QString key, keys) {
|
||||
qDebug() << "removing:" << key;
|
||||
settings.remove(key);
|
||||
}
|
||||
if (!group.isEmpty()) {
|
||||
settings.endGroup();
|
||||
}
|
||||
|
||||
settings.sync();
|
||||
}
|
||||
|
||||
QVariantMap SettingsHandler::getChangeset(QVariantMap newSettings, QString group) {
|
||||
const QVariantMap oldSettings = getSettings(group);
|
||||
|
||||
QVariantMap result;
|
||||
|
||||
for (QVariantMap::const_iterator iter = newSettings.begin(); iter != newSettings.end(); ++iter) {
|
||||
qDebug() << iter.key() << iter.value();
|
||||
QString key = iter.key();
|
||||
QVariant newValue = iter.value();
|
||||
QVariant oldValue = oldSettings.value(key);
|
||||
|
||||
if (oldValue == newValue) {
|
||||
qInfo() << "oldValue == newValue -> ignoring...";
|
||||
} else {
|
||||
const QString debugString =
|
||||
QString("oldValue != newValue -> adding '%1' to changeset...").arg(key);
|
||||
qInfo() << debugString;
|
||||
result.insert(key, newValue);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
SettingsHandler::SettingsHandler() {}
|
||||
|
||||
@ -7,6 +7,9 @@ class SettingsHandler {
|
||||
public:
|
||||
static QVariantMap getSettings(QString group = "");
|
||||
static void saveSettings(QVariantMap settingMap, QString group = "");
|
||||
static void deleteSettings(QStringList keys, QString group = "");
|
||||
|
||||
static QVariantMap getChangeset(QVariantMap newSettings, QString group = "");
|
||||
|
||||
private:
|
||||
SettingsHandler();
|
||||
|
||||
@ -52,7 +52,11 @@ bool CsvParser::isCsvCompatible(const rapidcsv::Document& doc) {
|
||||
qInfo() << "Checking CSV document for compatiblity...";
|
||||
const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
for (const QString& headerName : GET_HEADER_NAMES()) {
|
||||
bool isHeaderNameFound = false;
|
||||
if (OPTIONAL_CSV_HEADERS.contains(headerName)) {
|
||||
/// no need to have a column for the optional values
|
||||
continue;
|
||||
}
|
||||
/// these column must be found in CSV document
|
||||
if (std::find(columnNames.begin(), columnNames.end(), headerName) != columnNames.end()) {
|
||||
qDebug() << QString("Header found in column names: %1").arg(headerName);
|
||||
} else {
|
||||
@ -86,14 +90,13 @@ QHash<QString, std::vector<std::string>> CsvParser::extractColumnValues(
|
||||
const rapidcsv::Document& doc) {
|
||||
QHash<QString, std::vector<std::string>> columnValueMap;
|
||||
for (const QString& columnName : headerNames) {
|
||||
// NEXT add support for optional columns
|
||||
// if (optionalCsvHeaderNames.contains(columnName)) {
|
||||
// const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
// int columnIdx = doc.GetColumnIdx(columnName.toStdString());
|
||||
// if (columnIdx == -1) {
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
if (OPTIONAL_CSV_HEADERS.contains(columnName)) {
|
||||
const std::vector<std::string> columnNames = doc.GetColumnNames();
|
||||
int columnIdx = doc.GetColumnIdx(columnName.toStdString());
|
||||
if (columnIdx == -1) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const std::vector<std::string> columnValues =
|
||||
doc.GetColumn<std::string>(columnName.toStdString());
|
||||
columnValueMap.insert(columnName, columnValues);
|
||||
@ -127,6 +130,10 @@ QVariant CsvParser::parseItemValue(const int role, const std::string& valueStrin
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
/// string values
|
||||
result = QString::fromStdString(valueString);
|
||||
} else if (TYPE_ROLES.contains(role)) {
|
||||
/// type values
|
||||
// TODO validate string is allowed
|
||||
result = QString::fromStdString(valueString);
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
/// int values
|
||||
|
||||
@ -147,7 +154,7 @@ QVariant CsvParser::parseItemValue(const int role, const std::string& valueStrin
|
||||
result = doubleValue;
|
||||
|
||||
// } else if (typeColumns.contains(columnName)) {
|
||||
// // NEXT validate string is allowed
|
||||
// // TODO validate string is allowed
|
||||
// values[role] = QString::fromStdString(columnValueMap.value(columnName).at(row));
|
||||
} else {
|
||||
/// no type recognized for column
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
#include <QString>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
namespace rapidcsv {
|
||||
class Document;
|
||||
|
||||
@ -6,20 +6,34 @@
|
||||
#include "../model/metadata.h"
|
||||
|
||||
QList<ModelItemValues> JsonParser::toItemValuesList(const QByteArray& jsonData,
|
||||
const QString& objectName) {
|
||||
const QString& rootValueName) {
|
||||
QList<ModelItemValues> result;
|
||||
|
||||
if (jsonData.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
// TODO tidy up the following code and encapsulate into functions;
|
||||
|
||||
QJsonArray itemArray = extractItemArray(jsonData, objectName);
|
||||
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
||||
|
||||
foreach (QJsonValue value, itemArray) {
|
||||
QJsonObject itemJsonObject = value.toObject();
|
||||
/// case one: json value name in plural -> should contain an array of items
|
||||
if (rootValueName == ITEMS_KEY_STRING) {
|
||||
QJsonArray itemArray = extractItemArray(doc, rootValueName);
|
||||
|
||||
foreach (QJsonValue value, itemArray) {
|
||||
QJsonObject itemJsonObject = value.toObject();
|
||||
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
|
||||
result.append(values);
|
||||
}
|
||||
}
|
||||
/// case two: json value name in singular -> should contain an object of one item
|
||||
if (rootValueName == ITEM_KEY_STRING) {
|
||||
QJsonObject rootObject = doc.object();
|
||||
QJsonObject itemJsonObject = rootObject.value(rootValueName).toObject();
|
||||
ModelItemValues values = jsonObjectToItemValues(itemJsonObject);
|
||||
result.append(values);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -28,25 +42,8 @@ QByteArray JsonParser::itemValuesListToJson(const QList<ModelItemValues>& itemVa
|
||||
QJsonDocument jsonDoc;
|
||||
QJsonObject rootObject;
|
||||
QJsonArray itemArray;
|
||||
for (const QHash<int, QVariant>& itemValues : itemValuesList) {
|
||||
QJsonObject itemObject;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = itemValues.value(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toString());
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toInt());
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toDouble());
|
||||
} else {
|
||||
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
|
||||
for (const ModelItemValues& itemValues : itemValuesList) {
|
||||
QJsonObject itemObject = itemValuesToJsonObject(itemValues);
|
||||
itemArray.append(itemObject);
|
||||
}
|
||||
|
||||
@ -56,31 +53,85 @@ QByteArray JsonParser::itemValuesListToJson(const QList<ModelItemValues>& itemVa
|
||||
return jsonDoc.toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
QJsonObject JsonParser::itemValuesToJsonObject(const ModelItemValues& itemValues) {
|
||||
QJsonObject result;
|
||||
|
||||
// TODO add dates (entry, modification, end)
|
||||
const UserRoles idRole = IdRole;
|
||||
const QJsonValue idValue = extractJsonValue(itemValues, idRole);
|
||||
if (!idValue.isNull()) {
|
||||
const QString idRoleName = ROLE_NAMES.value(idRole);
|
||||
result.insert(idRoleName, idValue);
|
||||
}
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QJsonValue jsonValue = extractJsonValue(itemValues, role);
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
result.insert(roleName, jsonValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QByteArray JsonParser::userCredentialsToJsonDocument(const QString email, const QString password) {
|
||||
QJsonDocument jsonDoc;
|
||||
QJsonObject rootObject;
|
||||
|
||||
QJsonObject userObject;
|
||||
userObject.insert("email", email);
|
||||
userObject.insert("password", password);
|
||||
|
||||
rootObject.insert("user", userObject);
|
||||
jsonDoc.setObject(rootObject);
|
||||
|
||||
return jsonDoc.toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
QVariant JsonParser::getValueFromJson(const QByteArray& jsonData,
|
||||
const QString key,
|
||||
const QString objectName) {
|
||||
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
||||
QJsonObject rootObject = doc.object();
|
||||
QJsonObject userObject = rootObject.value(objectName).toObject();
|
||||
|
||||
return userObject.value(key);
|
||||
}
|
||||
|
||||
JsonParser::JsonParser() {}
|
||||
|
||||
QJsonArray JsonParser::extractItemArray(const QByteArray& jsonData, const QString& objectName) {
|
||||
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
||||
QJsonArray JsonParser::extractItemArray(const QJsonDocument& doc, const QString& objectName) {
|
||||
QJsonArray itemArray;
|
||||
if (objectName.isEmpty()) {
|
||||
itemArray = doc.array();
|
||||
|
||||
} else {
|
||||
QJsonObject rootObject = doc.object();
|
||||
itemArray = rootObject.value(objectName).toArray();
|
||||
}
|
||||
|
||||
return itemArray;
|
||||
}
|
||||
|
||||
ModelItemValues JsonParser::jsonObjectToItemValues(const QJsonObject& itemJsonObject) {
|
||||
ModelItemValues values;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, role);
|
||||
const UserRoles idRole = IdRole;
|
||||
const QString idRoleName = ROLE_NAMES.value(idRole);
|
||||
// QVariant idValue = data(idRole);
|
||||
if (itemJsonObject.contains(idRoleName)) {
|
||||
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, idRole);
|
||||
values.insert(keyValuePair.first, keyValuePair.second);
|
||||
}
|
||||
|
||||
for (auto iter = itemJsonObject.constBegin(), end = itemJsonObject.constEnd(); iter != end;
|
||||
++iter) {
|
||||
const QString roleName = iter.key();
|
||||
if (ROLE_NAMES.values().contains(roleName)) {
|
||||
const int role = ROLE_NAMES.key(roleName.toLatin1());
|
||||
std::pair<int, QVariant> keyValuePair = getKeyValuePair(itemJsonObject, role);
|
||||
values.insert(keyValuePair.first, keyValuePair.second);
|
||||
}
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
@ -93,8 +144,28 @@ pair<int, QVariant> JsonParser::getKeyValuePair(const QJsonObject& itemJsonObjec
|
||||
result = jsonValue.toInt();
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
result = jsonValue.toDouble();
|
||||
} else if (TYPE_ROLES.contains(role)) {
|
||||
result = jsonValue.toString();
|
||||
} else {
|
||||
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
|
||||
}
|
||||
return pair<int, QVariant>(role, result);
|
||||
}
|
||||
|
||||
QJsonValue JsonParser::extractJsonValue(const ModelItemValues& itemValues, const int role) {
|
||||
QJsonValue result;
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = itemValues.value(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
result = value.toString();
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
result = value.toInt();
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
result = value.toDouble();
|
||||
} else if (TYPE_ROLES.contains(role)) {
|
||||
result = value.toString();
|
||||
} else {
|
||||
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -8,24 +8,32 @@ class QString;
|
||||
class QByteArray;
|
||||
class QJsonArray;
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
using namespace std;
|
||||
|
||||
class JsonParser {
|
||||
public:
|
||||
static QList<ModelItemValues> toItemValuesList(const QByteArray& jsonData,
|
||||
const QString& objectName = "");
|
||||
const QString& rootValueName = "");
|
||||
static QByteArray itemValuesListToJson(const QList<ModelItemValues>& itemValuesList,
|
||||
const QString& objectName = "");
|
||||
static QJsonObject itemValuesToJsonObject(const ModelItemValues& itemValues);
|
||||
|
||||
static QByteArray userCredentialsToJsonDocument(const QString email, const QString password);
|
||||
static QVariant getValueFromJson(const QByteArray& jsonData,
|
||||
const QString key,
|
||||
const QString objectName = "");
|
||||
|
||||
private:
|
||||
explicit JsonParser();
|
||||
|
||||
static QJsonArray extractItemArray(const QByteArray& jsonData, const QString& objectName);
|
||||
static QJsonArray extractItemArray(const QJsonDocument& doc, const QString& objectName);
|
||||
static ModelItemValues jsonObjectToItemValues(const QJsonObject& itemJsonObject);
|
||||
|
||||
static pair<int, QVariant> getKeyValuePair(const QJsonObject& itemJsonObject, const int role);
|
||||
|
||||
static QJsonValue extractJsonValue(const ModelItemValues& itemValues, const int role);
|
||||
};
|
||||
|
||||
#endif // JSONPARSER_H
|
||||
|
||||
204
genericcore.cpp
204
genericcore.cpp
@ -1,5 +1,6 @@
|
||||
#include "genericcore.h"
|
||||
|
||||
#include <QAbstractItemModelTester>
|
||||
#include <QCoreApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
@ -12,9 +13,12 @@
|
||||
#include "CoreConfig.h"
|
||||
#include "constants.h"
|
||||
#include "data/filehandler.h"
|
||||
#include "data/settingshandler.h"
|
||||
#include "formats/jsonparser.h"
|
||||
#include "model/generalsortfiltermodel.h"
|
||||
#include "model/metadata.h"
|
||||
#include "model/tablemodel.h"
|
||||
#include "network/servercommunicator.h"
|
||||
|
||||
#include <QtGui/QUndoStack>
|
||||
|
||||
@ -36,6 +40,7 @@ GenericCore::GenericCore() {
|
||||
m_modelUndoStack = new QUndoStack(this);
|
||||
|
||||
setupModels();
|
||||
setupServerCommunication();
|
||||
}
|
||||
|
||||
GenericCore::~GenericCore() { qDebug() << "Destroying core..."; }
|
||||
@ -94,34 +99,20 @@ std::shared_ptr<GeneralSortFilterModel> GenericCore::getSortFilterModel() const
|
||||
return m_sortFilterModel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save items to default file (in standard location).
|
||||
* @brief GenericCore::saveItems Saves item fo file.
|
||||
*/
|
||||
void GenericCore::saveItems() {
|
||||
qDebug() << "saving items...";
|
||||
|
||||
const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc();
|
||||
const bool successfulSave = FileHandler::saveToFile(doc, ITEM_FILE_NAME);
|
||||
if (successfulSave) {
|
||||
m_modelUndoStack->setClean();
|
||||
emit displayStatusMessage(QString("Items saved."));
|
||||
} else {
|
||||
emit displayStatusMessage(QString("Error: Items couldn't be saved."));
|
||||
}
|
||||
}
|
||||
|
||||
void GenericCore::importCSVFile(const QString& filePath) {
|
||||
qInfo() << "importing items from CSV...";
|
||||
qDebug() << "filePath:" << filePath;
|
||||
const QList<ModelItemValues> itemValuesList = FileHandler::getItemValuesFromCSVFile(filePath);
|
||||
// NEXT inform UI on errors
|
||||
if (itemValuesList.isEmpty()) {
|
||||
qDebug() << "No items found. Doing nothing...";
|
||||
displayStatusMessage("No items found in CSV file. Either empty or not compatible.");
|
||||
return;
|
||||
}
|
||||
// qDebug() << "CSV file content:" << itemValuesList;
|
||||
m_mainModel->insertItems(m_mainModel->rowCount(), itemValuesList);
|
||||
const QString messageString =
|
||||
QString(tr("Imported %1 item(s) from CSV file.")).arg(itemValuesList.size());
|
||||
displayStatusMessage(messageString);
|
||||
}
|
||||
|
||||
bool GenericCore::exportCSVFile(const QString& filePath) {
|
||||
@ -131,11 +122,134 @@ bool GenericCore::exportCSVFile(const QString& filePath) {
|
||||
return FileHandler::exportToCSVFile(itemsAsStringLists, filePath);
|
||||
}
|
||||
|
||||
QVariantMap GenericCore::getSettings(QString group) const {
|
||||
return SettingsHandler::getSettings(group);
|
||||
}
|
||||
|
||||
void GenericCore::applySettings(QVariantMap settingMap, QString group) {
|
||||
const QVariantMap changeset = SettingsHandler::getChangeset(settingMap, group);
|
||||
|
||||
if (changeset.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (group == "Server") {
|
||||
const bool urlChanged = changeset.contains("url");
|
||||
const bool emailChanged = changeset.contains("email");
|
||||
const bool passwordChanged = changeset.contains("password");
|
||||
if (urlChanged || emailChanged || passwordChanged) {
|
||||
if (!changeset.contains("authToken")) {
|
||||
qInfo() << "Account settings changed, but no new token present. Deleting old token...";
|
||||
SettingsHandler::deleteSettings({"authToken"}, "Server");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SettingsHandler::saveSettings(settingMap, group);
|
||||
|
||||
if (group == "Server") {
|
||||
applyServerConfiguration();
|
||||
}
|
||||
}
|
||||
|
||||
bool GenericCore::isSyncServerSetup() const {
|
||||
if (m_serverCommunicator) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save items to default file (in standard location).
|
||||
* @brief GenericCore::saveItems Saves item fo file.
|
||||
*/
|
||||
void GenericCore::saveItems() {
|
||||
qDebug() << "saving items...";
|
||||
|
||||
const QJsonDocument doc = m_mainModel->getAllItemsAsJsonDoc();
|
||||
const bool successfulSave = FileHandler::saveToFile(doc, ITEMS_FILE_NAME);
|
||||
if (successfulSave) {
|
||||
m_modelUndoStack->setClean();
|
||||
emit displayStatusMessage(QString("Items saved."));
|
||||
} else {
|
||||
emit displayStatusMessage(QString("Error: Items couldn't be saved."));
|
||||
}
|
||||
}
|
||||
|
||||
void GenericCore::onLoginSuccessful(const QByteArray jsonData) {
|
||||
emit displayStatusMessage("Login successful.");
|
||||
qInfo() << "Storing auth token...";
|
||||
QString token = JsonParser::getValueFromJson(jsonData, "token", "user").toString();
|
||||
SettingsHandler::saveSettings({{"authToken", token}}, "Server");
|
||||
applyServerConfiguration();
|
||||
}
|
||||
|
||||
void GenericCore::onLoginFailure(const QString errorString) {
|
||||
emit displayStatusMessage(QString("Error: %1").arg(errorString));
|
||||
}
|
||||
|
||||
void GenericCore::onNotAuthorized(const QString /*path*/) {
|
||||
const QVariantMap serverSettings = SettingsHandler::getSettings("Server");
|
||||
const QString tokenValue = serverSettings.value("authToken").toString();
|
||||
if (!tokenValue.isEmpty()) {
|
||||
SettingsHandler::deleteSettings({"authToken"}, "Server");
|
||||
displayStatusMessage("Not authorized! Deleted token. Please retry.");
|
||||
} else {
|
||||
displayStatusMessage("Not authorized! But no token was present. Please check your settings.");
|
||||
}
|
||||
applyServerConfiguration();
|
||||
}
|
||||
|
||||
void GenericCore::onSendItemTriggered(const QByteArray& jsonData) {
|
||||
m_serverCommunicator->sendItem(jsonData);
|
||||
}
|
||||
|
||||
void GenericCore::onItemsFetched(const QByteArray jsonData) {
|
||||
emit displayStatusMessage("New items fetched.");
|
||||
// TODO ? check compability of JSON structure beforehand?
|
||||
// NEXT check if item already exists and apply changes (UUID,...) ? ;
|
||||
m_mainModel->appendItems(jsonData);
|
||||
}
|
||||
|
||||
void GenericCore::onItemsFetchFailure(const QString errorString) {
|
||||
emit displayStatusMessage(QString("Error: %1").arg(errorString));
|
||||
}
|
||||
|
||||
void GenericCore::onSendItemSuccessful(const QByteArray responseData) {
|
||||
const QString message = m_mainModel->updateItemsFromJson(responseData);
|
||||
emit displayStatusMessage(message);
|
||||
}
|
||||
|
||||
void GenericCore::onSendItemFailure(const QString errorString) {
|
||||
emit displayStatusMessage(QString("Error: %1").arg(errorString));
|
||||
}
|
||||
|
||||
void GenericCore::onDeleteItemSuccessful(const QByteArray responseData) {
|
||||
qWarning() << "TODO: Process success response!!!";
|
||||
}
|
||||
|
||||
void GenericCore::onDeleteItemFailure(const QString errorString) {
|
||||
qWarning() << "TODO: Process error response!!!";
|
||||
}
|
||||
|
||||
void GenericCore::setupModels() {
|
||||
m_mainModel = make_shared<TableModel>(m_modelUndoStack, this);
|
||||
m_sortFilterModel = make_shared<GeneralSortFilterModel>(m_mainModel);
|
||||
|
||||
// TODO add QAbstractItemModelTester
|
||||
/// QAbstractItemModelTester
|
||||
#ifdef QT_DEBUG
|
||||
m_mainModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
|
||||
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Fatal);
|
||||
#else
|
||||
m_mainModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_mainModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
|
||||
m_proxyModelTester = make_unique<QAbstractItemModelTester>(
|
||||
m_sortFilterModel.get(), QAbstractItemModelTester::FailureReportingMode::Warning);
|
||||
#endif
|
||||
|
||||
initModelData();
|
||||
}
|
||||
|
||||
@ -146,7 +260,7 @@ void GenericCore::setupModels() {
|
||||
*/
|
||||
void GenericCore::initModelData() {
|
||||
qInfo() << "Trying to read model data from file...";
|
||||
const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEM_FILE_NAME);
|
||||
const QByteArray jsonDoc = FileHandler::loadJSONDataFromFile(ITEMS_FILE_NAME);
|
||||
// qDebug() << "jsonDoc:" << jsonDoc;
|
||||
// TODO decide on lack of file(s) (config, data) if example items should be generated
|
||||
// (see welcome wizard)
|
||||
@ -175,3 +289,53 @@ QString GenericCore::getMaintenanceToolFilePath() const {
|
||||
const QString filePath = applicationDirPath + "/" + UPDATER_EXE;
|
||||
return filePath;
|
||||
}
|
||||
|
||||
void GenericCore::setupServerCommunication() {
|
||||
m_serverCommunicator = make_unique<ServerCommunicator>(this);
|
||||
/// request connections
|
||||
connect(this, &GenericCore::fetchItemsFromServer, m_serverCommunicator.get(),
|
||||
&ServerCommunicator::fetchItems);
|
||||
connect(this, &GenericCore::sendItemToServer, m_serverCommunicator.get(),
|
||||
&ServerCommunicator::sendItem);
|
||||
connect(this, &GenericCore::deleteItemFromServer, m_serverCommunicator.get(),
|
||||
&ServerCommunicator::deleteItem);
|
||||
|
||||
/// response connections
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::loginSuccessful, this,
|
||||
&GenericCore::onLoginSuccessful);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::loginFailure, this,
|
||||
&GenericCore::onLoginFailure);
|
||||
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::notAuthorized, this,
|
||||
&GenericCore::onNotAuthorized);
|
||||
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetched, this,
|
||||
&GenericCore::onItemsFetched);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::itemsFetchFailure, this,
|
||||
&GenericCore::onItemsFetchFailure);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::sendItemSuccessful, this,
|
||||
&GenericCore::onSendItemSuccessful);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::sendItemFailure, this,
|
||||
&GenericCore::onSendItemFailure);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::deleteItemSuccessful, this,
|
||||
&GenericCore::onDeleteItemSuccessful);
|
||||
connect(m_serverCommunicator.get(), &ServerCommunicator::deleteItemFailure, this,
|
||||
&GenericCore::onDeleteItemFailure);
|
||||
|
||||
applyServerConfiguration();
|
||||
}
|
||||
|
||||
void GenericCore::applyServerConfiguration() {
|
||||
const QVariantMap serverSettings = SettingsHandler::getSettings("Server");
|
||||
const QString urlValue = serverSettings.value("url").toString();
|
||||
if (urlValue.isEmpty()) {
|
||||
SettingsHandler::deleteSettings({"authToken"}, "Server");
|
||||
} else {
|
||||
/// urlValue in NOT empty
|
||||
const QString emailValue = serverSettings.value("email").toString();
|
||||
const QString passwordValue = serverSettings.value("password").toString();
|
||||
const QString authTokenValue = serverSettings.value("authToken").toString();
|
||||
m_serverCommunicator->setServerConfiguration(urlValue, emailValue, passwordValue,
|
||||
authTokenValue);
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,10 +5,12 @@
|
||||
|
||||
class QUndoStack;
|
||||
class QAbstractItemModel;
|
||||
class QAbstractItemModelTester;
|
||||
class QString;
|
||||
|
||||
class TableModel;
|
||||
class GeneralSortFilterModel;
|
||||
class ServerCommunicator;
|
||||
|
||||
class GenericCore : public QObject {
|
||||
Q_OBJECT
|
||||
@ -27,22 +29,51 @@ class GenericCore : public QObject {
|
||||
std::shared_ptr<TableModel> getModel() const;
|
||||
std::shared_ptr<GeneralSortFilterModel> getSortFilterModel() const;
|
||||
|
||||
void saveItems();
|
||||
void importCSVFile(const QString& filePath);
|
||||
bool exportCSVFile(const QString& filePath);
|
||||
|
||||
QVariantMap getSettings(QString group = "") const;
|
||||
void applySettings(QVariantMap settingMap, QString group = "");
|
||||
bool isSyncServerSetup() const;
|
||||
|
||||
public slots:
|
||||
void saveItems();
|
||||
|
||||
void onLoginSuccessful(const QByteArray jsonData);
|
||||
void onLoginFailure(const QString errorString);
|
||||
|
||||
void onNotAuthorized(const QString /*path*/);
|
||||
|
||||
void onSendItemTriggered(const QByteArray& jsonData);
|
||||
void onItemsFetched(const QByteArray jsonData);
|
||||
void onItemsFetchFailure(const QString errorString);
|
||||
void onSendItemSuccessful(const QByteArray responseData);
|
||||
void onSendItemFailure(const QString errorString);
|
||||
void onDeleteItemSuccessful(const QByteArray responseData);
|
||||
void onDeleteItemFailure(const QString errorString);
|
||||
|
||||
signals:
|
||||
void displayStatusMessage(QString message);
|
||||
void fetchItemsFromServer();
|
||||
void sendItemToServer(const QByteArray& jsonData);
|
||||
void deleteItemFromServer(const QString& id);
|
||||
|
||||
private:
|
||||
QUndoStack* m_modelUndoStack;
|
||||
std::shared_ptr<TableModel> m_mainModel;
|
||||
std::shared_ptr<GeneralSortFilterModel> m_sortFilterModel;
|
||||
std::unique_ptr<QAbstractItemModelTester> m_mainModelTester;
|
||||
std::unique_ptr<QAbstractItemModelTester> m_proxyModelTester;
|
||||
|
||||
void setupModels();
|
||||
void initModelData();
|
||||
|
||||
QString getMaintenanceToolFilePath() const;
|
||||
|
||||
/// Network communication
|
||||
std::unique_ptr<ServerCommunicator> m_serverCommunicator;
|
||||
void setupServerCommunication();
|
||||
void applyServerConfiguration();
|
||||
};
|
||||
|
||||
#endif // GENERICCORE_H
|
||||
|
||||
@ -26,6 +26,11 @@ EditItemCommand::EditItemCommand(TableModel* model,
|
||||
.arg(roleName)
|
||||
.arg(index.data(DEFAULT_ROLE).toString())
|
||||
.arg(value.toString());
|
||||
} else if (role == IdRole) {
|
||||
commandText = QString("Setting '%1' of item '%2' to '%3'")
|
||||
.arg(roleName)
|
||||
.arg(index.data(DEFAULT_ROLE).toString())
|
||||
.arg(value.toString());
|
||||
} else {
|
||||
qWarning() << "Role didn't match! Using a generic command text...";
|
||||
commandText = QString("Edit item '%1'").arg(index.data(DEFAULT_ROLE).toString());
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
#include <QUndoCommand>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class TableModel;
|
||||
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
|
||||
class TableModel;
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class RemoveRowsCommand : public QUndoCommand {
|
||||
public:
|
||||
|
||||
@ -23,6 +23,16 @@ QItemSelection GeneralSortFilterModel::findItems(const QString& text) const {
|
||||
return result;
|
||||
}
|
||||
|
||||
QString GeneralSortFilterModel::getUuid(const QModelIndex& itemIndex) const {
|
||||
return data(itemIndex, IdRole).toString();
|
||||
}
|
||||
|
||||
// NEXT remove when deprecated
|
||||
QByteArray GeneralSortFilterModel::jsonDataForServer(const QModelIndex& proxyIndex) {
|
||||
const QModelIndex sourceIndex = mapToSource(proxyIndex);
|
||||
return m_tableModel->jsonDataForServer(sourceIndex);
|
||||
}
|
||||
|
||||
void GeneralSortFilterModel::appendItems(const QByteArray& jsonDoc) {
|
||||
m_tableModel->appendItems(jsonDoc);
|
||||
}
|
||||
@ -50,6 +60,12 @@ bool GeneralSortFilterModel::lessThan(const QModelIndex& source_left,
|
||||
const QString rightString = rightData.toString();
|
||||
return m_collator.compare(leftString, rightString) > 0;
|
||||
}
|
||||
const bool isType = TYPE_ROLES.contains(role);
|
||||
if (isType) {
|
||||
const QString leftString = leftData.toString();
|
||||
const QString rightString = rightData.toString();
|
||||
return m_collator.compare(leftString, rightString) > 0;
|
||||
}
|
||||
const bool isInt = INT_ROLES.contains(role);
|
||||
if (isInt) {
|
||||
const int leftInt = leftData.toInt();
|
||||
|
||||
@ -17,6 +17,9 @@ class GeneralSortFilterModel : public QSortFilterProxyModel {
|
||||
* @return QItemSelection containing all successful ModelIndex results
|
||||
*/
|
||||
QItemSelection findItems(const QString& text) const;
|
||||
QString getUuid(const QModelIndex& itemIndex) const;
|
||||
|
||||
QByteArray jsonDataForServer(const QModelIndex& proxyIndex);
|
||||
|
||||
public slots:
|
||||
void appendItems(const QByteArray& jsonDoc);
|
||||
|
||||
@ -6,28 +6,56 @@
|
||||
#include <QList>
|
||||
#include <QString>
|
||||
|
||||
// TODO add namespace
|
||||
|
||||
/// model data
|
||||
enum UserRoles { NameRole = Qt::UserRole + 1, DescriptionRole, InfoRole, AmountRole, FactorRole };
|
||||
static UserRoles DEFAULT_ROLE = NameRole;
|
||||
static QList<UserRoles> USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole, AmountRole,
|
||||
FactorRole};
|
||||
static QHash<int, QByteArray> ROLE_NAMES = {{NameRole, "Name"},
|
||||
{DescriptionRole, "Description"},
|
||||
{InfoRole, "Info"},
|
||||
{AmountRole, "Amount"},
|
||||
{FactorRole, "Factor"}};
|
||||
static QList<UserRoles> STRING_ROLES = {NameRole, DescriptionRole, InfoRole};
|
||||
static QList<UserRoles> INT_ROLES = {AmountRole};
|
||||
static QList<UserRoles> DOUBLE_ROLES = {FactorRole};
|
||||
enum UserRoles {
|
||||
NameRole = Qt::UserRole + 1,
|
||||
DescriptionRole,
|
||||
InfoRole,
|
||||
TypeRole,
|
||||
AmountRole,
|
||||
FactorRole,
|
||||
/// Non user facing
|
||||
IdRole,
|
||||
/// read only roles
|
||||
ToStringRole,
|
||||
ToJsonRole
|
||||
};
|
||||
|
||||
static UserRoles DEFAULT_ROLE = NameRole;
|
||||
// TODO ?rename USER_FACING_ROLES -> MAIN_ROLES ?
|
||||
static QList<UserRoles> USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole, TypeRole,
|
||||
AmountRole, FactorRole, IdRole};
|
||||
|
||||
static QList<UserRoles> READ_ONLY_ROLES = {IdRole};
|
||||
|
||||
static QHash<int, QByteArray> ROLE_NAMES = {
|
||||
{NameRole, "name"}, {DescriptionRole, "description"},
|
||||
{InfoRole, "info"}, {TypeRole, "type"},
|
||||
{AmountRole, "amount"}, {FactorRole, "factor"},
|
||||
{ToStringRole, "ToString"}, {IdRole, "id"},
|
||||
{Qt::DisplayRole, "display"}, {Qt::EditRole, "edit"}};
|
||||
|
||||
static QList<UserRoles> STRING_ROLES = {NameRole, DescriptionRole, InfoRole, IdRole};
|
||||
static QList<UserRoles> INT_ROLES = {AmountRole};
|
||||
static QList<UserRoles> DOUBLE_ROLES = {FactorRole};
|
||||
static QList<UserRoles> NUMBER_ROLES = INT_ROLES + DOUBLE_ROLES;
|
||||
|
||||
static const QList<UserRoles> TYPE_ROLES = {TypeRole};
|
||||
static const QList<QString> TYPES = {"A", "B", "C", ""};
|
||||
|
||||
static const QStringList OPTIONAL_CSV_HEADERS = {"description", "info"};
|
||||
|
||||
/// JSON keys
|
||||
static const QString ITEM_KEY_STRING = "items";
|
||||
static const QString ITEMS_KEY_STRING = "items";
|
||||
static const QString ITEM_KEY_STRING = "item";
|
||||
|
||||
/// file naming
|
||||
static const QString ITEM_FILE_NAME = ITEM_KEY_STRING + ".json";
|
||||
static const QString ITEMS_FILE_NAME = ITEMS_KEY_STRING + ".json";
|
||||
|
||||
/// functions
|
||||
static int GET_ROLE_FOR_COLUMN(const int column) {
|
||||
static UserRoles GET_ROLE_FOR_COLUMN(const int column) {
|
||||
switch (column) {
|
||||
case 0:
|
||||
return NameRole;
|
||||
@ -39,17 +67,26 @@ static int GET_ROLE_FOR_COLUMN(const int column) {
|
||||
return InfoRole;
|
||||
break;
|
||||
case 3:
|
||||
return AmountRole;
|
||||
return TypeRole;
|
||||
break;
|
||||
case 4:
|
||||
return AmountRole;
|
||||
break;
|
||||
case 5:
|
||||
return FactorRole;
|
||||
break;
|
||||
case 6:
|
||||
return IdRole;
|
||||
break;
|
||||
default:
|
||||
qWarning() << QString("No role found for column %1! Returning 'NameRole'...").arg(column);
|
||||
return NameRole;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static int GET_COLUMN_FOR_ROLE(const UserRoles role) { return USER_FACING_ROLES.indexOf(role); }
|
||||
|
||||
static QList<QString> GET_HEADER_NAMES() {
|
||||
QList<QString> result;
|
||||
for (const UserRoles& role : USER_FACING_ROLES) {
|
||||
@ -59,4 +96,10 @@ static QList<QString> GET_HEADER_NAMES() {
|
||||
return result;
|
||||
}
|
||||
|
||||
static QString GET_HEADER_FOR_COLUMN(const int column) {
|
||||
const UserRoles role = GET_ROLE_FOR_COLUMN(column);
|
||||
const QString headerName = ROLE_NAMES.value(role);
|
||||
return headerName;
|
||||
}
|
||||
|
||||
#endif // METADATA_H
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
#include "modelitem.h"
|
||||
|
||||
#include "metadata.h"
|
||||
|
||||
#include <QJsonObject>
|
||||
#include <QJsonValue>
|
||||
|
||||
#include "../formats/jsonparser.h"
|
||||
#include "metadata.h"
|
||||
|
||||
ModelItem::ModelItem(const ModelItemValues values)
|
||||
: m_values(values) {}
|
||||
|
||||
@ -44,24 +45,28 @@ bool ModelItem::setItemData(const QMap<int, QVariant>& changedValues) {
|
||||
return valueChanged;
|
||||
}
|
||||
|
||||
QJsonObject ModelItem::toJsonObject() const {
|
||||
QJsonObject itemObject;
|
||||
// TODO add UUID and dates (entry, modification, end)
|
||||
QString ModelItem::toString() const {
|
||||
QString result;
|
||||
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant value = data(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toString());
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toInt());
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
itemObject.insert(roleName, value.toDouble());
|
||||
} else {
|
||||
qCritical() << QString("Cant find data type of role %1!!!").arg(role);
|
||||
}
|
||||
// result.append(value.toString());
|
||||
result.append(QString("%1: %2\n").arg(roleName, data(role).toString()));
|
||||
}
|
||||
|
||||
const UserRoles idRole = IdRole;
|
||||
QVariant idValue = data(idRole);
|
||||
if (!idValue.isNull()) {
|
||||
const QString idRoleName = ROLE_NAMES.value(idRole);
|
||||
result.append(QString("%1: %2\n").arg(idRoleName, idValue.toString()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonObject ModelItem::toJsonObject() const {
|
||||
QJsonObject itemObject = JsonParser::itemValuesToJsonObject(m_values);
|
||||
return itemObject;
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
#include <QVariant>
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class ModelItem {
|
||||
public:
|
||||
@ -14,11 +14,11 @@ class ModelItem {
|
||||
// TODO change return value to list of changed roles
|
||||
bool setItemData(const QMap<int, QVariant>& changedValues);
|
||||
|
||||
// QString toString() const;
|
||||
QString toString() const;
|
||||
QJsonObject toJsonObject() const;
|
||||
|
||||
private:
|
||||
QHash<int, QVariant> m_values;
|
||||
ModelItemValues m_values;
|
||||
};
|
||||
|
||||
#endif // MODELITEM_H
|
||||
|
||||
@ -16,6 +16,7 @@ QByteArray TableModel::generateExampleItems() {
|
||||
QJsonObject rootObject;
|
||||
QJsonArray array;
|
||||
|
||||
// TODO use JsonParser for the item generation
|
||||
for (int row = 0; row < 5; ++row) {
|
||||
QJsonObject itemObject;
|
||||
// itemObject.insert("uuid", m_uuid.toString());
|
||||
@ -28,7 +29,7 @@ QByteArray TableModel::generateExampleItems() {
|
||||
|
||||
array.append(itemObject);
|
||||
}
|
||||
rootObject.insert(ITEM_KEY_STRING, array);
|
||||
rootObject.insert(ITEMS_KEY_STRING, array);
|
||||
|
||||
doc.setObject(rootObject);
|
||||
return doc.toJson();
|
||||
@ -39,19 +40,35 @@ TableModel::TableModel(QUndoStack* undoStack, QObject* parent)
|
||||
, m_undoStack(undoStack) {}
|
||||
|
||||
Qt::ItemFlags TableModel::flags(const QModelIndex& index) const {
|
||||
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
|
||||
Qt::ItemFlags result = QAbstractTableModel::flags(index);
|
||||
if (!index.isValid()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const int column = index.column();
|
||||
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
/// roles which aren't editable by the user
|
||||
if (READ_ONLY_ROLES.contains(roleForColumn)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return result | Qt::ItemIsEditable;
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> TableModel::roleNames() const { return ROLE_NAMES; }
|
||||
|
||||
int TableModel::rowCount(const QModelIndex& parent) const {
|
||||
Q_UNUSED(parent);
|
||||
if (parent.isValid()) {
|
||||
return 0; /// no children
|
||||
}
|
||||
return m_items.size();
|
||||
}
|
||||
|
||||
int TableModel::columnCount(const QModelIndex& parent) const {
|
||||
Q_UNUSED(parent);
|
||||
return ROLE_NAMES.size();
|
||||
if (parent.isValid()) {
|
||||
return 0; /// no children
|
||||
}
|
||||
return USER_FACING_ROLES.size();
|
||||
}
|
||||
|
||||
QVariant TableModel::data(const QModelIndex& index, int role) const {
|
||||
@ -70,14 +87,15 @@ QVariant TableModel::data(const QModelIndex& index, int role) const {
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole:
|
||||
return m_items.at(row)->data(roleForColumn);
|
||||
case NameRole:
|
||||
case DescriptionRole:
|
||||
case InfoRole:
|
||||
case AmountRole:
|
||||
case FactorRole:
|
||||
case ToStringRole:
|
||||
return m_items.at(row)->toString();
|
||||
case ToJsonRole:
|
||||
return m_items.at(row)->toJsonObject();
|
||||
case IdRole:
|
||||
return m_items.at(row)->data(role);
|
||||
default:
|
||||
return m_items.at(row)->data(role);
|
||||
}
|
||||
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
@ -95,10 +113,9 @@ QVariant TableModel::headerData(int section, Qt::Orientation orientation, int ro
|
||||
}
|
||||
|
||||
bool TableModel::setData(const QModelIndex& index, const QVariant& value, int role) {
|
||||
if (role == Qt::EditRole && checkIndex(index)) {
|
||||
const int column = index.column();
|
||||
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
return setItemData(index, {{roleForColumn, value}});
|
||||
if (checkIndex(index)) {
|
||||
const int adjustedRole = getAppropriateRoleForIndex(index, role);
|
||||
return setItemData(index, {{adjustedRole, value}});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@ -140,7 +157,7 @@ QJsonDocument TableModel::getAllItemsAsJsonDoc() const {
|
||||
QJsonObject itemObject = item->toJsonObject();
|
||||
array.append(itemObject);
|
||||
}
|
||||
rootObject.insert(ITEM_KEY_STRING, array);
|
||||
rootObject.insert(ITEMS_KEY_STRING, array);
|
||||
|
||||
doc.setObject(rootObject);
|
||||
return doc;
|
||||
@ -159,6 +176,43 @@ QList<QStringList> TableModel::getItemsAsStringLists() const {
|
||||
return result;
|
||||
}
|
||||
|
||||
// TODO use item selection as parameter to wrap multiple items into JSON data structure
|
||||
QByteArray TableModel::jsonDataForServer(const QModelIndex& currentIndex) const {
|
||||
const QJsonObject itemObject = data(currentIndex, ToJsonRole).toJsonObject();
|
||||
QJsonObject rootObject;
|
||||
rootObject.insert(ITEM_KEY_STRING, itemObject);
|
||||
const QJsonDocument jsonDoc(rootObject);
|
||||
return jsonDoc.toJson(QJsonDocument::Compact);
|
||||
}
|
||||
|
||||
QString TableModel::updateItemsFromJson(const QByteArray& jsonData) {
|
||||
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonData, ITEM_KEY_STRING);
|
||||
int nChangedItems = 0;
|
||||
for (const ModelItemValues& itemValues : valueList) {
|
||||
bool updateHappened = updateItem(itemValues);
|
||||
if (updateHappened) {
|
||||
nChangedItems++;
|
||||
}
|
||||
}
|
||||
return QString("Found and updated %1 item(s).").arg(nChangedItems);
|
||||
}
|
||||
|
||||
bool TableModel::updateItem(const ModelItemValues& itemValues) {
|
||||
QModelIndex foundIndex = searchItemIndex(itemValues);
|
||||
|
||||
qDebug() << "Search done!";
|
||||
if (foundIndex == QModelIndex()) {
|
||||
const QString errorMessage = "No matching item found!";
|
||||
qWarning() << errorMessage;
|
||||
return false;
|
||||
} else {
|
||||
qInfo() << "Item found!";
|
||||
/// update existing item
|
||||
setItemData(foundIndex, itemValues);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
|
||||
if (parentIndex != QModelIndex()) {
|
||||
qWarning() << "Removing of child rows is not supported yet!";
|
||||
@ -182,7 +236,13 @@ void TableModel::appendItems(const QByteArray& jsonDoc) { insertItems(-1, jsonDo
|
||||
void TableModel::insertItems(int startPosition,
|
||||
const QByteArray& jsonDoc,
|
||||
const QModelIndex& parentIndex) {
|
||||
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEM_KEY_STRING);
|
||||
const QList<ModelItemValues> valueList = JsonParser::toItemValuesList(jsonDoc, ITEMS_KEY_STRING);
|
||||
|
||||
if (valueList.empty()) {
|
||||
/// don't try inserting if no values to insert
|
||||
qDebug() << "No items found in JSON document. Not adding anything...";
|
||||
return;
|
||||
}
|
||||
|
||||
insertItems(startPosition, valueList, parentIndex);
|
||||
}
|
||||
@ -234,7 +294,7 @@ void TableModel::execEditItemData(const int row, const QMap<int, QVariant>& chan
|
||||
/// is getting notified about (potential) data changes; dataChanged should be called only for
|
||||
/// the affected columns
|
||||
const QModelIndex firstIndex = this->index(row, 0);
|
||||
const QModelIndex lastIndex = this->index(row, ROLE_NAMES.size() - 1);
|
||||
const QModelIndex lastIndex = this->index(row, USER_FACING_ROLES.size() - 1);
|
||||
QList<int> roles = changedValues.keys();
|
||||
roles.insert(0, Qt::DisplayRole);
|
||||
emit dataChanged(firstIndex, lastIndex, roles.toVector());
|
||||
@ -251,12 +311,6 @@ QMap<int, QVariant> TableModel::onlyChangedValues(const QModelIndex& index,
|
||||
const QVariant oldValue = index.data(role);
|
||||
// TODO check if role is a editable role?
|
||||
if (oldValue != newValue) {
|
||||
bool emptyValueIsEqualToZero = isEmptyValueEqualToZero(role);
|
||||
if (emptyValueIsEqualToZero && oldValue == QVariant() && newValue == 0) {
|
||||
qDebug() << "oldValue:" << oldValue << "& newValue:" << newValue
|
||||
<< "mean the same. Ignoring...";
|
||||
continue;
|
||||
}
|
||||
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
|
||||
result.insert(role, newValue);
|
||||
} else {
|
||||
@ -275,3 +329,81 @@ bool TableModel::isEmptyValueEqualToZero(const int role) const {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
int TableModel::getAppropriateRoleForIndex(const QModelIndex& index, const int role) const {
|
||||
/// cases:
|
||||
/// 1. Qt::DisplayRole, Qt::EditRole
|
||||
/// -> get role for column
|
||||
/// 2. other roles
|
||||
/// -> use role as given
|
||||
const int column = index.column();
|
||||
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
case Qt::EditRole:
|
||||
return roleForColumn;
|
||||
break;
|
||||
default:
|
||||
return role;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const {
|
||||
for (int row = 0; row < rowCount(); ++row) {
|
||||
qDebug() << "Processing item at row" << row << "...";
|
||||
QModelIndex itemIndex = index(row, 0);
|
||||
if (isItemEqualToItemValues(itemIndex, givenItemValues)) {
|
||||
qInfo() << "Found item at row" << row << "! Returning its index...";
|
||||
return itemIndex;
|
||||
}
|
||||
}
|
||||
qDebug() << "No matching item found. Returning empty pointer...";
|
||||
return {};
|
||||
}
|
||||
|
||||
bool TableModel::isItemEqualToItemValues(const QModelIndex& itemIndex,
|
||||
const ModelItemValues givenItemValues) const {
|
||||
/// do both have a UUID?
|
||||
QVariant idOfItem = data(itemIndex, IdRole);
|
||||
QVariant given = givenItemValues.value(IdRole);
|
||||
if (idOfItem.isValid() && given.isValid()) {
|
||||
/// are the UUIDs the same?
|
||||
if (idOfItem.toString() == given.toString()) {
|
||||
qInfo() << "UUIDs are the same.";
|
||||
return true;
|
||||
} else {
|
||||
qDebug() << "UUIDs are NOT the same.";
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
/// are all other values the same? (for now only USER_FACING_ROLES are checked)
|
||||
QListIterator<UserRoles> i(USER_FACING_ROLES);
|
||||
while (i.hasNext()) {
|
||||
const UserRoles role = i.next();
|
||||
const QString roleName = ROLE_NAMES.value(role);
|
||||
const QVariant valueOfItem = data(itemIndex, role);
|
||||
const QVariant givenValue = givenItemValues.value(role);
|
||||
if (STRING_ROLES.contains(role)) {
|
||||
if (valueOfItem.toString() != givenValue.toString()) {
|
||||
return false;
|
||||
}
|
||||
} else if (TYPE_ROLES.contains(role)) {
|
||||
if (valueOfItem.toString() != givenValue.toString()) {
|
||||
return false;
|
||||
}
|
||||
} else if (INT_ROLES.contains(role)) {
|
||||
if (valueOfItem.toInt() != givenValue.toInt()) {
|
||||
return false;
|
||||
}
|
||||
} else if (DOUBLE_ROLES.contains(role)) {
|
||||
if (valueOfItem.toDouble() != givenValue.toDouble()) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
qCritical() << QString("Can't find data type for role %1!!!").arg(role);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -8,7 +8,7 @@ class ModelItem;
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef QHash<int, QVariant> ModelItemValues;
|
||||
typedef QMap<int, QVariant> ModelItemValues;
|
||||
|
||||
class TableModel : public QAbstractTableModel {
|
||||
Q_OBJECT
|
||||
@ -38,6 +38,11 @@ class TableModel : public QAbstractTableModel {
|
||||
QJsonDocument getAllItemsAsJsonDoc() const;
|
||||
QList<QStringList> getItemsAsStringLists() const;
|
||||
|
||||
QByteArray jsonDataForServer(const QModelIndex& currentIndex) const;
|
||||
|
||||
QString updateItemsFromJson(const QByteArray& jsonData);
|
||||
bool updateItem(const ModelItemValues& itemValues);
|
||||
|
||||
public slots:
|
||||
// bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex())
|
||||
// override;
|
||||
@ -66,6 +71,10 @@ class TableModel : public QAbstractTableModel {
|
||||
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
|
||||
const QMap<int, QVariant>& roleValueMap) const;
|
||||
bool isEmptyValueEqualToZero(const int role) const;
|
||||
int getAppropriateRoleForIndex(const QModelIndex& index, const int role) const;
|
||||
QModelIndex searchItemIndex(const ModelItemValues givenItemValues) const;
|
||||
bool isItemEqualToItemValues(const QModelIndex& itemIndex,
|
||||
const ModelItemValues givenItemValues) const;
|
||||
};
|
||||
|
||||
#endif // TABLEMODEL_H
|
||||
|
||||
14
network/apiroutes.h
Normal file
14
network/apiroutes.h
Normal file
@ -0,0 +1,14 @@
|
||||
#ifndef APIROUTES_H
|
||||
#define APIROUTES_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
// TODO add namespace
|
||||
|
||||
static const QString apiPrefix = "/api/";
|
||||
|
||||
static const QString ROUTE_LOG_IN = apiPrefix + "log_in";
|
||||
|
||||
static const QString ROUTE_ITEMS = apiPrefix + "items";
|
||||
|
||||
#endif // APIROUTES_H
|
||||
223
network/servercommunicator.cpp
Normal file
223
network/servercommunicator.cpp
Normal file
@ -0,0 +1,223 @@
|
||||
#include "servercommunicator.h"
|
||||
#include "apiroutes.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QRestReply>
|
||||
|
||||
#include "../formats/jsonparser.h"
|
||||
|
||||
using namespace Qt::StringLiterals;
|
||||
|
||||
ServerCommunicator::ServerCommunicator(QObject* parent)
|
||||
: QObject{parent} {
|
||||
m_netManager.setAutoDeleteReplies(true);
|
||||
m_restManager = std::make_shared<QRestAccessManager>(&m_netManager);
|
||||
m_serviceApi = std::make_shared<QNetworkRequestFactory>();
|
||||
}
|
||||
|
||||
bool ServerCommunicator::sslSupported() {
|
||||
#if QT_CONFIG(ssl)
|
||||
return QSslSocket::supportsSsl();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
QUrl ServerCommunicator::url() const { return m_serviceApi->baseUrl(); }
|
||||
|
||||
void ServerCommunicator::setUrl(const QUrl& url) {
|
||||
if (m_serviceApi->baseUrl() == url) {
|
||||
return;
|
||||
}
|
||||
m_serviceApi->setBaseUrl(url);
|
||||
QHttpHeaders authenticationHeaders;
|
||||
authenticationHeaders.append(QHttpHeaders::WellKnownHeader::ContentType, "application/json");
|
||||
m_serviceApi->setCommonHeaders(authenticationHeaders);
|
||||
emit urlChanged();
|
||||
}
|
||||
|
||||
void ServerCommunicator::setServerConfiguration(const QString url,
|
||||
const QString email,
|
||||
const QString password,
|
||||
const QString authToken) {
|
||||
setUrl(url);
|
||||
|
||||
m_email = email;
|
||||
m_password = password;
|
||||
m_authToken = authToken;
|
||||
|
||||
if (authToken.isEmpty()) {
|
||||
if (validLoginCredentials()) {
|
||||
const QByteArray userCredentials =
|
||||
JsonParser::userCredentialsToJsonDocument(m_email, m_password);
|
||||
sendPostRequest(ROUTE_LOG_IN, userCredentials);
|
||||
}
|
||||
} else {
|
||||
/// authToken not empty:
|
||||
m_serviceApi->setBearerToken(authToken.toLatin1());
|
||||
}
|
||||
}
|
||||
|
||||
void ServerCommunicator::fetchItems() { sendGetRequest(ROUTE_ITEMS); }
|
||||
|
||||
void ServerCommunicator::sendItem(const QByteArray& jsonData) {
|
||||
sendPostRequest(ROUTE_ITEMS, jsonData);
|
||||
}
|
||||
|
||||
void ServerCommunicator::deleteItem(const QString& id) {
|
||||
const QString path = QString("%1/%2").arg(ROUTE_ITEMS, id);
|
||||
sendDeleteRequest(path);
|
||||
}
|
||||
|
||||
bool ServerCommunicator::validLoginCredentials() {
|
||||
if (url().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (m_email.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (m_password.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void ServerCommunicator::sendGetRequest(const QString& path) {
|
||||
// TODO check for valid path, instead of emptiness
|
||||
if (path.isEmpty()) {
|
||||
qDebug() << "Empty path -> Not sending a request.";
|
||||
return;
|
||||
}
|
||||
|
||||
const QNetworkRequest request = m_serviceApi->createRequest(path);
|
||||
m_restManager->get(request, this, [this, path](QRestReply& reply) {
|
||||
if (reply.isSuccess()) {
|
||||
qInfo() << "Request successful.";
|
||||
const QJsonDocument doc = reply.readJson().value();
|
||||
onGetReplySuccessful(path, doc);
|
||||
} else {
|
||||
if (reply.hasError()) {
|
||||
const QString errorString = reply.errorString();
|
||||
qWarning() << "Network error:" << errorString;
|
||||
onGetReplyFailure(path, errorString);
|
||||
} else {
|
||||
int statusCode = reply.httpStatus();
|
||||
qWarning() << "Request not successful:" << statusCode;
|
||||
if (statusCode == 401) {
|
||||
notAuthorized(path);
|
||||
} else {
|
||||
onGetReplyFailure(path, QString("HTTP status code: %1").arg(statusCode));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerCommunicator::onGetReplySuccessful(const QString& path, const QJsonDocument doc) {
|
||||
if (path == ROUTE_ITEMS) {
|
||||
emit itemsFetched(doc.toJson());
|
||||
} else {
|
||||
qWarning() << "Can't match request path:" << path;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerCommunicator::onGetReplyFailure(const QString& path, const QString errorString) {
|
||||
if (path == ROUTE_ITEMS) {
|
||||
emit itemsFetchFailure(errorString);
|
||||
} else {
|
||||
qWarning() << "Can't match request path:" << path;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerCommunicator::sendPostRequest(const QString& path, const QByteArray data) {
|
||||
const QNetworkRequest request = m_serviceApi->createRequest(path);
|
||||
|
||||
m_restManager->post(request, data, this, [this, path](QRestReply& reply) {
|
||||
if (reply.isSuccess()) {
|
||||
int statusCode = reply.httpStatus();
|
||||
qInfo() << "Request successful. Status code:" << statusCode;
|
||||
const QJsonDocument doc = reply.readJson().value();
|
||||
onPostReplySuccessful(path, doc);
|
||||
} else {
|
||||
if (reply.hasError()) {
|
||||
const QString errorString = reply.errorString();
|
||||
qWarning() << "Network error:" << errorString;
|
||||
onPostReplyFailure(path, errorString);
|
||||
} else {
|
||||
int statusCode = reply.httpStatus();
|
||||
qWarning() << "Request not successful:" << statusCode;
|
||||
qInfo() << "Content:" << reply.readJson();
|
||||
if (statusCode == 401) {
|
||||
notAuthorized(path);
|
||||
} else {
|
||||
onPostReplyFailure(path, QString("HTTP status code: %1").arg(statusCode));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerCommunicator::onPostReplySuccessful(const QString& path, const QJsonDocument doc) {
|
||||
if (path == ROUTE_ITEMS) {
|
||||
emit sendItemSuccessful(doc.toJson());
|
||||
} else if (path == ROUTE_LOG_IN) {
|
||||
qCritical() << "Login success:" << doc.toJson(QJsonDocument::Compact);
|
||||
emit loginSuccessful(doc.toJson(QJsonDocument::Compact));
|
||||
} else {
|
||||
qWarning() << "Can't match request path:" << path;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerCommunicator::onPostReplyFailure(const QString& path, const QString errorString) {
|
||||
if (path == ROUTE_ITEMS) {
|
||||
emit sendItemFailure(errorString);
|
||||
} else if (path == ROUTE_LOG_IN) {
|
||||
qCritical() << "Login failure:" << errorString;
|
||||
emit loginFailure(errorString);
|
||||
} else {
|
||||
qWarning() << "Can't match request path:" << path;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerCommunicator::sendDeleteRequest(const QString& path) {
|
||||
const QNetworkRequest request = m_serviceApi->createRequest(path);
|
||||
m_restManager->deleteResource(request, this, [this, path](QRestReply& reply) {
|
||||
if (reply.isSuccess()) {
|
||||
qInfo() << "Request successful.";
|
||||
const QJsonDocument doc = reply.readJson().value();
|
||||
onDeleteReplySuccessful(path, doc);
|
||||
} else {
|
||||
if (reply.hasError()) {
|
||||
const QString errorString = reply.errorString();
|
||||
qWarning() << "Network error:" << errorString;
|
||||
onDeleteReplyFailure(path, errorString);
|
||||
} else {
|
||||
int statusCode = reply.httpStatus();
|
||||
qWarning() << "Request not successful:" << statusCode;
|
||||
if (statusCode == 401) {
|
||||
notAuthorized(path);
|
||||
} else {
|
||||
onDeleteReplyFailure(path, QString("HTTP status code: %1").arg(statusCode));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void ServerCommunicator::onDeleteReplySuccessful(const QString& path, const QJsonDocument doc) {
|
||||
if (path.startsWith(ROUTE_ITEMS)) {
|
||||
emit deleteItemSuccessful(doc.toJson());
|
||||
} else {
|
||||
qWarning() << "Can't match request path:" << path;
|
||||
}
|
||||
}
|
||||
|
||||
void ServerCommunicator::onDeleteReplyFailure(const QString& path, const QString errorString) {
|
||||
if (path.startsWith(ROUTE_ITEMS)) {
|
||||
emit deleteItemFailure(errorString);
|
||||
} else {
|
||||
qWarning() << "Can't match request path:" << path;
|
||||
}
|
||||
}
|
||||
71
network/servercommunicator.h
Normal file
71
network/servercommunicator.h
Normal file
@ -0,0 +1,71 @@
|
||||
#ifndef SERVERCOMMUNICATOR_H
|
||||
#define SERVERCOMMUNICATOR_H
|
||||
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkRequestFactory>
|
||||
#include <QObject>
|
||||
#include <QRestAccessManager>
|
||||
|
||||
class ServerCommunicator : public QObject {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ServerCommunicator(QObject* parent = nullptr);
|
||||
|
||||
bool sslSupported();
|
||||
|
||||
QUrl url() const;
|
||||
void setUrl(const QUrl& url);
|
||||
|
||||
void setServerConfiguration(const QString url,
|
||||
const QString email,
|
||||
const QString password,
|
||||
const QString authToken);
|
||||
|
||||
public slots:
|
||||
void fetchItems();
|
||||
void sendItem(const QByteArray& jsonData);
|
||||
void deleteItem(const QString& id);
|
||||
// NEXT editItem(const QByteArray& jsonData)
|
||||
|
||||
signals:
|
||||
void urlChanged();
|
||||
|
||||
void loginSuccessful(const QByteArray responseData);
|
||||
void loginFailure(const QString errorString);
|
||||
|
||||
void notAuthorized(const QString path);
|
||||
|
||||
void itemsFetched(const QByteArray jsonDoc);
|
||||
void itemsFetchFailure(const QString errorString);
|
||||
|
||||
void sendItemSuccessful(const QByteArray responseData);
|
||||
void sendItemFailure(const QString errorString);
|
||||
|
||||
void deleteItemSuccessful(const QByteArray responseData);
|
||||
void deleteItemFailure(const QString errorString);
|
||||
|
||||
private:
|
||||
QNetworkAccessManager m_netManager;
|
||||
std::shared_ptr<QRestAccessManager> m_restManager;
|
||||
std::shared_ptr<QNetworkRequestFactory> m_serviceApi;
|
||||
|
||||
QString m_email;
|
||||
QString m_password;
|
||||
QString m_authToken;
|
||||
|
||||
bool validLoginCredentials();
|
||||
|
||||
void sendGetRequest(const QString& path);
|
||||
void onGetReplySuccessful(const QString& path, const QJsonDocument doc);
|
||||
void onGetReplyFailure(const QString& path, const QString errorString);
|
||||
|
||||
void sendPostRequest(const QString& path, const QByteArray data);
|
||||
void onPostReplySuccessful(const QString& path, const QJsonDocument doc);
|
||||
void onPostReplyFailure(const QString& path, const QString errorString);
|
||||
|
||||
void sendDeleteRequest(const QString& path);
|
||||
void onDeleteReplySuccessful(const QString& path, const QJsonDocument doc);
|
||||
void onDeleteReplyFailure(const QString& path, const QString errorString);
|
||||
};
|
||||
|
||||
#endif // SERVERCOMMUNICATOR_H
|
||||
164
utils/messagehandler.h
Normal file
164
utils/messagehandler.h
Normal file
@ -0,0 +1,164 @@
|
||||
#ifndef MESSAGEHANDLER_H
|
||||
#define MESSAGEHANDLER_H
|
||||
/**
|
||||
* Color and formatting codes
|
||||
* @see: http://misc.flogisoft.com/bash/tip_colors_and_formatting
|
||||
*/
|
||||
|
||||
#include <QObject>
|
||||
|
||||
// qSetMessagePattern("%{file}(%{line}): %{message}");
|
||||
// qSetMessagePattern("%{type}(%{line}):\t%{message}");
|
||||
// qSetMessagePattern("%{type}%{file}(%{line}):\t%{message}");
|
||||
|
||||
void consoleHandlerColoredVerbose(QtMsgType type,
|
||||
const QMessageLogContext& context,
|
||||
const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
|
||||
// context.line, context.function, localMsg.constData()); // bold
|
||||
fprintf(stderr, "\033[107;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
void consoleHandlerColoredVerboseInDarkTheme(QtMsgType type,
|
||||
const QMessageLogContext& context,
|
||||
const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
// fprintf(stderr, "\033[1;30mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file,
|
||||
// context.line, context.function, localMsg.constData()); // bold
|
||||
fprintf(stderr, "\033[107;37mDebug: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "\033[107;32mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "\033[43;30mWarning: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "\033[41;30mCritical: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "\033[41;30mFatal: (%s:%u, %s) \t%s\n\033[0m", context.file, context.line,
|
||||
context.function, localMsg.constData());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
void consoleHandlerColored(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
fprintf(stderr, "\033[1;30mDebug: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "\033[0;30mInfo: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "\033[1;33mWarning: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "\033[31mCritical: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "\033[31mFatal: (%s:%u) \t%s\n\033[0m", context.file, context.line,
|
||||
localMsg.constData());
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
|
||||
QByteArray localMsg = msg.toLocal8Bit();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file,
|
||||
context.line, context.function);
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line,
|
||||
context.function);
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef Q_OS_ANDROID
|
||||
#include <android/log.h>
|
||||
|
||||
const char* const applicationName = "Pensieve";
|
||||
void androidMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) {
|
||||
QString report = msg;
|
||||
if (context.file && !QString(context.file).isEmpty()) {
|
||||
report += " in file ";
|
||||
report += QString(context.file);
|
||||
report += " line ";
|
||||
report += QString::number(context.line);
|
||||
}
|
||||
if (context.function && !QString(context.function).isEmpty()) {
|
||||
report += +" function ";
|
||||
report += QString(context.function);
|
||||
}
|
||||
const char* const local = report.toLocal8Bit().constData();
|
||||
switch (type) {
|
||||
case QtDebugMsg:
|
||||
__android_log_write(ANDROID_LOG_DEBUG, applicationName, local);
|
||||
break;
|
||||
case QtInfoMsg:
|
||||
__android_log_write(ANDROID_LOG_INFO, applicationName, local);
|
||||
break;
|
||||
case QtWarningMsg:
|
||||
__android_log_write(ANDROID_LOG_WARN, applicationName, local);
|
||||
break;
|
||||
case QtCriticalMsg:
|
||||
__android_log_write(ANDROID_LOG_ERROR, applicationName, local);
|
||||
break;
|
||||
case QtFatalMsg:
|
||||
default:
|
||||
__android_log_write(ANDROID_LOG_FATAL, applicationName, local);
|
||||
abort();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // MESSAGEHANDLER_H
|
||||
Reference in New Issue
Block a user