feat(update): add self-update check via Gitea releases API
tests / build-test (push) Has been cancelled
tests / build-test (push) Has been cancelled
Adds an UpdateManager that queries the Gitea releases API once per day, stores the last check state in a JSON file, and offers to pull + rebuild the source repository when a newer version exists. The running binary is left untouched until the next launch. Also sets the app version from the version file at build time instead of the hardcoded 1.0.0, and copies the version file next to the executable.
This commit is contained in:
6 files changed
+424
-6
No files matched your search
@@ -0,0 +1,238 @@
|
||||
#include "update-manager.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonArray>
|
||||
#include <QStandardPaths>
|
||||
#include <QDir>
|
||||
#include <QCoreApplication>
|
||||
#include <QProcessEnvironment>
|
||||
|
||||
// Repository base URL used to query the Gitea API for releases.
|
||||
// The app is hosted at https://gitea.nocode-var.tech/FWS/FWS-PacManage.
|
||||
static const char* kApiUrl =
|
||||
"https://gitea.nocode-var.tech/api/v1/repos/FWS/FWS-PacManage/releases/latest";
|
||||
static const char* kVersionToken = "FWSPACMANAGE_VERSION"; // replaced at build time
|
||||
static const char* kRepoUrl =
|
||||
"https://gitea.nocode-var.tech/FWS/FWS-PacManage.git";
|
||||
|
||||
UpdateManager::UpdateManager(QObject* parent) : QObject(parent) {
|
||||
loadState();
|
||||
|
||||
// The running executable is expected to live in the build/ directory when
|
||||
// launched from a source checkout. Walk up two levels to find the repo.
|
||||
// When installed to ~/.local/bin there is no source tree, so update
|
||||
// becomes impossible and the dialog simply points to the releases page.
|
||||
QDir dir(QCoreApplication::applicationDirPath());
|
||||
if (dir.dirName() == QLatin1String("build")) {
|
||||
dir.cdUp();
|
||||
if (dir.exists(QLatin1String("CMakeLists.txt"))) {
|
||||
m_repoPath = dir.absolutePath();
|
||||
}
|
||||
}
|
||||
|
||||
connect(&m_process, &QProcess::finished, this, [this](int exitCode) {
|
||||
const QString msg = QString::fromUtf8(m_process.readAllStandardOutput())
|
||||
+ QString::fromUtf8(m_process.readAllStandardError());
|
||||
emit selfUpdateFinished(exitCode == 0, msg.trimmed());
|
||||
});
|
||||
}
|
||||
|
||||
QString UpdateManager::currentVersion() {
|
||||
// The `version` file at the repo root is the single source of truth. It is
|
||||
// read from the executable's directory so a running build always reports
|
||||
// the same version the developer bumped in the repo.
|
||||
QString version;
|
||||
const QString localFile = QCoreApplication::applicationDirPath() + "/version";
|
||||
QFile f(localFile);
|
||||
if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
version = QString::fromUtf8(f.readAll()).trimmed();
|
||||
}
|
||||
if (version.isEmpty()) {
|
||||
// CMake configure-time token; falls back to 1.0.0 when built without.
|
||||
version = QString::fromLatin1(kVersionToken);
|
||||
if (version == QLatin1String("FWSPACMANAGE_VERSION")) {
|
||||
version = QStringLiteral("1.0.0");
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
QString UpdateManager::stateFilePath() {
|
||||
QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
|
||||
if (dir.isEmpty()) {
|
||||
dir = QDir::homePath() + "/.local/share/PacManager";
|
||||
}
|
||||
return dir + "/update-state.json";
|
||||
}
|
||||
|
||||
bool UpdateManager::shouldCheck() const {
|
||||
if (m_lastCheckDate.isEmpty()) return true;
|
||||
|
||||
QDateTime last = QDateTime::fromString(m_lastCheckDate, Qt::ISODate);
|
||||
if (!last.isValid()) return true;
|
||||
|
||||
// Only one network call per day keeps launch snappy and avoids hammering
|
||||
// the Gitea API on every start.
|
||||
return last.daysTo(QDateTime::currentDateTime()) >= 1;
|
||||
}
|
||||
|
||||
QString UpdateManager::lastKnownRemoteVersion() const {
|
||||
return m_lastKnownRemoteVersion;
|
||||
}
|
||||
|
||||
QString UpdateManager::repoPath() const {
|
||||
return m_repoPath;
|
||||
}
|
||||
|
||||
bool UpdateManager::canSelfUpdate() const {
|
||||
if (m_repoPath.isEmpty()) return false;
|
||||
|
||||
QDir repo(m_repoPath);
|
||||
if (!repo.exists(QLatin1String(".git"))) return false;
|
||||
|
||||
// The remote must point to the same FWS repo, otherwise we would build
|
||||
// someone else's code on the user's machine.
|
||||
QFile config(m_repoPath + "/.git/config");
|
||||
if (config.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
const QString content = QString::fromUtf8(config.readAll());
|
||||
if (content.contains(QLatin1String("FWS/FWS-PacManage"))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void UpdateManager::loadState() {
|
||||
QFile file(stateFilePath());
|
||||
if (!file.open(QIODevice::ReadOnly)) return;
|
||||
|
||||
QJsonParseError err;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &err);
|
||||
if (err.error != QJsonParseError::NoError || !doc.isObject()) return;
|
||||
|
||||
QJsonObject obj = doc.object();
|
||||
m_lastCheckDate = obj.value("lastCheckDate").toString();
|
||||
m_lastKnownRemoteVersion = obj.value("latestRemoteVersion").toString();
|
||||
}
|
||||
|
||||
void UpdateManager::saveState(const QString& remoteVersion) {
|
||||
QJsonObject obj;
|
||||
obj["lastCheckDate"] = QDateTime::currentDateTime().toString(Qt::ISODate);
|
||||
obj["latestRemoteVersion"] = remoteVersion;
|
||||
|
||||
QString path = stateFilePath();
|
||||
QDir().mkpath(QFileInfo(path).absolutePath());
|
||||
|
||||
QFile file(path);
|
||||
if (!file.open(QIODevice::WriteOnly)) return;
|
||||
file.write(QJsonDocument(obj).toJson(QJsonDocument::Indented));
|
||||
}
|
||||
|
||||
void UpdateManager::runShell(const QString& script, const QString& workingDir) {
|
||||
m_process.setWorkingDirectory(workingDir);
|
||||
m_process.setProcessChannelMode(QProcess::MergedChannels);
|
||||
#if defined(Q_OS_WIN)
|
||||
m_process.start("cmd.exe", QStringList{"/C", script});
|
||||
#else
|
||||
m_process.start("/bin/sh", QStringList{"-c", script});
|
||||
#endif
|
||||
}
|
||||
|
||||
void UpdateManager::checkForUpdates() {
|
||||
QNetworkRequest request{QUrl(QString::fromLatin1(kApiUrl))};
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader,
|
||||
QString("PacManager/%1").arg(currentVersion()));
|
||||
|
||||
QNetworkReply* reply = m_network.get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
||||
reply->deleteLater();
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
emit checkFinished(false, QString(),
|
||||
QStringLiteral("Impossible de contacter le serveur : %1")
|
||||
.arg(reply->errorString()));
|
||||
return;
|
||||
}
|
||||
|
||||
const QByteArray data = reply->readAll();
|
||||
QJsonParseError err;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(data, &err);
|
||||
if (err.error != QJsonParseError::NoError || !doc.isObject()) {
|
||||
emit checkFinished(false, QString(),
|
||||
QStringLiteral("Réponse du serveur invalide."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Gitea returns the release tag (e.g. "V1.2.1") as `tag_name`.
|
||||
QString tag = doc.object().value("tag_name").toString().trimmed();
|
||||
if (tag.isEmpty()) {
|
||||
emit checkFinished(false, QString(),
|
||||
QStringLiteral("Aucune release trouvée sur le serveur."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Normalise tags like "V1.2.1" or "v1.2.1" to "1.2.1" for comparison.
|
||||
if (tag.startsWith('v') || tag.startsWith('V')) {
|
||||
tag = tag.mid(1);
|
||||
}
|
||||
|
||||
saveState(tag);
|
||||
|
||||
bool hasUpdate = isNewerVersion(tag, currentVersion());
|
||||
m_lastKnownRemoteVersion = tag;
|
||||
m_latestVersion = tag;
|
||||
emit checkFinished(hasUpdate, tag, QString());
|
||||
});
|
||||
}
|
||||
|
||||
bool UpdateManager::isNewerVersion(const QString& remote, const QString& local) {
|
||||
// Simple dotted numeric comparison ("1.10.2" > "1.9.1"). Non-numeric
|
||||
// components are treated as 0 so pre-release tags stay comparable.
|
||||
auto parts = [](const QString& v) {
|
||||
QVector<int> out;
|
||||
for (const QString& chunk : v.split('.')) {
|
||||
bool ok = false;
|
||||
int n = chunk.toInt(&ok);
|
||||
out.append(ok ? n : 0);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const QVector<int> r = parts(remote);
|
||||
const QVector<int> l = parts(local);
|
||||
const int n = qMax(r.size(), l.size());
|
||||
for (int i = 0; i < n; ++i) {
|
||||
int ri = i < r.size() ? r[i] : 0;
|
||||
int li = i < l.size() ? l[i] : 0;
|
||||
if (ri != li) return ri > li;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pulls the latest source and rebuilds the app in the background. The script
|
||||
// exits with a non-zero code on failure so the caller can report it. The new
|
||||
// binary replaces the old one only when the build completes — the currently
|
||||
// running process is untouched and picks it up on its next launch.
|
||||
void UpdateManager::performSelfUpdate() {
|
||||
if (m_repoPath.isEmpty()) {
|
||||
emit selfUpdateFinished(false, QStringLiteral("Dépôt source introuvable."));
|
||||
return;
|
||||
}
|
||||
|
||||
QString script = QStringLiteral(
|
||||
"set -e\n"
|
||||
"echo 'Mise à jour de PacManager...'\n"
|
||||
"git pull --ff-only origin main 2>&1 || git pull --ff-only 2>&1\n"
|
||||
"if [ -d build ]; then\n"
|
||||
" cmake --build build -j$(nproc) 2>&1\n"
|
||||
"else\n"
|
||||
" cmake -B build -DCMAKE_BUILD_TYPE=Release . 2>&1\n"
|
||||
" cmake --build build -j$(nproc) 2>&1\n"
|
||||
"fi\n"
|
||||
"echo 'Mise à jour terminée. Redémarrez PacManager pour utiliser la nouvelle version.'");
|
||||
|
||||
runShell(script, m_repoPath);
|
||||
}
|
||||
Reference in new issue
Block a user