reservationmanager.cpp 15.4 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
*/

#include "reservationmanager.h"
19
#include "pkpassmanager.h"
20 21
#include "logging.h"

22 23
#include <KItinerary/ExtractorEngine>
#include <KItinerary/ExtractorPostprocessor>
24 25
#include <KItinerary/Flight>
#include <KItinerary/JsonLdDocument>
26
#include <KItinerary/MergeUtil>
27 28
#include <KItinerary/Reservation>
#include <KItinerary/SortUtil>
29

30
#include <QDate>
31 32 33 34 35
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
36
#include <QJsonObject>
37
#include <QStandardPaths>
Volker Krause's avatar
Volker Krause committed
38
#include <QUrl>
39 40 41 42 43
#include <QUuid>
#include <QVector>

using namespace KItinerary;

44 45 46 47 48 49 50 51 52 53 54
static bool isSameTrip(const QVariant &lhs, const QVariant &rhs)
{
    if (lhs.userType() != rhs.userType() || !JsonLd::canConvert<Reservation>(lhs) || !JsonLd::canConvert<Reservation>(rhs)) {
        return false;
    }

    const auto lhsTrip = JsonLd::convert<Reservation>(lhs).reservationFor();
    const auto rhsTrip = JsonLd::convert<Reservation>(rhs).reservationFor();
    return MergeUtil::isSame(lhsTrip, rhsTrip);
}

55 56 57
ReservationManager::ReservationManager(QObject* parent)
    : QObject(parent)
{
58
    loadBatches();
59 60 61 62
}

ReservationManager::~ReservationManager() = default;

63 64 65 66 67 68 69 70
void ReservationManager::setPkPassManager(PkPassManager* mgr)
{
    m_passMgr = mgr;
    connect(mgr, &PkPassManager::passAdded, this, &ReservationManager::passAdded);
    connect(mgr, &PkPassManager::passUpdated, this, &ReservationManager::passUpdated);
    connect(mgr, &PkPassManager::passRemoved, this, &ReservationManager::passRemoved);
}

71
bool ReservationManager::hasBatch(const QString &batchId) const
72
{
73
    return m_batchToResMap.contains(batchId);
74 75
}

76 77
QVector<QString> ReservationManager::reservations() const
{
78
    const auto base = reservationsBasePath();
79
    QDir::root().mkpath(base);
80 81

    QVector<QString> resIds;
82
    for (QDirIterator it(base, QDir::NoDotAndDotDot | QDir::Files); it.hasNext();) {
83 84 85 86 87 88 89 90 91
        it.next();
        resIds.push_back(it.fileInfo().baseName());
    }

    return resIds;
}

QVariant ReservationManager::reservation(const QString& id) const
{
92 93 94 95
    if (id.isEmpty()) {
        return {};
    }

96 97 98 99 100
    const auto it = m_reservations.constFind(id);
    if (it != m_reservations.constEnd()) {
        return it.value();
    }

101
    const QString resPath = reservationsBasePath() + id + QLatin1String(".jsonld");
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    QFile f(resPath);
    if (!f.open(QFile::ReadOnly)) {
        qCWarning(Log) << "Failed to open JSON-LD reservation data file:" << resPath << f.errorString();
        return {};
    }

    const auto doc = QJsonDocument::fromJson(f.readAll());
    if (!doc.isArray() && doc.array().size() != 1) {
        qCWarning(Log) << "Invalid JSON-LD reservation data file:" << resPath;
        return {};
    }

    const auto resData = JsonLdDocument::fromJson(doc.array());
    if (resData.size() != 1) {
        qCWarning(Log) << "Unable to parse JSON-LD reservation data file:" << resPath;
        return {};
    }

120 121 122 123 124 125 126 127 128 129 130
    // re-run post-processing to benefit from newer augmentations
    ExtractorPostprocessor postproc;
    postproc.process(resData);
    if (postproc.result().size() != 1) {
        qCWarning(Log) << "Post-processing discarded the reservation:" << resPath;
        return {};
    }

    const auto res = postproc.result().at(0);
    m_reservations.insert(id, res);
    return res;
131 132
}

133
QString ReservationManager::reservationsBasePath()
134 135 136 137
{
    return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QLatin1String("/reservations/");
}

138 139 140 141 142
QString ReservationManager::batchesBasePath()
{
    return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QLatin1String("/batches/");
}

143 144
void ReservationManager::importReservation(const QByteArray& data)
{
Volker Krause's avatar
Volker Krause committed
145 146
    QJsonParseError error;
    const auto doc = QJsonDocument::fromJson(data, &error);
147
    if (!doc.isArray()) {
Volker Krause's avatar
Volker Krause committed
148
        qCWarning(Log) << "Invalid JSON format." << error.errorString() << error.offset;
149 150 151 152
        return;
    }

    const auto resData = JsonLdDocument::fromJson(doc.array());
153 154 155 156 157
    importReservations(resData);
}

void ReservationManager::importReservations(const QVector<QVariant> &resData)
{
158 159 160 161
    ExtractorPostprocessor postproc;
    postproc.setContextDate(QDateTime(QDate::currentDate(), QTime(0, 0)));
    postproc.process(resData);

162 163 164 165 166
    const auto data = postproc.result();
    for (const auto &res : data) {
        addReservation(res);
    }
}
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
void ReservationManager::addReservation(const QVariant &res)
{
    // look for matching reservations, or matching batches
    // we need to do that within a +/-24h range, so we find unbound elements too
    const auto rangeBegin = SortUtil::startDateTime(res).addDays(-1);
    const auto rangeEnd = rangeBegin.addDays(2);

    const auto beginIt = std::lower_bound(m_batches.begin(), m_batches.end(), rangeBegin, [this](const auto &lhs, const auto &rhs) {
        return SortUtil::startDateTime(reservation(lhs)) < rhs;
    });
    for (auto it = beginIt; it != m_batches.end(); ++it) {
        const auto otherRes = reservation(*it);
        if (SortUtil::startDateTime(otherRes) > rangeEnd) {
            break; // no hit
        }
        if (MergeUtil::isSame(res, otherRes)) {
            // this is actually an update of otherRes!
            const auto newRes = JsonLdDocument::apply(otherRes, res);
            updateReservation(*it, newRes);
            return;
188
        }
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        if (isSameTrip(res, otherRes)) {
            // this is a multi-traveler element, check if we have it as one of the batch elements already
            const auto &batch = m_batchToResMap.value(*it);
            for (const auto &batchedId : batch) {
                const auto batchedRes = reservation(batchedId);
                if (MergeUtil::isSame(res, batchedRes)) {
                    // this is actually an update of a batched reservation
                    const auto newRes = JsonLdDocument::apply(otherRes, res);
                    updateReservation(batchedId, newRes);
                    return;
                }
            }

            // truely new, and added to an existing batch
            const QString resId = QUuid::createUuid().toString();
            storeReservation(resId, res);
            emit reservationAdded(resId);
206

207 208 209 210 211
            m_batchToResMap[*it].push_back(resId);
            m_resToBatchMap.insert(resId, *it);
            emit batchChanged(*it);
            storeBatch(*it);
            return;
212 213 214
        }
    }

215
    // truely new, and starting a new batch
216 217
    const QString resId = QUuid::createUuid().toString();
    storeReservation(resId, res);
218
    emit reservationAdded(resId);
219 220 221 222 223 224

    m_batches.insert(beginIt, resId);
    m_batchToResMap.insert(resId, {resId});
    m_resToBatchMap.insert(resId, resId);
    emit batchAdded(resId);
    storeBatch(resId);
225
}
226

227
void ReservationManager::updateReservation(const QString &resId, const QVariant &res)
228
{
229 230
    const auto oldRes = reservation(resId);

231 232
    storeReservation(resId, res);
    emit reservationUpdated(resId);
233

234
    updateBatch(resId, res, oldRes);
235 236 237
}

void ReservationManager::storeReservation(const QString &resId, const QVariant &res) const
238
{
239
    const QString basePath = reservationsBasePath();
240 241 242 243 244 245 246 247 248
    QDir::root().mkpath(basePath);
    const QString path = basePath + resId + QLatin1String(".jsonld");
    QFile f(path);
    if (!f.open(QFile::WriteOnly)) {
        qCWarning(Log) << "Unable to open file:" << f.errorString();
        return;
    }
    f.write(QJsonDocument(JsonLdDocument::toJson({res})).toJson());
    m_reservations.insert(resId, res);
249 250
}

251 252
void ReservationManager::removeReservation(const QString& id)
{
253 254 255 256
    const auto batchId = m_resToBatchMap.value(id);
    removeFromBatch(id, batchId);

    const QString basePath = reservationsBasePath();
257 258
    QFile::remove(basePath + QLatin1Char('/') + id + QLatin1String(".jsonld"));
    emit reservationRemoved(id);
259
    m_reservations.remove(id);
260
}
261

262 263 264 265 266 267
void ReservationManager::removeReservations(const QStringList& ids)
{
    for (const auto &id : ids)
        removeReservation(id);
}

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
const std::vector<QString>& ReservationManager::batches() const
{
    return m_batches;
}

QString ReservationManager::batchForReservation(const QString &resId) const
{
    return m_resToBatchMap.value(resId);
}

QStringList ReservationManager::reservationsForBatch(const QString &batchId) const
{
    return m_batchToResMap.value(batchId);
}

void ReservationManager::removeBatch(const QString &batchId)
{
    // TODO make this atomic, ie. don't emit batch range notifications
    const auto res = m_batchToResMap.value(batchId);
    for (const auto &id : res) {
        if (id != batchId) {
            removeReservation(id);
        }
    }
    removeReservation(batchId);
}

295 296 297
void ReservationManager::passAdded(const QString& passId)
{
    const auto pass = m_passMgr->pass(passId);
298 299 300 301 302
    ExtractorEngine engine;
    engine.setPass(pass);
    const auto data = engine.extract();
    const auto res = JsonLdDocument::fromJson(data);
    importReservations(res);
303 304 305 306 307 308 309 310 311 312 313 314
}

void ReservationManager::passUpdated(const QString& passId)
{
    passAdded(passId);
}

void ReservationManager::passRemoved(const QString& passId)
{
    Q_UNUSED(passId);
    // TODO
}
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

void ReservationManager::loadBatches()
{
    Q_ASSERT(m_batches.empty());

    const auto base = batchesBasePath();
    if (!QDir::root().exists(base)) {
        initialBatchCreate();
        return;
    }

    for (QDirIterator it(base, QDir::NoDotAndDotDot | QDir::Files); it.hasNext();) {
        it.next();
        QFile batchFile(it.filePath());
        if (!batchFile.open(QFile::ReadOnly)) {
            qCWarning(Log) << "Failed to open batch file" << it.filePath() << batchFile.errorString();
            continue;
        }

        const auto batchId = it.fileInfo().baseName();
        m_batches.push_back(batchId);

        const auto batchDoc = QJsonDocument::fromJson(batchFile.readAll());
        const auto top = batchDoc.object();
        const auto resArray = top.value(QLatin1String("elements")).toArray();
        QStringList l;
        l.reserve(resArray.size());
        for (const auto &v : resArray) {
            const auto resId = v.toString();
            l.push_back(resId);
            m_resToBatchMap.insert(resId, batchId);
        }
        m_batchToResMap.insert(batchId, l);
    }

    std::sort(m_batches.begin(), m_batches.end(), [this](const auto &lhs, const auto &rhs) {
        return SortUtil::isBefore(reservation(lhs), reservation(rhs));
    });
}

void ReservationManager::storeBatch(const QString &batchId) const
{
    QJsonArray elems;
    const auto &batch = m_batchToResMap.value(batchId);
    std::copy(batch.begin(), batch.end(), std::back_inserter(elems));

    QJsonObject top;
    top.insert(QLatin1String("elements"), elems);

    const QString path = batchesBasePath() + batchId + QLatin1String(".json");
    QFile f(path);
    if (!f.open(QFile::WriteOnly | QFile::Truncate)) {
        qCWarning(Log) << "Failed to open batch file!" << path << f.errorString();
        return;
    }

    f.write(QJsonDocument(top).toJson());
}

void ReservationManager::storeRemoveBatch(const QString &batchId) const
{
    const QString path = batchesBasePath() + batchId + QLatin1String(".json");
    QFile::remove(path);
}

void ReservationManager::initialBatchCreate()
{
    const auto batchBase = batchesBasePath();
    QDir::root().mkpath(batchBase);
    qCDebug(Log) << batchBase;

    const QSignalBlocker blocker(this);
    const auto base = reservationsBasePath();
    for (QDirIterator it(base, QDir::NoDotAndDotDot | QDir::Files); it.hasNext();) {
        it.next();
        const auto resId = it.fileInfo().baseName();
        const auto res = reservation(resId);
392
        updateBatch(resId, res, res);
393 394 395
    }
}

396
void ReservationManager::updateBatch(const QString &resId, const QVariant &newRes, const QVariant &oldRes)
397 398 399 400 401
{
    const auto oldBatchId = batchForReservation(resId);
    QString newBatchId;

    // find the destination batch
402
    const auto beginIt = std::lower_bound(m_batches.begin(), m_batches.end(), newRes, [this](const auto &lhs, const auto &rhs) {
403 404 405
        return SortUtil::startDateTime(reservation(lhs)) < SortUtil::startDateTime(rhs);
    });
    for (auto it = beginIt; it != m_batches.end(); ++it) {
406 407
        const auto otherRes = (resId == (*it)) ? oldRes : reservation(*it);
        if (SortUtil::startDateTime(otherRes) != SortUtil::startDateTime(newRes)) {
408 409
            break; // no hit
        }
410
        if (isSameTrip(newRes, otherRes)) {
411 412 413 414 415 416 417
            newBatchId = *it;
            break;
        }
    }

    // still in the same batch?
    if (!oldBatchId.isEmpty() && oldBatchId == newBatchId) {
418
        emit batchContentChanged(oldBatchId);
419 420 421 422 423 424 425 426 427 428 429 430
        // no need to store here, as batching didn't actually change
        return;
    }

    // move us out of the old batch
    // WARNING: beginIt will become invalid after this!
    removeFromBatch(resId, oldBatchId);

    // insert us into the new batch
    if (newBatchId.isEmpty()) {
        // we are starting a new batch
        // re-run search for insertion point, could be invalid due to the above deletions
431
        const auto it = std::lower_bound(m_batches.begin(), m_batches.end(), newRes, [this](const auto &lhs, const auto &rhs) {
432 433
            return SortUtil::startDateTime(reservation(lhs)) < SortUtil::startDateTime(rhs);
        });
434
        m_batches.insert(it, QString(resId));
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        m_batchToResMap.insert(resId, {resId});
        m_resToBatchMap.insert(resId, resId);
        emit batchAdded(resId);
        storeBatch(resId);
    } else {
        m_batchToResMap[newBatchId].push_back(resId);
        m_resToBatchMap.insert(resId, newBatchId);
        emit batchChanged(newBatchId);
        storeBatch(newBatchId);
    }
}

void ReservationManager::removeFromBatch(const QString &resId, const QString &batchId)
{
    if (batchId.isEmpty()) {
        return;
    }

    auto &batches = m_batchToResMap[batchId];
    m_resToBatchMap.remove(resId);
    if (batches.size() == 1) { // we were alone there, remove old batch
        m_batchToResMap.remove(batchId);
        const auto it = std::find(m_batches.begin(), m_batches.end(), batchId);
        m_batches.erase(it);
        emit batchRemoved(batchId);
        storeRemoveBatch(batchId);
    } else if (resId == batchId) {
        // our id was the batch id, so rename the old batch
        batches.removeAll(resId);
        const QString renamedBatchId = batches.first();
        auto it = std::find(m_batches.begin(), m_batches.end(), batchId);
        Q_ASSERT(it != m_batches.end());
        *it = renamedBatchId;
        for (const auto &id : batches) {
            m_resToBatchMap[id] = renamedBatchId;
        }
        m_batchToResMap[renamedBatchId] = batches;
        m_batchToResMap.remove(batchId);
        emit batchRenamed(batchId, renamedBatchId);
        storeRemoveBatch(batchId);
        storeBatch(renamedBatchId);
    } else {
        // old batch remains
        batches.removeAll(resId);
        emit batchChanged(batchId);
        storeBatch(batchId);
    }
}