hafasmgatebackend.cpp 21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
    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 "hafasmgatebackend.h"
19 20
#include "hafasmgateparser.h"
#include "logging.h"
21
#include "cache.h"
22

23
#include <KPublicTransport/Departure>
24 25
#include <KPublicTransport/DepartureReply>
#include <KPublicTransport/DepartureRequest>
26 27 28
#include <KPublicTransport/Journey>
#include <KPublicTransport/JourneyReply>
#include <KPublicTransport/JourneyRequest>
29
#include <KPublicTransport/Location>
30 31
#include <KPublicTransport/LocationReply>
#include <KPublicTransport/LocationRequest>
32

33
#include <QCryptographicHash>
34 35 36 37 38
#include <QDateTime>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
39
#include <QMetaEnum>
40 41 42
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
43
#include <QUrlQuery>
44 45 46 47 48

using namespace KPublicTransport;

HafasMgateBackend::HafasMgateBackend() = default;

49 50 51 52 53
bool HafasMgateBackend::isSecure() const
{
    return m_endpoint.startsWith(QLatin1String("https"));
}

54 55
bool HafasMgateBackend::queryJourney(JourneyReply *reply, QNetworkAccessManager *nam) const
{
56
    m_parser.setLocationIdentifierType(locationIdentifierType());
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 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 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 247 248 249 250 251 252 253
    const auto request = reply->request();

    const auto fromId = request.from().identifier(locationIdentifierType());
    if (!fromId.isEmpty()) {
        return queryJourney(reply, fromId, nam);
    }

    LocationRequest locReq;
    locReq.setCoordinate(request.from().latitude(), request.from().longitude());
    locReq.setName(request.from().name());
    // TODO set max result = 1

    // check if this location query is cached already
    const auto cacheEntry = Cache::lookupLocation(backendId(), locReq.cacheKey());
    switch (cacheEntry.type) {
        case CacheHitType::Negative:
            addError(reply, Reply::NotFoundError, {});
            return false;
        case CacheHitType::Positive:
            if (cacheEntry.data.size() >= 1) {
                return queryJourney(reply, cacheEntry.data[0].identifier(locationIdentifierType()), nam);
            }
            break;
        case CacheHitType::Miss:
            break;
    }

    // query from location
    const auto locReply = postLocationQuery(locReq, nam);
    if (!locReply) {
        return false;
    }
    QObject::connect(locReply, &QNetworkReply::finished, [this, reply, locReply, locReq, nam]() {
        switch (locReply->error()) {
            case QNetworkReply::NoError:
            {
                auto res = m_parser.parseLocations(locReply->readAll());
                if (m_parser.error() == Reply::NoError && !res.empty()) {
                    Cache::addLocationCacheEntry(backendId(), locReq.cacheKey(), res);
                    const auto id = res[0].identifier(locationIdentifierType());
                    if (!id.isEmpty()) {
                        queryJourney(reply, id, nam);
                    } else {
                        addError(reply, Reply::NotFoundError, QLatin1String("Location query found no result for departure."));
                    }
                } else {
                    Cache::addNegativeLocationCacheEntry(backendId(), locReq.cacheKey());
                    addError(reply, m_parser.error(), m_parser.errorMessage());
                }
                break;
            }
            default:
                addError(reply, Reply::NetworkError, locReply->errorString());
                qCDebug(Log) << locReply->error() << locReply->errorString();
                break;
        }
        locReply->deleteLater();
    });

    return true;
}

bool HafasMgateBackend::queryJourney(JourneyReply *reply, const QString &fromId, QNetworkAccessManager *nam) const
{
    const auto request = reply->request();

    const auto toId = request.to().identifier(locationIdentifierType());
    if (!toId.isEmpty()) {
        return queryJourney(reply, fromId, toId, nam);
    }

    LocationRequest locReq;
    locReq.setCoordinate(request.to().latitude(), request.to().longitude());
    locReq.setName(request.to().name());
    // TODO set max result = 1

    // check if this location query is cached already
    const auto cacheEntry = Cache::lookupLocation(backendId(), locReq.cacheKey());
    switch (cacheEntry.type) {
        case CacheHitType::Negative:
            addError(reply, Reply::NotFoundError, {});
            return false;
        case CacheHitType::Positive:
            if (cacheEntry.data.size() >= 1) {
                return queryJourney(reply, fromId, cacheEntry.data[0].identifier(locationIdentifierType()), nam);
            }
            break;
        case CacheHitType::Miss:
            break;
    }

    // query to location
    const auto locReply = postLocationQuery(locReq, nam);
    if (!locReply) {
        addError(reply, Reply::NotFoundError, {});
        return false;
    }
    QObject::connect(locReply, &QNetworkReply::finished, [this, fromId, reply, locReply, locReq, nam]() {
        switch (locReply->error()) {
            case QNetworkReply::NoError:
            {
                auto res = m_parser.parseLocations(locReply->readAll());
                if (m_parser.error() == Reply::NoError && !res.empty()) {
                    Cache::addLocationCacheEntry(backendId(), locReq.cacheKey(), res);
                    const auto id = res[0].identifier(locationIdentifierType());
                    if (!id.isEmpty()) {
                        queryJourney(reply, fromId, id, nam);
                    } else {
                        addError(reply, Reply::NotFoundError, QLatin1String("Location query found no result for arrival."));
                    }
                } else {
                    Cache::addNegativeLocationCacheEntry(backendId(), locReq.cacheKey());
                    addError(reply, m_parser.error(), m_parser.errorMessage());
                }
                break;
            }
            default:
                addError(reply, Reply::NetworkError, locReply->errorString());
                qCDebug(Log) << locReply->error() << locReply->errorString();
                break;
        }
        locReply->deleteLater();
    });

    return true;
}

bool HafasMgateBackend::queryJourney(JourneyReply *reply, const QString &fromId, const QString &toId, QNetworkAccessManager *nam) const
{
    qCDebug(Log) << backendId() << fromId << toId;
    const auto request = reply->request();

    QJsonObject tripSearch;
    {
        QJsonObject cfg;
        cfg.insert(QLatin1String("polyEnc"), QLatin1String("GPA"));

        QJsonArray arrLocL;
        QJsonObject arrLoc;
        arrLoc.insert(QLatin1String("extId"), toId);
        arrLoc.insert(QLatin1String("type"), QLatin1String("S")); // 'S' == station
        arrLocL.push_back(arrLoc);

        QJsonArray depLocL;
        QJsonObject depLoc;
        depLoc.insert(QLatin1String("extId"), fromId);
        depLoc.insert(QLatin1String("type"), QLatin1String("S"));
        depLocL.push_back(depLoc);

        QJsonArray jnyFltrL;
        QJsonObject jnyFltr;
        jnyFltr.insert(QLatin1String("mode"), QLatin1String("BIT"));
        jnyFltr.insert(QLatin1String("type"), QLatin1String("PROD"));
        jnyFltr.insert(QLatin1String("value"), QLatin1String("1111111001"));
        jnyFltrL.push_back(jnyFltr);

        QJsonObject req;
        req.insert(QLatin1String("arrLocL"), arrLocL);
        req.insert(QLatin1String("depLocL"), depLocL);
        req.insert(QLatin1String("extChgTime"), -1);
        req.insert(QLatin1String("getEco"), false);
        req.insert(QLatin1String("getIST"), false);
        req.insert(QLatin1String("getPasslist"), true); // ???
        req.insert(QLatin1String("getPolyline"), false);
        req.insert(QLatin1String("jnyFltrL"), jnyFltrL);

        req.insert(QLatin1String("outDate"), request.dateTime().date().toString(QLatin1String("yyyyMMdd")));
        req.insert(QLatin1String("outTime"), request.dateTime().time().toString(QLatin1String("hhmmss")));
        req.insert(QLatin1String("outFrwd"), true);

        tripSearch.insert(QLatin1String("cfg"), cfg);
        tripSearch.insert(QLatin1String("meth"), QLatin1String("TripSearch"));
        tripSearch.insert(QLatin1String("req"), req);
    }

    auto netReply = postRequest(tripSearch, nam);
    QObject::connect(netReply, &QNetworkReply::finished, [netReply, reply, this]() {
        switch (netReply->error()) {
            case QNetworkReply::NoError:
            {
                auto res = m_parser.parseJourneys(netReply->readAll());
                if (m_parser.error() == Reply::NoError) {
                    addResult(reply, std::move(res));
                } else {
                    addError(reply, m_parser.error(), m_parser.errorMessage());
                }
                break;
            }
            default:
                addError(reply, Reply::NetworkError, netReply->errorString());
                qCDebug(Log) << netReply->error() << netReply->errorString();
                break;
        }
        netReply->deleteLater();
    });

    return true;
254 255 256 257
}

bool HafasMgateBackend::queryDeparture(DepartureReply *reply, QNetworkAccessManager *nam) const
{
258
    m_parser.setLocationIdentifierType(locationIdentifierType());
259
    const auto request = reply->request();
260

261
    const auto id = request.stop().identifier(locationIdentifierType());
262 263 264 265 266 267 268 269 270 271
    if (!id.isEmpty()) {
        queryDeparture(reply, id, nam);
        return true;
    }

    // missing the station id
    LocationRequest locReq;
    locReq.setCoordinate(request.stop().latitude(), request.stop().longitude());
    locReq.setName(request.stop().name());
    // TODO set max result = 1
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

    // check if this location query is cached already
    const auto cacheEntry = Cache::lookupLocation(backendId(), locReq.cacheKey());
    switch (cacheEntry.type) {
        case CacheHitType::Negative:
            addError(reply, Reply::NotFoundError, {});
            return false;
        case CacheHitType::Positive:
            if (cacheEntry.data.size() >= 1) {
                queryDeparture(reply, cacheEntry.data[0].identifier(locationIdentifierType()), nam);
                return true;
            }
            break;
        case CacheHitType::Miss:
            break;
    }

289 290
    const auto locReply = postLocationQuery(locReq, nam);
    if (!locReply) {
291 292
        return false;
    }
293
    QObject::connect(locReply, &QNetworkReply::finished, [this, reply, locReply, locReq, nam]() {
294 295 296 297 298 299
        qDebug() << locReply->request().url();
        switch (locReply->error()) {
            case QNetworkReply::NoError:
            {
                auto res = m_parser.parseLocations(locReply->readAll());
                if (m_parser.error() == Reply::NoError && !res.empty()) {
300
                    Cache::addLocationCacheEntry(backendId(), locReq.cacheKey(), res);
301 302 303 304 305 306 307
                    const auto id = res[0].identifier(locationIdentifierType());
                    if (!id.isEmpty()) {
                        queryDeparture(reply, id, nam);
                    } else {
                        addError(reply, Reply::NotFoundError, QLatin1String("Location query found no results."));
                    }
                } else {
308
                    Cache::addNegativeLocationCacheEntry(backendId(), locReq.cacheKey());
309 310 311 312 313 314 315 316 317 318 319
                    addError(reply, m_parser.error(), m_parser.errorMessage());
                }
                break;
            }
            default:
                addError(reply, Reply::NetworkError, locReply->errorString());
                qCDebug(Log) << locReply->error() << locReply->errorString();
                break;
        }
        locReply->deleteLater();
    });
320

321 322 323 324 325 326 327
    return true;
}

void HafasMgateBackend::queryDeparture(DepartureReply *reply, const QString &locationId, QNetworkAccessManager *nam) const
{
    const auto request = reply->request();

328 329 330 331 332 333 334 335 336 337 338
    QJsonObject stationBoard;
    {
        QJsonObject cfg;
        cfg.insert(QLatin1String("polyEnc"), QLatin1String("GPA"));

        QJsonObject req;
        req.insert(QLatin1String("date"), request.dateTime().toString(QLatin1String("yyyyMMdd")));
        req.insert(QLatin1String("maxJny"), 12);
        req.insert(QLatin1String("stbFltrEquiv"), true);

        QJsonObject stbLoc;
339
        stbLoc.insert(QLatin1String("extId"), locationId);
340 341 342 343 344
        stbLoc.insert(QLatin1String("state"), QLatin1String("F"));
        stbLoc.insert(QLatin1String("type"), QLatin1String("S"));

        req.insert(QLatin1String("stbLoc"), stbLoc);
        req.insert(QLatin1String("time"), request.dateTime().toString(QLatin1String("hhmmss")));
345
        req.insert(QLatin1String("type"), request.mode() == DepartureRequest::QueryDeparture ? QLatin1String("DEP") : QLatin1String("ARR"));
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

        stationBoard.insert(QLatin1String("cfg"), cfg);
        stationBoard.insert(QLatin1String("meth"), QLatin1String("StationBoard"));
        stationBoard.insert(QLatin1String("req"), req);
    }

    auto netReply = postRequest(stationBoard, nam);
    QObject::connect(netReply, &QNetworkReply::finished, [netReply, reply, this]() {
        qDebug() << netReply->request().url();
        switch (netReply->error()) {
            case QNetworkReply::NoError:
            {
                auto result = m_parser.parseDepartures(netReply->readAll());
                if (m_parser.error() != Reply::NoError) {
                    addError(reply, m_parser.error(), m_parser.errorMessage());
                    qCDebug(Log) << m_parser.error() << m_parser.errorMessage();
                } else {
                    addResult(reply, std::move(result));
                }
                break;
            }
            default:
                addError(reply, Reply::NetworkError, netReply->errorString());
                qCDebug(Log) << netReply->error() << netReply->errorString();
                break;
        }
        netReply->deleteLater();
    });
}

376 377
bool HafasMgateBackend::queryLocation(LocationReply *reply, QNetworkAccessManager *nam) const
{
378
    m_parser.setLocationIdentifierType(locationIdentifierType());
379

380
    const auto req = reply->request();
381 382
    const auto netReply = postLocationQuery(req, nam);
    if (!netReply) {
383 384 385 386 387 388 389 390
        return false;
    }

    QObject::connect(netReply, &QNetworkReply::finished, [netReply, reply, this]() {
        qDebug() << netReply->request().url();
        switch (netReply->error()) {
            case QNetworkReply::NoError:
            {
Volker Krause's avatar
Volker Krause committed
391 392
                auto res = m_parser.parseLocations(netReply->readAll());
                if (m_parser.error() == Reply::NoError) {
393
                    Cache::addLocationCacheEntry(backendId(), reply->request().cacheKey(), res);
Volker Krause's avatar
Volker Krause committed
394 395
                    addResult(reply, std::move(res));
                } else {
396
                    Cache::addNegativeLocationCacheEntry(backendId(), reply->request().cacheKey());
Volker Krause's avatar
Volker Krause committed
397 398
                    addError(reply, m_parser.error(), m_parser.errorMessage());
                }
399 400 401 402 403 404 405 406 407 408 409 410 411
                break;
            }
            default:
                addError(reply, Reply::NetworkError, netReply->errorString());
                qCDebug(Log) << netReply->error() << netReply->errorString();
                break;
        }
        netReply->deleteLater();
    });

    return true;
}

412 413
QNetworkReply* HafasMgateBackend::postRequest(const QJsonObject &svcReq, QNetworkAccessManager *nam) const
{
414 415 416 417 418 419 420 421 422 423 424
    QJsonObject top;
    {
        QJsonObject auth;
        auth.insert(QLatin1String("aid"), m_aid);
        auth.insert(QLatin1String("type"), QLatin1String("AID"));
        top.insert(QLatin1String("auth"), auth);
    }
    {
        QJsonObject client;
        client.insert(QLatin1String("id"), m_clientId);
        client.insert(QLatin1String("type"), m_clientType);
425 426 427 428 429 430
        if (!m_clientVersion.isEmpty()) {
            client.insert(QLatin1String("v"), m_clientVersion);
        }
        if (!m_clientName.isEmpty()) {
            client.insert(QLatin1String("name"), m_clientName);
        }
431 432 433 434 435
        top.insert(QLatin1String("client"), client);
    }
    top.insert(QLatin1String("formatted"), false);
    top.insert(QLatin1String("lang"), QLatin1String("eng"));
    {
436
        QJsonArray svcReqs;
437 438 439 440 441 442 443 444 445
        {
            QJsonObject req;
            req.insert(QLatin1String("getServerDateTime"), true);
            req.insert(QLatin1String("getTimeTablePeriod"), false);

            QJsonObject serverInfo;
            serverInfo.insert(QLatin1String("meth"), QLatin1String("ServerInfo"));
            serverInfo.insert(QLatin1String("req"), req);

446
            svcReqs.push_back(serverInfo);
447
        }
448 449
        svcReqs.push_back(svcReq);
        top.insert(QLatin1String("svcReqL"), svcReqs);
450 451 452
    }
    top.insert(QLatin1String("ver"), m_version);

453
    const auto content = QJsonDocument(top).toJson(QJsonDocument::Compact);
454
    QUrl url(m_endpoint);
455
    QUrlQuery query;
456 457 458 459 460 461 462 463 464 465 466 467
    if (!m_micMacSalt.isEmpty()) {
        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(content);
        const auto mic = md5.result().toHex();
        query.addQueryItem(QLatin1String("mic"), QString::fromLatin1(mic));

        md5.reset();
        // yes, mic is added as hex-encoded string, and the salt is added as raw bytes
        md5.addData(mic);
        md5.addData(m_micMacSalt);
        query.addQueryItem(QLatin1String("mac"), QString::fromLatin1(md5.result().toHex()));
    }
468 469 470 471 472 473 474
    if (!m_checksumSalt.isEmpty()) {
        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(content);
        md5.addData(m_checksumSalt);
        query.addQueryItem(QLatin1String("checksum"), QString::fromLatin1(md5.result().toHex()));
    }
    url.setQuery(query);
475 476

    auto netReq = QNetworkRequest(url);
477
    netReq.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("application/json"));
478
    qCDebug(Log) << netReq.url();
479
    //qCDebug(Log).noquote() << QJsonDocument(top).toJson();
480
    return nam->post(netReq, content);
481
}
482

483 484 485 486 487 488 489 490
QNetworkReply* HafasMgateBackend::postLocationQuery(const LocationRequest &req, QNetworkAccessManager *nam) const
{
    QJsonObject methodObj;
    if (req.hasCoordinate()) {
        QJsonObject cfg;
        cfg.insert(QLatin1String("polyEnc"), QLatin1String("GPA"));

        QJsonObject coord;
491 492
        coord.insert(QLatin1String("x"), (int)(req.longitude() * 1000000));
        coord.insert(QLatin1String("y"), (int)(req.latitude() * 1000000));
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        QJsonObject ring;
        ring.insert(QLatin1String("cCrd"), coord);
        ring.insert(QLatin1String("maxDist"), 20000); // not sure which unit...

        QJsonObject reqObj;
        reqObj.insert(QLatin1String("ring"), ring);
        // ### make this configurable in LocationRequest
        reqObj.insert(QLatin1String("getStops"), true);
        reqObj.insert(QLatin1String("getPOIs"), false);
        reqObj.insert(QLatin1String("maxLoc"), 12);

        methodObj.insert(QLatin1String("cfg"), cfg);
        methodObj.insert(QLatin1String("meth"), QLatin1String("LocGeoPos"));
        methodObj.insert(QLatin1String("req"), reqObj);

    } else if (!req.name().isEmpty()) {
        QJsonObject cfg;
        cfg.insert(QLatin1String("polyEnc"), QLatin1String("GPA"));

        QJsonObject loc;
        loc.insert(QLatin1String("name"), req.name()); // + '?' for auto completion search?
        loc.insert(QLatin1String("type"), QLatin1String("S")); // station: S, address: A, POI: P

        QJsonObject input;
        input.insert(QLatin1String("field"), QLatin1String("S"));
        input.insert(QLatin1String("loc"), loc);
        // ### make this configurable in LocationRequest
        input.insert(QLatin1String("maxLoc"), 12);

        QJsonObject reqObj;
        reqObj.insert(QLatin1String("input"), input);

        methodObj.insert(QLatin1String("cfg"), cfg);
        methodObj.insert(QLatin1String("meth"), QLatin1String("LocMatch"));
        methodObj.insert(QLatin1String("req"), reqObj);

    } else {
        return nullptr;
    }

    return postRequest(methodObj, nam);
}

536 537 538 539
void HafasMgateBackend::setMicMacSalt(const QString &salt)
{
    m_micMacSalt = QByteArray::fromHex(salt.toUtf8());
}
540

541 542 543 544 545
void HafasMgateBackend::setChecksumSalt(const QString &salt)
{
    m_checksumSalt = QByteArray::fromHex(salt.toUtf8());
}

546 547 548 549 550 551 552 553 554 555 556 557
void HafasMgateBackend::setLineModeMap(const QJsonObject& obj)
{
    const auto idx = Line::staticMetaObject.indexOfEnumerator("Mode");
    Q_ASSERT(idx >= 0);
    const auto me = Line::staticMetaObject.enumerator(idx);

    std::unordered_map<int, Line::Mode> modeMap;
    for (auto it = obj.begin(); it != obj.end(); ++it) {
        modeMap[it.key().toInt()] = static_cast<Line::Mode>(me.keyToValue(it.value().toString().toUtf8()));
    }
    m_parser.setLineModeMap(std::move(modeMap));
}
558 559 560 561 562

QString HafasMgateBackend::locationIdentifierType() const
{
    return m_locationIdentifierType.isEmpty() ? backendId() : m_locationIdentifierType;
}