some little refactor, deleting assets

This commit is contained in:
Blue 2024-01-21 16:22:56 -03:00
parent 7a116bfdf2
commit 5c4bd18cdc
Signed by: blue
GPG Key ID: 9B203B252A63EE38
21 changed files with 139 additions and 36 deletions

View File

@ -4,15 +4,11 @@
set(HEADERS set(HEADERS
api.h api.h
codes.h codes.h
finalaction.h
helpers.h
) )
set(SOURCES set(SOURCES
api.cpp api.cpp
codes.cpp codes.cpp
finalaction.cpp
helpers.cpp
) )
target_sources(magpie PRIVATE ${SOURCES}) target_sources(magpie PRIVATE ${SOURCES})

View File

@ -13,13 +13,13 @@
#include "requests/poll.h" #include "requests/poll.h"
#include "requests/listassets.h" #include "requests/listassets.h"
#include "requests/addasset.h" #include "requests/addasset.h"
#include "requests/deleteasset.h"
API::API (Models::Magpie& magpie, QObject* parent): API::API (Models::Magpie& magpie, QObject* parent):
QObject(parent), QObject(parent),
idCounter(0), idCounter(0),
magpie(magpie), magpie(magpie),
network(), network(),
pollReply(),
requests() requests()
{} {}
@ -90,18 +90,6 @@ API::RequestId API::sendLogin (const QString& login, const QString& password, co
return registerAndSend(std::move(log)); return registerAndSend(std::move(log));
} }
API::RequestId API::addAsset (const QString& title, const QString& icon, const QJSValue& finished) {
qDebug() << "Adding asset...";
if (magpie.getState() != Models::Magpie::Authenticated)
return callCallback(finished, "Can not add assets in current state"), 0;
auto add = std::make_unique<Request::AddAsset>(title, icon, QColor::fromString("black"), 1, magpie.getAddress());
add->setAuthorizationToken(magpie.getAccessToken());
connect(add.get(), &Request::AddAsset::success, std::bind(&API::callCallback, this, finished, QString(), QJSValueList{QJSValue(true)}));
connect(add.get(), &Request::AddAsset::error, std::bind(&API::callCallback, this, finished, std::placeholders::_1, QJSValueList{QJSValue(false)}));
return registerAndSend(std::move(add));
}
API::RequestId API::requestAssets (const SuccessListHandler& success, const ErrorHandler& error) { API::RequestId API::requestAssets (const SuccessListHandler& success, const ErrorHandler& error) {
qDebug() << "Requesting assets..."; qDebug() << "Requesting assets...";
@ -112,6 +100,30 @@ API::RequestId API::requestAssets (const SuccessListHandler& success, const Erro
return registerAndSend(std::move(list)); return registerAndSend(std::move(list));
} }
API::RequestId API::addAsset (const QString& title, const QString& icon, const QColor& color, const QJSValue& finished) {
qDebug() << "Adding asset...";
if (magpie.getState() != Models::Magpie::Authenticated)
return callCallback(finished, "Can not add assets in current state"), 0;
auto add = std::make_unique<Request::AddAsset>(title, icon, color, 1, magpie.getAddress());
add->setAuthorizationToken(magpie.getAccessToken());
connect(add.get(), &Request::AddAsset::success, std::bind(&API::callCallback, this, finished, QString(), QJSValueList{QJSValue(true)}));
connect(add.get(), &Request::AddAsset::error, std::bind(&API::callCallback, this, finished, std::placeholders::_1, QJSValueList{QJSValue(false)}));
return registerAndSend(std::move(add));
}
API::RequestId API::deleteAsset (unsigned int id, const QJSValue& finished) {
qDebug() << "Deleting asset...";
if (magpie.getState() != Models::Magpie::Authenticated)
return callCallback(finished, "Can not delete assets in current state"), 0;
auto del = std::make_unique<Request::DeleteAsset>(id, magpie.getAddress());
del->setAuthorizationToken(magpie.getAccessToken());
connect(del.get(), &Request::DeleteAsset::success, std::bind(&API::callCallback, this, finished, QString(), QJSValueList{QJSValue(true)}));
connect(del.get(), &Request::DeleteAsset::error, std::bind(&API::callCallback, this, finished, std::placeholders::_1, QJSValueList{QJSValue(false)}));
return registerAndSend(std::move(del));
}
API::RequestId API::poll (const SuccessMapHandler& success, const ErrorHandler& error, bool clear) { API::RequestId API::poll (const SuccessMapHandler& success, const ErrorHandler& error, bool clear) {
auto poll = std::make_unique<Request::Poll>(magpie.getAddress(), clear); auto poll = std::make_unique<Request::Poll>(magpie.getAddress(), clear);
poll->setAuthorizationToken(magpie.getAccessToken()); poll->setAuthorizationToken(magpie.getAccessToken());

View File

@ -29,7 +29,6 @@ public:
explicit API(Models::Magpie& magpie, QObject* parent = nullptr); explicit API(Models::Magpie& magpie, QObject* parent = nullptr);
RequestId requestAssets(const SuccessListHandler& success, const ErrorHandler& error); RequestId requestAssets(const SuccessListHandler& success, const ErrorHandler& error);
RequestId poll(const SuccessMapHandler& success, const ErrorHandler& error, bool clear = false); RequestId poll(const SuccessMapHandler& success, const ErrorHandler& error, bool clear = false);
@ -40,7 +39,8 @@ public slots:
RequestId test(const QString& path, const QJSValue& finished = QJSValue()); RequestId test(const QString& path, const QJSValue& finished = QJSValue());
RequestId sendRegister(const QString& login, const QString& password, const QJSValue& finished = QJSValue()); RequestId sendRegister(const QString& login, const QString& password, const QJSValue& finished = QJSValue());
RequestId sendLogin(const QString& login, const QString& password, const QJSValue& finished = QJSValue()); RequestId sendLogin(const QString& login, const QString& password, const QJSValue& finished = QJSValue());
RequestId addAsset(const QString& title, const QString& icon, const QJSValue& finished = QJSValue()); RequestId addAsset(const QString& title, const QString& icon, const QColor& color, const QJSValue& finished = QJSValue());
RequestId deleteAsset(unsigned int id, const QJSValue& finished = QJSValue());
private slots: private slots:
void onRequestDone(RequestId id); void onRequestDone(RequestId id);
@ -54,5 +54,4 @@ private:
Models::Magpie& magpie; Models::Magpie& magpie;
QNetworkAccessManager network; QNetworkAccessManager network;
std::map<RequestId, std::unique_ptr<Request::Request>> requests; std::map<RequestId, std::unique_ptr<Request::Request>> requests;
std::unique_ptr<QNetworkReply> pollReply;
}; };

View File

@ -10,6 +10,7 @@ set(HEADERS
poll.h poll.h
listassets.h listassets.h
addasset.h addasset.h
deleteasset.h
) )
set(SOURCES set(SOURCES
@ -21,6 +22,7 @@ set(SOURCES
poll.cpp poll.cpp
listassets.cpp listassets.cpp
addasset.cpp addasset.cpp
deleteasset.cpp
) )
target_sources(magpie PRIVATE ${SOURCES}) target_sources(magpie PRIVATE ${SOURCES})

View File

@ -4,7 +4,12 @@
#include "addasset.h" #include "addasset.h"
Request::AddAsset::AddAsset (const QString& title, const QString& icon, const QColor& color, unsigned int currency, const QUrl& baseUrl): Request::AddAsset::AddAsset (const QString& title, const QString& icon, const QColor& color, unsigned int currency, const QUrl& baseUrl):
Post(createUrl(baseUrl, "/addAsset"), {{"title", title}, {"icon", icon}, {"currency", std::to_string(currency).c_str()}, {"color", "0"}}) Post(createUrl(baseUrl, "/addAsset"), {
{"title", title},
{"icon", icon},
{"currency", std::to_string(currency).c_str()},
{"color", std::to_string(color.rgba()).c_str()}
})
{ {
emptyResult = true; emptyResult = true;
} }

View File

@ -0,0 +1,12 @@
//SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#include "deleteasset.h"
Request::DeleteAsset::DeleteAsset(unsigned int id, const QUrl &baseUrl):
Post(createUrl(baseUrl, "/deleteAsset"), {
{"id", std::to_string(id).c_str()}
})
{
emptyResult = true;
}

View File

@ -0,0 +1,20 @@
//SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QObject>
#include "post.h"
namespace Request {
class DeleteAsset : public Post {
Q_OBJECT
public:
DeleteAsset(unsigned int id, const QUrl& baseUrl);
};
}

View File

@ -3,7 +3,7 @@
#include "listassets.h" #include "listassets.h"
#include "API/helpers.h" #include "utils/helpers.h"
Request::ListAssets::ListAssets (const QUrl& baseUrl): Request::ListAssets::ListAssets (const QUrl& baseUrl):
Request(createUrl(baseUrl, "/listAssets")) {} Request(createUrl(baseUrl, "/listAssets")) {}

View File

@ -60,6 +60,7 @@ endif()
add_subdirectory(qml) add_subdirectory(qml)
add_subdirectory(API) add_subdirectory(API)
add_subdirectory(models) add_subdirectory(models)
add_subdirectory(utils)
target_include_directories(magpie PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) target_include_directories(magpie PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(magpie PRIVATE target_link_libraries(magpie PRIVATE

View File

@ -3,7 +3,7 @@
#include "assets.h" #include "assets.h"
#include "API/helpers.h" #include "utils/helpers.h"
Models::Assets::Assets (QObject* parent): Models::Assets::Assets (QObject* parent):
QAbstractListModel(parent), QAbstractListModel(parent),
@ -45,14 +45,11 @@ void Models::Assets::addAssets (const std::deque<Asset>& assets) {
void Models::Assets::deleteAsset (unsigned int id) { void Models::Assets::deleteAsset (unsigned int id) {
QModelIndex index = getIndex(id); QModelIndex index = getIndex(id);
if (!index.isValid()) if (!index.isValid())
throw std::runtime_error("An attempt to insert to delete non existing Asset from asset model"); throw std::runtime_error("An attempt to delete non existing Asset from asset model");
int row = index.row(); int row = index.row();
beginRemoveRows(QModelIndex(), row, row); beginRemoveRows(QModelIndex(), row, row);
records.erase(records.begin() + row); records.erase(records.begin() + row);
if (state == State::syncronized) //give a second thought
state = State::initial;
endRemoveRows(); endRemoveRows();
} }
@ -67,9 +64,9 @@ int Models::Assets::rowCount (const QModelIndex& parent) const {
} }
QHash<int, QByteArray> Models::Assets::roleNames () const { QHash<int, QByteArray> Models::Assets::roleNames () const {
static const QHash<int, QByteArray> roleNames{ static const QHash<int, QByteArray> roleNames({
{Title, "title"}, {Icon, "icon"}, {Balance, "balance"}, {Archived, "archived"}, {Color, "color"} {Title, "title"}, {Icon, "icon"}, {Balance, "balance"}, {Archived, "archived"}, {Color, "color"}, {Id, "assetId"}
}; });
return roleNames; return roleNames;
} }
@ -103,6 +100,8 @@ QVariant Models::Assets::data (const QModelIndex& index, int role) const {
return records[row].archived; return records[row].archived;
case Color: case Color:
return records[row].color; return records[row].color;
case Id:
return records[row].id;
} }
} }
@ -122,8 +121,7 @@ bool Models::Assets::deserialize (const QVariantList& from, std::deque<Asset>& o
asset.id = ser.value("id").toUInt(); asset.id = ser.value("id").toUInt();
uint32_t color = ser.value("color").toUInt(); uint32_t color = ser.value("color").toUInt();
uint8_t* rgba = reinterpret_cast<uint8_t*>(&color); asset.color = QColor::fromRgba(color);
asset.color = QColor::fromRgb(rgba[0], rgba[1], rgba[2], rgba[3]);
} }
return true; return true;

View File

@ -33,7 +33,8 @@ public:
Icon, Icon,
Balance, Balance,
Archived, Archived,
Color Color,
Id
}; };
void clear(); void clear();

View File

@ -6,8 +6,8 @@
#include <QDebug> #include <QDebug>
#include "API/api.h" #include "API/api.h"
#include "API/helpers.h"
#include "API/codes.h" #include "API/codes.h"
#include "utils/helpers.h"
Models::Magpie::Magpie (QObject* parent): Models::Magpie::Magpie (QObject* parent):
QObject(parent), QObject(parent),
@ -190,6 +190,17 @@ bool Models::Magpie::handleChanges (const QVariantMap& changes) {
else else
Magpie::assets.addAssets(added); Magpie::assets.addAssets(added);
} }
aItr = assets.constFind("removed");
if (aItr != assets.constEnd() && aItr.value().canConvert<QVariantList>()) {
const QVariantList rem = qast<QVariantList>(aItr.value());
for (const QVariant& vId : rem) {
if (vId.isValid() && vId.canConvert<unsigned int>())
Magpie::assets.deleteAsset(vId.toUInt());
else
qDebug() << "Error deserializing removed assets";
}
}
} }
return true; return true;

View File

@ -52,6 +52,7 @@ signals:
void stateChanged(State state); void stateChanged(State state);
void storeTokens(const QString& access, const QString& renew); void storeTokens(const QString& access, const QString& renew);
void displayError(const QString& err);
public: public:
Assets assets; Assets assets;

View File

@ -4,7 +4,9 @@
import QtQuick import QtQuick
import QtQuick.Controls import QtQuick.Controls
import magpie
import magpie.Forms as Forms import magpie.Forms as Forms
import magpie.Components as Components
Item { Item {
StackView { StackView {
@ -27,4 +29,17 @@ Item {
onSuccess: stack.pop() onSuccess: stack.pop()
} }
} }
Connections {
target: Magpie
function onDisplayError (err) {
modal.status = err;
modal.open();
}
}
Components.Modal {
id: modal
closable: true
}
} }

View File

@ -4,16 +4,21 @@
import QtQuick import QtQuick
import QtQuick.Controls import QtQuick.Controls
import magpie
Item { Item {
id: line id: line
required property string title required property string title
required property string icon required property string icon
required property color color required property color color
required property string balance required property string balance
required property int assetId
signal error (err:string)
Row { Row {
readonly property int iconSize: height readonly property int iconSize: height
readonly property int freespace: width - iconSize - spacing * children.length - 1 readonly property int freespace: width - deleteButton.width - iconSize - spacing * children.length - 1
anchors.fill: parent anchors.fill: parent
spacing: 5 spacing: 5
@ -49,5 +54,16 @@ Item {
verticalAlignment: Text.AlignVCenter verticalAlignment: Text.AlignVCenter
color: palette.text color: palette.text
} }
Button {
id: deleteButton
text: qsTr("Delete")
flat: true
height: parent.height
onClicked: API.deleteAsset(line.assetId, function(err) {
if (err)
Magpie.displayError("Error deleting asset " + line.title + ": " + err);
})
}
} }
} }

View File

@ -86,7 +86,7 @@ Item {
modal.status = qsTr("Creating new asset ") + " " + title + "..."; modal.status = qsTr("Creating new asset ") + " " + title + "...";
modal.open(); modal.open();
API.addAsset(title, icon, function (err, result) { API.addAsset(title, icon, "blue", function (err, result) {
if (!modal.inProgress) if (!modal.inProgress)
return; return;

14
utils/CMakeLists.txt Normal file
View File

@ -0,0 +1,14 @@
# SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
# SPDX-License-Identifier: GPL-3.0-or-later
set(HEADERS
finalaction.h
helpers.h
)
set(SOURCES
finalaction.cpp
helpers.cpp
)
target_sources(magpie PRIVATE ${SOURCES})