| 1 | /* |
| 2 | This file is part of the KDE Baloo project. |
| 3 | SPDX-FileCopyrightText: 2019 Stefan BrĂ¼ns <stefan.bruens@rwth-aachen.de> |
| 4 | |
| 5 | SPDX-License-Identifier: LGPL-2.1-or-later |
| 6 | */ |
| 7 | |
| 8 | #include "propertydata.h" |
| 9 | #include <QJsonArray> |
| 10 | #include <QJsonValue> |
| 11 | |
| 12 | namespace Baloo |
| 13 | { |
| 14 | |
| 15 | const QJsonObject propertyMapToJson(const KFileMetaData::PropertyMultiMap& properties) |
| 16 | { |
| 17 | auto it = properties.cbegin(); |
| 18 | QJsonObject jsonDict; |
| 19 | |
| 20 | while (it != properties.cend()) { |
| 21 | auto property = it.key(); |
| 22 | QString keyString = QString::number(static_cast<int>(property)); |
| 23 | |
| 24 | auto rangeEnd = properties.upperBound(key: property); |
| 25 | |
| 26 | QJsonValue value; |
| 27 | // In case a key has multiple values, convert to QJsonArray |
| 28 | if (std::distance(first: it, last: rangeEnd) > 1) { |
| 29 | QJsonArray values; |
| 30 | |
| 31 | // Last inserted is first element, for backwards compatible |
| 32 | // ordering prepend earlier elements |
| 33 | while (it != rangeEnd) { |
| 34 | values.insert(i: 0, value: QJsonValue::fromVariant(variant: it.value())); |
| 35 | ++it; |
| 36 | }; |
| 37 | |
| 38 | value = values; |
| 39 | } else { |
| 40 | auto type = it.value().userType(); |
| 41 | if ((type == QMetaType::QVariantList) || (type == QMetaType::QStringList)) { |
| 42 | // if it is a QList<T>, recurse |
| 43 | auto list = it.value().toList(); |
| 44 | QJsonArray values; |
| 45 | while (!list.isEmpty()) { |
| 46 | values.push_back(t: QJsonValue::fromVariant(variant: list.takeLast())); |
| 47 | } |
| 48 | value = values; |
| 49 | } else { |
| 50 | value = QJsonValue::fromVariant(variant: it.value()); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | jsonDict.insert(key: keyString, value); |
| 55 | |
| 56 | // pivot to next key |
| 57 | it = rangeEnd; |
| 58 | } |
| 59 | |
| 60 | return jsonDict; |
| 61 | } |
| 62 | |
| 63 | const KFileMetaData::PropertyMultiMap jsonToPropertyMap(const QJsonObject& properties) |
| 64 | { |
| 65 | KFileMetaData::PropertyMultiMap propertyMap; |
| 66 | |
| 67 | auto it = properties.begin(); |
| 68 | while (it != properties.end()) { |
| 69 | int propNum = it.key().toInt(); |
| 70 | auto prop = static_cast<KFileMetaData::Property::Property>(propNum); |
| 71 | |
| 72 | if (it.value().isArray()) { |
| 73 | const auto values = it.value().toArray(); |
| 74 | for (const auto val : values) { |
| 75 | propertyMap.insert(key: prop, value: val.toVariant()); |
| 76 | } |
| 77 | |
| 78 | } else if (it.value().isDouble()) { |
| 79 | propertyMap.insert(key: prop, value: it.value().toDouble()); |
| 80 | } else { |
| 81 | propertyMap.insert(key: prop, value: it.value().toString()); |
| 82 | } |
| 83 | ++it; |
| 84 | } |
| 85 | |
| 86 | return propertyMap; |
| 87 | } |
| 88 | |
| 89 | } // namespace Baloo |
| 90 | |