| 1 | /* |
|---|---|
| 2 | This file is part of the KDE Baloo Project |
| 3 | SPDX-FileCopyrightText: 2013 Vishesh Handa <me@vhanda.in> |
| 4 | |
| 5 | SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL |
| 6 | */ |
| 7 | |
| 8 | #include "file.h" |
| 9 | #include "global.h" |
| 10 | #include "database.h" |
| 11 | #include "transaction.h" |
| 12 | #include "idutils.h" |
| 13 | #include "propertydata.h" |
| 14 | |
| 15 | #include <QJsonDocument> |
| 16 | #include <QFileInfo> |
| 17 | #include <QJsonObject> |
| 18 | |
| 19 | using namespace Baloo; |
| 20 | |
| 21 | class BALOO_CORE_NO_EXPORT File::Private { |
| 22 | public: |
| 23 | QString url; |
| 24 | KFileMetaData::PropertyMultiMap propertyMap; |
| 25 | }; |
| 26 | |
| 27 | File::File() |
| 28 | : d(new Private) |
| 29 | { |
| 30 | } |
| 31 | |
| 32 | File::File(const File& f) |
| 33 | : d(new Private(*f.d)) |
| 34 | { |
| 35 | } |
| 36 | |
| 37 | File::File(const QString& url) |
| 38 | : d(new Private) |
| 39 | { |
| 40 | d->url = QFileInfo(url).canonicalFilePath(); |
| 41 | } |
| 42 | |
| 43 | File::~File() = default; |
| 44 | |
| 45 | const File& File::operator=(const File& f) |
| 46 | { |
| 47 | if (&f != this) { |
| 48 | *d = *f.d; |
| 49 | } |
| 50 | return *this; |
| 51 | } |
| 52 | |
| 53 | QString File::path() const |
| 54 | { |
| 55 | return d->url; |
| 56 | } |
| 57 | |
| 58 | KFileMetaData::PropertyMultiMap File::properties() const |
| 59 | { |
| 60 | return d->propertyMap; |
| 61 | } |
| 62 | |
| 63 | QVariant File::property(KFileMetaData::Property::Property property) const |
| 64 | { |
| 65 | return d->propertyMap.value(key: property); |
| 66 | } |
| 67 | |
| 68 | bool File::load(const QString& url) |
| 69 | { |
| 70 | d->url = QFileInfo(url).canonicalFilePath(); |
| 71 | d->propertyMap.clear(); |
| 72 | return load(); |
| 73 | } |
| 74 | |
| 75 | bool File::load() |
| 76 | { |
| 77 | const QString& url = d->url; |
| 78 | if (url.isEmpty() || !QFile::exists(fileName: url)) { |
| 79 | return false; |
| 80 | } |
| 81 | |
| 82 | Database *db = globalDatabaseInstance(); |
| 83 | if (db->open(mode: Database::ReadOnlyDatabase) != Database::OpenResult::Success) { |
| 84 | return false; |
| 85 | } |
| 86 | |
| 87 | quint64 id = filePathToId(filePath: QFile::encodeName(fileName: d->url)); |
| 88 | if (!id) { |
| 89 | return false; |
| 90 | } |
| 91 | |
| 92 | QByteArray arr; |
| 93 | { |
| 94 | Transaction tr(db, Transaction::ReadOnly); |
| 95 | arr = tr.documentData(id); |
| 96 | } |
| 97 | // Ignore empty JSON documents, i.e. "" or "{}" |
| 98 | if (arr.isEmpty() || arr.size() <= 2) { |
| 99 | return false; |
| 100 | } |
| 101 | |
| 102 | const QJsonDocument jdoc = QJsonDocument::fromJson(json: arr); |
| 103 | d->propertyMap = Baloo::jsonToPropertyMap(properties: jdoc.object()); |
| 104 | |
| 105 | return true; |
| 106 | } |
| 107 |
