// SPDX-FileCopyrightText: 2023 Yury Gubich // SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include #include #include #include #include #include #include #include #include #include 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); void startPolling(); 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); void onPollFinished(QNetworkReply* reply); void onFirstPollSuccess(); private: void callCallback(const QJSValue& callback, const QString& error = QString(), const QJSValueList& arguments = QJSValueList()) const; void setAddress(const QUrl& path); static std::optional readResult(QNetworkReply* reply); static bool validateResponse(const std::optional& data, const std::map& structure); void setState(State newState); QUrl createUrl(const QString& path) const; private: QUrl address; QNetworkAccessManager network; State state; QString accessToken; QString renewToken; QTimer firstPoll; };