weatherforecastmanager.cpp 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
    Copyright (C) 2018 Volker Krause <vkrause@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This program is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU General Public License
15
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 17 18 19 20 21 22 23
*/

#include "weatherforecastmanager.h"
#include "weatherforecast.h"
#include "weathertile.h"

#include <QCoreApplication>
#include <QDir>
24
#include <QDirIterator>
25 26 27 28 29 30 31 32 33 34 35
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QStandardPaths>
#include <QUrlQuery>
#include <QVariant>
#include <QXmlStreamReader>

#include <zlib.h>

#include <cmath>

36 37 38 39 40
static void alignToHour(QDateTime &dt)
{
    dt.setTime(QTime(dt.time().hour(), 0, 0, 0));
}

41 42 43 44 45 46 47 48 49 50
static void roundToHour(QDateTime &dt)
{
    if (dt.time().minute() >= 30) {
        alignToHour(dt);
        dt = dt.addSecs(3600);
    } else {
        alignToHour(dt);
    }
}

51 52 53 54 55 56 57 58 59
/*
 * ATTENTION!
 * Before touching anything in here, especially regarding the network operations
 * make sure to read and understand https://api.met.no/conditions_service.html!
 */

WeatherForecastManager::WeatherForecastManager(QObject *parent)
    : QObject(parent)
{
60 61
    connect(&m_updateTimer, &QTimer::timeout, this, &WeatherForecastManager::updateAll);
    m_updateTimer.setSingleShot(true);
62 63 64 65
}

WeatherForecastManager::~WeatherForecastManager() = default;

66 67 68
void WeatherForecastManager::setAllowNetworkAccess(bool enabled)
{
    m_allowNetwork = enabled;
69 70 71 72 73
    if (enabled) {
        scheduleUpdate();
    } else {
        m_updateTimer.stop();
    }
74 75 76
    fetchNext();
}

77 78 79
void WeatherForecastManager::monitorLocation(float latitude, float longitude)
{
    WeatherTile t{latitude, longitude};
Volker Krause's avatar
Volker Krause committed
80
    qDebug() << latitude << longitude << t.lat << t.lon;
81 82 83 84 85 86 87 88 89 90

    auto it = std::lower_bound(m_monitoredTiles.begin(), m_monitoredTiles.end(), t);
    if (it != m_monitoredTiles.end() && (*it) == t) {
        return;
    }

    m_monitoredTiles.insert(it, t);
    fetchTile(t);
}

91
WeatherForecast WeatherForecastManager::forecast(float latitude, float longitude, const QDateTime &dt) const
92
{
93 94 95 96 97
    return forecast(latitude, longitude, dt, dt.addSecs(3600));
}

WeatherForecast WeatherForecastManager::forecast(float latitude, float longitude, const QDateTime &begin, const QDateTime &end) const
{
98 99 100 101 102 103 104 105 106 107 108 109 110
    if (Q_UNLIKELY(m_testMode)) {
        WeatherForecast fc;
        auto beginDt = begin;
        roundToHour(beginDt);
        fc.setDateTime(beginDt);
        fc.setTile({latitude, longitude});
        fc.setMinimumTemperature(std::min(latitude, longitude));
        fc.setMaximumTemperature(std::max(latitude, longitude));
        fc.setPrecipitation(23.0f);
        fc.setSymbolType(WeatherForecast::LightClouds);
        return fc;
    }

111
    auto beginDt = std::max(begin, QDateTime::currentDateTimeUtc());
112
    roundToHour(beginDt);
113
    auto endDt = std::max(end, QDateTime::currentDateTimeUtc());
114
    roundToHour(endDt);
115 116 117
    if (!beginDt.isValid() || !endDt.isValid() || beginDt > endDt) {
        return {};
    }
118 119 120
    if (beginDt == endDt) {
        endDt = endDt.addSecs(3600);
    }
121
    const auto range = beginDt.secsTo(endDt) / 3600;
122

123 124 125 126
    WeatherTile tile{latitude, longitude};
    if (!loadForecastData(tile)) {
        return {};
    }
127

128
    const auto &forecasts = m_forecastData[tile];
129
    const auto beginIt = std::lower_bound(forecasts.begin(), forecasts.end(), beginDt, [](const WeatherForecast &lhs, const QDateTime &rhs) {
130 131
        return lhs.dateTime() < rhs;
    });
132 133
    if (beginIt == forecasts.end()) {
        return {};
134
    }
135 136 137 138 139
    const auto endIt = std::lower_bound(forecasts.begin(), forecasts.end(), endDt, [](const WeatherForecast &lhs, const QDateTime &rhs) {
        return lhs.dateTime() < rhs;
    });

    WeatherForecast fc(*beginIt);
140
    fc.setRange(range);
141 142
    for (auto it = beginIt; it != endIt; ++it) {
        fc.merge(*it);
143
    }
144
    return fc;
145 146 147 148
}

void WeatherForecastManager::fetchTile(WeatherTile tile)
{
149 150 151 152 153
    QFileInfo fi(cachePath(tile) + QLatin1String("forecast.xml"));
    if (fi.exists() && fi.lastModified().toUTC().addSecs(3600 * 2) >= QDateTime::currentDateTimeUtc()) { // cache is already new enough
        return;
    }

154 155 156 157 158 159
    m_pendingTiles.push_back(tile);
    fetchNext();
}

void WeatherForecastManager::fetchNext()
{
160
    if (!m_allowNetwork || m_pendingReply || m_pendingTiles.empty()) {
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        return;
    }

    const auto tile = m_pendingTiles.front();
    m_pendingTiles.pop_front();

    if (!m_nam) {
        m_nam = new QNetworkAccessManager(this);
    }

    QUrl url;
    url.setScheme(QStringLiteral("https"));
    url.setHost(QStringLiteral("api.met.no"));
    url.setPath(QStringLiteral("/weatherapi/locationforecast/1.9/"));
    QUrlQuery query;
176 177
    query.addQueryItem(QStringLiteral("lat"), QString::number(tile.latitude()));
    query.addQueryItem(QStringLiteral("lon"), QString::number(tile.longitude()));
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    url.setQuery(query);

    qDebug() << url;
    QNetworkRequest req(url);
    req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
    req.setAttribute(QNetworkRequest::User, QVariant::fromValue(tile));

    // see §Identification on https://api.met.no/conditions_service.html
    req.setHeader(QNetworkRequest::UserAgentHeader, QString(QCoreApplication::applicationName() +
        QLatin1Char(' ') + QCoreApplication::applicationVersion() + QLatin1String(" (kde-pim@kde.org)")));
    // TODO see §Cache on https://api.met.no/conditions_service.html
    // see §Compression on https://api.met.no/conditions_service.html
    req.setRawHeader("Accept-Encoding", "gzip");

    m_pendingReply = m_nam->get(req);
    connect(m_pendingReply, &QNetworkReply::finished, this, &WeatherForecastManager::tileDownloaded);
}

void WeatherForecastManager::tileDownloaded()
{
    // TODO handle 304 Not Modified
    // TODO handle 429 Too Many Requests
    if (m_pendingReply->error() != QNetworkReply::NoError) {
        qWarning() << m_pendingReply->errorString();
    } else {
        writeToCacheFile(m_pendingReply);
    }

    m_pendingReply->deleteLater();
    m_pendingReply = nullptr;
    if (m_pendingTiles.empty()) {
        emit forecastUpdated();
    }
    fetchNext();
}

QString WeatherForecastManager::cachePath(WeatherTile tile) const
{
    const auto path = QString(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
        + QLatin1String("/weather/")
Volker Krause's avatar
Volker Krause committed
218 219
        + QString::number(tile.lat) + QLatin1Char('/')
        + QString::number(tile.lon) + QLatin1Char('/'));
220 221 222 223 224 225 226
    QDir().mkpath(path);
    return path;
}

void WeatherForecastManager::writeToCacheFile(QNetworkReply* reply) const
{
    const auto tile = reply->request().attribute(QNetworkRequest::User).value<WeatherTile>();
Volker Krause's avatar
Volker Krause committed
227
    qDebug() << tile.lat << tile.lon;
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    qDebug() << reply->rawHeaderPairs();
    QFile f(cachePath(tile) + QLatin1String("forecast.xml"));
    if (!f.open(QFile::WriteOnly)) {
        qWarning() << "Failed to open weather cache location:" << f.errorString();
        return;
    }

    const auto contentEncoding = reply->rawHeader("Content-Encoding");
    if (contentEncoding == "gzip") {
        const auto data = reply->readAll();
        if (data.size() < 4 || data.at(0) != 0x1f || data.at(1) != char(0x8b)) {
            qWarning() << "Invalid gzip format";
            return;
        }

        z_stream stream;
        unsigned char buffer[1024];

        stream.zalloc = nullptr;
        stream.zfree = nullptr;
        stream.opaque = nullptr;
        stream.avail_in = data.size();
        stream.next_in = reinterpret_cast<unsigned char*>(const_cast<char*>(data.data()));

        auto ret = inflateInit2(&stream, 15 + 32); // see docs, the magic numbers enable gzip decoding
        if (ret != Z_OK) {
            qWarning() << "Failed to initialize zlib stream.";
            return;
        }

        do {
            stream.avail_out = sizeof(buffer);
            stream.next_out = buffer;

            ret = inflate(&stream, Z_NO_FLUSH);
            if (ret != Z_OK && ret != Z_STREAM_END) {
                qWarning() << "Zlib decoding failed!" << ret;
                break;
            }

            f.write(reinterpret_cast<char*>(buffer), sizeof(buffer) - stream.avail_out);
        } while (stream.avail_out == 0);
        inflateEnd(&stream);
    } else {
        f.write(reply->readAll());
    }
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

    m_forecastData.erase(tile);
}

bool WeatherForecastManager::loadForecastData(WeatherTile tile) const
{
    const auto it = m_forecastData.find(tile);
    if (it != m_forecastData.end()) {
        return true;
    }

    QFile f(cachePath(tile) + QLatin1String("forecast.xml"));
    if (!f.exists() || !f.open(QFile::ReadOnly)) {
        return false;
    }

    QXmlStreamReader reader(&f);
291
    auto forecasts = parseForecast(reader, tile);
292 293 294 295 296 297 298
    mergeForecasts(forecasts);
    if (forecasts.empty()) {
        return false;
    }

    m_forecastData.insert(it, {tile, std::move(forecasts)});
    return true;
299 300 301 302 303
}

void WeatherForecastManager::mergeForecasts(std::vector<WeatherForecast>& forecasts) const
{
    std::stable_sort(forecasts.begin(), forecasts.end(), [](const WeatherForecast &lhs, const WeatherForecast &rhs) {
304 305
        if (lhs.dateTime() == rhs.dateTime())
            return lhs.range() < rhs.range();
306 307 308 309 310 311 312 313 314 315 316 317
        return lhs.dateTime() < rhs.dateTime();
    });

    // merge duplicated time slices
    auto storeIt = forecasts.begin();
    for (auto it = forecasts.begin(); it != forecasts.end();) {
        (*storeIt) = (*it);
        auto mergeIt = it;
        for (; mergeIt != forecasts.end(); ++mergeIt) {
            if ((*it).dateTime() == (*mergeIt).dateTime()) {
                (*storeIt).merge(*mergeIt);
            } else {
318
                (*mergeIt).setRange(1);
319 320 321 322 323 324 325 326 327
                break;
            }
        }
        ++storeIt;
        it = mergeIt;
    }
    forecasts.erase(storeIt, forecasts.end());
}

328
std::vector<WeatherForecast> WeatherForecastManager::parseForecast(QXmlStreamReader &reader, WeatherTile tile) const
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
{
    std::vector<WeatherForecast> result;

    auto beginDt = QDateTime::currentDateTimeUtc();
    alignToHour(beginDt);

    while (!reader.atEnd()) {
        if (reader.tokenType() == QXmlStreamReader::StartElement) {
            if (reader.name() == QLatin1String("weatherdata") || reader.name() == QLatin1String("product")) {
                reader.readNext(); // enter these elements
                continue;
            }
            if (reader.name() == QLatin1String("time") && reader.attributes().value(QLatin1String("datatype")) == QLatin1String("forecast")) {
                // normalize time ranges to 1 hour
                auto from = QDateTime::fromString(reader.attributes().value(QLatin1String("from")).toString(), Qt::ISODate);
                from = std::max(from, beginDt);
                alignToHour(from);
                auto to = QDateTime::fromString(reader.attributes().value(QLatin1String("to")).toString(), Qt::ISODate);
                alignToHour(to);
348
                const auto range = from.secsTo(to) / 3600;
349 350 351 352 353 354 355 356 357
                if (to == from) {
                    to = to.addSecs(3600);
                }
                if (to < beginDt || to <= from || !to.isValid() || !from.isValid()) {
                    reader.skipCurrentElement();
                    continue;
                }
                auto fc = parseForecastElement(reader);
                for (int i = 0; i < from.secsTo(to); i += 3600) {
358
                    fc.setTile(tile);
359
                    fc.setDateTime(from.addSecs(i));
360
                    fc.setRange(range);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
                    result.push_back(fc);
                }
                continue;
            }
            // unknown element
            reader.skipCurrentElement();
        } else {
            reader.readNext();
        }
    }

    return result;
}

// Icon mapping: https://api.met.no/weatherapi/weathericon/1.1/documentation
Volker Krause's avatar
Volker Krause committed
376 377 378 379 380 381 382
struct symbol_map_t {
    uint8_t id;
    WeatherForecast::SymbolType type;
};

static const symbol_map_t symbol_map[] = {
    {  1, WeatherForecast::Clear }, // 1 Sun
383 384
    {  2, WeatherForecast::Clear | WeatherForecast::LightClouds }, // 2 LightCloud
    {  3, WeatherForecast::Clear | WeatherForecast::Clouds }, // 3 PartlyCloud
Volker Krause's avatar
Volker Krause committed
385
    {  4, WeatherForecast::Clouds }, // 4 Cloud
386 387 388 389
    {  5, WeatherForecast::Clear | WeatherForecast::LightRain }, // 5 LightRainSun
    {  6, WeatherForecast::Clear | WeatherForecast::LightRain | WeatherForecast::ThunderStorm }, // 6 LightRainThunderSun
    {  7, WeatherForecast::Clear | WeatherForecast::Hail }, // 7 SleetSun
    {  8, WeatherForecast::Clear | WeatherForecast::Snow }, // 8 SnowSun
Volker Krause's avatar
Volker Krause committed
390 391
    {  9, WeatherForecast::LightRain }, // 9 LightRain
    { 10, WeatherForecast::Rain }, // 10 Rain
392
    { 11, WeatherForecast::Rain | WeatherForecast::ThunderStorm }, // 11 RainThunder
Volker Krause's avatar
Volker Krause committed
393 394
    { 12, WeatherForecast::Hail }, // 12 Sleet
    { 13, WeatherForecast::Snow }, // 13 Snow
395
    { 14, WeatherForecast::Snow | WeatherForecast::ThunderStorm }, // 14 SnowThunder
Volker Krause's avatar
Volker Krause committed
396
    { 15, WeatherForecast::Fog }, // 15 Fog
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    { 20, WeatherForecast::Clear | WeatherForecast::Hail | WeatherForecast::ThunderStorm }, // 20 SleetSunThunder
    { 21, WeatherForecast::Clear | WeatherForecast::Snow | WeatherForecast::ThunderStorm }, // 21 SnowSunThunder
    { 22, WeatherForecast::LightRain | WeatherForecast::ThunderStorm }, // 22 LightRainThunder
    { 23, WeatherForecast::Hail | WeatherForecast::ThunderStorm }, // 23 SleetThunder
    { 24, WeatherForecast::Clear | WeatherForecast::LightRain | WeatherForecast::ThunderStorm }, // 24 DrizzleThunderSun
    { 25, WeatherForecast::Clear | WeatherForecast::Rain | WeatherForecast::ThunderStorm }, // 25 RainThunderSun
    { 26, WeatherForecast::Clear | WeatherForecast::Hail | WeatherForecast::ThunderStorm }, // 26 LightSleetThunderSun
    { 27, WeatherForecast::Clear | WeatherForecast::Hail | WeatherForecast::ThunderStorm }, // 27 HeavySleetThunderSun
    { 28, WeatherForecast::Clear |  WeatherForecast::LightSnow | WeatherForecast::ThunderStorm }, // 28 LightSnowThunderSun
    { 29, WeatherForecast::Clear | WeatherForecast::Snow | WeatherForecast::ThunderStorm }, // 29 HeavySnowThunderSun
    { 30, WeatherForecast::LightRain | WeatherForecast::ThunderStorm }, // 30 DrizzleThunder
    { 31, WeatherForecast::Hail | WeatherForecast::ThunderStorm }, // 31 LightSleetThunder
    { 32, WeatherForecast::Hail | WeatherForecast::ThunderStorm }, // 32 HeavySleetThunder
    { 33, WeatherForecast::LightSnow | WeatherForecast::ThunderStorm }, // 33 LightSnowThunder
    { 34, WeatherForecast::Snow | WeatherForecast::ThunderStorm }, // 34 HeavySnowThunder
    { 40, WeatherForecast::Clear | WeatherForecast::LightRain }, // 40 DrizzleSun
    { 41, WeatherForecast::Clear | WeatherForecast::Rain}, // 41 RainSun
    { 42, WeatherForecast::Clear | WeatherForecast::Hail }, // 42 LightSleetSun
    { 43, WeatherForecast::Clear | WeatherForecast::Hail }, // 43 HeavySleetSun
    { 44, WeatherForecast::Clear | WeatherForecast::LightSnow }, // 44 LightSnowSun
    { 45, WeatherForecast::Clear | WeatherForecast::Snow }, // 45 HeavysnowSun
Volker Krause's avatar
Volker Krause committed
418 419 420 421 422
    { 46, WeatherForecast::LightRain }, // 46 Drizzle
    { 47, WeatherForecast::Hail }, // 47 LightSleet
    { 48, WeatherForecast::Hail }, // 48 HeavySleet
    { 49, WeatherForecast::LightSnow }, // 49 LightSnow
    { 50, WeatherForecast::Snow } // 50 HeavySnow
423 424 425 426 427 428 429 430 431
};

WeatherForecast WeatherForecastManager::parseForecastElement(QXmlStreamReader &reader) const
{
    WeatherForecast fc;
    while (!reader.atEnd()) {
        switch (reader.tokenType()) {
            case QXmlStreamReader::StartElement:
                if (reader.name() == QLatin1String("temperature")) {
432 433 434 435 436 437 438
                    const auto t = reader.attributes().value(QLatin1String("value")).toFloat();
                    fc.setMinimumTemperature(t);
                    fc.setMaximumTemperature(t);
                } else if (reader.name() == QLatin1String("minTemperature")) {
                    fc.setMinimumTemperature(reader.attributes().value(QLatin1String("value")).toFloat());
                } else if (reader.name() == QLatin1String("maxTemperature")) {
                    fc.setMaximumTemperature(reader.attributes().value(QLatin1String("value")).toFloat());
439 440 441 442 443
                } else if (reader.name() == QLatin1String("symbol")) {
                    auto symId = reader.attributes().value(QLatin1String("number")).toInt();
                    if (symId > 100) {
                        symId -= 100; // map polar night symbols
                    }
Volker Krause's avatar
Volker Krause committed
444 445 446 447 448
                    const auto it = std::lower_bound(std::begin(symbol_map), std::end(symbol_map), symId, [](symbol_map_t lhs, uint8_t rhs) {
                        return lhs.id < rhs;
                    });
                    if (it != std::end(symbol_map) && (*it).id == symId) {
                        fc.setSymbolType((*it).type);
449
                    }
Volker Krause's avatar
Volker Krause committed
450 451
                } else if (reader.name() == QLatin1String("precipitation")) {
                    fc.setPrecipitation(reader.attributes().value(QLatin1String("value")).toFloat());
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
                }
                break;
            case QXmlStreamReader::EndElement:
                if (reader.name() == QLatin1String("time")) {
                    return fc;
                }
                break;
            default:
                break;
        }
        reader.readNext();
    }

    return fc;
}

468
QDateTime WeatherForecastManager::maximumForecastTime(const QDate &today) const
469
{
470
    return QDateTime(today.addDays(9), QTime(0, 0));
471 472
}

473 474 475 476 477
void WeatherForecastManager::setTestModeEnabled(bool testMode)
{
    m_testMode = testMode;
}

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
void WeatherForecastManager::scheduleUpdate()
{
    if (m_updateTimer.isActive()) {
        return;
    }

    // see §Updates on https://api.met.no/conditions_service.html
    m_updateTimer.setInterval(std::chrono::hours(2) + std::chrono::minutes(QTime::currentTime().msec() % 30));
    qDebug() << "Next weather update:" << m_updateTimer.interval();
    m_updateTimer.start();
}

void WeatherForecastManager::updateAll()
{
    for (const auto tile : m_monitoredTiles) {
        fetchTile(tile);
    }
    purgeCache();
    scheduleUpdate();
}

void WeatherForecastManager::purgeCache()
{
    const auto basePath = QString(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/weather/"));
    const auto cutoffDate = QDateTime::currentDateTimeUtc().addDays(-9);

    QDirIterator it(basePath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Writable, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        it.next();
        if (it.fileInfo().isFile() && it.fileInfo().lastModified() < cutoffDate) {
            qDebug() << "Purging old weather data:" << it.filePath();
            QFile::remove(it.filePath());
        } else if (it.fileInfo().isDir() && QDir(it.filePath()).isEmpty()) {
            qDebug() << "Purging old weather cache folder:" << it.filePath();
            QDir().rmdir(it.filePath());
        }
    }
}

517
#include "moc_weatherforecastmanager.cpp"