hafasmgateparser.cpp 12 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 "hafasmgateparser.h"
19
#include "logging.h"
20 21

#include <KPublicTransport/Departure>
22
#include <KPublicTransport/Journey>
23 24
#include <KPublicTransport/Line>

Volker Krause's avatar
Volker Krause committed
25
#include <QColor>
26 27 28 29 30 31 32 33
#include <QDateTime>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

using namespace KPublicTransport;

34 35 36 37 38 39 40
HafasMgateParser::HafasMgateParser() = default;
HafasMgateParser::~HafasMgateParser() = default;

void HafasMgateParser::setLineModeMap(std::unordered_map<int, Line::Mode> &&modeMap)
{
    m_lineModeMap = std::move(modeMap);
}
Volker Krause's avatar
Volker Krause committed
41

42 43 44 45 46
void HafasMgateParser::setLocationIdentifierType(const QString &idType)
{
    m_locIdType = idType;
}

Volker Krause's avatar
Volker Krause committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
static std::vector<Ico> parseIcos(const QJsonArray &icoL)
{
    std::vector<Ico> icos;
    icos.reserve(icoL.size());
    for (const auto &icoV : icoL) {
        const auto icoObj = icoV.toObject();
        Ico ico;
        const auto fg = icoObj.value(QLatin1String("fg")).toObject();
        if (!fg.isEmpty()) {
            ico.fg = QColor(fg.value(QLatin1String("r")).toInt(), fg.value(QLatin1String("g")).toInt(), fg.value(QLatin1String("b")).toInt());
        }
        const auto bg = icoObj.value(QLatin1String("bg")).toObject();
        if (!bg.isEmpty()) {
            ico.bg = QColor(bg.value(QLatin1String("r")).toInt(), bg.value(QLatin1String("g")).toInt(), bg.value(QLatin1String("b")).toInt());
        }
        icos.push_back(ico);
    }
    return icos;
}

67
std::vector<Location> HafasMgateParser::parseLocations(const QJsonArray &locL) const
68 69 70 71 72 73 74
{
    std::vector<Location> locs;
    locs.reserve(locL.size());
    for (const auto &locV : locL) {
        const auto locObj = locV.toObject();
        Location loc;
        loc.setName(locObj.value(QLatin1String("name")).toString());
75
        loc.setIdentifier(m_locIdType, locObj.value(QLatin1String("extId")).toString());
76
        const auto coordObj = locObj.value(QLatin1String("crd")).toObject();
77
        loc.setCoordinate(coordObj.value(QLatin1String("y")).toDouble() / 1000000.0, coordObj.value(QLatin1String("x")).toDouble() / 1000000.0);
78 79 80 81 82
        locs.push_back(loc);
    }
    return locs;
}

83
std::vector<Line> HafasMgateParser::parseLines(const QJsonArray &prodL, const std::vector<Ico> &icos) const
84 85 86 87 88 89 90 91 92
{
    std::vector<Line> lines;
    lines.reserve(prodL.size());
    for (const auto &prodV : prodL) {
        const auto prodObj = prodV.toObject();
        Line line;
        line.setName(prodObj.value(QLatin1String("name")).toString());

        const auto prodCode = prodObj.value(QLatin1String("cls")).toInt();
93 94 95 96
        const auto lineModeIt = m_lineModeMap.find(prodCode);
        if (lineModeIt != m_lineModeMap.end()) {
            line.setMode((*lineModeIt).second);
        } else {
97 98
            qCDebug(Log) << "Encountered unknown line type:" << prodCode << line.name();
        }
Volker Krause's avatar
Volker Krause committed
99 100 101 102 103 104 105

        const auto icoIdx = prodObj.value(QLatin1String("icoX")).toInt();
        if ((unsigned int)icoIdx < icos.size()) {
            line.setColor(icos[icoIdx].bg);
            line.setTextColor(icos[icoIdx].fg);
        }

106 107 108 109 110 111
        lines.push_back(line);
    }

    return lines;
}

112
std::vector<Departure> HafasMgateParser::parseStationBoardResponse(const QJsonObject &obj) const
113 114
{
    const auto commonObj = obj.value(QLatin1String("common")).toObject();
Volker Krause's avatar
Volker Krause committed
115
    const auto icos = parseIcos(commonObj.value(QLatin1String("icoL")).toArray());
116
    const auto locs = parseLocations(commonObj.value(QLatin1String("locL")).toArray());
Volker Krause's avatar
Volker Krause committed
117
    const auto lines = parseLines(commonObj.value(QLatin1String("prodL")).toArray(), icos);
118 119 120 121 122 123 124 125 126 127 128

    std::vector<Departure> res;
    const auto jnyL = obj.value(QLatin1String("jnyL")).toArray();
    res.reserve(jnyL.size());

    for (const auto &jny : jnyL) {
        const auto jnyObj = jny.toObject();
        const auto stbStop = jnyObj.value(QLatin1String("stbStop")).toObject();

        Route route;
        route.setDirection(jnyObj.value(QLatin1String("dirTxt")).toString());
Volker Krause's avatar
Volker Krause committed
129
        const auto lineIdx = jnyObj.value(QLatin1String("prodX")).toInt();
130 131 132 133 134 135 136 137
        if ((unsigned int)lineIdx < lines.size()) {
            route.setLine(lines[lineIdx]);
        }

        Departure dep;
        dep.setRoute(route);

        const auto dateStr = jnyObj.value(QLatin1String("date")).toString();
138
        dep.setScheduledDepartureTime(QDateTime::fromString(dateStr + stbStop.value(QLatin1String("dTimeS")).toString(), QLatin1String("yyyyMMddhhmmss")));
Volker Krause's avatar
Volker Krause committed
139 140
        const auto dTimeR = stbStop.value(QLatin1String("dTimeR")).toString();
        if (!dTimeR.isEmpty()) {
141 142 143 144 145 146
            dep.setExpectedDepartureTime(QDateTime::fromString(dateStr + dTimeR, QLatin1String("yyyyMMddhhmmss")));
        }
        dep.setScheduledArrivalTime(QDateTime::fromString(dateStr + stbStop.value(QLatin1String("aTimeS")).toString(), QLatin1String("yyyyMMddhhmmss")));
        const auto aTimeR = stbStop.value(QLatin1String("aTimeR")).toString();
        if (!aTimeR.isEmpty()) {
            dep.setExpectedArrivalTime(QDateTime::fromString(dateStr + aTimeR, QLatin1String("yyyyMMddhhmmss")));
147 148
        }

149 150
        dep.setScheduledPlatform(stbStop.value(QLatin1String("dPlatfS")).toString());
        dep.setExpectedPlatform(stbStop.value(QLatin1String("dPlatfR")).toString());
151 152 153 154 155 156
        if (dep.scheduledPlatform().isEmpty()) {
            dep.setScheduledPlatform(stbStop.value(QLatin1String("aPlatfS")).toString());
        }
        if (dep.expectedPlatform().isEmpty()) {
            dep.setExpectedPlatform(stbStop.value(QLatin1String("aPlatfR")).toString());
        }
157 158 159 160 161 162 163 164 165 166 167 168

        const auto locIdx = stbStop.value(QLatin1String("locX")).toInt();
        if ((unsigned int)locIdx < locs.size()) {
            dep.setStopPoint(locs[locIdx]);
        }

        res.push_back(dep);
    }

    return res;
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182
bool HafasMgateParser::parseError(const QJsonObject& obj) const
{
    if (obj.value(QLatin1String("err")).toString() != QLatin1String("OK")) {
        m_error = Reply::NotFoundError;
        m_errorMsg = obj.value(QLatin1String("errTxt")).toString();
        return false;
    }

    m_error = Reply::NoError;
    m_errorMsg.clear();
    return true;
}


183
std::vector<Departure> HafasMgateParser::parseDepartures(const QByteArray &data) const
184 185
{
    const auto topObj = QJsonDocument::fromJson(data).object();
186
    //qDebug().noquote() << QJsonDocument(topObj).toJson();
187 188 189 190 191
    const auto svcResL = topObj.value(QLatin1String("svcResL")).toArray();

    for (const auto &v : svcResL) {
        const auto obj = v.toObject();
        if (obj.value(QLatin1String("meth")).toString() == QLatin1String("StationBoard")) {
192 193 194 195
            if (parseError(obj)) {
                return parseStationBoardResponse(obj.value(QLatin1String("res")).toObject());
            }
            return {};
196 197 198 199 200
        }
    }

    return {};
}
201

Volker Krause's avatar
Volker Krause committed
202 203 204 205 206 207 208 209 210 211 212 213
std::vector<Location> HafasMgateParser::parseLocations(const QByteArray &data) const
{
    const auto topObj = QJsonDocument::fromJson(data).object();
    const auto svcResL = topObj.value(QLatin1String("svcResL")).toArray();

    for (const auto &v : svcResL) {
        const auto obj = v.toObject();
        const auto meth = obj.value(QLatin1String("meth")).toString();
        if (meth == QLatin1String("LocMatch") || meth == QLatin1String("LocGeoPos")) {
            if (parseError(obj)) {
                const auto resObj = obj.value(QLatin1String("res")).toObject();
                if (resObj.contains(QLatin1String("locL"))) {
214
                    return parseLocations(resObj.value(QLatin1String("locL")).toArray());
Volker Krause's avatar
Volker Krause committed
215 216
                }
                if (resObj.contains(QLatin1String("match"))) {
217
                    return parseLocations(resObj.value(QLatin1String("match")).toObject().value(QLatin1String("locL")).toArray());
Volker Krause's avatar
Volker Krause committed
218 219 220 221 222 223 224 225 226 227 228
                }
                qCDebug(Log).noquote() << "Failed to parse location query response:" << QJsonDocument(obj).toJson();
                return {};
            }
            return {};
        }
    }

    return {};
}

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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
std::vector<Journey> HafasMgateParser::parseJourneys(const QByteArray &data) const
{
    const auto topObj = QJsonDocument::fromJson(data).object();
//     qDebug().noquote() << QJsonDocument(topObj).toJson();
    const auto svcResL = topObj.value(QLatin1String("svcResL")).toArray();

    for (const auto &v : svcResL) {
        const auto obj = v.toObject();
        if (obj.value(QLatin1String("meth")).toString() == QLatin1String("TripSearch")) {
            if (parseError(obj)) {
                return parseTripSearch(obj.value(QLatin1String("res")).toObject());
            }
            return {};
        }
    }

    return {};
}

std::vector<Journey> HafasMgateParser::parseTripSearch(const QJsonObject &obj) const
{
    const auto commonObj = obj.value(QLatin1String("common")).toObject();
    const auto icos = parseIcos(commonObj.value(QLatin1String("icoL")).toArray());
    const auto locs = parseLocations(commonObj.value(QLatin1String("locL")).toArray());
    const auto lines = parseLines(commonObj.value(QLatin1String("prodL")).toArray(), icos);

    std::vector<Journey> res;
    const auto outConL = obj.value(QLatin1String("outConL")).toArray();
    res.reserve(outConL.size());

    for (const auto &outConV: outConL) {
        const auto outCon = outConV.toObject();

        const auto dateStr = outCon.value(QLatin1String("date")).toString();

        const auto secL = outCon.value(QLatin1String("secL")).toArray();
        std::vector<JourneySection> sections;
        sections.reserve(secL.size());


        for (const auto &secV : secL) {
            const auto secObj = secV.toObject();
            JourneySection section;

            // TODO add real-time data
            const auto dep = secObj.value(QLatin1String("dep")).toObject();
            section.setDepartureTime(QDateTime::fromString(dateStr + dep.value(QLatin1String("dTimeS")).toString(), QLatin1String("yyyyMMddhhmmss")));
            auto locIdx = dep.value(QLatin1String("locX")).toInt();
            if ((unsigned int)locIdx < locs.size()) {
                section.setFrom(locs[locIdx]);
            }

            const auto arr = secObj.value(QLatin1String("arr")).toObject();
            section.setArrivalTime(QDateTime::fromString(dateStr + arr.value(QLatin1String("aTimeS")).toString(), QLatin1String("yyyyMMddhhmmss")));
            locIdx = arr.value(QLatin1String("locX")).toInt();
            if ((unsigned int)locIdx < locs.size()) {
                section.setTo(locs[locIdx]);
            }

            const auto typeStr = secObj.value(QLatin1String("type")).toString();
            if (typeStr == QLatin1String("JNY")) {
                section.setMode(JourneySection::PublicTransport);

                const auto jnyObj = secObj.value(QLatin1String("jny")).toObject();
                Route route;
                route.setDirection(jnyObj.value(QLatin1String("dirTxt")).toString());
                const auto lineIdx = jnyObj.value(QLatin1String("prodX")).toInt();
                if ((unsigned int)lineIdx < lines.size()) {
                    route.setLine(lines[lineIdx]);
                }
                section.setRoute(route);
            } else if (typeStr == QLatin1String("WALK")) {
                section.setMode(JourneySection::Walking);
            }

            sections.push_back(section);
        }

        Journey journey;
        journey.setSections(std::move(sections));
        res.push_back(journey);
    }

    return res;
}

315 316 317 318 319 320 321 322 323
Reply::Error HafasMgateParser::error() const
{
    return m_error;
}

QString HafasMgateParser::errorMessage() const
{
    return m_errorMsg;
}