File indexing completed on 2024-04-28 17:05:12

0001 // SPDX-FileCopyrightText: 2022 Felipe Kinoshita <kinofhek@gmail.com>
0002 // SPDX-License-Identifier: LGPL-2.1-or-later
0003 
0004 #include <QNetworkReply>
0005 
0006 #include <QJsonDocument>
0007 #include <QJsonObject>
0008 #include <QUrlQuery>
0009 
0010 #include "controller.h"
0011 
0012 Controller::Controller(QObject* parent)
0013     : QObject(parent)
0014 {
0015 }
0016 
0017 void Controller::fetch(QUrl url, QJsonObject options)
0018 {
0019     // handle data
0020     QJsonDocument doc(data());
0021     QByteArray inputData = doc.toJson();
0022 
0023     // handle request and timeout
0024     int timeout = options.value(QStringLiteral("timeout")).toInt();
0025     QNetworkRequest request = QNetworkRequest(url);
0026     request.setTransferTimeout(timeout);
0027 
0028     // handle headers
0029     auto headers = options.value(QStringLiteral("headers")).toObject().toVariantMap();
0030     QMap<QString, QVariant>::const_iterator j = headers.constBegin();
0031     while (j != headers.constEnd()) {
0032         request.setRawHeader(QByteArray(j.key().toLocal8Bit()), QByteArray(j.value().toString().toLocal8Bit()));
0033         j++;
0034     }
0035 
0036     // handle reply
0037     QNetworkReply* reply;
0038     QString method = options.value(QStringLiteral("method")).toString();
0039 
0040     if (method == QStringLiteral("get")) {
0041         reply = m_manager.get(request);
0042     } else if (method == QStringLiteral("post")) {
0043         reply = m_manager.post(request, inputData);
0044     } else if (method == QStringLiteral("put")) {
0045         reply = m_manager.put(request, inputData);
0046     } else if (method == QStringLiteral("patch")) {
0047         reply = m_manager.sendCustomRequest(request, "PATCH", inputData);
0048     } else if (method == QStringLiteral("delete")) {
0049         reply = m_manager.deleteResource(request);
0050     } else {
0051         reply = m_manager.get(request);
0052     }
0053 
0054     // read data
0055     QObject::connect(reply, &QNetworkReply::finished, [this, reply]() {
0056         QJsonDocument data = QJsonDocument::fromJson(reply->readAll());
0057         auto formattedString = QString::fromLatin1(data.toJson());
0058 
0059         Q_EMIT response(formattedString);
0060         Q_EMIT status(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString());
0061 
0062         reply->deleteLater(); // make sure to clean up
0063     });
0064 }