File indexing completed on 2024-04-28 11:32:52

0001 /*
0002     This file is part of the KDE Baloo Project
0003     SPDX-FileCopyrightText: 2013 Vishesh Handa <me@vhanda.in>
0004 
0005     SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
0006 */
0007 
0008 #include "file.h"
0009 #include "global.h"
0010 #include "database.h"
0011 #include "transaction.h"
0012 #include "idutils.h"
0013 #include "propertydata.h"
0014 
0015 #include <QJsonDocument>
0016 #include <QFileInfo>
0017 #include <QJsonObject>
0018 
0019 using namespace Baloo;
0020 
0021 class BALOO_CORE_NO_EXPORT File::Private {
0022 public:
0023     QString url;
0024     KFileMetaData::PropertyMultiMap propertyMap;
0025 };
0026 
0027 File::File()
0028     : d(new Private)
0029 {
0030 }
0031 
0032 File::File(const File& f)
0033     : d(new Private(*f.d))
0034 {
0035 }
0036 
0037 File::File(const QString& url)
0038     : d(new Private)
0039 {
0040     d->url = QFileInfo(url).canonicalFilePath();
0041 }
0042 
0043 File::~File()
0044 {
0045     delete d;
0046 }
0047 
0048 const File& File::operator=(const File& f)
0049 {
0050     if (&f != this) {
0051         *d = *f.d;
0052     }
0053     return *this;
0054 }
0055 
0056 QString File::path() const
0057 {
0058     return d->url;
0059 }
0060 
0061 #if BALOO_CORE_BUILD_DEPRECATED_SINCE(5, 91)
0062 KFileMetaData::PropertyMap File::properties() const
0063 #else
0064 KFileMetaData::PropertyMultiMap File::properties() const
0065 #endif
0066 {
0067     return d->propertyMap;
0068 }
0069 
0070 QVariant File::property(KFileMetaData::Property::Property property) const
0071 {
0072     return d->propertyMap.value(property);
0073 }
0074 
0075 bool File::load(const QString& url)
0076 {
0077     d->url = QFileInfo(url).canonicalFilePath();
0078     d->propertyMap.clear();
0079     return load();
0080 }
0081 
0082 bool File::load()
0083 {
0084     const QString& url = d->url;
0085     if (url.isEmpty() || !QFile::exists(url)) {
0086         return false;
0087     }
0088 
0089     Database *db = globalDatabaseInstance();
0090     if (!db->open(Database::ReadOnlyDatabase)) {
0091         return false;
0092     }
0093 
0094     quint64 id = filePathToId(QFile::encodeName(d->url));
0095     if (!id) {
0096         return false;
0097     }
0098 
0099     QByteArray arr;
0100     {
0101         Transaction tr(db, Transaction::ReadOnly);
0102         arr = tr.documentData(id);
0103     }
0104     // Ignore empty JSON documents, i.e. "" or "{}"
0105     if (arr.isEmpty() || arr.size() <= 2) {
0106         return false;
0107     }
0108 
0109     const QJsonDocument jdoc = QJsonDocument::fromJson(arr);
0110     d->propertyMap = Baloo::jsonToPropertyMap(jdoc.object());
0111 
0112     return true;
0113 }