FlatpakBackend.cpp 49.7 KB
Newer Older
Jan Grulich's avatar
Jan Grulich committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/***************************************************************************
 *   Copyright © 2013 Aleix Pol Gonzalez <aleixpol@blue-systems.com>       *
 *   Copyright © 2017 Jan Grulich <jgrulich@redhat.com>                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU General Public License as        *
 *   published by the Free Software Foundation; either version 2 of        *
 *   the License or (at your option) version 3 or any later version        *
 *   accepted by the membership of KDE e.V. (or its successor approved     *
 *   by the membership of KDE e.V.), which shall act as a proxy            *
 *   defined in Section 14 of version 3 of the license.                    *
 *                                                                         *
 *   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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/

#include "FlatpakBackend.h"
23
#include "FlatpakFetchDataJob.h"
Jan Grulich's avatar
Jan Grulich committed
24 25
#include "FlatpakResource.h"
#include "FlatpakSourcesBackend.h"
26
#include "FlatpakJobTransaction.h"
Jan Grulich's avatar
Jan Grulich committed
27 28 29 30

#include <resources/StandardBackendUpdater.h>
#include <resources/SourcesModel.h>
#include <Transaction/Transaction.h>
31 32
#include <appstream/OdrsReviewsBackend.h>
#include <appstream/AppStreamIntegration.h>
Jan Grulich's avatar
Jan Grulich committed
33

34 35
#include <AppStreamQt/bundle.h>
#include <AppStreamQt/component.h>
Jan Grulich's avatar
Jan Grulich committed
36
#include <AppStreamQt/icon.h>
37
#include <AppStreamQt/metadata.h>
38

Jan Grulich's avatar
Jan Grulich committed
39 40 41 42 43 44 45
#include <KAboutData>
#include <KLocalizedString>
#include <KPluginFactory>
#include <KConfigGroup>
#include <KSharedConfig>

#include <QAction>
46
#include <QtConcurrentRun>
Jan Grulich's avatar
Jan Grulich committed
47 48 49
#include <QDebug>
#include <QDir>
#include <QFile>
50
#include <QFileInfo>
51
#include <QFutureWatcher>
52
#include <QSettings>
Jan Grulich's avatar
Jan Grulich committed
53 54
#include <QThread>
#include <QTimer>
55 56
#include <QTextStream>
#include <QTemporaryFile>
57
#include <QNetworkAccessManager>
Jan Grulich's avatar
Jan Grulich committed
58

59
#include <glib.h>
60
#include "FlatpakSourcesBackend.h"
61

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
62
DISCOVER_BACKEND_PLUGIN(FlatpakBackend)
Jan Grulich's avatar
Jan Grulich committed
63

64 65 66 67 68 69 70 71 72 73 74 75 76
static QString idForInstalledRef(FlatpakInstallation *installation, FlatpakInstalledRef *ref)
{
    const FlatpakResource::ResourceType appType = flatpak_ref_get_kind(FLATPAK_REF(ref)) == FLATPAK_REF_KIND_APP ? FlatpakResource::DesktopApp : FlatpakResource::Runtime;
    const QString name = QLatin1String(flatpak_ref_get_name(FLATPAK_REF(ref)));
    const QString appId = appType == FlatpakResource::DesktopApp ? QLatin1String(flatpak_ref_get_name(FLATPAK_REF(ref))) + QStringLiteral(".desktop") : name;

    const QString arch = QString::fromUtf8(flatpak_ref_get_arch(FLATPAK_REF(ref)));
    const QString branch = QString::fromUtf8(flatpak_ref_get_branch(FLATPAK_REF(ref)));

    return QStringLiteral("%1/%2/%3/%4/%5/%6").arg(FlatpakResource::installationPath(installation), QLatin1String("flatpak"), QString::fromUtf8(flatpak_installed_ref_get_origin(ref)),
                                                   FlatpakResource::typeAsString(appType), appId, branch);
}

Jan Grulich's avatar
Jan Grulich committed
77 78 79
FlatpakBackend::FlatpakBackend(QObject* parent)
    : AbstractResourcesBackend(parent)
    , m_updater(new StandardBackendUpdater(this))
80
    , m_reviews(AppStreamIntegration::global()->reviews())
81
    , m_refreshAppstreamMetadataJobs(0)
82
    , m_threadPool(new QThreadPool(this))
Jan Grulich's avatar
Jan Grulich committed
83 84
{
    g_autoptr(GError) error = nullptr;
85
    m_cancellable = g_cancellable_new();
Jan Grulich's avatar
Jan Grulich committed
86

Jan Grulich's avatar
Jan Grulich committed
87 88
    connect(m_updater, &StandardBackendUpdater::updatesCountChanged, this, &FlatpakBackend::updatesCountChanged);

Jan Grulich's avatar
Jan Grulich committed
89
    // Load flatpak installation
90
    if (!setupFlatpakInstallations(&error)) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
91
        qWarning() << "Failed to setup flatpak installations:" << error->message;
Jan Grulich's avatar
Jan Grulich committed
92
    } else {
93
        loadAppsFromAppstreamData();
94

95
        m_sources = new FlatpakSourcesBackend(m_installations, this);
96
        SourcesModel::global()->addSourcesBackend(m_sources);
Jan Grulich's avatar
Jan Grulich committed
97 98
    }

99
    connect(m_reviews.data(), &OdrsReviewsBackend::ratingsReady, this, &FlatpakBackend::announceRatingsReady);
Jan Grulich's avatar
Jan Grulich committed
100 101
}

102 103
FlatpakBackend::~FlatpakBackend()
{
104
    m_threadPool.clear();
105 106 107
    for(auto inst : m_installations)
        g_object_unref(inst);

108
    g_object_unref(m_cancellable);
109 110
}

111 112
bool FlatpakBackend::isValid() const
{
113
    return m_sources && !m_installations.isEmpty();
114 115
}

116 117 118 119 120 121 122 123 124 125 126 127
void FlatpakBackend::announceRatingsReady()
{
    emitRatingsReady();

    const auto ids = m_reviews->appstreamIds().toSet();
    foreach(AbstractResource* res, m_resources) {
        if (ids.contains(res->appstreamId())) {
            res->ratingFetched();
        }
    }
}

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
class FlatpakFetchRemoteResourceJob : public QNetworkAccessManager
{
Q_OBJECT
public:
    FlatpakFetchRemoteResourceJob(const QUrl &url, FlatpakBackend *backend)
        : QNetworkAccessManager(backend)
        , m_backend(backend)
        , m_url(url)
    {
    }

    void start()
    {
        auto replyGet = get(QNetworkRequest(m_url));

        connect(replyGet, &QNetworkReply::finished, this, [this, replyGet] {
            const QUrl originalUrl = replyGet->request().url();
            if (replyGet->error() != QNetworkReply::NoError) {
                qWarning() << "couldn't download" << originalUrl << replyGet->errorString();
                Q_EMIT jobFinished(false, nullptr);
                return;
            }

            const QUrl fileUrl = QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1Char('/') + originalUrl.fileName());
            auto replyPut = put(QNetworkRequest(fileUrl), replyGet->readAll());
            connect(replyPut, &QNetworkReply::finished, this, [this, originalUrl, fileUrl, replyPut]() {
                if (replyPut->error() == QNetworkReply::NoError) {
                    auto res = m_backend->resourceForFile(fileUrl);
                    if (res) {
                        FlatpakResource *resource = qobject_cast<FlatpakResource*>(res);
                        resource->setResourceFile(originalUrl);
                        Q_EMIT jobFinished(true, resource);
                    } else {
                        qWarning() << "couldn't download" << originalUrl << "into" << fileUrl << replyPut->errorString();
                        Q_EMIT jobFinished(false, nullptr);
                    }
                }
            });
        });
    }

Q_SIGNALS:
    void jobFinished(bool success, FlatpakResource *resource);

private:
    FlatpakBackend *m_backend;
    QUrl m_url;
};

Jan Grulich's avatar
Jan Grulich committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
FlatpakRemote * FlatpakBackend::getFlatpakRemoteByUrl(const QString &url, FlatpakInstallation *installation) const
{
    auto remotes = flatpak_installation_list_remotes(installation, m_cancellable, nullptr);
    if (!remotes) {
        return nullptr;
    }

    const QByteArray comparableUrl = url.toUtf8();
    for (uint i = 0; i < remotes->len; i++) {
        FlatpakRemote *remote = FLATPAK_REMOTE(g_ptr_array_index(remotes, i));

        if (comparableUrl == flatpak_remote_get_url(remote)) {
            return remote;
        }
    }
    return nullptr;
}

195
FlatpakInstalledRef * FlatpakBackend::getInstalledRefForApp(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource) const
196 197 198 199 200 201 202 203
{
    FlatpakInstalledRef *ref = nullptr;
    g_autoptr(GError) localError = nullptr;

    if (!flatpakInstallation) {
        return ref;
    }

204 205 206 207
    const auto type = resource->type() == FlatpakResource::DesktopApp ? FLATPAK_REF_KIND_APP : FLATPAK_REF_KIND_RUNTIME;

    return flatpak_installation_get_installed_ref(flatpakInstallation,
                                                 type,
208 209 210
                                                 resource->flatpakName().toUtf8().constData(),
                                                 resource->arch().toUtf8().constData(),
                                                 resource->branch().toUtf8().constData(),
211
                                                 m_cancellable, &localError);
212 213
}

214
FlatpakResource * FlatpakBackend::getAppForInstalledRef(FlatpakInstallation *flatpakInstallation, FlatpakInstalledRef *ref) const
Jan Grulich's avatar
Jan Grulich committed
215
{
216
    return m_resources.value(idForInstalledRef(flatpakInstallation, ref));
Jan Grulich's avatar
Jan Grulich committed
217 218
}

219
FlatpakResource * FlatpakBackend::getRuntimeForApp(FlatpakResource *resource) const
220 221
{
    FlatpakResource *runtime = nullptr;
222
    const auto runtimeInfo = resource->runtime().split(QLatin1Char('/'));
223 224 225 226 227

    if (runtimeInfo.count() != 3) {
        return runtime;
    }

228
    const QString runtimeId = QStringLiteral("runtime/") + runtimeInfo.at(0) + QLatin1Char('/') + runtimeInfo.at(2);
Jan Grulich's avatar
Jan Grulich committed
229

230 231 232
    for(auto it = m_resources.constBegin(), itEnd = m_resources.constEnd(); it!=itEnd; ++it) {
        if (it.key().endsWith(runtimeId)) {
            runtime = *it;
233 234 235 236 237 238 239 240 241
            break;
        }
    }

    // TODO if runtime wasn't found, create a new one from available info

    return runtime;
}

Jan Grulich's avatar
Jan Grulich committed
242 243 244 245 246 247
FlatpakResource * FlatpakBackend::addAppFromFlatpakBundle(const QUrl &url)
{
    g_autoptr(GBytes) appstreamGz = nullptr;
    g_autoptr(GError) localError = nullptr;
    g_autoptr(GFile) file = nullptr;
    g_autoptr(FlatpakBundleRef) bundleRef = nullptr;
248
    AppStream::Component asComponent;
Jan Grulich's avatar
Jan Grulich committed
249

250
    file = g_file_new_for_path(url.toLocalFile().toUtf8().constData());
Jan Grulich's avatar
Jan Grulich committed
251 252 253
    bundleRef = flatpak_bundle_ref_new(file, &localError);

    if (!bundleRef) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
254
        qWarning() << "Failed to load bundle:" << localError->message;
Jan Grulich's avatar
Jan Grulich committed
255 256 257
        return nullptr;
    }

258
    g_autoptr(GBytes) metadata = flatpak_bundle_ref_get_metadata(bundleRef);
Jan Grulich's avatar
Jan Grulich committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    appstreamGz = flatpak_bundle_ref_get_appstream(bundleRef);
    if (appstreamGz) {
        g_autoptr(GZlibDecompressor) decompressor = nullptr;
        g_autoptr(GInputStream) streamGz = nullptr;
        g_autoptr(GInputStream) streamData = nullptr;
        g_autoptr(GBytes) appstream = nullptr;

        /* decompress data */
        decompressor = g_zlib_decompressor_new (G_ZLIB_COMPRESSOR_FORMAT_GZIP);
        streamGz = g_memory_input_stream_new_from_bytes (appstreamGz);
        if (!streamGz) {
            return nullptr;
        }

        streamData = g_converter_input_stream_new (streamGz, G_CONVERTER (decompressor));

        appstream = g_input_stream_read_bytes (streamData, 0x100000, m_cancellable, &localError);
        if (!appstream) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
277
            qWarning() << "Failed to extract appstream metadata from bundle:" << localError->message;
Jan Grulich's avatar
Jan Grulich committed
278 279 280
            return nullptr;
        }

281 282 283
        gsize len = 0;
        gconstpointer data = g_bytes_get_data(appstream, &len);

284 285
        AppStream::Metadata metadata;
        metadata.setFormatStyle(AppStream::Metadata::FormatStyleCollection);
286
        AppStream::Metadata::MetadataError error = metadata.parse(QString::fromUtf8((char*)data, len), AppStream::Metadata::FormatKindXml);
287 288
        if (error != AppStream::Metadata::MetadataErrorNoError) {
            qWarning() << "Failed to parse appstream metadata: " << error;
Jan Grulich's avatar
Jan Grulich committed
289 290 291
            return nullptr;
        }

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
292
        const QList<AppStream::Component> components = metadata.components();
293 294
        if (components.size()) {
            asComponent = AppStream::Component(components.first());
Jan Grulich's avatar
Jan Grulich committed
295 296 297 298 299 300
        } else {
            qWarning() << "Failed to parse appstream metadata";
            return nullptr;
        }
    } else {
        qWarning() << "No appstream metadata in bundle";
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320

        QTemporaryFile tempFile;
        tempFile.setAutoRemove(false);
        if (!tempFile.open()) {
            qWarning() << "Failed to get metadata file";
            return nullptr;
        }

        gsize len = 0;
        QByteArray metadataContent = QByteArray((char *)g_bytes_get_data(metadata, &len));
        tempFile.write(metadataContent);
        tempFile.close();

        // Parse the temporary file
        QSettings setting(tempFile.fileName(), QSettings::NativeFormat);
        setting.beginGroup(QLatin1String("Application"));

        asComponent.setName(setting.value(QLatin1String("name")).toString());

        tempFile.remove();
Jan Grulich's avatar
Jan Grulich committed
321 322
    }

323
    FlatpakResource *resource = new FlatpakResource(asComponent, preferredInstallation(), this);
Jan Grulich's avatar
Jan Grulich committed
324

325
    gsize len = 0;
Jan Grulich's avatar
Jan Grulich committed
326 327
    QByteArray metadataContent = QByteArray((char *)g_bytes_get_data(metadata, &len));
    if (!updateAppMetadata(resource, metadataContent)) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
328
        delete resource;
Jan Grulich's avatar
Jan Grulich committed
329 330 331 332
        qWarning() << "Failed to update metadata from app bundle";
        return nullptr;
    }

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
333
    g_autoptr(GBytes) iconData = flatpak_bundle_ref_get_icon(bundleRef, 128);
Jan Grulich's avatar
Jan Grulich committed
334 335 336 337 338 339 340
    if (!iconData) {
        iconData = flatpak_bundle_ref_get_icon(bundleRef, 64);
    }

    if (iconData) {
        gsize len = 0;
        char * data = (char *)g_bytes_get_data(iconData, &len);
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
341 342 343

        QPixmap pixmap;
        pixmap.loadFromData(QByteArray(data, len), "PNG");
Jan Grulich's avatar
Jan Grulich committed
344 345 346
        resource->setBundledIcon(pixmap);
    }

347 348
    const QString origin = QString::fromUtf8(flatpak_bundle_ref_get_origin(bundleRef));

349
    resource->setDownloadSize(0);
Jan Grulich's avatar
Jan Grulich committed
350
    resource->setInstalledSize(flatpak_bundle_ref_get_installed_size(bundleRef));
351 352
    resource->setPropertyState(FlatpakResource::DownloadSize, FlatpakResource::AlreadyKnown);
    resource->setPropertyState(FlatpakResource::InstalledSize, FlatpakResource::AlreadyKnown);
Jan Grulich's avatar
Jan Grulich committed
353
    resource->setFlatpakFileType(QStringLiteral("flatpak"));
354
    resource->setOrigin(origin.isEmpty() ? i18n("Local bundle") : origin);
Jan Grulich's avatar
Jan Grulich committed
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    resource->setResourceFile(url);
    resource->setState(FlatpakResource::None);
    resource->setType(FlatpakResource::DesktopApp);

    addResource(resource);
    return resource;
}

FlatpakResource * FlatpakBackend::addAppFromFlatpakRef(const QUrl &url)
{
    QSettings settings(url.toLocalFile(), QSettings::NativeFormat);
    const QString refurl = settings.value(QStringLiteral("Flatpak Ref/Url")).toString();

    g_autoptr(GError) error = NULL;
    g_autoptr(FlatpakRemoteRef) remoteRef = nullptr;
    {
        QFile f(url.toLocalFile());
        if (!f.open(QFile::ReadOnly | QFile::Text)) {
            return nullptr;
        }

        QByteArray contents = f.readAll();

        g_autoptr(GBytes) bytes = g_bytes_new (contents.data(), contents.size());

380
        remoteRef = flatpak_installation_install_ref_file (preferredInstallation(), bytes, m_cancellable, &error);
Jan Grulich's avatar
Jan Grulich committed
381
        if (!remoteRef) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
382
            qWarning() << "Failed to install ref file:" << error->message;
Jan Grulich's avatar
Jan Grulich committed
383 384 385 386 387 388 389 390
            return nullptr;
        }
    }

    const auto remoteName = flatpak_remote_ref_get_remote_name(remoteRef);

    auto ref = FLATPAK_REF(remoteRef);

391 392 393 394 395 396 397
    AppStream::Component asComponent;
    asComponent.addUrl(AppStream::Component::UrlKindHomepage, settings.value(QStringLiteral("Flatpak Ref/Homepage")).toString());
    asComponent.setDescription(settings.value(QStringLiteral("Flatpak Ref/Description")).toString());
    asComponent.setName(settings.value(QStringLiteral("Flatpak Ref/Title")).toString());
    asComponent.setSummary(settings.value(QStringLiteral("Flatpak Ref/Comment")).toString());
    asComponent.setId(settings.value(QStringLiteral("Flatpak Ref/Name")).toString());

Jan Grulich's avatar
Jan Grulich committed
398 399
    const QString iconUrl = settings.value(QStringLiteral("Flatpak Ref/Icon")).toString();
    if (!iconUrl.isEmpty()) {
400 401 402 403
        AppStream::Icon icon;
        icon.setKind(AppStream::Icon::KindRemote);
        icon.setUrl(QUrl(iconUrl));
        asComponent.addIcon(icon);
Jan Grulich's avatar
Jan Grulich committed
404 405
    }

406
    auto resource = new FlatpakResource(asComponent, preferredInstallation(), this);
Jan Grulich's avatar
Jan Grulich committed
407 408 409
    resource->setFlatpakFileType(QStringLiteral("flatpakref"));
    resource->setOrigin(QString::fromUtf8(remoteName));
    resource->updateFromRef(ref);
410 411 412

    QUrl runtimeUrl = QUrl(settings.value(QStringLiteral("Flatpak Ref/RuntimeRepo")).toString());
    if (!runtimeUrl.isEmpty()) {
413
        auto installation = preferredInstallation();
414
        // We need to fetch metadata to find information about required runtime
415 416 417 418
        auto fw = new QFutureWatcher<QByteArray>(this);
        fw->setFuture(QtConcurrent::run(&m_threadPool, &FlatpakRunnables::fetchMetadata, installation, resource));
        connect(fw, &QFutureWatcher<QByteArray>::finished, this, [this, installation, resource, fw, runtimeUrl]() {
            const auto metadata = fw->result();
419
            // Even when we failed to fetch information about runtime we still want to show the application
420 421
            if (metadata.isEmpty()) {
                onFetchMetadataFinished(installation, resource, metadata);
422
            } else {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
                updateAppMetadata(resource, metadata);

                auto runtime = getRuntimeForApp(resource);
                if (!runtime || (runtime && !runtime->isInstalled())) {
                    FlatpakFetchRemoteResourceJob *fetchRemoteResource = new FlatpakFetchRemoteResourceJob(runtimeUrl, this);
                    connect(fetchRemoteResource, &FlatpakFetchRemoteResourceJob::jobFinished, this, [this, resource] (bool success, FlatpakResource *repoResource) {
                        if (success) {
                            installApplication(repoResource);
                        }
                        addResource(resource);
                    });
                    fetchRemoteResource->start();
                    return;
                } else {
                    addResource(resource);
                }
439
            }
440
            fw->deleteLater();
441 442 443 444 445
        });
    } else {
        addResource(resource);
    }

Jan Grulich's avatar
Jan Grulich committed
446 447 448
    return resource;
}

449 450
FlatpakResource * FlatpakBackend::addSourceFromFlatpakRepo(const QUrl &url)
{
451
    Q_ASSERT(url.isLocalFile());
452 453 454 455 456 457 458 459 460 461 462 463 464 465
    QSettings settings(url.toLocalFile(), QSettings::NativeFormat);

    const QString gpgKey = settings.value(QStringLiteral("Flatpak Repo/GPGKey")).toString();
    const QString title = settings.value(QStringLiteral("Flatpak Repo/Title")).toString();
    const QString repoUrl = settings.value(QStringLiteral("Flatpak Repo/Url")).toString();

    if (gpgKey.isEmpty() || title.isEmpty() || repoUrl.isEmpty()) {
        return nullptr;
    }

    if (gpgKey.startsWith(QStringLiteral("http://")) || gpgKey.startsWith(QStringLiteral("https://"))) {
        return nullptr;
    }

466 467 468 469 470 471 472
    AppStream::Component asComponent;
    asComponent.addUrl(AppStream::Component::UrlKindHomepage, settings.value(QStringLiteral("Flatpak Repo/Homepage")).toString());
    asComponent.setSummary(settings.value(QStringLiteral("Flatpak Repo/Comment")).toString());
    asComponent.setDescription(settings.value(QStringLiteral("Flatpak Repo/Description")).toString());
    asComponent.setName(title);
    asComponent.setId(settings.value(QStringLiteral("Flatpak Ref/Name")).toString());

473
    const QString iconUrl = settings.value(QStringLiteral("Flatpak Repo/Icon")).toString();
474
    if (!iconUrl.isEmpty()) {
475 476 477 478
        AppStream::Icon icon;
        icon.setKind(AppStream::Icon::KindRemote);
        icon.setUrl(QUrl(iconUrl));
        asComponent.addIcon(icon);
479 480
    }

481
    auto resource = new FlatpakResource(asComponent, preferredInstallation(), this);
482 483 484 485 486 487 488
    // Use metadata only for stuff which are not common for all resources
    resource->addMetadata(QStringLiteral("gpg-key"), gpgKey);
    resource->addMetadata(QStringLiteral("repo-url"), repoUrl);
    resource->setBranch(settings.value(QStringLiteral("Flatpak Repo/DefaultBranch")).toString());
    resource->setFlatpakName(url.fileName().remove(QStringLiteral(".flatpakrepo")));
    resource->setType(FlatpakResource::Source);

489
    auto repo = flatpak_installation_get_remote_by_name(preferredInstallation(), resource->flatpakName().toUtf8().constData(), m_cancellable, nullptr);
490 491 492 493 494 495 496 497 498
    if (!repo) {
        resource->setState(AbstractResource::State::None);
    } else {
        resource->setState(AbstractResource::State::Installed);
    }

    return resource;
}

499 500 501 502
void FlatpakBackend::addResource(FlatpakResource *resource)
{
    // Update app with all possible information we have
    if (!parseMetadataFromAppBundle(resource)) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
503
        qWarning() << "Failed to parse metadata from app bundle for" << resource->name();
504 505
    }

506
    auto installation = resource->installation();
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
507
    updateAppState(installation, resource);
508

509
    // This will update also metadata (required runtime)
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
510
    updateAppSize(installation, resource);
511 512 513 514

    m_resources.insert(resource->uniqueId(), resource);
}

515
bool FlatpakBackend::compareAppFlatpakRef(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource, FlatpakInstalledRef *ref) const
516
{
517
    return resource->uniqueId() == idForInstalledRef(flatpakInstallation, ref);
518 519
}

520
class FlatpakSource
Jan Grulich's avatar
Jan Grulich committed
521
{
522 523
public:
    FlatpakSource(FlatpakRemote* remote) : m_remote(remote) {}
Jan Grulich's avatar
Jan Grulich committed
524

525 526 527
    bool isEnabled() const
    {
        return !flatpak_remote_get_disabled(m_remote);
Jan Grulich's avatar
Jan Grulich committed
528 529
    }

530 531 532 533
    QString appstreamDir() const
    {
        g_autoptr(GFile) appstreamDir = flatpak_remote_get_appstream_dir(m_remote, nullptr);
        if (!appstreamDir) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
534
            qWarning() << "No appstream dir for" << flatpak_remote_get_name(m_remote);
535 536 537 538 539 540 541 542 543 544 545 546 547 548
            return {};
        }
        return QString::fromUtf8(g_file_get_path(appstreamDir));
    }

    QString name() const
    {
        return QString::fromUtf8(flatpak_remote_get_name(m_remote));
    }

private:
    FlatpakRemote* m_remote;
};

549 550 551 552 553 554 555 556 557 558
void FlatpakBackend::loadAppsFromAppstreamData()
{
    for (auto installation : qAsConst(m_installations)) {
        // Load applications from appstream metadata
        if (!loadAppsFromAppstreamData(installation)) {
            qWarning() << "Failed to load packages from appstream data from installation" << installation;
        }
    }
}

559 560 561 562
bool FlatpakBackend::loadAppsFromAppstreamData(FlatpakInstallation *flatpakInstallation)
{
    Q_ASSERT(flatpakInstallation);

563
    GPtrArray *remotes = flatpak_installation_list_remotes(flatpakInstallation, m_cancellable, nullptr);
Jan Grulich's avatar
Jan Grulich committed
564 565 566 567
    if (!remotes) {
        return false;
    }

568 569
    m_refreshAppstreamMetadataJobs += remotes->len;

Jan Grulich's avatar
Jan Grulich committed
570 571
    for (uint i = 0; i < remotes->len; i++) {
        FlatpakRemote *remote = FLATPAK_REMOTE(g_ptr_array_index(remotes, i));
572
        g_autoptr(GFile) fileTimestamp = flatpak_remote_get_appstream_timestamp(remote, nullptr);
573

574 575 576 577 578 579 580
        QFileInfo fileInfo = QFileInfo(QString::fromUtf8(g_file_get_path(fileTimestamp)));
        // Refresh appstream metadata in case they have never been refreshed or the cache is older than 6 hours
        if (!fileInfo.exists() || fileInfo.lastModified().toUTC().secsTo(QDateTime::currentDateTimeUtc()) > 21600) {
            refreshAppstreamMetadata(flatpakInstallation, remote);
        } else {
            integrateRemote(flatpakInstallation, remote);
        }
581
    }
Jan Grulich's avatar
Jan Grulich committed
582

583 584
    return true;
}
Jan Grulich's avatar
Jan Grulich committed
585

586 587
void FlatpakBackend::integrateRemote(FlatpakInstallation *flatpakInstallation, FlatpakRemote *remote)
{
588
    Q_ASSERT(m_refreshAppstreamMetadataJobs != 0);
589 590
    m_refreshAppstreamMetadataJobs--;

591 592 593 594
    FlatpakSource source(remote);
    if (!source.isEnabled() || flatpak_remote_get_noenumerate(remote)) {
        return;
    }
Jan Grulich's avatar
Jan Grulich committed
595

596
    const QString appstreamDirPath = source.appstreamDir();
597
    const QString appstreamIconsPath = source.appstreamDir() + QLatin1String("/icons/");
598 599
    const QString appDirFileName = appstreamDirPath + QLatin1String("/appstream.xml.gz");
    if (!QFile::exists(appDirFileName)) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
600
        qWarning() << "No" << appDirFileName << "appstream metadata found for" << source.name();
601
        return;
Jan Grulich's avatar
Jan Grulich committed
602 603
    }

604 605 606 607 608 609 610 611 612
    auto fw = new QFutureWatcher<QList<AppStream::Component>>(this);
    fw->setFuture(QtConcurrent::run(&m_threadPool, [appDirFileName]() -> QList<AppStream::Component> {
        AppStream::Metadata metadata;
        metadata.setFormatStyle(AppStream::Metadata::FormatStyleCollection);
        AppStream::Metadata::MetadataError error = metadata.parseFile(appDirFileName, AppStream::Metadata::FormatKindXml);
        if (error != AppStream::Metadata::MetadataErrorNoError) {
            qWarning() << "Failed to parse appstream metadata: " << error;
            return {};
        }
613

614 615 616
        return metadata.components();
    }));
    const auto sourceName = source.name();
617
    acquireFetching(true);
618 619 620 621 622 623 624 625 626
    connect(fw, &QFutureWatcher<QList<AppStream::Component>>::finished, this, [this, fw, flatpakInstallation, appstreamIconsPath, sourceName]() {
        const auto components = fw->result();
        foreach (const AppStream::Component& appstreamComponent, components) {
            FlatpakResource *resource = new FlatpakResource(appstreamComponent, flatpakInstallation, this);
            resource->setIconPath(appstreamIconsPath);
            resource->setOrigin(sourceName);
            addResource(resource);
        }
        if (!m_refreshAppstreamMetadataJobs) {
627 628 629
            loadInstalledApps();
            checkForUpdates();

630
        }
631
        acquireFetching(false);
632 633
        fw->deleteLater();
    });
634 635 636 637 638 639 640 641 642 643
}

void FlatpakBackend::loadInstalledApps()
{
    for (auto installation : qAsConst(m_installations)) {
        // Load installed applications and update existing resources with info from installed application
        if (!loadInstalledApps(installation)) {
            qWarning() << "Failed to load installed packages from installation" << installation;
        }
    }
Jan Grulich's avatar
Jan Grulich committed
644 645
}

646
bool FlatpakBackend::loadInstalledApps(FlatpakInstallation *flatpakInstallation)
Jan Grulich's avatar
Jan Grulich committed
647
{
648
    Q_ASSERT(flatpakInstallation);
Jan Grulich's avatar
Jan Grulich committed
649

650 651 652 653 654 655 656
    g_autoptr(GError) localError = nullptr;
    g_autoptr(GPtrArray) refs = flatpak_installation_list_installed_refs(flatpakInstallation, m_cancellable, &localError);
    if (!refs) {
        qWarning() << "Failed to get list of installed refs for listing updates:" << localError->message;
        return false;
    }

657 658
    const QString pathExports = FlatpakResource::installationPath(flatpakInstallation) + QLatin1String("/exports/");
    const QString pathApps = pathExports + QLatin1String("share/applications/");
Jan Grulich's avatar
Jan Grulich committed
659

660 661
    for (uint i = 0; i < refs->len; i++) {
        FlatpakInstalledRef *ref = FLATPAK_INSTALLED_REF(g_ptr_array_index(refs, i));
Jan Grulich's avatar
Jan Grulich committed
662

663 664 665
        if (flatpak_ref_get_kind(FLATPAK_REF(ref)) == FLATPAK_REF_KIND_RUNTIME) {
            continue;
        }
666 667 668 669 670
        const auto res = getAppForInstalledRef(flatpakInstallation, ref);
        if (res) {
            res->setState(AbstractResource::Installed);
            continue;
        }
671

672 673
        const auto name = QLatin1String(flatpak_ref_get_name(FLATPAK_REF(ref)));
        AppStream::Metadata metadata;
674
        const QString fnDesktop = pathApps + name + QLatin1String(".desktop");
675
        AppStream::Metadata::MetadataError error = metadata.parseFile(fnDesktop, AppStream::Metadata::FormatKindDesktopEntry);
676 677 678 679 680
        if (error != AppStream::Metadata::MetadataErrorNoError) {
            qWarning() << "Failed to parse appstream metadata: " << error << fnDesktop;
            continue;
        }

681 682 683
        auto component = metadata.component();
        component.setId(name + QLatin1String(".desktop"));
        FlatpakResource *resource = new FlatpakResource(component, flatpakInstallation, this);
684 685 686 687 688 689

        resource->setIconPath(pathExports);
        resource->setState(AbstractResource::Installed);
        resource->setOrigin(QString::fromUtf8(flatpak_installed_ref_get_origin(ref)));
        resource->updateFromRef(FLATPAK_REF(ref));

690
        addResource(resource);
Jan Grulich's avatar
Jan Grulich committed
691 692 693 694 695
    }

    return true;
}

Jan Grulich's avatar
Jan Grulich committed
696 697 698 699 700 701 702
void FlatpakBackend::loadLocalUpdates(FlatpakInstallation *flatpakInstallation)
{
    g_autoptr(GError) localError = nullptr;
    g_autoptr(GPtrArray) refs = nullptr;

    refs = flatpak_installation_list_installed_refs(flatpakInstallation, m_cancellable, &localError);
    if (!refs) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
703
        qWarning() << "Failed to get list of installed refs for listing updates:" << localError->message;
Jan Grulich's avatar
Jan Grulich committed
704 705 706 707 708
        return;
    }

    for (uint i = 0; i < refs->len; i++) {
        FlatpakInstalledRef *ref = FLATPAK_INSTALLED_REF(g_ptr_array_index(refs, i));
709

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
710
        const gchar *latestCommit = flatpak_installed_ref_get_latest_commit(ref);
Jan Grulich's avatar
Jan Grulich committed
711 712

        if (!latestCommit) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
713
            qWarning() << "Couldn't get latest commit for" << flatpak_ref_get_name(FLATPAK_REF(ref));
714
            continue;
Jan Grulich's avatar
Jan Grulich committed
715 716
        }

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
717
        const gchar *commit = flatpak_ref_get_commit(FLATPAK_REF(ref));
Jan Grulich's avatar
Jan Grulich committed
718 719 720 721 722 723 724
        if (g_strcmp0(commit, latestCommit) == 0) {
            continue;
        }

        FlatpakResource *resource = getAppForInstalledRef(flatpakInstallation, ref);
        if (resource) {
            resource->setState(AbstractResource::Upgradeable);
725
            updateAppSize(flatpakInstallation, resource);
Jan Grulich's avatar
Jan Grulich committed
726 727 728 729
        }
    }
}

730
void FlatpakBackend::loadRemoteUpdates(FlatpakInstallation* installation)
Jan Grulich's avatar
Jan Grulich committed
731
{
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
    auto fw = new QFutureWatcher<GPtrArray *>(this);
    fw->setFuture(QtConcurrent::run(&m_threadPool, [installation]() -> GPtrArray * {
        g_autoptr(GCancellable) cancellable = g_cancellable_new();
        g_autoptr(GError) localError = nullptr;
        GPtrArray *refs = flatpak_installation_list_installed_refs_for_update(installation, cancellable, &localError);
        if (!refs) {
            qWarning() << "Failed to get list of installed refs for listing updates: " << localError->message;
        }
        return refs;
    }));
    connect(fw, &QFutureWatcher<GPtrArray *>::finished, this, [this, installation, fw](){
        auto refs = fw->result();
        onFetchUpdatesFinished(installation, refs);
        fw->deleteLater();
    });
747
}
Jan Grulich's avatar
Jan Grulich committed
748

749 750
void FlatpakBackend::onFetchUpdatesFinished(FlatpakInstallation *flatpakInstallation, GPtrArray *updates)
{
751 752 753 754 755
    if (!updates) {
        qWarning() << "could not get updates for" << flatpakInstallation;
        return;
    }

756
    g_autoptr(GPtrArray) fetchedUpdates = updates;
Jan Grulich's avatar
Jan Grulich committed
757

758 759
    for (uint i = 0; i < fetchedUpdates->len; i++) {
        FlatpakInstalledRef *ref = FLATPAK_INSTALLED_REF(g_ptr_array_index(fetchedUpdates, i));
Jan Grulich's avatar
Jan Grulich committed
760 761 762
        FlatpakResource *resource = getAppForInstalledRef(flatpakInstallation, ref);
        if (resource) {
            resource->setState(AbstractResource::Upgradeable);
763
            updateAppSize(flatpakInstallation, resource);
Jan Grulich's avatar
Jan Grulich committed
764 765 766 767
        }
    }
}

768 769 770 771
bool FlatpakBackend::parseMetadataFromAppBundle(FlatpakResource *resource)
{
    g_autoptr(FlatpakRef) ref = nullptr;
    g_autoptr(GError) localError = nullptr;
772
    AppStream::Bundle bundle = resource->appstreamComponent().bundle(AppStream::Bundle::KindFlatpak);
773 774

    // Get arch/branch/commit/name from FlatpakRef
775
    if (!bundle.isEmpty()) {
776
        ref = flatpak_ref_parse(bundle.id().toUtf8().constData(), &localError);
777
        if (!ref) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
778
            qWarning() << "Failed to parse" << bundle.id() << localError->message;
779 780
            return false;
        } else {
781
            resource->updateFromRef(ref);
782 783 784 785 786 787
        }
    }

    return true;
}

788 789 790 791 792 793
class FlatpakRefreshAppstreamMetadataJob : public QThread
{
    Q_OBJECT
public:
    FlatpakRefreshAppstreamMetadataJob(FlatpakInstallation *installation, FlatpakRemote *remote)
        : QThread()
794
        , m_cancellable(g_cancellable_new())
795 796 797
        , m_installation(installation)
        , m_remote(remote)
    {
798
        connect(this, &FlatpakRefreshAppstreamMetadataJob::finished, this, &QObject::deleteLater);
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    }

    ~FlatpakRefreshAppstreamMetadataJob()
    {
        g_object_unref(m_cancellable);
    }

    void cancel()
    {
        g_cancellable_cancel(m_cancellable);
    }

    void run() override
    {
        g_autoptr(GError) localError = nullptr;

#if FLATPAK_CHECK_VERSION(0,9,4)
        // With Flatpak 0.9.4 we can use flatpak_installation_update_appstream_full_sync() providing progress reporting which we don't use at this moment, but still
        // better to use newer function in case the previous one gets deprecated
        if (!flatpak_installation_update_appstream_full_sync(m_installation, flatpak_remote_get_name(m_remote), nullptr, nullptr, nullptr, nullptr, m_cancellable, &localError)) {
#else
        if (!flatpak_installation_update_appstream_sync(m_installation, flatpak_remote_get_name(m_remote), nullptr, nullptr, m_cancellable, &localError)) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
821
#endif
822
            qWarning() << "Failed to refresh appstream metadata for " << flatpak_remote_get_name(m_remote) << ": " << (localError ? localError->message : "<no error>");
823
            Q_EMIT jobRefreshAppstreamMetadataFailed();
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
824 825
        } else  {
            Q_EMIT jobRefreshAppstreamMetadataFinished(m_installation, m_remote);
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
        }
    }

Q_SIGNALS:
    void jobRefreshAppstreamMetadataFailed();
    void jobRefreshAppstreamMetadataFinished(FlatpakInstallation *installation, FlatpakRemote *remote);

private:
    GCancellable *m_cancellable;
    FlatpakInstallation *m_installation;
    FlatpakRemote *m_remote;
};

void FlatpakBackend::refreshAppstreamMetadata(FlatpakInstallation *installation, FlatpakRemote *remote)
{
    FlatpakRefreshAppstreamMetadataJob *job = new FlatpakRefreshAppstreamMetadataJob(installation, remote);
842 843 844
    connect(job, &FlatpakRefreshAppstreamMetadataJob::jobRefreshAppstreamMetadataFailed, this, [this] () {
        m_refreshAppstreamMetadataJobs--;
    });
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
845
    connect(job, &FlatpakRefreshAppstreamMetadataJob::jobRefreshAppstreamMetadataFinished, this, &FlatpakBackend::integrateRemote);
846 847 848
    job->start();
}

849
bool FlatpakBackend::setupFlatpakInstallations(GError **error)
Jan Grulich's avatar
Jan Grulich committed
850
{
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
851 852 853 854 855 856 857 858
    if (qEnvironmentVariableIsSet("FLATPAK_TEST_MODE")) {
        const QString path = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1String("/discover-flatpak-test");
        qDebug() << "running flatpak backend on test mode" << path;
        g_autoptr(GFile) file = g_file_new_for_path(QFile::encodeName(path).constData());
        m_installations << flatpak_installation_new_for_path(file, true, m_cancellable, error);
        return true;
    }

859
    GPtrArray *installations = flatpak_get_system_installations(m_cancellable, error);
860 861 862 863
    if (*error) {
        qWarning() << "Failed to call flatpak_get_system_installations:" << (*error)->message;
    }
    for (uint i = 0; installations && i < installations->len; i++) {
864
        m_installations << FLATPAK_INSTALLATION(g_ptr_array_index(installations, i));
Jan Grulich's avatar
Jan Grulich committed
865 866
    }

867 868 869
    auto user = flatpak_installation_new_user(m_cancellable, error);
    if (user) {
        m_installations << user;
Jan Grulich's avatar
Jan Grulich committed
870 871
    }

872
    return !m_installations.isEmpty();
Jan Grulich's avatar
Jan Grulich committed
873 874
}

875
void FlatpakBackend::updateAppInstalledMetadata(FlatpakInstalledRef *installedRef, FlatpakResource *resource)
Jan Grulich's avatar
Jan Grulich committed
876
{
877
    // Update the rest
878
    resource->updateFromRef(FLATPAK_REF(installedRef));
879
    resource->setInstalledSize(flatpak_installed_ref_get_installed_size(installedRef));
880
    resource->setOrigin(QString::fromUtf8(flatpak_installed_ref_get_origin(installedRef)));
881 882
    if (resource->state() < AbstractResource::Installed)
        resource->setState(AbstractResource::Installed);
883 884
}

885
bool FlatpakBackend::updateAppMetadata(FlatpakInstallation* flatpakInstallation, FlatpakResource *resource)
886 887 888
{
    g_autoptr(GFile) installationPath = nullptr;

889
    if (resource->type() != FlatpakResource::DesktopApp) {
890
        return true;
Jan Grulich's avatar
Jan Grulich committed
891 892
    }

893
    installationPath = flatpak_installation_get_path(flatpakInstallation);
894
    const QString path = QString::fromUtf8(g_file_get_path(installationPath)) + QStringLiteral("/app/%1/%2/%3/active/metadata").arg(resource->flatpakName()).arg(resource->arch()).arg(resource->branch());
Jan Grulich's avatar
Jan Grulich committed
895

896
    if (QFile::exists(path)) {
897
        return updateAppMetadata(resource, path);
898
    } else {
899 900 901 902 903 904 905 906 907
        auto fw = new QFutureWatcher<QByteArray>(this);
        fw->setFuture(QtConcurrent::run(&m_threadPool, &FlatpakRunnables::fetchMetadata, flatpakInstallation, resource));
        connect(fw, &QFutureWatcher<QByteArray>::finished, this, [this, flatpakInstallation, resource, fw]() {
            const auto metadata = fw->result();
            if (!metadata.isEmpty())
                onFetchMetadataFinished(flatpakInstallation, resource, metadata);
            fw->deleteLater();
        });

908
        // Return false to indicate we cannot continue (right now used only in updateAppSize())
909 910
        return false;
    }
911 912 913 914 915
}

void FlatpakBackend::onFetchMetadataFinished(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource, const QByteArray &metadata)
{
    updateAppMetadata(resource, metadata);
916

917 918 919 920
    // Right now we attempt to update metadata for calculating the size so call updateSizeFromRemote()
    // as it's what we want. In future if there are other reason to update metadata we will need to somehow
    // distinguish betwen these calls
    updateAppSizeFromRemote(flatpakInstallation, resource);
Jan Grulich's avatar
Jan Grulich committed
921 922
}

923 924 925 926 927 928 929 930 931 932 933
bool FlatpakBackend::updateAppMetadata(FlatpakResource *resource, const QString &path)
{
    // Parse the temporary file
    QSettings setting(path, QSettings::NativeFormat);
    setting.beginGroup(QLatin1String("Application"));
    // Set the runtime in form of name/arch/version which can be later easily parsed
    resource->setRuntime(setting.value(QLatin1String("runtime")).toString());
    // TODO get more information?
    return true;
}

Jan Grulich's avatar
Jan Grulich committed
934 935
bool FlatpakBackend::updateAppMetadata(FlatpakResource *resource, const QByteArray &data)
{
936 937 938 939 940 941 942 943
    // Save the content to temporary file
    QTemporaryFile tempFile;
    tempFile.setAutoRemove(false);
    if (!tempFile.open()) {
        qWarning() << "Failed to get metadata file";
        return false;
    }

Jan Grulich's avatar
Jan Grulich committed
944
    tempFile.write(data);
945 946
    tempFile.close();

947
    updateAppMetadata(resource, tempFile.fileName());
948 949 950 951

    tempFile.remove();

    return true;
Jan Grulich's avatar
Jan Grulich committed
952 953
}

954
bool FlatpakBackend::updateAppSize(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource)
Jan Grulich's avatar
Jan Grulich committed
955
{
956 957 958 959
    // Check if the size is already set, we should also distiguish between download and installed size,
    // right now it doesn't matter whether we get size for installed or not installed app, but if we
    // start making difference then for not installed app check download and install size separately

960
    if (resource->state() == AbstractResource::Installed) {
961
        // The size appears to be already set (from updateAppInstalledMetadata() apparently)
962
        if (resource->installedSize() > 0) {
963 964
            return true;
        }
965 966 967 968 969
    } else {
        if (resource->installedSize() > 0 && resource->downloadSize() > 0) {
            return true;
        }
    }
970 971 972

    // Check if we know the needed runtime which is needed for calculating the size
    if (resource->runtime().isEmpty()) {
973
        if (!updateAppMetadata(flatpakInstallation, resource)) {
974 975
            return false;
        }
Jan Grulich's avatar
Jan Grulich committed
976 977
    }

978 979 980 981 982
    return updateAppSizeFromRemote(flatpakInstallation, resource);
}

bool FlatpakBackend::updateAppSizeFromRemote(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource)
{
983
    // Calculate the runtime size
984
    if (resource->state() == AbstractResource::None && resource->type() == FlatpakResource::DesktopApp) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
985
        auto runtime = getRuntimeForApp(resource);
986 987
        if (runtime) {
            // Re-check runtime state if case a new one was created
988
            updateAppState(flatpakInstallation, runtime);
989 990

            if (!runtime->isInstalled()) {
991
                if (!updateAppSize(flatpakInstallation, runtime)) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
992
                    qWarning() << "Failed to get runtime size needed for total size of" << resource->name();
993 994
                    return false;
                }
Jan Grulich's avatar
Jan Grulich committed
995 996 997
                // Set required download size to include runtime size even now, in case we fail to
                // get the app size (e.g. when installing bundles where download size is 0)
                resource->setDownloadSize(runtime->downloadSize());
998 999
            }
        }
Jan Grulich's avatar
Jan Grulich committed
1000 1001
    }

1002
    if (resource->state() == AbstractResource::Installed) {
1003
        g_autoptr(FlatpakInstalledRef) ref = nullptr;
1004
        ref = getInstalledRefForApp(flatpakInstallation, resource);
1005
        if (!ref) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
1006
            qWarning() << "Failed to get installed size of" << resource->name();
1007 1008
            return false;
        }
1009
        resource->setInstalledSize(flatpak_installed_ref_get_installed_size(ref));
1010 1011
    } else {
        if (resource->origin().isEmpty()) {
Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
1012
            qWarning() << "Failed to get size of" << resource->name() << " because of missing origin";
Jan Grulich's avatar
Jan Grulich committed
1013
            return false;
Jan Grulich's avatar
Jan Grulich committed
1014 1015
        }

1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        auto futureWatcher = new QFutureWatcher<FlatpakRunnables::SizeInformation>(this);
        futureWatcher->setFuture(QtConcurrent::run(&m_threadPool, &FlatpakRunnables::fetchFlatpakSize, flatpakInstallation, resource));
        connect(futureWatcher, &QFutureWatcher<FlatpakRunnables::SizeInformation>::finished, this, [this, resource, futureWatcher]() {
            auto value = futureWatcher->result();
            if (value.valid) {
                onFetchSizeFinished(resource, value.downloadSize, value.installedSize);
            } else {
                resource->setPropertyState(FlatpakResource::DownloadSize, FlatpakResource::UnknownOrFailed);
                resource->setPropertyState(FlatpakResource::InstalledSize, FlatpakResource::UnknownOrFailed);
            }
            futureWatcher->deleteLater();
1027
        });
1028
    }
Jan Grulich's avatar
Jan Grulich committed
1029

1030 1031
    return true;
}
Jan Grulich's avatar
Jan Grulich committed
1032

1033 1034 1035 1036 1037
void FlatpakBackend::onFetchSizeFinished(FlatpakResource *resource, guint64 downloadSize, guint64 installedSize)
{
    FlatpakResource *runtime = nullptr;
    if (resource->state() == AbstractResource::None && resource->type() == FlatpakResource::DesktopApp) {
        runtime = getRuntimeForApp(resource);
1038 1039
    }

1040 1041 1042 1043 1044 1045 1046
    if (runtime && !runtime->isInstalled()) {
        resource->setDownloadSize(runtime->downloadSize() + downloadSize);
        resource->setInstalledSize(installedSize);
    } else {
        resource->setDownloadSize(downloadSize);
        resource->setInstalledSize(installedSize);