jsonldimportfilter.cpp 13.5 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 "jsonldimportfilter.h"
19
#include "logging.h"
20

21
#include <QDebug>
22 23
#include <QJsonArray>
#include <QJsonDocument>
24
#include <QJsonObject>
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
25
#include <QUrl>
26

27 28
#include <cstring>

29 30
using namespace KItinerary;

31 32 33 34 35 36
// type normalization from full schema.org type hierarchy to our simplified subset
// IMPORTANT: keep alphabetically sorted by fromType!
static const struct {
    const char* fromType;
    const char* toType;
} type_mapping[] = {
37 38 39
    { "AutoDealer", "LocalBusiness" },
    { "AutoRepair", "LocalBusiness" },
    { "AutomotiveBusiness", "LocalBusiness" },
40 41 42 43 44
    { "Bakery", "FoodEstablishment" },
    { "BarOrPub", "FoodEstablishment" },
    { "BedAndBreakfast", "LodgingBusiness" },
    { "Brewery", "FoodEstablishment" },
    { "BusStop", "BusStation" },
45
    { "BusinessEvent", "Event" },
46 47 48 49
    { "CafeOrCoffeeShop", "FoodEstablishment" },
    { "Campground", "LodgingBusiness" },
    { "ChildrensEvent", "Event" },
    { "ComedyEvent", "Event" },
50
    { "ComputerStore", "LocalBusiness" },
51 52 53 54
    { "DanceEvent", "Event" },
    { "Distillery", "FoodEstablishment" },
    { "EditAction", "UpdateAction" },
    { "EducationEvent", "Event" },
55 56
    { "ElectronicsStore", "LocalBusiness" },
    { "EntertainmentBusiness", "LocalBusiness" },
57 58 59
    { "ExhibitionEvent", "Event" },
    { "FastFoodRestaurant", "FoodEstablishment" },
    { "Festival", "Event" },
60 61
    { "HobbyShop", "LocalBusiness" },
    { "HomeAndConstructionBusiness", "LocalBusiness" },
62 63 64 65 66
    { "Hostel", "LodgingBusiness" },
    { "Hotel", "LodgingBusiness" },
    { "IceCreamShop", "FoodEstablishment" },
    { "LiteraryEvent", "Event" },
    { "Motel", "LodgingBusiness" },
67
    { "MovieTheater", "LocalBusiness" },
68 69 70 71 72 73 74
    { "MusicEvent", "Event" },
    { "Resort", "LodgingBusiness" },
    { "Restaurant", "FoodEstablishment" },
    { "SaleEvent", "Event" },
    { "ScreeningEvent", "Event" },
    { "SocialEvent", "Event" },
    { "SportsEvent", "Event" },
75
    { "Store", "LocalBusiness" },
76 77 78 79 80
    { "TheaterEvent", "Event" },
    { "VisualArtsEvent", "Event" },
    { "Winery", "FoodEstablishment" },
};

81 82 83 84 85 86 87 88 89
static void renameProperty(QJsonObject &obj, const char *oldName, const char *newName)
{
    const auto value = obj.value(QLatin1String(oldName));
    if (!value.isNull() && !obj.contains(QLatin1String(newName))) {
        obj.insert(QLatin1String(newName), value);
        obj.remove(QLatin1String(oldName));
    }
}

90
static void migrateToAction(QJsonObject &obj, const char *propName, const char *typeName, bool remove)
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
{
    const auto value = obj.value(QLatin1String(propName));
    if (value.isNull() || value.isUndefined()) {
        return;
    }

    auto actions = obj.value(QLatin1String("potentialAction")).toArray();
    for (const auto &act : actions) {
        if (act.toObject().value(QLatin1String("@type")).toString() == QLatin1String(typeName)) {
            return;
        }
    }

    QJsonObject action;
    action.insert(QStringLiteral("@type"), QLatin1String(typeName));
    action.insert(QStringLiteral("target"), value);
    actions.push_back(action);
Laurent Montel's avatar
Laurent Montel committed
108
    obj.insert(QStringLiteral("potentialAction"), actions);
109 110

    if (remove) {
Laurent Montel's avatar
Laurent Montel committed
111
        obj.remove(QStringLiteral("propName"));
112
    }
113 114
}

115 116 117
static void filterTrainTrip(QJsonObject &trip)
{
    // move TrainTrip::trainCompany to TrainTrip::provider (as defined by schema.org)
118 119 120 121 122 123 124 125
    renameProperty(trip, "trainCompany", "provider");
}

static void filterLodgingReservation(QJsonObject &res)
{
    // check[in|out]Date -> check[in|out]Time (legacy Google format)
    renameProperty(res, "checkinDate", "checkinTime");
    renameProperty(res, "checkoutDate", "checkoutTime");
126 127
}

128 129 130 131 132 133 134 135
static void filterFlight(QJsonObject &res)
{
    // move incomplete departureTime (ie. just ISO date, no time) to departureDay
    if (res.value(QLatin1String("departureTime")).toString().size() == 10) {
        renameProperty(res, "departureTime", "departureDay");
    }
}

136
static void filterReservation(QJsonObject &res)
137 138 139 140 141 142
{
    // move ticketToken to Ticket (Google vs. schema.org difference)
    const auto token = res.value(QLatin1String("ticketToken")).toString();
    if (!token.isEmpty()) {
        auto ticket = res.value(QLatin1String("reservedTicket")).toObject();
        if (ticket.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
143
            ticket.insert(QStringLiteral("@type"), QLatin1String("Ticket"));
144 145
        }
        if (!ticket.contains(QLatin1String("ticketToken"))) {
Laurent Montel's avatar
Laurent Montel committed
146 147 148
            ticket.insert(QStringLiteral("ticketToken"), token);
            res.insert(QStringLiteral("reservedTicket"), ticket);
            res.remove(QStringLiteral("ticketToken"));
149 150
        }
    }
151

152 153 154 155 156 157 158 159 160 161 162 163
    // unpack reservationFor array - if we ever encounter more than one element in here we'd need to multiply the result
    const auto resFor = res.value(QLatin1String("reservationFor"));
    if (resFor.isArray()) {
        const auto a = resFor.toArray();
        if (a.size() > 1) {
            qCWarning(Log) << "Found reservationFor array with" << a.size() << "elements!";
        }
        if (!a.isEmpty()) {
            res.insert(QStringLiteral("reservationFor"), a.at(0));
        }
    }

164 165 166
    // legacy potentialAction property
    renameProperty(res, "action", "potentialAction");

167
    // move Google xxxUrl properties to Action instances
168 169 170 171 172
    migrateToAction(res, "cancelReservationUrl", "CancelAction", true);
    migrateToAction(res, "checkinUrl", "CheckInAction", true);
    migrateToAction(res, "modifyReservationUrl", "UpdateAction", true);
    migrateToAction(res, "ticketDownloadUrl", "DownloadAction", true);
    migrateToAction(res, "url", "ViewAction", false);
173

174 175 176
    // technically the wrong way (reservationId is the current schema.org standard), but hardly used anywhere (yet)
    renameProperty(res, "reservationId", "reservationNumber");

177 178 179 180
    // "typos"
    renameProperty(res, "Url", "url");
}

181 182 183 184 185 186 187
static void filterBusTrip(QJsonObject &trip)
{
    renameProperty(trip, "arrivalStation", "arrivalBusStop");
    renameProperty(trip, "departureStation", "departureBusStop");
    renameProperty(trip, "busCompany", "provider");
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
static void filterFoodEstablishment(QJsonObject &restaurant)
{
    // This can be a bool, "Yes"/"No", or a URL.
    auto reservationsValue = restaurant.value(QLatin1String("acceptsReservations"));
    if (reservationsValue.isString()) {
        const QString reservations = reservationsValue.toString();
        if (reservations == QLatin1String("Yes")) {
            restaurant.insert(QLatin1String("acceptsReservations"), true);
        } else if (reservations == QLatin1String("No")) {
            restaurant.insert(QLatin1String("acceptsReservations"), false);
        } else {
            migrateToAction(restaurant, "acceptsReservations", "ReserveAction", true);
        }
    }
}

Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
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 254 255 256
static void filterActionTarget(QJsonObject &action)
{
    QJsonArray targets;
    QString filteredTargetUrlString;

    const QJsonValue oldTarget = action.value(QLatin1String("target"));
    if (oldTarget.isArray()) {
        targets = oldTarget.toArray();
    } else if (oldTarget.isObject()) {
        targets.push_back(oldTarget);
    }

    for (auto it = targets.begin(); it != targets.end(); ++it) {
        auto target = (*it).toObject();

        QJsonArray platforms;

        const QJsonValue actionPlatform = target.value(QLatin1String("actionPlatform"));
        if (actionPlatform.isArray()) {
            platforms = actionPlatform.toArray();
        } else {
            platforms.push_back(actionPlatform);
        }

        // Always return at least one URL but prefer the current platform if possible
        if (!filteredTargetUrlString.isEmpty()) {
            const bool hasPreferredPlatform = std::any_of(platforms.begin(), platforms.end(), [](const QJsonValue &platformValue) {
                const QString platform = platformValue.toString();
                // FIXME android
                return platform == QLatin1String("http://schema.org/DesktopWebPlatform");
            });

            if (!hasPreferredPlatform) {
                continue;
            }
        }

        const QUrl url(target.value(QLatin1String("urlTemplate")).toString());
        // It could also be a "URL template"
        if (!url.isValid()) {
            continue;
        }

        filteredTargetUrlString = url.toString();
    }

    if (filteredTargetUrlString.isEmpty()) {
        renameProperty(action, "url", "target");
    } else {
        action.insert(QStringLiteral("target"), filteredTargetUrlString);
    }
}

257 258 259 260 261 262 263 264 265 266 267
static QJsonArray filterActions(const QJsonValue &v)
{
    QJsonArray actions;
    if (v.isArray()) {
        actions = v.toArray();
    } else {
        actions.push_back(v);
    }

    for (auto it = actions.begin(); it != actions.end(); ++it) {
        auto action = (*it).toObject();
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
268
        filterActionTarget(action);
269 270 271 272 273 274
        *it = action;
    }

    return actions;
}

275 276 277 278 279 280 281 282 283

// filter functions applied to objects of the corresponding (already normalized) type
// IMPORTANT: keep alphabetically sorted by type!
static const struct {
    const char* type;
    void(*filterFunc)(QJsonObject&);
} type_filters[] = {
    { "BusTrip", filterBusTrip },
    { "Flight", filterFlight },
284
    { "FoodEstablishment", filterFoodEstablishment },
285 286 287 288
    { "LodgingReservation", filterLodgingReservation },
    { "TrainTrip", filterTrainTrip },
};

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
static void filterRecursive(QJsonObject &obj);

static void filterRecursive(QJsonArray &array)
{
    for (auto it = array.begin(); it != array.end(); ++it) {
        if ((*it).type() == QJsonValue::Object) {
            QJsonObject subObj = (*it).toObject();
            filterRecursive(subObj);
            *it = subObj;
        } else if ((*it).type() == QJsonValue::Array) {
            QJsonArray array = (*it).toArray();
            filterRecursive(array);
            *it = array;
        }
    }
}

static void filterRecursive(QJsonObject &obj)
{
308
    auto type = obj.value(QLatin1String("@type")).toString().toUtf8();
309 310

    // normalize type
311 312 313 314
    const auto it = std::lower_bound(std::begin(type_mapping), std::end(type_mapping), type, [](const auto &lhs, const auto &rhs) {
        return std::strcmp(lhs.fromType, rhs.constData()) < 0;
    });
    if (it != std::end(type_mapping) && std::strcmp((*it).fromType, type.constData()) == 0) {
315 316
        type = it->toType;
        obj.insert(QStringLiteral("@type"), QLatin1String(type));
317 318 319 320 321 322 323 324 325 326 327 328 329
    }

    for (auto it = obj.begin(); it != obj.end(); ++it) {
        if ((*it).type() == QJsonValue::Object) {
            QJsonObject subObj = (*it).toObject();
            filterRecursive(subObj);
            *it = subObj;
        } else if ((*it).type() == QJsonValue::Array) {
            QJsonArray array = (*it).toArray();
            filterRecursive(array);
            *it = array;
        }
    }
330 331 332 333 334 335 336 337

    // apply filter functions
    const auto filterIt = std::lower_bound(std::begin(type_filters), std::end(type_filters), type, [](const auto &lhs, const auto &rhs) {
        return std::strcmp(lhs.type, rhs.constData()) < 0;
    });
    if (filterIt != std::end(type_filters) && std::strcmp((*filterIt).type, type.constData()) == 0) {
        (*filterIt).filterFunc(obj);
    }
338 339
}

340 341 342 343 344 345 346 347 348 349 350 351 352 353
static QJsonArray graphExpand(const QJsonObject &obj)
{
    QJsonArray result;

    const auto graph = obj.value(QLatin1String("@graph")).toArray();
    for (const auto &o : graph) {
        const auto a = JsonLdImportFilter::filterObject(o.toObject());
        std::copy(a.begin(), a.end(), std::back_inserter(result));
    }

    return result;
}

QJsonArray JsonLdImportFilter::filterObject(const QJsonObject &obj)
354
{
355 356 357 358 359 360 361 362 363 364 365
    QStringList types;
    const auto typeVal = obj.value(QLatin1String("@type"));
    if (typeVal.isString()) {
        types.push_back(typeVal.toString());
    } else if (typeVal.isArray()) {
        const auto typeNames = typeVal.toArray();
        for (const auto &t : typeNames) {
            if (t.isString()) {
                types.push_back(t.toString());
            }
        }
366
    }
367
    // TODO consider additionalTypes property
368

369 370 371 372
    if (types.isEmpty()) {
        return graphExpand(obj);
    }

373
    QJsonArray results;
374

375 376 377 378 379 380 381 382
    for (const auto &type : types) {
        QJsonObject res(obj);
        res.insert(QStringLiteral("@type"), type);
        filterRecursive(res);

        if (type.endsWith(QLatin1String("Reservation"))) {
            filterReservation(res);
        }
383

384 385 386
        auto actions = res.value(QLatin1String("potentialAction"));
        if (!actions.isUndefined()) {
            res.insert(QStringLiteral("potentialAction"), filterActions(actions));
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
387
        }
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

        auto image = res.value(QLatin1String("image"));
        if (image.isArray()) {
            res.insert(QStringLiteral("image"), image.toArray().first());
        }

        image = res.value(QLatin1String("image"));
        if (image.isObject()) {
            const auto imageObject = image.toObject();
            if (imageObject.value(QLatin1String("@type")).toString() == QLatin1String("ImageObject")) {
                res.insert(QStringLiteral("image"), imageObject.value(QLatin1String("url")));
            }
        }

        results.push_back(res);
Kai Uwe Broulik's avatar
Kai Uwe Broulik committed
403 404
    }

405
    return results;
406
}