File indexing completed on 2024-12-29 04:51:01

0001 /*
0002    SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
0003    SPDX-License-Identifier: LGPL-2.0-or-later
0004 */
0005 
0006 #include "plistdocumentprocessor.h"
0007 
0008 #include "plist/plistreader_p.h"
0009 
0010 #include <KItinerary/ExtractorEngine>
0011 #include <KItinerary/ExtractorDocumentNodeFactory>
0012 
0013 #include <QJsonObject>
0014 
0015 using namespace KItinerary;
0016 
0017 bool PListDocumentProcessor::canHandleData(const QByteArray &encodedData, [[maybe_unused]] QStringView fileName) const
0018 {
0019     return PListReader::maybePList(encodedData);
0020 }
0021 
0022 ExtractorDocumentNode PListDocumentProcessor::createNodeFromData(const QByteArray &encodedData) const
0023 {
0024     ExtractorDocumentNode node;
0025     node.setContent(QVariant::fromValue(PListReader(encodedData)));
0026     return node;
0027 }
0028 
0029 static void searchSchemaOrgRecursive(const QJsonValue &val, QJsonArray &result)
0030 {
0031     if (val.isObject()) {
0032         const auto obj = val.toObject();
0033         if (obj.contains(QLatin1StringView("@type"))) {
0034           result.push_back(obj);
0035           return;
0036         }
0037 
0038         for (auto it = obj.begin(); it != obj.end(); ++it) {
0039             if (it.value().isObject() || it.value().isArray()) {
0040                 searchSchemaOrgRecursive(it.value(), result);
0041             }
0042         }
0043     }
0044 
0045     if (val.isArray()) {
0046         const auto a = val.toArray();
0047         for (const auto &v : a) {
0048             if (v.isObject() || v.isArray()) {
0049                 searchSchemaOrgRecursive(v, result);
0050             }
0051         }
0052     }
0053 }
0054 
0055 void PListDocumentProcessor::expandNode(ExtractorDocumentNode &node, const ExtractorEngine *engine) const
0056 {
0057     const auto plist = node.content<PListReader>();
0058     const auto nsKeyedArchive = plist.unpackKeyedArchive();
0059     if (!nsKeyedArchive.isObject()) {
0060         return;
0061     }
0062 
0063     // search for schema.org JSON-LD sub-trees in this
0064     QJsonArray childData;
0065     searchSchemaOrgRecursive(nsKeyedArchive, childData);
0066     if (childData.isEmpty()) {
0067         auto child = engine->documentNodeFactory()->createNode(QVariant::fromValue(QJsonArray({nsKeyedArchive})), u"application/json");
0068         node.appendChild(child);
0069     } else {
0070         auto child = engine->documentNodeFactory()->createNode(childData, u"application/json");
0071         node.appendChild(child);
0072     }
0073 }