magpie/API/api.h

68 lines
2.0 KiB
C++

#pragma once
#include <memory>
#include <optional>
#include <map>
#include <QObject>
#include <QString>
#include <QUrl>
#include <QJSValue>
#include <QNetworkAccessManager>
#include <QNetworkReply>
class Root;
class API : public QObject {
friend class Root;
Q_OBJECT
public:
enum State {
Offline,
NoServer,
NotAuthenticated,
Authenticating,
Authenticated
};
Q_ENUM(State)
private:
Q_PROPERTY(QUrl address READ getAddress NOTIFY addressChanged)
Q_PROPERTY(State state READ getState NOTIFY stateChanged)
public:
explicit API(const QUrl& path = QString(), QObject* parent = nullptr);
QUrl getAddress() const;
State getState() const;
void setTokens(const QString access, const QString& renew);
signals:
void addressChanged(const QUrl& path);
void stateChanged(State state);
void storeTokens(const QString& access, const QString& renew);
public slots:
void test(const QString& path, const QJSValue& finished = QJSValue());
void sendRegister(const QString& login, const QString& password, const QJSValue& finished = QJSValue());
void sendLogin(const QString& login, const QString& password, const QJSValue& finished = QJSValue());
private slots:
void onTestFinished(QNetworkReply* reply, const QUrl& addr, const QJSValue& finished);
void onRegisterFinished(QNetworkReply* reply, const QJSValue& finished) const;
void onLoginFinished(QNetworkReply* reply, const QJSValue& finished);
private:
void callCallback(const QJSValue& callback, const QString& error = QString(), const QJSValueList& arguments = QJSValueList()) const;
void setAddress(const QUrl& path);
static std::optional<QVariantMap> readResult(QNetworkReply* reply);
static bool validateResponse(const std::optional<QVariantMap>& data, const std::map<QString, QMetaType::Type>& structure);
private:
QUrl address;
QNetworkAccessManager network;
State state;
QString accessToken;
QString renewToken;
};