diff --git a/src/declarative/pkupdates.cpp b/src/declarative/pkupdates.cpp index 401c887..1c958db 100644 --- a/src/declarative/pkupdates.cpp +++ b/src/declarative/pkupdates.cpp @@ -1,621 +1,653 @@ /*************************************************************************** * Copyright (C) 2015 Lukáš Tinkl * * * * 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) any later version. * * * * 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; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include "pkupdates.h" #include "PkStrings.h" Q_LOGGING_CATEGORY(PLASMA_PK_UPDATES, "plasma-pk-updates") namespace { const auto s_pkUpdatesIconName = QStringLiteral("system-software-update"); const auto s_componentName = QStringLiteral("plasma_pk_updates"); const auto s_eventIdUpdatesAvailable = QStringLiteral("updatesAvailable"); const auto s_eventIdUpdatesInstalled = QStringLiteral("updatesInstalled"); const auto s_eventIdRestartRequired = QStringLiteral("restartRequired"); const auto s_eventIdError = QStringLiteral("updateError"); } // namespace { PkUpdates::PkUpdates(QObject *parent) : QObject(parent), m_isOnBattery(true) { setStatusMessage(i18n("Idle")); connect(PackageKit::Daemon::global(), &PackageKit::Daemon::changed, this, &PkUpdates::onChanged); connect(PackageKit::Daemon::global(), &PackageKit::Daemon::updatesChanged, this, &PkUpdates::onUpdatesChanged); connect(PackageKit::Daemon::global(), &PackageKit::Daemon::networkStateChanged, this, &PkUpdates::networkStateChanged); connect(Solid::Power::self(), &Solid::Power::resumeFromSuspend, this, [this] {PackageKit::Daemon::stateHasChanged(QStringLiteral("resume"));}); connect(Solid::Power::self(), &Solid::Power::acPluggedChanged, this, [this] (bool acPlugged) { qCDebug(PLASMA_PK_UPDATES) << "acPluggedChanged onBattery:" << m_isOnBattery << "->" << !acPlugged; if (!acPlugged != m_isOnBattery) { m_isOnBattery = !acPlugged; emit PkUpdates::isOnBatteryChanged(); } }); auto acPluggedJob = Solid::Power::self()->isAcPlugged(this); connect(acPluggedJob , &Solid::Job::result, this, [this] (Solid::Job* job) { bool acPlugged = static_cast(job)->isPlugged(); qCDebug(PLASMA_PK_UPDATES) << "acPlugged initial state" << acPlugged; m_isOnBattery = !acPlugged; emit PkUpdates::isOnBatteryChanged(); }); acPluggedJob->start(); connect(PackageKit::Daemon::global(), &PackageKit::Daemon::networkStateChanged, this, &PkUpdates::doDelayedCheckUpdates); connect(this, &PkUpdates::isActiveChanged, this, &PkUpdates::messageChanged); connect(this, &PkUpdates::networkStateChanged, this, &PkUpdates::messageChanged); } PkUpdates::~PkUpdates() { if (m_cacheTrans) { if (m_cacheTrans->allowCancel()) m_cacheTrans->cancel(); m_cacheTrans->deleteLater(); } if (m_updatesTrans) { if (m_updatesTrans->allowCancel()) m_updatesTrans->cancel(); m_updatesTrans->deleteLater(); } if (m_installTrans) { m_installTrans->deleteLater(); } if (m_detailTrans) { m_detailTrans->deleteLater(); } } int PkUpdates::count() const { return m_updateList.count(); } int PkUpdates::importantCount() const { return m_importantList.count(); } int PkUpdates::securityCount() const { return m_securityList.count(); } bool PkUpdates::isSystemUpToDate() const { return m_updateList.isEmpty(); } QString PkUpdates::iconName() const { if (securityCount() > 0) { return QStringLiteral("update-high"); } else if (importantCount() > 0) { return QStringLiteral("update-medium"); } else if (count() > 0) { return QStringLiteral("update-low"); } else { return QStringLiteral("update-none"); } } QString PkUpdates::message() const { if (isActive()) { if (m_activity == CheckingUpdates) return i18n("Checking updates"); else if (m_activity == GettingUpdates) return i18n("Getting updates"); else if (m_activity == InstallingUpdates) return i18n("Installing updates"); return i18n("Working"); } else if (!isSystemUpToDate()) { QStringList extra; const QString msg = i18np("You have 1 new update", "You have %1 new updates", count()); if (securityCount() > 0) extra += i18np("1 security update", "%1 security updates", securityCount()); if (importantCount() > 0) extra += i18np("1 important update", "%1 important updates", importantCount()); if (extra.isEmpty()) return msg; else return msg + "\n" + i18n("(including %1)", extra.join(i18n(" and "))); } else if (!isNetworkOnline()) { return i18n("Your system is offline"); } else if (!m_lastCheckSuccessful) { return i18n("Checking for updates failed"); } return i18n("Your system is up to date"); } int PkUpdates::percentage() const { return m_percentage; } QString PkUpdates::statusMessage() const { return m_statusMessage; } bool PkUpdates::isActive() const { return m_activity != Idle; } QVariantMap PkUpdates::packages() const { return m_updateList; } bool PkUpdates::isNetworkOnline() const { qCDebug(PLASMA_PK_UPDATES) << "Is net online:" << (PackageKit::Daemon::networkState() > PackageKit::Daemon::Network::NetworkOffline); return (PackageKit::Daemon::networkState() > PackageKit::Daemon::Network::NetworkOffline); } void PkUpdates::doDelayedCheckUpdates() { if (m_checkUpdatesWhenNetworkOnline && isNetworkOnline()) { qCDebug(PLASMA_PK_UPDATES) << "CheckUpdates was delayed. Doing it now"; m_checkUpdatesWhenNetworkOnline = false; - checkUpdates(); + checkUpdates(true /* force */, m_isManualCheck /* manual */); } } bool PkUpdates::isNetworkMobile() const { qCDebug(PLASMA_PK_UPDATES) << "Is net mobile:" << (PackageKit::Daemon::networkState() == PackageKit::Daemon::Network::NetworkMobile); return (PackageKit::Daemon::networkState() == PackageKit::Daemon::Network::NetworkMobile); } bool PkUpdates::isOnBattery() const { qCDebug(PLASMA_PK_UPDATES) << "Is on battery:" << m_isOnBattery; return m_isOnBattery; } void PkUpdates::getUpdateDetails(const QString &pkgID) { qCDebug(PLASMA_PK_UPDATES) << "Requesting update details for" << pkgID; m_detailTrans = PackageKit::Daemon::getUpdateDetail(pkgID); connect(m_detailTrans.data(), &PackageKit::Transaction::updateDetail, this, &PkUpdates::onUpdateDetail); } QString PkUpdates::timestamp() const { const qint64 lastCheck = QDateTime::currentMSecsSinceEpoch() - lastRefreshTimestamp(); if (lastCheck != -1) return i18n("Last check: %1 ago", KFormat().formatSpelloutDuration(lastCheck)); return i18n("Last check: never"); } -void PkUpdates::checkUpdates(bool force) +void PkUpdates::checkUpdates(bool force, bool manual) { + m_isManualCheck = manual; + if (!isNetworkOnline()) { qCDebug(PLASMA_PK_UPDATES) << "Checking updates delayed. Network is offline"; m_checkUpdatesWhenNetworkOnline = true; return; } qCDebug(PLASMA_PK_UPDATES) << "Checking updates, forced"; // ask the Packagekit daemon to refresh the cache m_cacheTrans = PackageKit::Daemon::refreshCache(force); setActivity(CheckingUpdates); // evaluate the result connect(m_cacheTrans.data(), &PackageKit::Transaction::statusChanged, this, &PkUpdates::onStatusChanged); connect(m_cacheTrans.data(), &PackageKit::Transaction::finished, this, &PkUpdates::onFinished); - connect(m_cacheTrans.data(), &PackageKit::Transaction::errorCode, this, &PkUpdates::onErrorCode); + connect(m_cacheTrans.data(), &PackageKit::Transaction::errorCode, this, &PkUpdates::onRefreshErrorCode); connect(m_cacheTrans.data(), &PackageKit::Transaction::requireRestart, this, &PkUpdates::onRequireRestart); connect(m_cacheTrans.data(), &PackageKit::Transaction::repoSignatureRequired, this, &PkUpdates::onRepoSignatureRequired); } qint64 PkUpdates::lastRefreshTimestamp() const { KConfigGroup grp(KSharedConfig::openConfig("plasma-pk-updates"), "General"); return grp.readEntry("Timestamp", -1); } QString PkUpdates::packageName(const QString &pkgId) { return PackageKit::Daemon::packageName(pkgId); } QString PkUpdates::packageVersion(const QString &pkgId) { return PackageKit::Daemon::packageVersion(pkgId); } void PkUpdates::getUpdates() { m_updatesTrans = PackageKit::Daemon::getUpdates(); setActivity(GettingUpdates); m_updateList.clear(); m_importantList.clear(); m_securityList.clear(); connect(m_updatesTrans.data(), &PackageKit::Transaction::statusChanged, this, &PkUpdates::onStatusChanged); connect(m_updatesTrans.data(), &PackageKit::Transaction::finished, this, &PkUpdates::onFinished); connect(m_updatesTrans.data(), &PackageKit::Transaction::errorCode, this, &PkUpdates::onErrorCode); connect(m_updatesTrans.data(), &PackageKit::Transaction::package, this, &PkUpdates::onPackage); connect(m_updatesTrans.data(), &PackageKit::Transaction::requireRestart, this, &PkUpdates::onRequireRestart); connect(m_updatesTrans.data(), &PackageKit::Transaction::repoSignatureRequired, this, &PkUpdates::onRepoSignatureRequired); } void PkUpdates::installUpdates(const QStringList &packageIds, bool simulate, bool untrusted) { qCDebug(PLASMA_PK_UPDATES) << "Installing updates" << packageIds << ", simulate:" << simulate << ", untrusted:" << untrusted; PackageKit::Transaction::TransactionFlags flags = PackageKit::Transaction::TransactionFlagOnlyTrusted; if (simulate) { flags |= PackageKit::Transaction::TransactionFlagSimulate; } else if (untrusted) { flags = PackageKit::Transaction::TransactionFlagNone; } m_requiredEulas.clear(); m_packages = packageIds; m_installTrans = PackageKit::Daemon::updatePackages(m_packages, flags); setActivity(InstallingUpdates); connect(m_installTrans.data(), &PackageKit::Transaction::statusChanged, this, &PkUpdates::onStatusChanged); connect(m_installTrans.data(), &PackageKit::Transaction::finished, this, &PkUpdates::onFinished); connect(m_installTrans.data(), &PackageKit::Transaction::errorCode, this, &PkUpdates::onErrorCode); connect(m_installTrans.data(), &PackageKit::Transaction::package, this, &PkUpdates::onPackageUpdating); connect(m_installTrans.data(), &PackageKit::Transaction::requireRestart, this, &PkUpdates::onRequireRestart); connect(m_installTrans.data(), &PackageKit::Transaction::repoSignatureRequired, this, &PkUpdates::onRepoSignatureRequired); connect(m_installTrans.data(), &PackageKit::Transaction::eulaRequired, this, &PkUpdates::onEulaRequired); } void PkUpdates::onChanged() { qCDebug(PLASMA_PK_UPDATES) << "Daemon changed"; } void PkUpdates::onUpdatesChanged() { qCDebug(PLASMA_PK_UPDATES) << "Updates changed, getting updates!"; getUpdates(); } void PkUpdates::onStatusChanged() { PackageKit::Transaction * trans; if ((trans = qobject_cast(sender()))) { qCDebug(PLASMA_PK_UPDATES) << "Transaction status changed:" << PackageKit::Daemon::enumToString((int)trans->status(), "Status") << QStringLiteral("(%1%)").arg(trans->percentage()); if (trans->status() == PackageKit::Transaction::StatusFinished) return; setStatusMessage(PkStrings::status(trans->status(), trans->speed(), trans->downloadSizeRemaining())); setPercentage(trans->percentage()); } } void PkUpdates::onPackage(PackageKit::Transaction::Info info, const QString &packageID, const QString &summary) { qCDebug(PLASMA_PK_UPDATES) << "Got update package:" << packageID << ", summary:" << summary << ", type:" << PackageKit::Daemon::enumToString((int)info, "Info"); switch (info) { case PackageKit::Transaction::InfoBlocked: // Blocked updates are not installable updates so there is no // reason to show/count them return; case PackageKit::Transaction::InfoImportant: m_importantList << packageID; break; case PackageKit::Transaction::InfoSecurity: m_securityList << packageID; break; default: break; } m_updateList.insert(packageID, summary); } void PkUpdates::onPackageUpdating(PackageKit::Transaction::Info info, const QString &packageID, const QString &summary) { Q_UNUSED(summary) qCDebug(PLASMA_PK_UPDATES) << "Package updating:" << packageID << ", info:" << PackageKit::Daemon::enumToString((int)info, "Info"); const uint percent = m_installTrans->percentage(); if (percent <= 100) { setStatusMessage(i18nc("1 installation status, 2 pkg name, 3 percentage", "%1 %2 (%3%)", PkStrings::infoPresent(info), PackageKit::Daemon::packageName(packageID), percent)); } else { setStatusMessage(i18nc("1 installation status, 2 pkg name", "%1 %2", PkStrings::infoPresent(info), PackageKit::Daemon::packageName(packageID), percent)); } setPercentage(percent); } void PkUpdates::onFinished(PackageKit::Transaction::Exit status, uint runtime) { PackageKit::Transaction * trans = qobject_cast(sender()); if (!trans) return; trans->deleteLater(); qCDebug(PLASMA_PK_UPDATES) << "Transaction" << trans->tid().path() << "finished with status" << PackageKit::Daemon::enumToString((int)status, "Exit") << "in" << runtime/1000 << "seconds"; if (trans->role() == PackageKit::Transaction::RoleRefreshCache) { m_lastCheckSuccessful = status == PackageKit::Transaction::ExitSuccess; if (m_lastCheckSuccessful) { qCDebug(PLASMA_PK_UPDATES) << "Cache transaction finished successfully"; // save the timestamp KConfigGroup grp(KSharedConfig::openConfig("plasma-pk-updates"), "General"); grp.writeEntry("Timestamp", QDateTime::currentDateTime().toMSecsSinceEpoch()); + grp.writeEntry("FailedAutoRefeshCount", 0); grp.sync(); return; } else { qCDebug(PLASMA_PK_UPDATES) << "Cache transaction didn't finish successfully"; emit done(); } } else if (trans->role() == PackageKit::Transaction::RoleGetUpdates) { m_lastCheckSuccessful = status == PackageKit::Transaction::ExitSuccess; if (m_lastCheckSuccessful) { qCDebug(PLASMA_PK_UPDATES) << "Check updates transaction finished successfully"; const int upCount = count(); if (upCount != m_lastUpdateCount && m_lastNotification) { qCDebug(PLASMA_PK_UPDATES) << "Disposing old update count notification"; m_lastNotification->close(); } if (upCount > 0 && upCount != m_lastUpdateCount) { m_lastUpdateCount = upCount; m_lastNotification = KNotification::event(s_eventIdUpdatesAvailable, QString(), i18np("You have 1 new update", "You have %1 new updates", upCount), s_pkUpdatesIconName, nullptr, KNotification::Persistent, s_componentName); connect(m_lastNotification, &KNotification::closed, this, [this] { qCDebug(PLASMA_PK_UPDATES) << "Old notification closed"; m_lastNotification = nullptr; m_lastUpdateCount = 0; }); } } else { qCDebug(PLASMA_PK_UPDATES) << "Check updates transaction didn't finish successfully"; } qCDebug(PLASMA_PK_UPDATES) << "Total number of updates: " << count(); emit done(); } else if (trans->role() == PackageKit::Transaction::RoleUpdatePackages) { qCDebug(PLASMA_PK_UPDATES) << "Finished updating packages:" << m_packages; if (status == PackageKit::Transaction::ExitNeedUntrusted) { qCDebug(PLASMA_PK_UPDATES) << "Transaction needs untrusted packages"; // restart transaction with "untrusted" flag installUpdates(m_packages, false /*simulate*/, true /*untrusted*/); return; } else if (status == PackageKit::Transaction::ExitEulaRequired) { qCDebug(PLASMA_PK_UPDATES) << "Acceptance of EULAs required"; promptNextEulaAgreement(); return; } else if (status == PackageKit::Transaction::ExitSuccess && trans->transactionFlags().testFlag(PackageKit::Transaction::TransactionFlagSimulate)) { qCDebug(PLASMA_PK_UPDATES) << "Simulation finished with success, restarting the transaction"; installUpdates(m_packages, false /*simulate*/, false /*untrusted*/); return; } else if (status == PackageKit::Transaction::ExitSuccess) { qCDebug(PLASMA_PK_UPDATES) << "Update packages transaction finished successfully"; if (m_lastNotification) { m_lastNotification->close(); } KNotification::event(s_eventIdUpdatesInstalled, i18n("Updates Installed"), i18np("Successfully updated %1 package", "Successfully updated %1 packages", m_packages.count()), s_pkUpdatesIconName, nullptr, KNotification::CloseOnTimeout, s_componentName); emit updatesInstalled(); } else { qCDebug(PLASMA_PK_UPDATES) << "Update packages transaction didn't finish successfully"; // just try to refresh cache in case of error, the user might have installed the updates manually meanwhile - checkUpdates(false /* force */); + checkUpdates(false /* force */, false /* manual */); return; } setActivity(Idle); return; } else { qCDebug(PLASMA_PK_UPDATES) << "Unhandled transaction type:" << PackageKit::Daemon::enumToString(trans->role(), "Role"); setActivity(Idle); return; } setActivity(Idle); emit updatesChanged(); } void PkUpdates::onErrorCode(PackageKit::Transaction::Error error, const QString &details) +{ + showError(error, details); +} + +void PkUpdates::onRefreshErrorCode(PackageKit::Transaction::Error error, const QString &details) +{ + if(!m_isManualCheck) { + auto isTransientError = [] (PackageKit::Transaction::Error error) { + return (error == PackageKit::Transaction::ErrorFailedInitialization) || + (error == PackageKit::Transaction::ErrorNoNetwork) || + (error == PackageKit::Transaction::ErrorCannotGetLock); + }; + + KConfigGroup grp(KSharedConfig::openConfig("plasma-pk-updates"), "General"); + auto failCount = grp.readEntry("FailedAutoRefeshCount", 0); + failCount += 1; + grp.writeEntry("FailedAutoRefeshCount", failCount); + grp.sync(); + + if(failCount <= 1 && isTransientError(error)) { + qDebug(PLASMA_PK_UPDATES) << "Ignoring notification for likely transient error during automatic check"; + return; + } + } + + showError(error, details); +} + +void PkUpdates::showError(PackageKit::Transaction::Error error, const QString &details) { qWarning() << "PK error:" << details << "type:" << PackageKit::Daemon::enumToString((int)error, "Error"); if (error == PackageKit::Transaction::ErrorBadGpgSignature || error == PackageKit::Transaction::ErrorNoLicenseAgreement) return; KNotification::event(s_eventIdError, i18n("Update Error"), details, s_pkUpdatesIconName, nullptr, KNotification::Persistent, s_componentName); } void PkUpdates::onRequireRestart(PackageKit::Transaction::Restart type, const QString &packageID) { if (type == PackageKit::Transaction::RestartSystem || type == PackageKit::Transaction::RestartSession) { KNotification *notification = new KNotification(s_eventIdRestartRequired, KNotification::Persistent); notification->setComponentName(s_componentName); notification->setIconName(s_pkUpdatesIconName); if (type == PackageKit::Transaction::RestartSystem) { notification->setActions(QStringList{i18nc("@action:button", "Restart")}); notification->setTitle(i18n("Restart is required")); notification->setText(i18n("The computer will have to be restarted after the update for the changes to take effect.")); } else { notification->setActions(QStringList{i18nc("@action:button", "Logout")}); notification->setTitle(i18n("Session restart is required")); notification->setText(i18n("You will need to log out and back in after the update for the changes to take effect.")); } connect(notification, &KNotification::action1Activated, this, [type] () { QDBusInterface interface("org.kde.ksmserver", "/KSMServer", "org.kde.KSMServerInterface", QDBusConnection::sessionBus()); if (type == PackageKit::Transaction::RestartSystem) { interface.asyncCall("logout", 0, 1, 2); // Options: do not ask again | reboot | force } else { interface.asyncCall("logout", 0, 0, 2); // Options: do not ask again | logout | force } }); notification->sendEvent(); } qCDebug(PLASMA_PK_UPDATES) << "RESTART" << PackageKit::Daemon::enumToString((int)type, "Restart") << "is required for package" << packageID; } void PkUpdates::onUpdateDetail(const QString &packageID, const QStringList &updates, const QStringList &obsoletes, const QStringList &vendorUrls, const QStringList &bugzillaUrls, const QStringList &cveUrls, PackageKit::Transaction::Restart restart, const QString &updateText, const QString &changelog, PackageKit::Transaction::UpdateState state, const QDateTime &issued, const QDateTime &updated) { Q_UNUSED(updates); Q_UNUSED(obsoletes); Q_UNUSED(vendorUrls); Q_UNUSED(cveUrls); Q_UNUSED(restart); Q_UNUSED(changelog); Q_UNUSED(state); Q_UNUSED(issued); Q_UNUSED(updated); qCDebug(PLASMA_PK_UPDATES) << "Got update details for" << packageID; emit updateDetail(packageID, updateText, bugzillaUrls); } void PkUpdates::onRepoSignatureRequired(const QString &packageID, const QString &repoName, const QString &keyUrl, const QString &keyUserid, const QString &keyId, const QString &keyFingerprint, const QString &keyTimestamp, PackageKit::Transaction::SigType type) { Q_UNUSED(repoName); Q_UNUSED(keyUrl); Q_UNUSED(keyUserid); Q_UNUSED(keyId); Q_UNUSED(keyFingerprint); Q_UNUSED(keyTimestamp); Q_UNUSED(type); // TODO provide a way to confirm and import GPG keys qCDebug(PLASMA_PK_UPDATES) << "Repo sig required" << packageID; } void PkUpdates::onEulaRequired(const QString &eulaID, const QString &packageID, const QString &vendor, const QString &licenseAgreement) { m_requiredEulas[eulaID] = {packageID, vendor, licenseAgreement}; } void PkUpdates::promptNextEulaAgreement() { if(m_requiredEulas.empty()) { // Restart the transaction installUpdates(m_packages, false, false); return; } QString eulaID = m_requiredEulas.firstKey(); const EulaData &eula = m_requiredEulas[eulaID]; emit eulaRequired(eulaID, eula.packageID, eula.vendor, eula.licenseAgreement); } void PkUpdates::eulaAgreementResult(const QString &eulaID, bool agreed) { if(!agreed) { qCDebug(PLASMA_PK_UPDATES) << "EULA declined"; // Do the same as the failure case in onFinished - checkUpdates(false /* force */); + checkUpdates(false /* force */, m_isManualCheck /* manual */); return; } m_eulaTrans = PackageKit::Daemon::acceptEula(eulaID); connect(m_eulaTrans.data(), &PackageKit::Transaction::finished, this, [this, eulaID] (PackageKit::Transaction::Exit exit, uint) { if (exit == PackageKit::Transaction::ExitSuccess) { m_requiredEulas.remove(eulaID); promptNextEulaAgreement(); } else { qCWarning(PLASMA_PK_UPDATES) << "EULA acceptance failed"; } } ); } void PkUpdates::setStatusMessage(const QString &message) { m_statusMessage = message; emit statusMessageChanged(); } void PkUpdates::setActivity(Activity act) { if (act != m_activity) { m_activity = act; emit isActiveChanged(); } } void PkUpdates::setPercentage(int value) { if (value != m_percentage) { m_percentage = value; emit percentageChanged(); } } diff --git a/src/declarative/pkupdates.h b/src/declarative/pkupdates.h index 0f48d2d..c1872d0 100644 --- a/src/declarative/pkupdates.h +++ b/src/declarative/pkupdates.h @@ -1,275 +1,280 @@ /*************************************************************************** * Copyright (C) 2015 Lukáš Tinkl * * * * 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) any later version. * * * * 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; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PLASMA_PK_UPDATES_H #define PLASMA_PK_UPDATES_H #include #include #include #include #include class QTimer; class KNotification; Q_DECLARE_LOGGING_CATEGORY(PLASMA_PK_UPDATES) /** * @brief The PkUpdates class * * Backend class to check for available PackageKit system updates. * Use checkUpdates() to perform the check, retrieve them with packages() */ class PkUpdates : public QObject { Q_OBJECT Q_PROPERTY(int count READ count NOTIFY updatesChanged) Q_PROPERTY(int importantCount READ importantCount NOTIFY updatesChanged) Q_PROPERTY(int securityCount READ securityCount NOTIFY updatesChanged) Q_PROPERTY(bool isSystemUpToDate READ isSystemUpToDate NOTIFY updatesChanged) Q_PROPERTY(QString iconName READ iconName NOTIFY updatesChanged) Q_PROPERTY(QString message READ message NOTIFY messageChanged) Q_PROPERTY(int percentage READ percentage NOTIFY percentageChanged) Q_PROPERTY(QString timestamp READ timestamp NOTIFY updatesChanged) Q_PROPERTY(QString statusMessage READ statusMessage NOTIFY statusMessageChanged) Q_PROPERTY(QVariantMap packages READ packages NOTIFY updatesChanged) Q_PROPERTY(bool isActive READ isActive NOTIFY isActiveChanged) Q_PROPERTY(bool isNetworkOnline READ isNetworkOnline NOTIFY networkStateChanged) Q_PROPERTY(bool isNetworkMobile READ isNetworkMobile NOTIFY networkStateChanged) Q_PROPERTY(bool isOnBattery READ isOnBattery NOTIFY isOnBatteryChanged) public: enum Activity {Idle, CheckingUpdates, GettingUpdates, InstallingUpdates}; Q_ENUM(Activity) explicit PkUpdates(QObject *parent = nullptr); ~PkUpdates(); /** * @return the total number of updates, including important and/or security ones */ int count() const; /** * @return the number of important updates, included in total count() */ int importantCount() const; /** * @return the number of security updates, included in total count() */ int securityCount() const; /** * @return whether the system is up to date (count() == 0) */ bool isSystemUpToDate() const; /** * @return the system update status icon name */ QString iconName() const; /** * @return the overall status with number of available updates */ QString message() const; /** * @return the progress percentage (0..100), 101 as a special value indicating indeterminate value */ int percentage() const; /** * @return time stamp of the last update check */ QString timestamp() const; /** * @return status messsage conveying the action being currently performed */ QString statusMessage() const; /** * @return whether we're currently checking for updates or not */ bool isActive() const; /** * @return the packages to update (key=packageId, value=description) */ QVariantMap packages() const; /** * @return whether the network is online */ bool isNetworkOnline() const; /** * @return whether we are on a mobile network connection (assumes isNetworkOnline()) */ bool isNetworkMobile() const; /** * @return whether we are running on battery */ bool isOnBattery() const; signals: /** * Emitted when the number uf updates has changed */ void updatesChanged(); /** * Emitted when the updates check is finished (with success or error) */ void done(); /** * Emitted after updates were installed successfully */ void updatesInstalled(); /** * Emitted with update details * @see getUpdateDetails() */ void updateDetail(const QString &packageID, const QString &updateText, const QStringList &urls); /** * Emitted when an EULA agreement prevents the transaction from running * @param eulaId the EULA identifier * @param packageID ID of the package for which an EULA is required * @param vendorName the vendor name * @param licenseAgreement the EULA text * * @see eulaAgreementResult() */ void eulaRequired(const QString &eulaID, const QString &packageID, const QString &vendor, const QString &licenseAgreement); // private ;) void statusMessageChanged(); void isActiveChanged(); void percentageChanged(); void networkStateChanged(); void isOnBatteryChanged(); void messageChanged(); public slots: /** * Perform a cache update, possibly resulting in an update check. Signal updatesChanged() gets emitted * as a result. Consult the count() property whether there are new updates available. * * @param force whether to force the cache refresh + * @param manual whether this check was triggered via explicit user interaction */ - Q_INVOKABLE void checkUpdates(bool force = true); + Q_INVOKABLE void checkUpdates(bool force = true, bool manual = false); /** * Launch the update process * * @param packageIds list of package IDs to update */ Q_INVOKABLE void installUpdates(const QStringList & packageIds, bool simulate = true, bool untrusted = false); /** * @return the timestamp (in milliseconds) of the last cache check, -1 if never */ Q_INVOKABLE qint64 lastRefreshTimestamp() const; /** * @return the package name extracted from its ID */ Q_INVOKABLE static QString packageName(const QString & pkgId); /** * @return the package version extracted from its ID */ Q_INVOKABLE static QString packageVersion(const QString & pkgId); /** * Request details about the details * @param pkgIds Package IDs * * Emits updateDetail() */ Q_INVOKABLE void getUpdateDetails(const QString & pkgID); Q_INVOKABLE void doDelayedCheckUpdates(); /** * If agreed to eulaID, starts an EULA acceptance transaction and continues. */ Q_INVOKABLE void eulaAgreementResult(const QString &eulaID, bool agreed); private slots: void getUpdates(); void onChanged(); void onUpdatesChanged(); void onStatusChanged(); void onPackage(PackageKit::Transaction::Info info, const QString &packageID, const QString &summary); void onPackageUpdating(PackageKit::Transaction::Info info, const QString &packageID, const QString &summary); void onFinished(PackageKit::Transaction::Exit status, uint runtime); void onErrorCode(PackageKit::Transaction::Error error, const QString &details); + void onRefreshErrorCode(PackageKit::Transaction::Error error, const QString &details); void onRequireRestart(PackageKit::Transaction::Restart type, const QString &packageID); void onUpdateDetail(const QString &packageID, const QStringList &updates, const QStringList &obsoletes, const QStringList &vendorUrls, const QStringList &bugzillaUrls, const QStringList &cveUrls, PackageKit::Transaction::Restart restart, const QString &updateText, const QString &changelog, PackageKit::Transaction::UpdateState state, const QDateTime &issued, const QDateTime &updated); void onRepoSignatureRequired(const QString & packageID, const QString & repoName, const QString & keyUrl, const QString & keyUserid, const QString & keyId, const QString & keyFingerprint, const QString & keyTimestamp, PackageKit::Transaction::SigType type); void onEulaRequired(const QString &eulaID, const QString &packageID, const QString &vendor, const QString &licenseAgreement); private: struct EulaData { QString packageID; QString vendor; QString licenseAgreement; }; void setStatusMessage(const QString &message); void setActivity(Activity act); void setPercentage(int value); + void showError(PackageKit::Transaction::Error error, const QString &details); void promptNextEulaAgreement(); QPointer m_updatesTrans; QPointer m_cacheTrans; QPointer m_installTrans; QPointer m_detailTrans; QPointer m_eulaTrans; QStringList m_packages; QPointer m_lastNotification; int m_lastUpdateCount = 0; QVariantMap m_updateList; QStringList m_importantList; QStringList m_securityList; QString m_statusMessage; int m_percentage = 0; Activity m_activity = Idle; bool m_lastCheckSuccessful = false; bool m_checkUpdatesWhenNetworkOnline = false; bool m_isOnBattery; + // If the current check was triggered manually + bool m_isManualCheck; // If a transaction failed because of required EULAs, // this contains a map of their IDs to their data QMap m_requiredEulas; }; #endif // PLASMA_PK_UPDATES_H diff --git a/src/plasma/contents/ui/Full.qml b/src/plasma/contents/ui/Full.qml index de2a47e..e612738 100644 --- a/src/plasma/contents/ui/Full.qml +++ b/src/plasma/contents/ui/Full.qml @@ -1,357 +1,357 @@ /*************************************************************************** * Copyright (C) 2013 by Aleix Pol Gonzalez * * Copyright (C) 2015 by Lukáš Tinkl * * Copyright (C) 2015 by 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) any later version. * * * * 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, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * ***************************************************************************/ import QtQuick 2.1 import QtQuick.Layouts 1.1 import QtQuick.Controls 1.3 import QtQuick.Dialogs 1.2 import org.kde.plasma.components 2.0 as PlasmaComponents import org.kde.plasma.extras 2.0 as PlasmaExtras import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.PackageKit 1.0 Item { id: fullRepresentation property bool anySelected: checkAnySelected() property bool allSelected: checkAllSelected() property bool populatePreSelected: true Binding { target: timestampLabel property: "text" value: PkUpdates.timestamp when: !plasmoid.expanded } Connections { target: PkUpdates onUpdatesChanged: populateModel() onUpdateDetail: updateDetails(packageID, updateText, urls) onUpdatesInstalled: plasmoid.expanded = false onEulaRequired: eulaDialog.showPrompt(eulaID, packageID, vendor, licenseAgreement) } Component.onCompleted: populateModel() Dialog { property string eulaID: "" property string packageName: "" property string vendor: "" property string licenseText: "" property bool buttonClicked: false id: eulaDialog title: i18n("License Agreement for %1").arg(packageName) standardButtons: StandardButton.Yes | StandardButton.No ColumnLayout { anchors.fill: parent Label { text: i18n("License agreement required for %1 (from %2):").arg(eulaDialog.packageName).arg(eulaDialog.vendor) } TextArea { Layout.fillWidth: true Layout.fillHeight: true Layout.minimumWidth: 400 Layout.minimumHeight: 200 text: eulaDialog.licenseText readOnly: true } Label { text: i18n("Do you accept?") } } onVisibleChanged: { // onRejected does not fire on dialog closing, so implement that ourselves if(!visible && !buttonClicked) onNo(); } onNo: { buttonClicked = true; PkUpdates.eulaAgreementResult(this.eulaID, false); } onYes: { buttonClicked = true; PkUpdates.eulaAgreementResult(this.eulaID, true); } function showPrompt(eulaID, packageID, vendor, licenseAgreement) { this.eulaID = eulaID; this.packageName = PkUpdates.packageName(packageID); this.vendor = vendor; this.licenseText = licenseAgreement; this.visible = true; } } ListModel { id: updatesModel } PlasmaExtras.Heading { id: header level: 4 wrapMode: Text.WordWrap text: !PkUpdates.isNetworkOnline ? i18n("Network is offline") : PkUpdates.message } ColumnLayout { id: statusbar anchors { left: parent.left right: parent.right top: header.bottom rightMargin: Math.round(units.gridUnit / 2) } spacing: units.largeSpacing PlasmaComponents.Label { id: timestampLabel visible: !PkUpdates.isActive wrapMode: Text.WordWrap font.italic: true font.pointSize: theme.smallestFont.pointSize; opacity: 0.6; text: PkUpdates.timestamp } PlasmaComponents.Label { visible: PkUpdates.isActive || !PkUpdates.count font.pointSize: theme.smallestFont.pointSize; opacity: 0.6; text: { if (PkUpdates.isActive) return PkUpdates.statusMessage else if (PkUpdates.isNetworkOnline) return i18n("Updates are automatically checked %1.
Click the 'Check For Updates' button below to search for updates manually.", updateInterval(plasmoid.configuration.daily, plasmoid.configuration.weekly, plasmoid.configuration.monthly)); return "" } Layout.fillWidth: true wrapMode: Text.WordWrap } } ProgressBar { id: progressBar anchors { left: parent.left right: parent.right top: statusbar.bottom } visible: PkUpdates.isActive minimumValue: 0 maximumValue: 101 // BUG workaround a bug in ProgressBar! if the value is > max, it's set to max and never changes below value: PkUpdates.percentage indeterminate: PkUpdates.percentage > 100 } ColumnLayout { spacing: units.smallSpacing anchors { bottom: parent.bottom left: parent.left right: parent.right top: statusbar.bottom } PlasmaExtras.ScrollArea { id: updatesScrollArea Layout.fillWidth: true Layout.fillHeight: true visible: PkUpdates.count && PkUpdates.isNetworkOnline && !PkUpdates.isActive ListView { id: updatesView clip: true model: PlasmaCore.SortFilterModel { sourceModel: updatesModel filterRole: "name" } anchors.fill: parent currentIndex: -1 boundsBehavior: Flickable.StopAtBounds delegate: PackageDelegate { onClicked: { if (updatesView.currentIndex === index) { updatesView.currentIndex = -1 } else { updatesView.currentIndex = index PkUpdates.getUpdateDetails(id) } } onCheckedStateChanged: { if (checked) { fullRepresentation.anySelected = true } else { fullRepresentation.anySelected = checkAnySelected() } } } } } RowLayout { visible: PkUpdates.count && PkUpdates.isNetworkOnline && !PkUpdates.isActive PlasmaComponents.CheckBox { id: chkSelectAll anchors { left: parent.left leftMargin: Math.round(units.gridUnit / 3) } checkedState: fullRepresentation.anySelected ? (fullRepresentation.allSelected ? Qt.Checked : Qt.PartiallyChecked) : Qt.Unchecked partiallyCheckedEnabled: true } PlasmaComponents.Label { id: lblSelectAll height: paintedHeight anchors { left: chkSelectAll.right leftMargin: Math.round(units.gridUnit / 2) } elide: Text.ElideRight; text: i18n("Select all packages") } MouseArea { anchors.fill: parent enabled: true onClicked: { if (chkSelectAll.checkedState == Qt.Unchecked) { populatePreSelected = true populateModel() } else if (chkSelectAll.checkedState == Qt.PartiallyChecked) { populatePreSelected = true populateModel() } else { populatePreSelected = false populateModel() } fullRepresentation.anySelected = checkAnySelected() } } } PlasmaComponents.Button { id: btnCheck visible: !PkUpdates.count && PkUpdates.isNetworkOnline && !PkUpdates.isActive enabled: !PkUpdates.isActive anchors { bottom: parent.bottom bottomMargin: Math.round(units.gridUnit / 3) horizontalCenter: parent.horizontalCenter } text: i18n("Check For Updates") tooltip: i18n("Checks for any available updates") - onClicked: PkUpdates.checkUpdates() // circumvent the checks, the user knows what they're doing ;) + onClicked: PkUpdates.checkUpdates(true /* force */, true /* manual */) // circumvent the checks, the user knows what they're doing ;) } PlasmaComponents.Button { id: btnUpdate visible: PkUpdates.count && PkUpdates.isNetworkOnline && !PkUpdates.isActive enabled: fullRepresentation.anySelected anchors { bottom: parent.bottom bottomMargin: Math.round(units.gridUnit / 3) horizontalCenter: parent.horizontalCenter } text: i18n("Install Updates") tooltip: i18n("Performs the software update") onClicked: PkUpdates.installUpdates(selectedPackages()) } PlasmaComponents.BusyIndicator { running: PkUpdates.isActive visible: running anchors.centerIn: parent } } function checkAnySelected() { for (var i = 0; i < updatesModel.count; i++) { var pkg = updatesModel.get(i) if (pkg.selected) return true } return false } function checkAllSelected() { for (var i = 0; i < updatesModel.count; i++) { var pkg = updatesModel.get(i) if (!pkg.selected) return false } return true } function selectedPackages() { var result = [] for (var i = 0; i < updatesModel.count; i++) { var pkg = updatesModel.get(i) if (pkg.selected) { print("Package " + pkg.id + " selected for update") result.push(pkg.id) } } return result } function populateModel() { print("Populating model") updatesModel.clear() var packages = PkUpdates.packages for (var id in packages) { if (packages.hasOwnProperty(id)) { var desc = packages[id] updatesModel.append({"selected": populatePreSelected, "id": id, "name": PkUpdates.packageName(id), "desc": desc, "version": PkUpdates.packageVersion(id)}) } } } function updateDetails(packageID, updateText, urls) { //print("Got update details for: " + packageID) print("Update text: " + updateText) print("URLs: " + urls) updatesView.currentItem.updateText = updateText updatesView.currentItem.updateUrls = urls } function updateInterval(daily, weekly, monthly) { if (weekly) return i18n("weekly"); else if (monthly) return i18n("monthly"); return i18n("daily"); } } diff --git a/src/plasma/contents/ui/main.qml b/src/plasma/contents/ui/main.qml index b18f15d..aaec014 100644 --- a/src/plasma/contents/ui/main.qml +++ b/src/plasma/contents/ui/main.qml @@ -1,100 +1,100 @@ /*************************************************************************** * Copyright (C) 2014 by Aleix Pol Gonzalez * * Copyright (C) 2015 by Lukáš Tinkl * * Copyright (C) 2015 by 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) any later version. * * * * 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, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * ***************************************************************************/ import QtQuick 2.2 import org.kde.plasma.plasmoid 2.0 import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.PackageKit 1.0 Item { Plasmoid.fullRepresentation: Full {} Plasmoid.toolTipSubText: PkUpdates.message Plasmoid.icon: PkUpdates.iconName Plasmoid.switchWidth: units.gridUnit * 10; Plasmoid.switchHeight: units.gridUnit * 10; property bool checkDaily: plasmoid.configuration.daily property bool checkWeekly: plasmoid.configuration.weekly property bool checkMonthly: plasmoid.configuration.monthly property bool checkOnMobile: plasmoid.configuration.check_on_mobile property bool checkOnBattery: plasmoid.configuration.check_on_battery readonly property int secsInDay: 60 * 60 * 24; readonly property int secsInWeek: secsInDay * 7; readonly property int secsInMonth: secsInDay * 30; readonly property bool networkAllowed: PkUpdates.isNetworkMobile ? checkOnMobile : PkUpdates.isNetworkOnline readonly property bool batteryAllowed: PkUpdates.isOnBattery ? checkOnBattery : true Timer { id: timer repeat: true triggeredOnStart: true interval: 1000 * 60 * 60; // 1 hour onTriggered: { if (needsForcedUpdate() && networkAllowed && batteryAllowed) { - PkUpdates.checkUpdates(); + PkUpdates.checkUpdates(true /* force */, false /* manual */); } } } Binding { target: plasmoid property: "status" value: PkUpdates.isActive || !PkUpdates.isSystemUpToDate ? PlasmaCore.Types.ActiveStatus : PlasmaCore.Types.PassiveStatus; } Plasmoid.compactRepresentation: PlasmaCore.IconItem { source: PkUpdates.iconName anchors.fill: parent MouseArea { anchors.fill: parent onClicked: plasmoid.expanded = !plasmoid.expanded } } function needsForcedUpdate() { var secs = (Date.now() - PkUpdates.lastRefreshTimestamp())/1000; // compare with the saved timestamp if (secs < 0) { // never checked before return true; } else if (checkDaily) { return secs >= secsInDay; } else if (checkWeekly) { return secs >= secsInWeek; } else if (checkMonthly) { return secs >= secsInMonth; } return false; } Connections { target: PkUpdates onNetworkStateChanged: timer.restart() onIsOnBatteryChanged: timer.restart() } Component.onCompleted: { timer.start() } }