| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #ifndef APISERVER_H |
| 4 | #define APISERVER_H |
| 5 | |
| 6 | #include "network-web/httpserver.h" |
| 7 | |
| 8 | #include <QJsonDocument> |
| 9 | #include <QJsonObject> |
| 10 | |
| 11 | struct ApiRequest { |
| 12 | Q_GADGET |
| 13 | |
| 14 | public: |
| 15 | enum class Method { |
| 16 | Unknown = 0, |
| 17 | AppVersion = 1, |
| 18 | ArticlesFromFeed = 2, |
| 19 | MarkArticles = 3 |
| 20 | }; |
| 21 | |
| 22 | Q_ENUM(Method) |
| 23 | |
| 24 | explicit ApiRequest(const QJsonDocument& data); |
| 25 | |
| 26 | Method m_method; |
| 27 | QJsonValue m_parameters; |
| 28 | }; |
| 29 | |
| 30 | struct ApiResponse { |
| 31 | Q_GADGET |
| 32 | |
| 33 | public: |
| 34 | enum class Result { |
| 35 | Success = 1, |
| 36 | Error = 2 |
| 37 | }; |
| 38 | |
| 39 | Q_ENUM(Result) |
| 40 | |
| 41 | explicit ApiResponse(Result result, ApiRequest::Method method, const QJsonValue& response = {}); |
| 42 | |
| 43 | Result m_result; |
| 44 | ApiRequest::Method m_method; |
| 45 | QJsonValue m_response; |
| 46 | |
| 47 | QJsonDocument toJson() const; |
| 48 | }; |
| 49 | |
| 50 | class ApiServer : public HttpServer { |
| 51 | public: |
| 52 | explicit ApiServer(QObject* parent = nullptr); |
| 53 | |
| 54 | protected: |
| 55 | virtual void answerClient(QTcpSocket* socket, const HttpRequest& request); |
| 56 | |
| 57 | private: |
| 58 | QByteArray processCorsPreflight() const; |
| 59 | QByteArray processHtmlPage() const; |
| 60 | |
| 61 | ApiResponse processRequest(const ApiRequest& req) const; |
| 62 | ApiResponse processAppVersion() const; |
| 63 | ApiResponse processArticlesFromFeed(const QJsonValue& req) const; |
| 64 | ApiResponse processUnknown() const; |
| 65 | ApiResponse processMarkArticles(const QJsonValue& req) const; |
| 66 | }; |
| 67 | |
| 68 | #endif // APISERVER_H |