diff --git a/libdiscover/backends/FlatpakBackend/FlatpakBackend.cpp b/libdiscover/backends/FlatpakBackend/FlatpakBackend.cpp index 224fac66..421a43e1 100644 --- a/libdiscover/backends/FlatpakBackend/FlatpakBackend.cpp +++ b/libdiscover/backends/FlatpakBackend/FlatpakBackend.cpp @@ -1,1070 +1,1070 @@ /*************************************************************************** * Copyright © 2013 Aleix Pol Gonzalez * * Copyright © 2017 Jan Grulich * * * * 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 . * ***************************************************************************/ #include "FlatpakBackend.h" #include "FlatpakFetchDataJob.h" #include "FlatpakResource.h" #include "FlatpakReviewsBackend.h" #include "FlatpakSourcesBackend.h" #include "FlatpakTransaction.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include MUON_BACKEND_PLUGIN(FlatpakBackend) FlatpakBackend::FlatpakBackend(QObject* parent) : AbstractResourcesBackend(parent) , m_updater(new StandardBackendUpdater(this)) , m_reviews(new FlatpakReviewsBackend(this)) , m_fetching(false) { g_autoptr(GError) error = nullptr; m_cancellable = g_cancellable_new(); connect(m_updater, &StandardBackendUpdater::updatesCountChanged, this, &FlatpakBackend::updatesCountChanged); // Load flatpak installation if (!setupFlatpakInstallations(&error)) { qWarning() << "Failed to setup flatpak installations: " << error->message; } else { reloadPackageList(); checkForUpdates(); } QAction* updateAction = new QAction(this); updateAction->setIcon(QIcon::fromTheme(QStringLiteral("system-software-update"))); updateAction->setText(i18nc("@action Checks the Internet for updates", "Check for Updates")); updateAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R)); connect(updateAction, &QAction::triggered, this, &FlatpakBackend::checkForUpdates); m_messageActions = QList() << updateAction; m_sources = new FlatpakSourcesBackend(m_flatpakInstallationSystem, m_flatpakInstallationUser, this); SourcesModel::global()->addSourcesBackend(m_sources); } FlatpakBackend::~FlatpakBackend() { g_object_unref(m_flatpakInstallationSystem); g_object_unref(m_flatpakInstallationUser); g_object_unref(m_cancellable); } FlatpakRef * FlatpakBackend::createFakeRef(FlatpakResource *resource) { FlatpakRef *ref = nullptr; g_autoptr(GError) localError = nullptr; const QString id = QString::fromUtf8("%1/%2/%3/%4").arg(resource->typeAsString()).arg(resource->flatpakName()).arg(resource->arch()).arg(resource->branch()); ref = flatpak_ref_parse(id.toStdString().c_str(), &localError); if (!ref) { qWarning() << "Failed to create fake ref: " << localError->message; } return ref; } 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; } FlatpakInstalledRef * FlatpakBackend::getInstalledRefForApp(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource) { AppStream::Component *component = resource->appstreamComponent(); AppStream::Component::Kind appKind = component->kind(); FlatpakInstalledRef *ref = nullptr; GPtrArray *installedApps = nullptr; g_autoptr(GError) localError = nullptr; if (!flatpakInstallation) { return ref; } ref = flatpak_installation_get_installed_ref(flatpakInstallation, resource->type() == FlatpakResource::DesktopApp ? FLATPAK_REF_KIND_APP : FLATPAK_REF_KIND_RUNTIME, resource->flatpakName().toStdString().c_str(), resource->arch().toStdString().c_str(), resource->branch().toStdString().c_str(), m_cancellable, &localError); // If we found installed ref this way, we can return it if (ref) { return ref; } // Otherwise go through all installed apps and try to match info we have installedApps = flatpak_installation_list_installed_refs_by_kind(flatpakInstallation, appKind == AppStream::Component::KindDesktopApp ? FLATPAK_REF_KIND_APP : FLATPAK_REF_KIND_RUNTIME, m_cancellable, &localError); if (!installedApps) { return ref; } for (uint i = 0; i < installedApps->len; i++) { FlatpakInstalledRef *installedRef = FLATPAK_INSTALLED_REF(g_ptr_array_index(installedApps, i)); // Check if the installed_reference and app_id are the same and update the app with installed metadata if (compareAppFlatpakRef(flatpakInstallation, resource, installedRef)) { return installedRef; } } // We found nothing, return nullptr return ref; } FlatpakResource * FlatpakBackend::getAppForInstalledRef(FlatpakInstallation *flatpakInstallation, FlatpakInstalledRef *ref) { foreach (FlatpakResource *resource, m_resources) { if (compareAppFlatpakRef(flatpakInstallation, resource, ref)) { return resource; } } return nullptr; } FlatpakResource * FlatpakBackend::getRuntimeForApp(FlatpakResource *resource) { FlatpakResource *runtime = nullptr; const auto runtimeInfo = resource->runtime().split(QLatin1Char('/')); if (runtimeInfo.count() != 3) { return runtime; } const QString runtimeId = QString::fromUtf8("runtime/%1/%2").arg(runtimeInfo.at(0)).arg(runtimeInfo.at(2)); foreach (const QString &id, m_resources.keys()) { if (id.endsWith(runtimeId)) { runtime = m_resources.value(id); break; } } // TODO if runtime wasn't found, create a new one from available info return runtime; } 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; AppStream::Component *asComponent = nullptr; file = g_file_new_for_path(url.toLocalFile().toStdString().c_str()); bundleRef = flatpak_bundle_ref_new(file, &localError); if (!bundleRef) { qWarning() << "Failed to load bundle: " << localError->message; return nullptr; } 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) { qWarning() << "Failed to extract appstream metadata from bundle: " << localError->message; return nullptr; } gsize len = 0; gconstpointer data = g_bytes_get_data(appstream, &len); g_autofree gchar *appstreamContent = g_strndup((char*)data, len); g_autoptr(AsMetadata) metadata = as_metadata_new(); as_metadata_set_format_style(metadata, AS_FORMAT_STYLE_COLLECTION); as_metadata_parse(metadata, appstreamContent, AS_FORMAT_KIND_XML, &localError); if (localError) { qWarning() << "Failed to parse appstream metadata: " << localError->message; return nullptr; } g_autoptr(GPtrArray) components = as_metadata_get_components(metadata); if (g_ptr_array_index(components, 0)) { asComponent = new AppStream::Component(AS_COMPONENT(g_ptr_array_index(components, 0))); } else { qWarning() << "Failed to parse appstream metadata"; return nullptr; } } else { AsComponent *component = as_component_new(); asComponent = new AppStream::Component(component); qWarning() << "No appstream metadata in bundle"; } gsize len = 0; g_autoptr(GBytes) iconData = nullptr; g_autoptr(GBytes) metadata = nullptr; FlatpakResource *resource = new FlatpakResource(asComponent, this); metadata = flatpak_bundle_ref_get_metadata(bundleRef); QByteArray metadataContent = QByteArray((char *)g_bytes_get_data(metadata, &len)); if (!updateAppMetadata(resource, metadataContent)) { qWarning() << "Failed to update metadata from app bundle"; return nullptr; } iconData = flatpak_bundle_ref_get_icon(bundleRef, 128); if (!iconData) { iconData = flatpak_bundle_ref_get_icon(bundleRef, 64); } if (iconData) { gsize len = 0; QPixmap pixmap; char * data = (char *)g_bytes_get_data(iconData, &len); QByteArray icon = QByteArray(data, len); pixmap.loadFromData(icon, "PNG"); resource->setBundledIcon(pixmap); } resource->setInstalledSize(flatpak_bundle_ref_get_installed_size(bundleRef)); resource->setFlatpakFileType(QStringLiteral("flatpak")); resource->setOrigin(QString::fromUtf8(flatpak_bundle_ref_get_origin(bundleRef))); resource->setResourceFile(url); resource->setState(FlatpakResource::None); resource->setType(FlatpakResource::DesktopApp); addResource(resource); return resource; } FlatpakResource * FlatpakBackend::addAppFromFlatpakRef(const QUrl &url) { auto installation = m_flatpakInstallationSystem; 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()); remoteRef = flatpak_installation_install_ref_file (installation, bytes, m_cancellable, &error); if (!remoteRef) { return nullptr; } } const auto remoteName = flatpak_remote_ref_get_remote_name(remoteRef); auto ref = FLATPAK_REF(remoteRef); AsComponent *component = as_component_new(); as_component_add_url(component, AS_URL_KIND_HOMEPAGE, settings.value(QStringLiteral("Flatpak Ref/Homepage")).toString().toStdString().c_str()); as_component_set_description(component, settings.value(QStringLiteral("Flatpak Ref/Description")).toString().toStdString().c_str(), nullptr); as_component_set_name(component, settings.value(QStringLiteral("Flatpak Ref/Title")).toString().toStdString().c_str(), nullptr); as_component_set_summary(component, settings.value(QStringLiteral("Flatpak Ref/Comment")).toString().toStdString().c_str(), nullptr); const QString iconUrl = settings.value(QStringLiteral("Flatpak Ref/Icon")).toString(); if (!iconUrl.isEmpty()) { AsIcon *icon = as_icon_new(); as_icon_set_kind(icon, AS_ICON_KIND_REMOTE); as_icon_set_url(icon, iconUrl.toStdString().c_str()); as_component_add_icon(component, icon); } AppStream::Component *asComponent = new AppStream::Component(component); auto resource = new FlatpakResource(asComponent, this); resource->setFlatpakFileType(QStringLiteral("flatpakref")); resource->setOrigin(QString::fromUtf8(remoteName)); resource->updateFromRef(ref); addResource(resource); return resource; } FlatpakResource * FlatpakBackend::addSourceFromFlatpakRepo(const QUrl &url) { 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; } AsComponent *component = as_component_new(); as_component_add_url(component, AS_URL_KIND_HOMEPAGE, settings.value(QStringLiteral("Flatpak Repo/Homepage")).toString().toStdString().c_str()); as_component_set_summary(component, settings.value(QStringLiteral("Flatpak Repo/Comment")).toString().toStdString().c_str(), nullptr); as_component_set_description(component, settings.value(QStringLiteral("Flatpak Repo/Description")).toString().toStdString().c_str(), nullptr); as_component_set_name(component, title.toStdString().c_str(), nullptr); - const QString iconUrl = settings.value(QStringLiteral("Flatpak Ref/Icon")).toString(); + const QString iconUrl = settings.value(QStringLiteral("Flatpak Repo/Icon")).toString(); if (!iconUrl.isEmpty()) { AsIcon *icon = as_icon_new(); as_icon_set_kind(icon, AS_ICON_KIND_REMOTE); as_icon_set_url(icon, iconUrl.toStdString().c_str()); as_component_add_icon(component, icon); } AppStream::Component *asComponent = new AppStream::Component(component); auto resource = new FlatpakResource(asComponent, this); // 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); auto repo = flatpak_installation_get_remote_by_name(m_flatpakInstallationSystem, resource->flatpakName().toStdString().c_str(), m_cancellable, nullptr); if (!repo) { resource->setState(AbstractResource::State::None); } else { resource->setState(AbstractResource::State::Installed); } return resource; } void FlatpakBackend::addResource(FlatpakResource *resource) { // Update app with all possible information we have if (!parseMetadataFromAppBundle(resource)) { qWarning() << "Failed to parse metadata from app bundle for " << resource->name(); } auto installation = resource->scope() == FlatpakResource::System ? m_flatpakInstallationSystem : m_flatpakInstallationUser; updateAppState(installation, resource); if (resource->type() == FlatpakResource::DesktopApp) { if (!updateAppMetadata(installation, resource)) { qWarning() << "Failed to update" << resource->name() << "with installed metadata"; } } updateAppSize(installation, resource); connect(resource, &FlatpakResource::stateChanged, this, &FlatpakBackend::updatesCountChanged); m_resources.insert(resource->uniqueId(), resource); } bool FlatpakBackend::compareAppFlatpakRef(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource, FlatpakInstalledRef *ref) { const QString arch = QString::fromUtf8(flatpak_ref_get_arch(FLATPAK_REF(ref))); const QString branch = QString::fromUtf8(flatpak_ref_get_branch(FLATPAK_REF(ref))); FlatpakResource::ResourceType appType = flatpak_ref_get_kind(FLATPAK_REF(ref)) == FLATPAK_REF_KIND_APP ? FlatpakResource::DesktopApp : FlatpakResource::Runtime; FlatpakResource::Scope appScope = flatpak_installation_get_is_user(flatpakInstallation) ? FlatpakResource::User : FlatpakResource::System; g_autofree gchar *appId = nullptr; if (appType == FlatpakResource::DesktopApp) { appId = g_strdup_printf("%s.desktop", flatpak_ref_get_name(FLATPAK_REF(ref))); } else { appId = g_strdup(flatpak_ref_get_name(FLATPAK_REF(ref))); } const QString uniqueId = QString::fromUtf8("%1/%2/%3/%4/%5/%6").arg(FlatpakResource::scopeAsString(appScope)) .arg(QLatin1String("flatpak")) .arg(QString::fromUtf8(flatpak_installed_ref_get_origin(ref))) .arg(FlatpakResource::typeAsString(appType)) .arg(QString::fromUtf8(appId)) .arg(QString::fromUtf8(flatpak_ref_get_branch(FLATPAK_REF(ref)))); // Compare uniqueId first then attempt to compare what we have if (resource->uniqueId() == uniqueId) { return true; } // Check if we have information about architecture and branch, otherwise compare names only // Happens with apps which don't have appstream metadata bug got here thanks to installed desktop file if (!resource->arch().isEmpty() && !resource->branch().isEmpty()) { return resource->arch() == arch && resource->branch() == branch && (resource->flatpakName() == QString::fromUtf8(appId) || resource->flatpakName() == QString::fromUtf8(flatpak_ref_get_name(FLATPAK_REF(ref)))); } return (resource->flatpakName() == QString::fromUtf8(appId) || resource->flatpakName() == QString::fromUtf8(flatpak_ref_get_name(FLATPAK_REF(ref)))); } class FlatpakSource { public: FlatpakSource(FlatpakRemote* remote) : m_remote(remote) {} bool isEnabled() const { return !flatpak_remote_get_disabled(m_remote); } QString appstreamDir() const { g_autoptr(GFile) appstreamDir = flatpak_remote_get_appstream_dir(m_remote, nullptr); if (!appstreamDir) { qWarning() << "No appstream dir for " << flatpak_remote_get_name(m_remote); 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; }; bool FlatpakBackend::loadAppsFromAppstreamData(FlatpakInstallation *flatpakInstallation) { Q_ASSERT(flatpakInstallation); g_autoptr(GPtrArray) remotes = flatpak_installation_list_remotes(flatpakInstallation, m_cancellable, nullptr); if (!remotes) { return false; } for (uint i = 0; i < remotes->len; i++) { FlatpakRemote *remote = FLATPAK_REMOTE(g_ptr_array_index(remotes, i)); integrateRemote(flatpakInstallation, remote); } return true; } void FlatpakBackend::integrateRemote(FlatpakInstallation *flatpakInstallation, FlatpakRemote *remote) { g_autoptr(GError) localError = nullptr; FlatpakSource source(remote); if (!source.isEnabled() || flatpak_remote_get_noenumerate(remote)) { return; } const QString appstreamDirPath = source.appstreamDir(); const QString appDirFileName = appstreamDirPath + QLatin1String("/appstream.xml.gz"); if (!QFile::exists(appDirFileName)) { qWarning() << "No " << appDirFileName << " appstream metadata found for " << source.name(); return; } g_autoptr(AsMetadata) metadata = as_metadata_new(); g_autoptr(GFile) file = g_file_new_for_path(appDirFileName.toStdString().c_str()); as_metadata_set_format_style (metadata, AS_FORMAT_STYLE_COLLECTION); as_metadata_parse_file(metadata, file, AS_FORMAT_KIND_XML, &localError); if (localError) { qWarning() << "Failed to parse appstream metadata " << localError->message; return; } g_autoptr(GPtrArray) components = as_metadata_get_components(metadata); const FlatpakResource::Scope scope = flatpak_installation_get_is_user(flatpakInstallation) ? FlatpakResource::User : FlatpakResource::System; for (uint i = 0; i < components->len; i++) { AsComponent *component = AS_COMPONENT(g_ptr_array_index(components, i)); AppStream::Component *appstreamComponent = new AppStream::Component(component); FlatpakResource *resource = new FlatpakResource(appstreamComponent, this); resource->setScope(scope); resource->setIconPath(appstreamDirPath); resource->setOrigin(source.name()); addResource(resource); } } bool FlatpakBackend::loadInstalledApps(FlatpakInstallation *flatpakInstallation) { QDir dir; QString pathExports; QString pathApps; g_autoptr(GFile) path = nullptr; if (!flatpakInstallation) { return false; } // List installed applications from installed desktop files path = flatpak_installation_get_path(flatpakInstallation); pathExports = QString::fromUtf8(g_file_get_path(path)) + QLatin1String("/exports/"); pathApps = pathExports + QLatin1String("share/applications/"); dir = QDir(pathApps); if (dir.exists()) { foreach (const QString &file, dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) { QString fnDesktop; AsComponent *component; g_autoptr(GError) localError = nullptr; g_autoptr(GFile) desktopFile = nullptr; g_autoptr(AsMetadata) metadata = as_metadata_new(); if (file == QLatin1String("mimeinfo.cache")) { continue; } fnDesktop = pathApps + file; desktopFile = g_file_new_for_path(fnDesktop.toStdString().c_str()); if (!desktopFile) { qWarning() << "Couldn't open " << fnDesktop << " :" << localError->message; continue; } as_metadata_parse_file(metadata, desktopFile, AS_FORMAT_KIND_DESKTOP_ENTRY, &localError); if (localError) { qWarning() << "Failed to parse appstream metadata " << localError->message; continue; } component = as_metadata_get_component(metadata); AppStream::Component *appstreamComponent = new AppStream::Component(component); FlatpakResource *resource = new FlatpakResource(appstreamComponent, this); resource->setScope(flatpak_installation_get_is_user(flatpakInstallation) ? FlatpakResource::User : FlatpakResource::System); resource->setIconPath(pathExports); resource->setType(FlatpakResource::DesktopApp); resource->setState(AbstractResource::Installed); // Go through apps we already know about from appstream metadata bool resourceExists = false; foreach (FlatpakResource *res, m_resources) { // Compare the only information we have if (res->appstreamId() == QString::fromUtf8("%1.desktop").arg(resource->appstreamId()) && res->name() == resource->name()) { resourceExists = true; res->setScope(resource->scope()); res->setState(resource->state()); break; } } if (!resourceExists) { addResource(resource); } else { resource->deleteLater(); } } } return true; } 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) { qWarning() << "Failed to get list of installed refs for listing updates: " << localError->message; return; } for (uint i = 0; i < refs->len; i++) { FlatpakInstalledRef *ref = FLATPAK_INSTALLED_REF(g_ptr_array_index(refs, i)); const gchar *latestCommit = flatpak_installed_ref_get_latest_commit(ref); if (!latestCommit) { qWarning() << "Couldn'g get latest commit for " << flatpak_ref_get_name(FLATPAK_REF(ref)); } const gchar *commit = flatpak_ref_get_commit(FLATPAK_REF(ref)); if (g_strcmp0(commit, latestCommit) == 0) { continue; } FlatpakResource *resource = getAppForInstalledRef(flatpakInstallation, ref); if (resource) { resource->setState(AbstractResource::Upgradeable); updateAppSize(flatpakInstallation, resource); } } } void FlatpakBackend::loadRemoteUpdates(FlatpakInstallation *flatpakInstallation) { FlatpakFetchDataJob *job = new FlatpakFetchDataJob(flatpakInstallation, FlatpakFetchDataJob::FetchUpdates); connect(job, &FlatpakFetchDataJob::finished, job, &FlatpakFetchDataJob::deleteLater); connect(job, &FlatpakFetchDataJob::jobFetchUpdatesFinished, this, &FlatpakBackend::onFetchUpdatesFinished); job->start(); } void FlatpakBackend::onFetchUpdatesFinished(FlatpakInstallation *flatpakInstallation, GPtrArray *updates) { g_autoptr(GPtrArray) fetchedUpdates = updates; for (uint i = 0; i < fetchedUpdates->len; i++) { FlatpakInstalledRef *ref = FLATPAK_INSTALLED_REF(g_ptr_array_index(fetchedUpdates, i)); FlatpakResource *resource = getAppForInstalledRef(flatpakInstallation, ref); if (resource) { resource->setState(AbstractResource::Upgradeable); updateAppSize(flatpakInstallation, resource); } } } bool FlatpakBackend::parseMetadataFromAppBundle(FlatpakResource *resource) { g_autoptr(FlatpakRef) ref = nullptr; g_autoptr(GError) localError = nullptr; AppStream::Bundle bundle = resource->appstreamComponent()->bundle(AppStream::Bundle::KindFlatpak); // Get arch/branch/commit/name from FlatpakRef if (!bundle.isEmpty()) { ref = flatpak_ref_parse(bundle.id().toStdString().c_str(), &localError); if (!ref) { qWarning() << "Failed to parse " << bundle.id() << localError->message; return false; } else { resource->updateFromRef(ref); } } return true; } void FlatpakBackend::reloadPackageList() { setFetching(true); // Load applications from appstream metadata if (!loadAppsFromAppstreamData(m_flatpakInstallationSystem)) { qWarning() << "Failed to load packages from appstream data from system installation"; } if (!loadAppsFromAppstreamData(m_flatpakInstallationUser)) { qWarning() << "Failed to load packages from appstream data from user installation"; } // Load installed applications and update existing resources with info from installed application if (!loadInstalledApps(m_flatpakInstallationSystem)) { qWarning() << "Failed to load installed packages from system installation"; } if (!loadInstalledApps(m_flatpakInstallationUser)) { qWarning() << "Failed to load installed packages from user installation"; } setFetching(false); } bool FlatpakBackend::setupFlatpakInstallations(GError **error) { m_flatpakInstallationSystem = flatpak_installation_new_system(m_cancellable, error); if (!m_flatpakInstallationSystem) { return false; } m_flatpakInstallationUser = flatpak_installation_new_user(m_cancellable, error); if (!m_flatpakInstallationUser) { return false; } return true; } void FlatpakBackend::updateAppInstalledMetadata(FlatpakInstalledRef *installedRef, FlatpakResource *resource) { // Update the rest resource->updateFromRef(FLATPAK_REF(installedRef)); resource->setInstalledSize(flatpak_installed_ref_get_installed_size(installedRef)); resource->setOrigin(QString::fromUtf8(flatpak_installed_ref_get_origin(installedRef))); resource->setState(AbstractResource::Installed); } bool FlatpakBackend::updateAppMetadata(FlatpakInstallation* flatpakInstallation, FlatpakResource *resource) { QByteArray metadataContent; g_autoptr(GBytes) data = nullptr; g_autoptr(GFile) installationPath = nullptr; g_autoptr(GError) localError = nullptr; if (resource->type() != FlatpakResource::DesktopApp) { return true; } installationPath = flatpak_installation_get_path(flatpakInstallation); const QString path = QString::fromUtf8(g_file_get_path(installationPath)) + QString::fromUtf8("/app/%1/%2/%3/active/metadata").arg(resource->flatpakName()).arg(resource->arch()).arg(resource->branch()); if (QFile::exists(path)) { QFile file(path); if (file.open(QFile::ReadOnly | QFile::Text)) { metadataContent = file.readAll(); } } else { g_autoptr(FlatpakRef) fakeRef = nullptr; if (resource->origin().isEmpty()) { qWarning() << "Failed to get metadata file because of missing origin"; return false; } fakeRef = createFakeRef(resource); if (!fakeRef) { return false; } data = flatpak_installation_fetch_remote_metadata_sync(flatpakInstallation, resource->origin().toStdString().c_str(), fakeRef, m_cancellable, &localError); if (data) { gsize len = 0; metadataContent = QByteArray((char *)g_bytes_get_data(data, &len)); } else { qWarning() << "Failed to get metadata file: " << localError->message; return false; } } if (metadataContent.isEmpty()) { qWarning() << "Failed to get metadata file"; return false; } return updateAppMetadata(resource, metadataContent); } bool FlatpakBackend::updateAppMetadata(FlatpakResource *resource, const QByteArray &data) { // Save the content to temporary file QTemporaryFile tempFile; tempFile.setAutoRemove(false); if (!tempFile.open()) { qWarning() << "Failed to get metadata file"; return false; } tempFile.write(data); tempFile.close(); // Parse the temporary file QSettings setting(tempFile.fileName(), 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? tempFile.remove(); return true; } bool FlatpakBackend::updateAppSize(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource) { // 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 if (resource->state() == AbstractResource::Installed) { // The size appears to be already set (from updateAppInstalledMetadata() apparently) if (resource->installedSize() > 0) { return true; } } else { if (resource->installedSize() > 0 && resource->downloadSize() > 0) { return true; } } // Check if we know the needed runtime which is needed for calculating the size if (resource->runtime().isEmpty()) { if (!updateAppMetadata(flatpakInstallation, resource)) { qWarning() << "Failed to get runtime for " << resource->name() << " needed for calculating of size"; return false; } } // Calculate the runtime size FlatpakResource *runtime = nullptr; if (resource->state() == AbstractResource::None && resource->type() == FlatpakResource::DesktopApp) { runtime = getRuntimeForApp(resource); if (runtime) { // Re-check runtime state if case a new one was created updateAppState(flatpakInstallation, runtime); if (!runtime->isInstalled()) { if (!updateAppSize(flatpakInstallation, runtime)) { qWarning() << "Failed to get runtime size needed for total size of " << resource->name(); return false; } // 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()); } } } if (resource->state() == AbstractResource::Installed) { g_autoptr(FlatpakInstalledRef) ref = nullptr; ref = getInstalledRefForApp(flatpakInstallation, resource); if (!ref) { qWarning() << "Failed to get installed size of " << resource->name(); return false; } resource->setInstalledSize(flatpak_installed_ref_get_installed_size(ref)); } else { if (resource->origin().isEmpty()) { qWarning() << "Failed to get size of " << resource->name() << " because of missing origin"; return false; } FlatpakFetchDataJob *job = new FlatpakFetchDataJob(flatpakInstallation, resource, FlatpakFetchDataJob::FetchSize); connect(job, &FlatpakFetchDataJob::finished, job, &FlatpakFetchDataJob::deleteLater); connect(job, &FlatpakFetchDataJob::jobFetchSizeFinished, this, &FlatpakBackend::onFetchSizeFinished); job->start(); } return true; } void FlatpakBackend::onFetchSizeFinished(FlatpakResource *resource, guint64 downloadSize, guint64 installedSize) { FlatpakResource *runtime = nullptr; if (resource->state() == AbstractResource::None && resource->type() == FlatpakResource::DesktopApp) { runtime = getRuntimeForApp(resource); } if (runtime && !runtime->isInstalled()) { resource->setDownloadSize(runtime->downloadSize() + downloadSize); resource->setInstalledSize(installedSize); } else { resource->setDownloadSize(downloadSize); resource->setInstalledSize(installedSize); } } void FlatpakBackend::updateAppState(FlatpakInstallation *flatpakInstallation, FlatpakResource *resource) { FlatpakInstalledRef *ref = getInstalledRefForApp(flatpakInstallation, resource); if (ref) { // If the app is installed, we can set information about commit, arch etc. updateAppInstalledMetadata(ref, resource); } else { // TODO check if the app is actuall still available resource->setState(AbstractResource::None); } } void FlatpakBackend::setFetching(bool fetching) { if (m_fetching != fetching) { m_fetching = fetching; emit fetchingChanged(); } } int FlatpakBackend::updatesCount() const { return m_updater->updatesCount(); } ResultsStream * FlatpakBackend::search(const AbstractResourcesBackend::Filters &filter) { QVector ret; foreach(AbstractResource* r, m_resources) { if (qobject_cast(r)->type() == FlatpakResource::Runtime && filter.state != AbstractResource::Upgradeable) { continue; } if (r->name().contains(filter.search, Qt::CaseInsensitive) || r->comment().contains(filter.search, Qt::CaseInsensitive)) { ret += r; } } return new ResultsStream(QStringLiteral("FlatpakStream"), ret); } ResultsStream * FlatpakBackend::findResourceByPackageName(const QUrl &url) { QVector resources; if (url.scheme() == QLatin1String("appstream")) { if (url.host().isEmpty()) passiveMessage(i18n("Malformed appstream url '%1'", url.toDisplayString())); else { foreach(FlatpakResource* res, m_resources) { if (res->appstreamId() == url.host()) resources << res; } } } return new ResultsStream(QStringLiteral("FlatpakStream"), resources); } AbstractBackendUpdater * FlatpakBackend::backendUpdater() const { return m_updater; } AbstractReviewsBackend * FlatpakBackend::reviewsBackend() const { return m_reviews; } FlatpakInstallation * FlatpakBackend::flatpakInstallationForAppScope(FlatpakResource::Scope appScope) const { if (appScope == FlatpakResource::Scope::System) { return m_flatpakInstallationSystem; } else { return m_flatpakInstallationUser; } } void FlatpakBackend::installApplication(AbstractResource *app, const AddonList &addons) { FlatpakResource *resource = qobject_cast(app); if (resource->type() == FlatpakResource::Source) { // Let source backend handle this FlatpakRemote *remote = m_sources->installSource(resource); if (remote) { resource->setState(AbstractResource::Installed); integrateRemote(m_flatpakInstallationSystem, remote); } return; } FlatpakTransaction *transaction = nullptr; FlatpakInstallation *installation = resource->scope() == FlatpakResource::System ? m_flatpakInstallationSystem : m_flatpakInstallationUser; FlatpakResource *runtime = getRuntimeForApp(resource); if (runtime && !runtime->isInstalled()) { transaction = new FlatpakTransaction(installation, resource, runtime, addons, Transaction::InstallRole); } else { transaction = new FlatpakTransaction(installation, resource, addons, Transaction::InstallRole); } connect(transaction, &FlatpakTransaction::statusChanged, [this, installation, resource] (Transaction::Status status) { if (status == Transaction::Status::DoneStatus) { updateAppState(installation, resource); } }); } void FlatpakBackend::installApplication(AbstractResource *app) { installApplication(app, {}); } void FlatpakBackend::removeApplication(AbstractResource *app) { FlatpakResource *resource = qobject_cast(app); if (resource->type() == FlatpakResource::Source) { // Let source backend handle this if (m_sources->removeSource(resource->flatpakName())) { resource->setState(AbstractResource::None); } return; } FlatpakInstallation *installation = resource->scope() == FlatpakResource::System ? m_flatpakInstallationSystem : m_flatpakInstallationUser; FlatpakTransaction *transaction = new FlatpakTransaction(installation, resource, Transaction::RemoveRole); connect(transaction, &FlatpakTransaction::statusChanged, [this, installation, resource] (Transaction::Status status) { if (status == Transaction::Status::DoneStatus) { updateAppSize(installation, resource); } }); } void FlatpakBackend::checkForUpdates() { // Load local updates, comparing current and latest commit loadLocalUpdates(m_flatpakInstallationSystem); loadLocalUpdates(m_flatpakInstallationUser); // Load updates from remote repositories loadRemoteUpdates(m_flatpakInstallationSystem); loadRemoteUpdates(m_flatpakInstallationUser); } AbstractResource * FlatpakBackend::resourceForFile(const QUrl &url) { if ((!url.path().endsWith(QLatin1String(".flatpakref")) && !url.path().endsWith(QLatin1String(".flatpak")) && !url.path().endsWith(QLatin1String(".flatpakrepo"))) || !url.isLocalFile()) { return nullptr; } FlatpakResource *resource = nullptr; if (url.path().endsWith(QLatin1String(".flatpak"))) { resource = addAppFromFlatpakBundle(url); } else if (url.path().endsWith(QLatin1String(".flatpakref"))) { resource = addAppFromFlatpakRef(url); } else { resource = addSourceFromFlatpakRepo(url); } return resource; } #include "FlatpakBackend.moc" diff --git a/libdiscover/backends/FlatpakBackend/FlatpakResource.cpp b/libdiscover/backends/FlatpakBackend/FlatpakResource.cpp index fb296ffb..4afce8f4 100644 --- a/libdiscover/backends/FlatpakBackend/FlatpakResource.cpp +++ b/libdiscover/backends/FlatpakBackend/FlatpakResource.cpp @@ -1,513 +1,547 @@ /*************************************************************************** * Copyright © 2013 Aleix Pol Gonzalez * * Copyright © 2017 Jan Grulich * * * * 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 . * ***************************************************************************/ #include "FlatpakResource.h" #include "FlatpakBackend.h" #include #include #include #include #include #include #include #include #include #include +#include +#include +#include #include #include FlatpakResource::FlatpakResource(AppStream::Component *component, FlatpakBackend *parent) : AbstractResource(parent) , m_appdata(component) , m_downloadSize(0) , m_installedSize(0) , m_scope(FlatpakResource::System) , m_state(AbstractResource::None) , m_type(FlatpakResource::DesktopApp) { + // Start fetching remote icons during initialization + const auto icons = m_appdata->icons(); + if (!icons.isEmpty()) { + foreach (const AppStream::Icon &icon, icons) { + if (icon.kind() == AppStream::Icon::KindRemote) { + const QString fileName = QStringLiteral("%1/%2").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)) + .arg(icon.url().fileName()); + if (!QFileInfo::exists(fileName)) { + QNetworkAccessManager *manager = new QNetworkAccessManager(this); + connect(manager, &QNetworkAccessManager::finished, [this, icon, fileName, manager] (QNetworkReply *reply) { + if (reply->error() == QNetworkReply::NoError) { + QByteArray iconData = reply->readAll(); + QFile file(fileName); + if (file.open(QIODevice::WriteOnly)) { + file.write(iconData); + } + file.close(); + Q_EMIT iconChanged(); + } + manager->deleteLater(); + }); + manager->get(QNetworkRequest(icon.url())); + } + } + } + } } AppStream::Component *FlatpakResource::appstreamComponent() const { return m_appdata; } QList FlatpakResource::addonsInformation() { return m_addons; } QString FlatpakResource::availableVersion() const { // TODO check if there is actually version available QString version = branch(); if (version.isEmpty()) { version = i18n("Unknown"); } return version; } QString FlatpakResource::appstreamId() const { return m_appdata->id(); } QString FlatpakResource::arch() const { return m_arch; } QString FlatpakResource::branch() const { return m_branch; } bool FlatpakResource::canExecute() const { return (m_type == DesktopApp && (m_state == AbstractResource::Installed || m_state == AbstractResource::Upgradeable)); } void FlatpakResource::updateFromRef(FlatpakRef* ref) { setArch(QString::fromUtf8(flatpak_ref_get_arch(ref))); setBranch(QString::fromUtf8(flatpak_ref_get_branch(ref))); setCommit(QString::fromUtf8(flatpak_ref_get_commit(ref))); setFlatpakName(QString::fromUtf8(flatpak_ref_get_name(ref))); setType(flatpak_ref_get_kind(ref) == FLATPAK_REF_KIND_APP ? FlatpakResource::DesktopApp : FlatpakResource::Runtime); } QStringList FlatpakResource::categories() { auto cats = m_appdata->categories(); if (m_appdata->kind() != AppStream::Component::KindAddon) cats.append(QStringLiteral("Application")); return cats; } QString FlatpakResource::comment() { const auto summary = m_appdata->summary(); if (!summary.isEmpty()) { return summary; } return QString(); } QString FlatpakResource::commit() const { return m_commit; } int FlatpakResource::downloadSize() const { return m_downloadSize; } QStringList FlatpakResource::executables() const { // return m_appdata->provided(AppStream::Provided::KindBinary).items(); return QStringList(); } QVariant FlatpakResource::icon() const { QIcon ret; const auto icons = m_appdata->icons(); if (!m_bundledIcon.isNull()) { ret = QIcon(m_bundledIcon); } else if (icons.isEmpty()) { ret = QIcon::fromTheme(QStringLiteral("package-x-generic")); } else foreach(const AppStream::Icon &icon, icons) { QStringList stock; QString url = QString::fromUtf8("%1/icons/").arg(m_iconPath); switch (icon.kind()) { case AppStream::Icon::KindLocal: case AppStream::Icon::KindCached: url += icon.url().toLocalFile(); if (QFileInfo::exists(url)) { ret.addFile(url); } else { ret = QIcon::fromTheme(QStringLiteral("package-x-generic")); } break; case AppStream::Icon::KindStock: stock += icon.name(); break; case AppStream::Icon::KindRemote: - // TODO fetch remote icon - ret = QIcon::fromTheme(QStringLiteral("package-x-generic")); - break; + const QString fileName = QStringLiteral("%1/%2").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)) + .arg(icon.url().fileName()); + if (QFileInfo::exists(fileName)) { + ret.addFile(fileName); + } else { + ret = QIcon::fromTheme(QStringLiteral("package-x-generic")); + break; + } } if (ret.isNull() && !stock.isEmpty()) { ret = QIcon::fromTheme(stock.first(), QIcon::fromTheme(QStringLiteral("package-x-generic"))); } } return ret; } QString FlatpakResource::installedVersion() const { // TODO check if there is actually version available QString version = branch(); if (version.isEmpty()) { version = i18n("Unknown"); } return version; } int FlatpakResource::installedSize() const { return m_installedSize; } bool FlatpakResource::isTechnical() const { return false; } QUrl FlatpakResource::homepage() { return m_appdata->url(AppStream::Component::UrlKindHomepage); } QString FlatpakResource::flatpakFileType() const { return m_flatpakFileType; } QString FlatpakResource::flatpakName() const { // If the flatpak name is not known (known only for installed apps), then use // appstream id instead; if (m_flatpakName.isEmpty()) { return m_appdata->id(); } return m_flatpakName; } QString FlatpakResource::license() { return m_appdata->projectLicense(); } QString FlatpakResource::longDescription() { return m_appdata->description(); } QString FlatpakResource::name() { QString name = m_appdata->name(); if (name.isEmpty()) { name = m_appdata->id(); } if (name.startsWith(QLatin1String("(Nightly) "))) { return name.mid(10); } return name; } QVariant FlatpakResource::metadata(const QString &key) { return m_metadata.value(key); } QString FlatpakResource::origin() const { return m_origin; } QString FlatpakResource::packageName() const { return m_appdata->name(); } QUrl FlatpakResource::resourceFile() const { return m_resourceFile; } QString FlatpakResource::runtime() const { return m_runtime; } static QUrl imageOfKind(const QList &images, AppStream::Image::Kind kind) { QUrl ret; Q_FOREACH (const AppStream::Image &i, images) { if (i.kind() == kind) { ret = i.url(); break; } } return ret; } static QUrl screenshot(AppStream::Component *comp, AppStream::Image::Kind kind) { QUrl ret; Q_FOREACH (const AppStream::Screenshot &s, comp->screenshots()) { ret = imageOfKind(s.images(), kind); if (s.isDefault() && !ret.isEmpty()) break; } return ret; } FlatpakResource::Scope FlatpakResource::scope() const { return m_scope; } QString FlatpakResource::scopeAsString() const { return m_scope == System ? QLatin1String("system") : QLatin1String("user"); } QUrl FlatpakResource::screenshotUrl() { return screenshot(m_appdata, AppStream::Image::KindSource); } QString FlatpakResource::section() { return QString(); } int FlatpakResource::size() { if (m_state == Installed) { return m_installedSize; } else { return m_downloadSize; } } QString FlatpakResource::sizeDescription() { KFormat f; if (!isInstalled() || canUpgrade()) { return i18nc("@info app size", "%1 to download, %2 on disk", f.formatByteSize(downloadSize()), f.formatByteSize(installedSize())); } else { return i18nc("@info app size", "%1 on disk", f.formatByteSize(installedSize())); } } AbstractResource::State FlatpakResource::state() { return m_state; } QUrl FlatpakResource::thumbnailUrl() { return screenshot(m_appdata, AppStream::Image::KindThumbnail); } FlatpakResource::ResourceType FlatpakResource::type() const { return m_type; } QString FlatpakResource::typeAsString() const { switch (m_type) { case FlatpakResource::DesktopApp: return QLatin1String("app"); break; case FlatpakResource::Runtime: return QLatin1String("runtime"); break; } return QLatin1String("app"); } QString FlatpakResource::uniqueId() const { // Build uniqueId const QString scope = m_scope == System ? QLatin1String("system") : QLatin1String("user"); return QString::fromUtf8("%1/%2/%3/%4/%5/%6").arg(scope) .arg(QLatin1String("flatpak")) .arg(origin()) .arg(typeAsString()) .arg(m_appdata->id()) .arg(branch()); } void FlatpakResource::invokeApplication() const { g_autoptr(GCancellable) cancellable = g_cancellable_new(); g_autoptr(GError) localError = nullptr; const FlatpakBackend *p = static_cast(parent()); if (!flatpak_installation_launch(p->flatpakInstallationForAppScope(scope()), flatpakName().toStdString().c_str(), arch().toStdString().c_str(), branch().toStdString().c_str(), nullptr, cancellable, &localError)) { qWarning() << "Failed to launch " << m_appdata->name() << ": " << localError->message; } } void FlatpakResource::fetchChangelog() { QString log = longDescription(); log.replace(QLatin1Char('\n'), QLatin1String("
")); emit changelogFetched(log); } void FlatpakResource::fetchScreenshots() { QList thumbnails, screenshots; Q_FOREACH (const AppStream::Screenshot &s, m_appdata->screenshots()) { const QUrl thumbnail = imageOfKind(s.images(), AppStream::Image::KindThumbnail); const QUrl plain = imageOfKind(s.images(), AppStream::Image::KindSource); if (plain.isEmpty()) qWarning() << "invalid screenshot for" << name(); screenshots << plain; thumbnails << (thumbnail.isEmpty() ? plain : thumbnail); } Q_EMIT screenshotsFetched(thumbnails, screenshots); } void FlatpakResource::addMetadata(const QString &key, const QVariant &value) { m_metadata.insert(key, value); } void FlatpakResource::setArch(const QString &arch) { m_arch = arch; } void FlatpakResource::setBranch(const QString &branch) { m_branch = branch; } void FlatpakResource::setBundledIcon(const QPixmap &pixmap) { m_bundledIcon = pixmap; } void FlatpakResource::setCommit(const QString &commit) { m_commit = commit; } void FlatpakResource::setDownloadSize(int size) { m_downloadSize = size; Q_EMIT sizeChanged(); } void FlatpakResource::setFlatpakFileType(const QString &fileType) { m_flatpakFileType = fileType; } void FlatpakResource::setFlatpakName(const QString &name) { m_flatpakName = name; } void FlatpakResource::setIconPath(const QString &path) { m_iconPath = path; } void FlatpakResource::setInstalledSize(int size) { m_installedSize = size; Q_EMIT sizeChanged(); } void FlatpakResource::setOrigin(const QString &origin) { m_origin = origin; } void FlatpakResource::setResourceFile(const QUrl &url) { m_resourceFile = url; } void FlatpakResource::setRuntime(const QString &runtime) { m_runtime = runtime; } void FlatpakResource::setScope(FlatpakResource::Scope scope) { m_scope = scope; } void FlatpakResource::setState(AbstractResource::State state) { m_state = state; emit stateChanged(); } void FlatpakResource::setType(FlatpakResource::ResourceType type) { m_type = type; } // void FlatpakResource::setAddons(const AddonList& addons) // { // Q_FOREACH (const QString& toInstall, addons.addonsToInstall()) { // setAddonInstalled(toInstall, true); // } // Q_FOREACH (const QString& toRemove, addons.addonsToRemove()) { // setAddonInstalled(toRemove, false); // } // } // void FlatpakResource::setAddonInstalled(const QString& addon, bool installed) // { // for(auto & elem : m_addons) { // if(elem.name() == addon) { // elem.setInstalled(installed); // } // } // } diff --git a/libdiscover/resources/AbstractResource.h b/libdiscover/resources/AbstractResource.h index edff3e2d..274fabe0 100644 --- a/libdiscover/resources/AbstractResource.h +++ b/libdiscover/resources/AbstractResource.h @@ -1,210 +1,211 @@ /*************************************************************************** * Copyright © 2012 Aleix Pol Gonzalez * * * * 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 . * ***************************************************************************/ #ifndef ABSTRACTRESOURCE_H #define ABSTRACTRESOURCE_H #include #include #include #include #include #include #include "discovercommon_export.h" #include "PackageState.h" class Category; class Rating; class AbstractResourcesBackend; /** * \class AbstractResource AbstractResource.h "AbstractResource.h" * * \brief This is the base class of all resources. * * Each backend must reimplement its own resource class which needs to derive from this one. */ class DISCOVERCOMMON_EXPORT AbstractResource : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name CONSTANT) Q_PROPERTY(QString packageName READ packageName CONSTANT) Q_PROPERTY(QString comment READ comment CONSTANT) - Q_PROPERTY(QVariant icon READ icon CONSTANT) + Q_PROPERTY(QVariant icon READ icon NOTIFY iconChanged) Q_PROPERTY(bool canExecute READ canExecute CONSTANT) Q_PROPERTY(State state READ state NOTIFY stateChanged) Q_PROPERTY(QString status READ status NOTIFY stateChanged) Q_PROPERTY(QStringList category READ categories CONSTANT) Q_PROPERTY(bool isTechnical READ isTechnical CONSTANT) Q_PROPERTY(QUrl homepage READ homepage CONSTANT) Q_PROPERTY(QUrl thumbnailUrl READ thumbnailUrl CONSTANT) Q_PROPERTY(QUrl screenshotUrl READ screenshotUrl CONSTANT) Q_PROPERTY(bool canUpgrade READ canUpgrade NOTIFY stateChanged) Q_PROPERTY(bool isInstalled READ isInstalled NOTIFY stateChanged) Q_PROPERTY(QString license READ license CONSTANT) Q_PROPERTY(QString longDescription READ longDescription CONSTANT) Q_PROPERTY(QString origin READ origin CONSTANT) Q_PROPERTY(int size READ size NOTIFY sizeChanged) Q_PROPERTY(QString sizeDescription READ sizeDescription NOTIFY sizeChanged) Q_PROPERTY(QString installedVersion READ installedVersion NOTIFY stateChanged) Q_PROPERTY(QString availableVersion READ availableVersion NOTIFY stateChanged) Q_PROPERTY(QString section READ section CONSTANT) Q_PROPERTY(QStringList mimetypes READ mimetypes CONSTANT) Q_PROPERTY(AbstractResourcesBackend* backend READ backend CONSTANT) Q_PROPERTY(Rating* rating READ rating NOTIFY ratingFetched) Q_PROPERTY(QString appstreamId READ appstreamId CONSTANT) Q_PROPERTY(QString categoryDisplay READ categoryDisplay CONSTANT) public: /** * This describes the state of the resource */ enum State { /** * When the resource is somehow broken */ Broken, /** * This means that the resource is neither installed nor broken */ None, /** * The resource is installed and up-to-date */ Installed, /** * The resource is installed and an update is available */ Upgradeable }; Q_ENUM(State) /** * Constructs the AbstractResource with its corresponding backend */ explicit AbstractResource(AbstractResourcesBackend* parent); ///used as internal identification of a resource virtual QString packageName() const = 0; ///resource name to be displayed virtual QString name() = 0; ///short description of the resource virtual QString comment() = 0; ///xdg-compatible icon name to represent the resource, url or QIcon virtual QVariant icon() const = 0; ///@returns whether invokeApplication makes something /// false if not overridden virtual bool canExecute() const; ///executes the resource, if applies. Q_SCRIPTABLE virtual void invokeApplication() const; virtual State state() = 0; virtual QStringList categories() = 0; ///@returns a URL that points to the content virtual QUrl homepage() = 0; virtual bool isTechnical() const; virtual QUrl thumbnailUrl() = 0; virtual QUrl screenshotUrl() = 0; virtual int size() = 0; virtual QString sizeDescription(); virtual QString license() = 0; virtual QString installedVersion() const = 0; virtual QString availableVersion() const = 0; virtual QString longDescription() = 0; virtual QString origin() const = 0; virtual QString section() = 0; ///@returns what kind of mime types the resource can consume virtual QStringList mimetypes() const; virtual QList addonsInformation() = 0; bool isFromSecureOrigin() const; virtual QStringList executables() const; virtual QStringList extends() const; virtual QString appstreamId() const; bool canUpgrade(); bool isInstalled(); ///@returns a user-readable explaination of the resource status ///by default, it will specify what state() is returning virtual QString status(); AbstractResourcesBackend* backend() const; /** * @returns a name sort key for faster sorting */ QCollatorSortKey nameSortKey(); /** * Convenience method to fetch the resource's rating * * @returns the rating for the resource or null if not available */ Rating* rating() const; /** * @returns a string defining the categories the resource belongs to */ QString categoryDisplay() const; bool categoryMatches(Category* cat); QSet categoryObjects() const; public Q_SLOTS: virtual void fetchScreenshots(); virtual void fetchChangelog() = 0; Q_SIGNALS: + void iconChanged(); void sizeChanged(); void stateChanged(); void ratingFetched(); ///response to the fetchScreenshots method ///@p thumbnails and @p screenshots should have the same number of elements void screenshotsFetched(const QList& thumbnails, const QList& screenshots); void changelogFetched(const QString& changelog); private: void reportNewState(); // TODO: make it std::optional or make QCollatorSortKey() QScopedPointer m_collatorKey; }; Q_DECLARE_METATYPE(QVector) #endif // ABSTRACTRESOURCE_H