livedatamanager.cpp 8.76 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
/*
    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
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "livedatamanager.h"
#include "logging.h"
#include "pkpassmanager.h"
#include "reservationmanager.h"

#include <KItinerary/LocationUtil>
#include <KItinerary/Place>
#include <KItinerary/Reservation>
#include <KItinerary/SortUtil>
#include <KItinerary/TrainTrip>

#include <KPublicTransport/Departure>
#include <KPublicTransport/DepartureReply>
#include <KPublicTransport/DepartureRequest>
#include <KPublicTransport/Location>
#include <KPublicTransport/Manager>

#include <QDateTime>
Volker Krause's avatar
Volker Krause committed
36 37 38 39 40 41
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStandardPaths>
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <QVector>

using namespace KItinerary;

LiveDataManager::LiveDataManager(QObject *parent)
    : QObject(parent)
{
}

LiveDataManager::~LiveDataManager() = default;

void LiveDataManager::setReservationManager(ReservationManager *resMgr)
{
    m_resMgr = resMgr;
    // TODO set up change monitoring

    const auto resIds = resMgr->reservations();
    for (const auto &resId : resIds) {
        const auto res = resMgr->reservation(resId);
        if (!LocationUtil::isLocationChange(res)) { // we only care about transit reservations
            continue;
        }
        if (SortUtil::endtDateTime(res) < QDateTime::currentDateTime().addDays(-1)) {
            continue; // we don't care about past events
        }

        m_reservations.push_back(resId);
    }

    std::sort(m_reservations.begin(), m_reservations.end(), [this](const auto &lhs, const auto &rhs) {
        return SortUtil::isBefore(m_resMgr->reservation(lhs), m_resMgr->reservation(rhs));
    });
Volker Krause's avatar
Volker Krause committed
74 75

    loadPublicTransportData();
76 77 78 79 80 81 82
}

void LiveDataManager::setPkPassManager(PkPassManager *pkPassMgr)
{
    m_pkPassMgr = pkPassMgr;
}

83 84 85 86 87
QVariant LiveDataManager::arrival(const QString &resId)
{
    return QVariant::fromValue(m_arrivals.value(resId));
}

88 89 90 91
QVariant LiveDataManager::departure(const QString &resId)
{
    return QVariant::fromValue(m_departures.value(resId));
}
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

void LiveDataManager::checkForUpdates()
{
    qCDebug(Log) << m_reservations.size();
    m_pkPassMgr->updatePasses(); // TODO do this as part of the below loop

    for (auto it = m_reservations.begin(); it != m_reservations.end();) {
        const auto res = m_resMgr->reservation(*it);

        // clean up old stuff (TODO: do this a bit more precisely)
        if (SortUtil::endtDateTime(res) < QDateTime::currentDateTime().addDays(-1)) {
            it = m_reservations.erase(it);
            continue;
        }

        if (JsonLd::isA<TrainReservation>(res)) {
            checkTrainTrip(res.value<TrainReservation>().reservationFor().value<TrainTrip>(), *it);
        }

        // TODO check for pkpass updates

        ++it;
    }
}

static QString stripSpecial(const QString &str)
{
    QString res;
    res.reserve(str.size());
    std::copy_if(str.begin(), str.end(), std::back_inserter(res), [](const auto c) {
        return c.isLetter() || c.isDigit();
    });
    return res;
}

static bool isSameLine(const QString &lineName, const QString &trainName, const QString &trainNumber)
{
    const auto lhs = stripSpecial(lineName);
    const auto rhs = stripSpecial(trainName + trainNumber);
    return lhs.compare(rhs, Qt::CaseInsensitive) == 0;
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
static KPublicTransport::Location locationFromStation(const TrainStation &station)
{
    using namespace KPublicTransport;
    Location loc;
    loc.setName(station.name());
    loc.setCoordinate(station.geo().latitude(), station.geo().longitude());
    if (!station.identifier().isEmpty()) {
        const auto idSplit = station.identifier().split(QLatin1Char(':'));
        if (idSplit.size() == 2) {
            loc.setIdentifier(idSplit.at(0), idSplit.at(1));
        }
    }
    return loc;
}

149 150 151 152 153 154 155 156 157
void LiveDataManager::checkTrainTrip(const TrainTrip& trip, const QString& resId)
{
    qCDebug(Log) << trip.trainName() << trip.trainNumber() << trip.departureTime();
    if (!m_ptMgr) {
        m_ptMgr.reset(new KPublicTransport::Manager);
    }

    using namespace KPublicTransport;

158
    DepartureRequest req(locationFromStation(trip.departureStation()));
159 160
    req.setDateTime(trip.departureTime());
    auto reply = m_ptMgr->queryDeparture(req);
161
    connect(reply, &Reply::finished, this, [this, trip, resId, reply]() {
162 163 164 165 166 167
        reply->deleteLater();
        if (reply->error() != Reply::NoError) {
            qCDebug(Log) << reply->error() << reply->errorString();
            return;
        }

168
        for (const auto &dep : reply->result()) {
169 170
            qCDebug(Log) << "Got departure information:" << dep.route().line().name() << dep.scheduledDepartureTime() << "for" << trip.trainNumber();
            if (dep.scheduledDepartureTime() != trip.departureTime() || !isSameLine(dep.route().line().name(), trip.trainName(), trip.trainNumber())) {
171 172
                continue;
            }
173
            qCDebug(Log) << "Found departure information:" << dep.route().line().name() << dep.expectedPlatform() << dep.expectedDepartureTime();
174
            m_departures.insert(resId, dep);
Volker Krause's avatar
Volker Krause committed
175
            storePublicTransportData(resId, dep, QStringLiteral("departure"));
176
            emit departureUpdated(resId);
177 178 179
            break;
        }
    });
180 181 182 183 184 185 186 187 188 189 190 191

    req = DepartureRequest(locationFromStation(trip.arrivalStation()));
    req.setMode(DepartureRequest::QueryArrival);
    req.setDateTime(trip.arrivalTime());
    reply = m_ptMgr->queryDeparture(req);
    connect(reply, &Reply::finished, this, [this, trip, resId, reply]() {
        reply->deleteLater();
        if (reply->error() != Reply::NoError) {
            qCDebug(Log) << reply->error() << reply->errorString();
            return;
        }

192
        for (const auto &arr : reply->result()) {
193 194 195 196 197 198
            qCDebug(Log) << "Got arrival information:" << arr.route().line().name() << arr.scheduledArrivalTime() << "for" << trip.trainNumber();
            if (arr.scheduledArrivalTime() != trip.arrivalTime() || !isSameLine(arr.route().line().name(), trip.trainName(), trip.trainNumber())) {
                continue;
            }
            qCDebug(Log) << "Found arrival information:" << arr.route().line().name() << arr.expectedPlatform() << arr.expectedDepartureTime();
            m_arrivals.insert(resId, arr);
Volker Krause's avatar
Volker Krause committed
199
            storePublicTransportData(resId, arr, QStringLiteral("arrival"));
200 201 202 203 204
            emit arrivalUpdated(resId);
            break;
        }
    });

205
}
206

Volker Krause's avatar
Volker Krause committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
void LiveDataManager::loadPublicTransportData(const QString &prefix, QHash<QString, KPublicTransport::Departure> &data) const
{
    const auto basePath = QString(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/publictransport/"));
    QDirIterator it(basePath + prefix, QDir::Files | QDir::NoSymLinks);
    while (it.hasNext()) {
        it.next();
        const auto resId = it.fileInfo().baseName();
        if (std::find(m_reservations.begin(), m_reservations.end(), resId) == m_reservations.end()) {
            QDir(it.path()).remove(it.fileName());
        } else {
            QFile f(it.filePath());
            if (!f.open(QFile::ReadOnly)) {
                qCWarning(Log) << "Failed to load public transport file" << f.fileName() << f.errorString();
                continue;
            }
            data.insert(resId, KPublicTransport::Departure::fromJson(QJsonDocument::fromJson(f.readAll()).object()));
        }
    }
}

void LiveDataManager::loadPublicTransportData()
{
    loadPublicTransportData(QStringLiteral("arrival"), m_arrivals);
    loadPublicTransportData(QStringLiteral("departure"), m_departures);
}

void LiveDataManager::storePublicTransportData(const QString &resId, const KPublicTransport::Departure &dep, const QString &type) const
{
    const auto basePath = QString(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + QLatin1String("/publictransport/")
        + type + QLatin1Char('/'));
    QDir().mkpath(basePath);

    QFile file(basePath + resId + QLatin1String(".json"));
    if (!file.open(QFile::WriteOnly | QFile::Truncate)) {
        qCWarning(Log) << "Failed to open public transport cache file:" << file.fileName() << file.errorString();
        return;
    }
    file.write(QJsonDocument(KPublicTransport::Departure::toJson(dep)).toJson());
}

247
#include "moc_livedatamanager.cpp"