KWeatherCore

weatherforecastsource.cpp
1 /*
2  * SPDX-FileCopyrightText: 2020-2021 Han Young <[email protected]>
3  * SPDX-FileCopyrightText: 2020 Devin Lin <[email protected]>
4  *
5  * SPDX-License-Identifier: LGPL-2.0-or-later
6  */
7 
8 #include "weatherforecastsource.h"
9 #include "kweathercore_p.h"
10 #include "locationqueryresult.h"
11 #include "weatherforecast.h"
12 
13 #include <QFile>
14 #include <QJsonDocument>
15 #include <QNetworkAccessManager>
16 #include <QStandardPaths>
17 
18 #include <algorithm>
19 
20 namespace KWeatherCore
21 {
22 class WeatherForecastSourcePrivate
23 {
24 public:
25  QNetworkAccessManager *m_nam = nullptr;
26 };
27 
28 WeatherForecastSource::WeatherForecastSource(QObject *parent)
29  : QObject(parent)
30  , d(new WeatherForecastSourcePrivate)
31 {
32 }
33 
34 WeatherForecastSource::~WeatherForecastSource() = default;
35 
37 {
38  QFile cache(KWeatherCorePrivate::getCacheDirectory(latitude, longitude).path() + QStringLiteral("/cache.json"));
39  QString timezone;
40  // valid cache
41  if (cache.exists() && cache.open(QIODevice::ReadOnly)) {
42  auto weatherforecast = WeatherForecast::fromJson(QJsonDocument::fromJson(cache.readAll()).object());
43  timezone = weatherforecast.timezone();
44  if (weatherforecast.createdTime().secsTo(QDateTime::currentDateTime()) <= 3600) {
45  return new PendingWeatherForecast(weatherforecast);
46  }
47  }
48 
49  if (!d->m_nam) {
50  d->m_nam = new QNetworkAccessManager(this);
51  d->m_nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy);
52  d->m_nam->setStrictTransportSecurityEnabled(true);
53  d->m_nam->enableStrictTransportSecurityStore(true,
55  + QLatin1String("/org.kde.kweathercore/hsts/"));
56  }
57 
58  return new PendingWeatherForecast(latitude, longitude, timezone, d->m_nam);
59 }
60 
62 {
63  return requestData(result.latitude(), result.longitude());
64 }
65 
67 {
68  if (d->m_nam == nam) {
69  return;
70  }
71 
72  if (d->m_nam->parent() == this) {
73  delete d->m_nam;
74  }
75  d->m_nam = nam;
76 }
77 }
QJsonObject object() const const
static WeatherForecast fromJson(QJsonObject obj)
construct from json
QJsonDocument fromJson(const QByteArray &json, QJsonParseError *error)
virtual bool open(QIODevice::OpenMode mode) override
QDateTime currentDateTime()
QString writableLocation(QStandardPaths::StandardLocation type)
bool exists() const const
PendingWeatherForecast * requestData(double latitude, double longitude)
requestData
void setNetworkAccessManager(QNetworkAccessManager *nam)
Set the network access manager to use for network operations.
Class represents location query result.
QByteArray readAll()
The PendingWeatherForecast class contains the reply to an asynchronous weather forecast request.
This file is part of the KDE documentation.
Documentation copyright © 1996-2022 The KDE developers.
Generated on Fri Sep 30 2022 03:57:06 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.