2017-06-06 21:18:05 +02:00
|
|
|
#pragma once
|
2017-04-12 17:46:44 +02:00
|
|
|
|
|
|
|
#include <QJsonArray>
|
|
|
|
#include <QJsonDocument>
|
|
|
|
#include <QJsonObject>
|
|
|
|
#include <QJsonValue>
|
|
|
|
#include <QNetworkAccessManager>
|
|
|
|
#include <QNetworkReply>
|
|
|
|
#include <QNetworkRequest>
|
|
|
|
#include <QString>
|
|
|
|
|
|
|
|
#include <functional>
|
|
|
|
|
2017-04-14 17:52:22 +02:00
|
|
|
namespace chatterino {
|
|
|
|
namespace util {
|
2017-04-12 17:46:44 +02:00
|
|
|
|
|
|
|
static void urlFetch(const QString &url, std::function<void(QNetworkReply &)> successCallback)
|
|
|
|
{
|
|
|
|
QNetworkAccessManager *manager = new QNetworkAccessManager();
|
|
|
|
|
|
|
|
QUrl requestUrl(url);
|
|
|
|
QNetworkRequest request(requestUrl);
|
|
|
|
|
|
|
|
QNetworkReply *reply = manager->get(request);
|
|
|
|
|
|
|
|
QObject::connect(reply, &QNetworkReply::finished, [=] {
|
2017-06-06 21:18:05 +02:00
|
|
|
/* uncomment to follow redirects
|
|
|
|
QVariant replyStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
|
|
|
|
if (replyStatus >= 300 && replyStatus <= 304) {
|
|
|
|
QString newUrl =
|
|
|
|
reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
|
|
|
|
urlFetch(newUrl, successCallback);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
|
2017-04-12 17:46:44 +02:00
|
|
|
if (reply->error() == QNetworkReply::NetworkError::NoError) {
|
|
|
|
successCallback(*reply);
|
|
|
|
}
|
|
|
|
|
|
|
|
reply->deleteLater();
|
|
|
|
manager->deleteLater();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
static void urlJsonFetch(const QString &url, std::function<void(QJsonObject &)> successCallback)
|
|
|
|
{
|
|
|
|
urlFetch(url, [=](QNetworkReply &reply) {
|
|
|
|
QByteArray data = reply.readAll();
|
|
|
|
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
|
|
|
|
|
|
|
|
if (jsonDoc.isNull()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
QJsonObject rootNode = jsonDoc.object();
|
|
|
|
|
|
|
|
successCallback(rootNode);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-06-06 21:18:05 +02:00
|
|
|
} // namespace util
|
|
|
|
} // namespace chatterino
|