Files

93 lines
2.3 KiB
C++
Raw Permalink Normal View History

2017-12-19 21:34:44 +01:00
#include "weatherwidget.h"
2017-12-19 22:01:06 +01:00
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QUrl>
2017-12-29 02:00:36 +01:00
#include <QDebug>
2017-12-19 22:01:06 +01:00
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
2017-12-19 21:34:44 +01:00
#include "mainwindow.h"
2017-12-19 22:01:06 +01:00
#include "zeiterfassungsettings.h"
#include "zeiterfassungapi.h"
2017-12-19 21:34:44 +01:00
2018-03-11 14:46:34 +01:00
#include "weathersettings.h"
2017-12-19 21:34:44 +01:00
WeatherWidget::WeatherWidget(MainWindow &mainWindow) :
QLabel(&mainWindow),
m_mainWindow(mainWindow)
{
2017-12-19 22:01:06 +01:00
setFrameShape(QFrame::Panel);
setFrameShadow(QFrame::Sunken);
connect(&m_mainWindow, &MainWindow::refreshEverything, this, &WeatherWidget::refresh);
refresh();
}
void WeatherWidget::refresh()
{
setText(tr("Loading..."));
2018-03-11 14:46:34 +01:00
auto url = WeatherSettings(m_mainWindow.settings()).url();
2017-12-19 22:01:06 +01:00
2018-03-11 14:46:34 +01:00
m_reply = std::unique_ptr<QNetworkReply>(m_mainWindow.erfassung().manager()->get(QNetworkRequest(url)));
2017-12-19 22:01:06 +01:00
connect(m_reply.get(), &QNetworkReply::finished, this, &WeatherWidget::finished);
}
void WeatherWidget::finished()
{
if(m_reply->error() != QNetworkReply::NoError)
{
qWarning() << m_reply->errorString();
setText(tr("Request failed"));
goto after;
}
{
QJsonParseError error;
auto document = QJsonDocument::fromJson(m_reply->readAll(), &error);
if(error.error != QJsonParseError::NoError)
{
qWarning() << error.errorString();
setText(tr("Parsing failed"));
goto after;
}
if(!document.isObject())
{
setText(tr("Not an json obj"));
goto after;
}
auto obj = document.object();
if(!obj.contains(QStringLiteral("weather")))
{
qWarning() << "no weather" << obj;
2017-12-21 21:49:02 +01:00
setText(tr("No weather found"));
2017-12-19 22:01:06 +01:00
goto after;
}
if(!obj.contains(QStringLiteral("main")))
{
qWarning() << "no main" << obj;
2017-12-21 21:49:02 +01:00
setText(tr("No main found"));
2017-12-19 22:01:06 +01:00
goto after;
}
auto weaterObj = obj.value(QStringLiteral("weather")).toArray();
auto mainObj = obj.value(QStringLiteral("main")).toObject();
setText(tr("%0 (%1°C)").arg(weaterObj.first().toObject().value(QStringLiteral("main")).toString())
.arg(mainObj.value(QStringLiteral("temp")).toDouble()));
}
after:
m_reply = Q_NULLPTR;
2017-12-19 21:34:44 +01:00
}