426 lines
17 KiB
C++
426 lines
17 KiB
C++
#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();
|
|
|
|
// Detect a source checkout around the running executable so the dev
|
|
// workflow (git pull + rebuild in place) keeps working. Supported
|
|
// layouts: <repo>/build/PacManager and <repo>/build/<cfg>/PacManager.
|
|
const QDir appDir(QCoreApplication::applicationDirPath());
|
|
QDir dir = appDir;
|
|
for (int i = 0; i < 3; ++i) {
|
|
if (dir.exists(QLatin1String("CMakeLists.txt")) &&
|
|
dir.exists(QLatin1String("src/main.cpp"))) {
|
|
m_repoPath = dir.absolutePath();
|
|
break;
|
|
}
|
|
if (!dir.cdUp()) break;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
QString UpdateManager::tarballUrl() const {
|
|
return m_tarballUrl;
|
|
}
|
|
|
|
QString UpdateManager::prebuiltUrl() const {
|
|
return m_prebuiltUrl;
|
|
}
|
|
|
|
bool UpdateManager::hasPrebuiltUpdate() const {
|
|
return !m_prebuiltUrl.isEmpty();
|
|
}
|
|
|
|
QString UpdateManager::releasePageUrl() const {
|
|
return m_releasePageUrl;
|
|
}
|
|
|
|
// Pre-flight: which tools would a source rebuild need that are missing?
|
|
// A prebuilt archive only needs a downloader + tar (curl/wget handled in
|
|
// the script); the source path additionally needs cmake + a C++ compiler.
|
|
QStringList UpdateManager::missingSelfUpdateTools() const {
|
|
if (!m_repoPath.isEmpty()) return {};
|
|
if (!m_prebuiltUrl.isEmpty()) return {};
|
|
QStringList missing;
|
|
auto have = [](const char* tool) {
|
|
return QProcess::execute("/bin/sh", {"-c", QString("command -v %1 >/dev/null 2>&1").arg(tool)}) == 0;
|
|
};
|
|
if (!have("cmake")) missing << "cmake";
|
|
if (!have("g++") && !have("c++") && !have("clang++")) missing << "g++";
|
|
return missing;
|
|
}
|
|
|
|
QString UpdateManager::installPrefix() const {
|
|
// Infer the install prefix from the running binary location:
|
|
// <prefix>/bin/PacManager -> <prefix>. Falls back to ~/.local.
|
|
QDir dir(QCoreApplication::applicationDirPath());
|
|
if (dir.dirName() == QLatin1String("bin")) {
|
|
dir.cdUp();
|
|
return dir.absolutePath();
|
|
}
|
|
return QDir::homePath() + "/.local";
|
|
}
|
|
|
|
bool UpdateManager::canSelfUpdate() const {
|
|
if (!m_repoPath.isEmpty()) {
|
|
QDir repo(m_repoPath);
|
|
if (!repo.exists(QLatin1String(".git"))) {
|
|
return !m_prebuiltUrl.isEmpty() || !m_tarballUrl.isEmpty();
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
}
|
|
}
|
|
// Installed mode: a prebuilt archive or tarball needs no git checkout.
|
|
return !m_prebuiltUrl.isEmpty() || !m_tarballUrl.isEmpty();
|
|
}
|
|
|
|
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`.
|
|
// Keep the tarball + release page so an installed app (no git
|
|
// checkout) can still self-update by downloading the sources.
|
|
const QJsonObject obj = doc.object();
|
|
QString tag = obj.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);
|
|
}
|
|
|
|
// Prefer the prebuilt binary archive (no compiler needed on the user
|
|
// machine); fall back to an attached source archive, then to the
|
|
// auto-generated tarball Gitea always provides.
|
|
QString tarball = obj.value("tarball_url").toString().trimmed();
|
|
QString prebuilt;
|
|
const QJsonArray assets = obj.value("assets").toArray();
|
|
for (const QJsonValue& v : assets) {
|
|
const QJsonObject a = v.toObject();
|
|
const QString name = a.value("name").toString();
|
|
const QString dl = a.value("browser_download_url").toString().trimmed();
|
|
if (name.startsWith(QLatin1String("PacManager-"))
|
|
&& dl.endsWith(QLatin1String(".tar.gz"))) {
|
|
prebuilt = dl;
|
|
break;
|
|
}
|
|
}
|
|
if (prebuilt.isEmpty()) {
|
|
for (const QJsonValue& v : assets) {
|
|
const QString dl = v.toObject().value("browser_download_url").toString().trimmed();
|
|
if (dl.endsWith(QLatin1String(".tar.gz")) || dl.endsWith(QLatin1String(".zip"))) {
|
|
tarball = dl;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
m_tarballUrl = tarball;
|
|
m_prebuiltUrl = prebuilt;
|
|
m_releasePageUrl = obj.value("html_url").toString().trimmed();
|
|
if (m_releasePageUrl.isEmpty()) {
|
|
m_releasePageUrl = QStringLiteral("https://gitea.nocode-var.tech/FWS/FWS-PacManage/releases");
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
// Rebuilds + reinstalls the app in the background.
|
|
// - Source checkout present: git pull + rebuild in place.
|
|
// - Prebuilt archive attached: download + unpack straight to the prefix.
|
|
// - Otherwise: tarball download + compile in /tmp + reinstall to the prefix
|
|
// the running binary came from (sudo for system prefixes).
|
|
// The new binary takes effect at the next launch; the running process is
|
|
// untouched. Exits non-zero on failure so the caller can report it.
|
|
void UpdateManager::performSelfUpdate(const QString& sudoPassword) {
|
|
if (!m_repoPath.isEmpty()) {
|
|
QString script = QStringLiteral(
|
|
"set -e\n"
|
|
"echo 'Mise a 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"
|
|
"cmake --install build 2>&1\n"
|
|
"echo 'Mise a jour terminee.'");
|
|
|
|
runShell(script, m_repoPath);
|
|
return;
|
|
}
|
|
|
|
if (!m_prebuiltUrl.isEmpty()) {
|
|
performPrebuiltUpdate(sudoPassword);
|
|
return;
|
|
}
|
|
|
|
if (m_tarballUrl.isEmpty() || m_latestVersion.isEmpty()) {
|
|
emit selfUpdateFinished(false, QStringLiteral("Dépôt source introuvable."));
|
|
return;
|
|
}
|
|
performTarballUpdate(sudoPassword);
|
|
}
|
|
|
|
// Shared install command: plain when the prefix is writable, sudo otherwise
|
|
// (password piped when provided, interactive prompt otherwise).
|
|
QString UpdateManager::installCommand(const QString& quotedPassword,
|
|
const QString& action) const {
|
|
if (!quotedPassword.isEmpty()) {
|
|
// NOTE: single %s — QString::arg() only substitutes %1..%99.
|
|
return QStringLiteral("printf '%s\\n' %1 | sudo -S %2 2>&1\n")
|
|
.arg(quotedPassword, action);
|
|
}
|
|
if (QFileInfo(installPrefix()).isWritable()
|
|
|| QFileInfo(installPrefix() + "/bin").isWritable()) {
|
|
return action + QStringLiteral(" 2>&1\n");
|
|
}
|
|
return QStringLiteral("sudo %1 2>&1\n").arg(action);
|
|
}
|
|
|
|
QString UpdateManager::quoteShell(const QString& s) {
|
|
QString q = s;
|
|
q.replace(QLatin1String("'"), QLatin1String("'\\''"));
|
|
return QStringLiteral("'") + q + QStringLiteral("'");
|
|
}
|
|
|
|
QString UpdateManager::quotedPassword(const QString& sudoPassword) {
|
|
if (sudoPassword.isEmpty()) return {};
|
|
QString p = sudoPassword;
|
|
p.replace(QLatin1String("'"), QLatin1String("'\\''"));
|
|
return QStringLiteral("'") + p + QStringLiteral("'");
|
|
}
|
|
|
|
// Prebuilt path: unpack bin/ + plugins/ straight into the install prefix.
|
|
// Archive layout matches the release workflow (bin/, plugins/).
|
|
void UpdateManager::performPrebuiltUpdate(const QString& sudoPassword) {
|
|
QString script = QStringLiteral(
|
|
"set -e\n"
|
|
"echo 'Mise a jour de PacManager...'\n"
|
|
"WORK=$(mktemp -d /tmp/pacmanager-update-XXXXXX)\n"
|
|
"trap 'rm -rf \"$WORK\"' EXIT\n"
|
|
"URL=%1\n"
|
|
"PREFIX=%2\n"
|
|
"ARCHIVE=\"$WORK/update.tar.gz\"\n"
|
|
"if command -v curl >/dev/null; then curl -fsSL -o \"$ARCHIVE\" \"$URL\" 2>&1;\n"
|
|
"elif command -v wget >/dev/null; then wget -O \"$ARCHIVE\" \"$URL\" 2>&1;\n"
|
|
"else echo 'curl ou wget est requis'; exit 1; fi\n"
|
|
"tar xzf \"$ARCHIVE\" -C \"$WORK\" 2>&1\n"
|
|
"[ -x \"$WORK/bin/PacManager\" ] || { echo 'Archive invalide'; exit 1; }\n"
|
|
"mkdir -p \"$PREFIX/bin\"\n"
|
|
"cp \"$WORK/bin/PacManager\" \"$WORK/bin/version\" \"$PREFIX/bin/\" 2>&1 || %3\n"
|
|
"if [ -d \"$WORK/plugins\" ]; then\n"
|
|
" mkdir -p \"$PREFIX/bin/plugins\"\n"
|
|
" cp \"$WORK/plugins/\"*.so \"$PREFIX/bin/plugins/\" 2>/dev/null || true\n"
|
|
"fi\n"
|
|
"echo 'Mise a jour terminee.'");
|
|
QString fallback = installCommand(
|
|
quotedPassword(sudoPassword),
|
|
QStringLiteral("cp \"$WORK/bin/PacManager\" \"$WORK/bin/version\" \"$PREFIX/bin/\""));
|
|
script = script.arg(quoteShell(m_prebuiltUrl))
|
|
.arg(quoteShell(installPrefix()))
|
|
.arg(fallback);
|
|
runShell(script, QDir::homePath());
|
|
}
|
|
|
|
// Source path: fetch the tarball, compile in /tmp, reinstall to the prefix.
|
|
void UpdateManager::performTarballUpdate(const QString& sudoPassword) {
|
|
QString script = QStringLiteral(
|
|
"set -e\n"
|
|
"echo 'Mise a jour de PacManager...'\n"
|
|
"command -v cmake >/dev/null || { echo 'cmake requis (pacman -S cmake)'; exit 1; }\n"
|
|
"WORK=$(mktemp -d /tmp/pacmanager-update-XXXXXX)\n"
|
|
"trap 'rm -rf \"$WORK\"' EXIT\n"
|
|
"TARBALL_URL=%1\n"
|
|
"PREFIX=%2\n"
|
|
"ARCHIVE=\"$WORK/src.tar.gz\"\n"
|
|
"if command -v curl >/dev/null; then curl -fsSL -o \"$ARCHIVE\" \"$TARBALL_URL\" 2>&1;\n"
|
|
"elif command -v wget >/dev/null; then wget -O \"$ARCHIVE\" \"$TARBALL_URL\" 2>&1;\n"
|
|
"else echo 'curl ou wget est requis'; exit 1; fi\n"
|
|
"tar xzf \"$ARCHIVE\" -C \"$WORK\" 2>&1\n"
|
|
// NOTE: single %h — QString::arg() leaves %h untouched (only
|
|
// %1..%99 are placeholders), so find gets the correct -printf.
|
|
"SRC=$(find \"$WORK\" -maxdepth 2 -name CMakeLists.txt -printf '%h\\n' | head -n 1)\n"
|
|
"[ -n \"$SRC\" ] || { echo 'Archive invalide'; exit 1; }\n"
|
|
"cmake -S \"$SRC\" -B \"$WORK/build\" -DCMAKE_BUILD_TYPE=Release 2>&1\n"
|
|
"cmake --build \"$WORK/build\" -j$(nproc) 2>&1\n"
|
|
"%3\n"
|
|
"echo 'Mise a jour terminee.'");
|
|
QString install = installCommand(
|
|
quotedPassword(sudoPassword),
|
|
QStringLiteral("cmake --install \"$WORK/build\" --prefix \"$PREFIX\""));
|
|
script = script.arg(quoteShell(m_tarballUrl))
|
|
.arg(quoteShell(installPrefix()))
|
|
.arg(install);
|
|
runShell(script, QDir::homePath());
|
|
} |