commit 24e1f3b376382b3894a368563a806257ac8e57ad Author: Carlo Baratto Date: Wed Oct 28 09:12:34 2026 +0100 harbour-server 0.1.0: schermata parametri server (schema status/1) Prima release dell'app Sailfish: schermata unica con CPU, memoria, disco, container, backup, servizi, SSH, aggiornamenti e VPN, letti da un endpoint read-only /v1/status. Soglie giallo/rosso, aggiornamento ogni 60 s, copertina, impostazioni con indirizzo e token. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..79b7043 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Artefatti di build (rigenerati da build-rpm.sh) +*.o +moc_*.cpp +qrc_*.cpp +Makefile +documentation.list +harbour-server +*.qm +RPMS/ +.sfdk/ + +# Tarball sorgente generati dallo spec (Source0) +rpm/*.tar.gz diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb3108a --- /dev/null +++ b/README.md @@ -0,0 +1,65 @@ +# harbour-server + +App **Sailfish OS** che mostra i parametri di un server Linux in **una sola +schermata**: CPU, memoria (RAM e swap), disco, container, backup, servizi in +errore, tentativi SSH, aggiornamenti e stato VPN. + +Sola lettura. Nessuna credenziale di sistema: legge un endpoint JSON +documentato, quindi funziona con qualunque host che parli lo stesso formato. + +## Il formato consumato + +`GET /v1/status` con header `X-Status-Token: ` → +JSON **schema `status/1`**. + +Il contratto è descritto nel progetto del collector: `statod/README.md`. +Il punto fermo: **ogni sezione può essere `null`** (collector fallito) e il +client non deve assumere la presenza di un campo. + +## Schermata + +Card impilate con valore, dettaglio e barra; soglie: verde, giallo all'85%, +rosso al 95%. Pull-to-refresh, aggiornamento automatico ogni 60 s, copertina +con la percentuale di CPU, badge rosso sulle card fuori soglia. + +## Build + +```sh +cd .. && ./build-rpm.sh harbour-server +# RPM in pacchetti/rpm-SailfishOS-/harbour-server--1.aarch64.rpm +``` + +Requisiti: SDK Sailfish in `~/SailfishOS`, build engine Docker. + +## Installazione sul telefono + +```sh +devel-su rpm -Uvh harbour-server-0.1.0-1.aarch64.rpm +``` + +Poi, all'apertura: indicare indirizzo (es. `http://192.168.3.21:8792`) e token. +Il token si legge sul server con `cat ~/.config/statusd/token`. + +Fuori casa serve la VPN attiva: la porta **8792** è aperta solo da LAN e +WireGuard, non da Internet. + +## Note + +- Le impostazioni vivono in `~/.config/harbour/server/server.conf` (zona + persistente della sandbox SailJail, dichiarata in `X-Sailjail`). +- Il token è salvato in chiaro in quel file: è una credenziale di sola lettura + su una porta raggiungibile solo via LAN/VPN. +- Timeout di rete a 8 s con watchdog: `QNetworkAccessManager` non applica + timeout e senza watchdog la UI resterebbe in attesa per sempre. + +## Struttura + +``` +src/statusclient.* fetch + parsing JSON, watchdog, formattazione (locale it) +src/settings.* indirizzo e token +qml/pages/ StatusPage (le card), SettingsPage +qml/components/ MetricCard +qml/cover/ copertina +rpm/ spec + desktop file (SailJail: Internet) +scripts/make_icons.py +``` diff --git a/harbour-server.pro b/harbour-server.pro new file mode 100644 index 0000000..4abf39b --- /dev/null +++ b/harbour-server.pro @@ -0,0 +1,37 @@ +TEMPLATE = app +TARGET = harbour-server + +CONFIG += sailfishapp +CONFIG += c++11 + +QT += network + +SOURCES += \ + src/main.cpp \ + src/settings.cpp \ + src/statusclient.cpp + +HEADERS += \ + src/settings.h \ + src/statusclient.h + +OTHER_FILES += \ + qml/harbour-server.qml \ + qml/pages/*.qml \ + qml/components/*.qml \ + qml/cover/*.qml \ + rpm/harbour-server.spec \ + rpm/harbour-server.desktop + +DISTFILES += $$OTHER_FILES + +# Icone installate via make install (struttura standard hicolor) +icons86.path = /usr/share/icons/hicolor/86x86/apps +icons86.files = $$PWD/icons/86x86/harbour-server.png +icons108.path = /usr/share/icons/hicolor/108x108/apps +icons108.files = $$PWD/icons/108x108/harbour-server.png +icons128.path = /usr/share/icons/hicolor/128x128/apps +icons128.files = $$PWD/icons/128x128/harbour-server.png +icons172.path = /usr/share/icons/hicolor/172x172/apps +icons172.files = $$PWD/icons/172x172/harbour-server.png +INSTALLS += icons86 icons108 icons128 icons172 diff --git a/icons/108x108/harbour-server.png b/icons/108x108/harbour-server.png new file mode 100644 index 0000000..d6c0418 Binary files /dev/null and b/icons/108x108/harbour-server.png differ diff --git a/icons/128x128/harbour-server.png b/icons/128x128/harbour-server.png new file mode 100644 index 0000000..2858a36 Binary files /dev/null and b/icons/128x128/harbour-server.png differ diff --git a/icons/172x172/harbour-server.png b/icons/172x172/harbour-server.png new file mode 100644 index 0000000..0448e7b Binary files /dev/null and b/icons/172x172/harbour-server.png differ diff --git a/icons/86x86/harbour-server.png b/icons/86x86/harbour-server.png new file mode 100644 index 0000000..530d77b Binary files /dev/null and b/icons/86x86/harbour-server.png differ diff --git a/qml/components/MetricCard.qml b/qml/components/MetricCard.qml new file mode 100644 index 0000000..d6f1ac7 --- /dev/null +++ b/qml/components/MetricCard.qml @@ -0,0 +1,79 @@ +import QtQuick 2.0 +import Sailfish.Silica 1.0 +import "../components" + +// Un parametro in una card: titolo a sinistra, valore a destra, riga di +// dettaglio e barra opzionale. level: 0 = ok, 1 = attenzione, 2 = critico. +Rectangle { + id: card + + property string title + property string value + property string detail + property real progress: -1 + property int level: 0 + + function levelColor() { + if (level === 2) return "#e53935" + if (level === 1) return "#ffb300" + return "#43a047" + } + + width: parent ? parent.width : 0 + height: content.height + 2 * Theme.paddingMedium + radius: Theme.paddingSmall + color: Theme.rgba(Theme.highlightBackgroundColor, 0.08) + + Column { + id: content + x: Theme.paddingMedium + y: Theme.paddingMedium + width: parent.width - 2 * Theme.paddingMedium + spacing: Theme.paddingSmall / 2 + + Row { + width: parent.width + + Label { + text: card.title + font.pixelSize: Theme.fontSizeSmall + color: Theme.secondaryColor + width: parent.width * 0.55 + truncationMode: TruncationMode.Fade + } + + Label { + text: card.value + font.pixelSize: Theme.fontSizeMedium + color: card.level === 0 ? Theme.primaryColor : card.levelColor() + horizontalAlignment: Text.AlignRight + width: parent.width * 0.45 + truncationMode: TruncationMode.Fade + } + } + + Label { + text: card.detail + visible: card.detail !== "" + font.pixelSize: Theme.fontSizeExtraSmall + color: Theme.secondaryColor + width: parent.width + wrapMode: Text.WordWrap + } + + Rectangle { + visible: card.progress >= 0 + width: parent.width + height: 4 + radius: 2 + color: Theme.rgba(Theme.primaryColor, 0.15) + + Rectangle { + width: parent.width * Math.max(0, Math.min(100, card.progress)) / 100 + height: parent.height + radius: 2 + color: card.levelColor() + } + } + } +} diff --git a/qml/cover/CoverPage.qml b/qml/cover/CoverPage.qml new file mode 100644 index 0000000..f2548ee --- /dev/null +++ b/qml/cover/CoverPage.qml @@ -0,0 +1,52 @@ +import QtQuick 2.0 +import Sailfish.Silica 1.0 + +CoverBackground { + id: cover + + // Guardie: quando lo snapshot non è ancora arrivato i campi mancano e in + // JS leggere una proprietà di undefined solleva un'eccezione. + function num(v, fallback) { + return (v === undefined || v === null) ? fallback : v + } + + Column { + anchors.centerIn: parent + width: parent.width - 2 * Theme.paddingLarge + spacing: Theme.paddingSmall + + Label { + text: "Server" + font.pixelSize: Theme.fontSizeSmall + color: Theme.secondaryColor + anchors.horizontalCenter: parent.horizontalCenter + } + + Label { + text: statusClient.error !== "" ? "—" : statusClient.fmtNum(num(statusClient.data.cpu ? statusClient.data.cpu.percent : undefined, -1), 0) + " %" + font.pixelSize: Theme.fontSizeExtraLarge + anchors.horizontalCenter: parent.horizontalCenter + } + + Label { + text: "CPU" + font.pixelSize: Theme.fontSizeExtraSmall + color: Theme.secondaryColor + anchors.horizontalCenter: parent.horizontalCenter + } + + Label { + text: statusClient.fetchedAt !== "" ? statusClient.fetchedAt : "" + font.pixelSize: Theme.fontSizeExtraSmall + color: Theme.secondaryColor + anchors.horizontalCenter: parent.horizontalCenter + } + } + + CoverActionList { + CoverAction { + iconSource: "image://theme/icon-cover-refresh" + onTriggered: statusClient.refresh() + } + } +} diff --git a/qml/harbour-server.qml b/qml/harbour-server.qml new file mode 100644 index 0000000..3ab6044 --- /dev/null +++ b/qml/harbour-server.qml @@ -0,0 +1,10 @@ +import QtQuick 2.0 +import Sailfish.Silica 1.0 +import "pages" + +ApplicationWindow { + objectName: "applicationWindow" + initialPage: Component { StatusPage { } } + cover: Qt.resolvedUrl("cover/CoverPage.qml") + allowedOrientations: defaultAllowedOrientations +} diff --git a/qml/pages/SettingsPage.qml b/qml/pages/SettingsPage.qml new file mode 100644 index 0000000..428822e --- /dev/null +++ b/qml/pages/SettingsPage.qml @@ -0,0 +1,79 @@ +import QtQuick 2.0 +import Sailfish.Silica 1.0 + +Page { + id: page + + Column { + anchors.fill: parent + spacing: Theme.paddingMedium + + PageHeader { + title: qsTr("Impostazioni") + } + + TextField { + id: urlField + anchors.left: parent.left + anchors.right: parent.right + anchors.leftMargin: Theme.paddingLarge + anchors.rightMargin: Theme.paddingLarge + label: qsTr("Indirizzo del server") + placeholderText: "http://192.168.3.21:8792" + text: appSettings.baseUrl + inputMethodHints: Qt.ImhUrlCharactersOnly | Qt.ImhNoPredictiveText + } + + TextField { + id: tokenField + anchors.left: parent.left + anchors.right: parent.right + anchors.leftMargin: Theme.paddingLarge + anchors.rightMargin: Theme.paddingLarge + label: qsTr("Token") + placeholderText: qsTr("incolla il token del server") + text: appSettings.token + echoMode: TextInput.Password + inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase + } + + Label { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + font.pixelSize: Theme.fontSizeExtraSmall + color: Theme.secondaryColor + wrapMode: Text.WordWrap + text: qsTr("Il token è il contenuto di ~/.config/statusd/token sul server. " + + "Fuori casa serve la VPN attiva: la porta 8792 è chiusa su Internet.") + } + + Button { + anchors.horizontalCenter: parent.horizontalCenter + text: qsTr("Salva e verifica") + onClicked: { + appSettings.save(urlField.text, tokenField.text) + statusClient.refresh() + } + } + + Label { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + visible: statusClient.error !== "" + text: statusClient.error + font.pixelSize: Theme.fontSizeSmall + color: "#e53935" + wrapMode: Text.WordWrap + } + + Label { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + visible: statusClient.error === "" && statusClient.fetchedAt !== "" + text: qsTr("Risposta ricevuta alle ") + statusClient.fetchedAt + font.pixelSize: Theme.fontSizeSmall + color: "#43a047" + wrapMode: Text.WordWrap + } + } +} diff --git a/qml/pages/StatusPage.qml b/qml/pages/StatusPage.qml new file mode 100644 index 0000000..2694922 --- /dev/null +++ b/qml/pages/StatusPage.qml @@ -0,0 +1,231 @@ +import QtQuick 2.0 +import Sailfish.Silica 1.0 +import "../components" + +Page { + id: page + + // ── Letture difensive dello snapshot ────────────────────────────────── + // Il JSON arriva da un altro processo: ogni campo può mancare. In JS + // leggere una proprietà di undefined solleva un'eccezione, quindi si + // passa sempre da queste funzioni. + function cpuPct() { var d = statusClient.data; return (d && d.cpu && d.cpu.percent !== undefined) ? d.cpu.percent : -1 } + function cpuTemp() { var d = statusClient.data; return (d && d.cpu && d.cpu.temp_c !== undefined) ? d.cpu.temp_c : -1 } + function cpuCores() { var d = statusClient.data; return (d && d.cpu && d.cpu.cores !== undefined) ? d.cpu.cores : 0 } + function memPercent() { var d = statusClient.data; return (d && d.memory && d.memory.percent !== undefined) ? d.memory.percent : -1 } + function memText() { + var d = statusClient.data + if (!d || !d.memory) return "" + return statusClient.fmtBytes(d.memory.used_bytes) + " / " + statusClient.fmtBytes(d.memory.total_bytes) + } + function swapPercent() { + var d = statusClient.data + if (!d || !d.memory || !d.memory.swap_total_bytes) return 0 + return 100 * d.memory.swap_used_bytes / d.memory.swap_total_bytes + } + function disk() { var d = statusClient.data; return (d && d.disks && d.disks.length > 0) ? d.disks[0] : null } + function diskPct() { var x = disk(); return x ? x.percent : -1 } + function diskText() { var x = disk(); return x ? statusClient.fmtBytes(x.used_bytes) + " / " + statusClient.fmtBytes(x.total_bytes) : "" } + function containers() { var d = statusClient.data; return (d && d.containers && d.containers.running) ? d.containers.running : [] } + function containersBad() { + var list = containers(), n = 0, i + for (i = 0; i < list.length; i++) if (!list[i].ok) n++ + return n + } + function containersText() { + var list = containers(), names = [], i + for (i = 0; i < list.length; i++) names.push(list[i].name) + return names.join(", ") + } + function backupAge() { var d = statusClient.data; return (d && d.backups && d.backups.age_hours !== null && d.backups.age_hours !== undefined) ? d.backups.age_hours : -1 } + function backupResult() { var d = statusClient.data; return (d && d.backups && d.backups.result) ? d.backups.result : "" } + function backupLevel() { + if (backupResult() === "") return 1 + if (backupResult() !== "success") return 2 + var age = backupAge() + if (age < 0) return 1 + if (age > 72) return 2 + if (age > 36) return 1 + return 0 + } + function failedServices() { var d = statusClient.data; return (d && d.services && d.services.failed) ? d.services.failed.length : 0 } + function sshFailed() { var d = statusClient.data; return (d && d.access && d.access.ssh_failed_24h !== undefined) ? d.access.ssh_failed_24h : 0 } + function updatesTotal() { var d = statusClient.data; return (d && d.updates && d.updates.total !== undefined) ? d.updates.total : 0 } + function updatesSecurity() { var d = statusClient.data; return (d && d.updates && d.updates.security !== undefined) ? d.updates.security : 0 } + function vpnText() { + var d = statusClient.data + if (!d || !d.net || !d.net.interfaces || d.net.interfaces.length === 0) return "nessuna" + return d.net.interfaces.join(", ") + } + function hostText() { + var d = statusClient.data + if (!d || !d.host) return "" + var s = d.host.hostname + if (d.host.uptime_s) s = s + " · attivo da " + statusClient.fmtUptime(d.host.uptime_s) + return s + } + function levelFor(percent, warn, bad) { + if (percent < 0) return 0 + if (percent >= bad) return 2 + if (percent >= warn) return 1 + return 0 + } + + SilicaFlickable { + anchors.fill: parent + contentHeight: column.height + Theme.paddingLarge + + PullDownMenu { + MenuItem { + text: qsTr("Aggiorna") + onClicked: statusClient.refresh() + } + MenuItem { + text: qsTr("Impostazioni") + onClicked: pageStack.push(Qt.resolvedUrl("SettingsPage.qml")) + } + } + + Column { + id: column + width: parent.width + spacing: Theme.paddingMedium + + PageHeader { title: qsTr("Stato server") } + + Label { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + text: hostText() + visible: text !== "" + font.pixelSize: Theme.fontSizeExtraSmall + color: Theme.secondaryColor + truncationMode: TruncationMode.Fade + } + + // Nessun server configurato: un solo comando, nel menu. + Label { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + visible: !statusClient.configured + text: qsTr("Nessun server configurato. Menu in alto → Impostazioni.") + font.pixelSize: Theme.fontSizeSmall + color: Theme.highlightColor + wrapMode: Text.WordWrap + } + + // Errore visibile: senza questo la schermata resta vuota e muta. + Label { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + visible: statusClient.error !== "" + text: statusClient.error + font.pixelSize: Theme.fontSizeSmall + color: "#e53935" + wrapMode: Text.WordWrap + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("CPU") + value: cpuPct() < 0 ? "—" : statusClient.fmtNum(cpuPct(), 0) + " %" + detail: (cpuTemp() >= 0 ? statusClient.fmtNum(cpuTemp(), 0) + " °C · " : "") + cpuCores() + " core" + progress: cpuPct() + level: levelFor(cpuPct(), 85, 95) + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("Memoria") + value: memPercent() < 0 ? "—" : statusClient.fmtNum(memPercent(), 0) + " %" + detail: memText() + " · swap " + statusClient.fmtNum(swapPercent(), 0) + " %" + progress: memPercent() + level: Math.max(levelFor(memPercent(), 85, 95), levelFor(swapPercent(), 80, 95)) + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("Disco") + (disk() ? " " + disk().mount : "") + value: diskPct() < 0 ? "—" : statusClient.fmtNum(diskPct(), 0) + " %" + detail: diskText() + progress: diskPct() + level: levelFor(diskPct(), 85, 95) + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("Container") + value: containers().length + " " + qsTr("attivi") + detail: containersText() + progress: -1 + level: containersBad() > 0 ? 2 : 0 + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("Backup") + value: backupAge() < 0 ? "—" : statusClient.fmtAge(backupAge()) + detail: backupResult() === "" ? qsTr("nessun dato") : "borg · " + backupResult() + progress: -1 + level: backupLevel() + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("Servizi") + value: failedServices() === 0 ? qsTr("tutti attivi") : failedServices() + " " + qsTr("in errore") + detail: "" + progress: -1 + level: failedServices() > 0 ? 2 : 0 + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("SSH") + value: sshFailed() + " " + qsTr("tentativi") + detail: qsTr("password fallite nelle ultime 24 h") + progress: -1 + level: sshFailed() >= 200 ? 2 : (sshFailed() >= 50 ? 1 : 0) + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("Aggiornamenti") + value: updatesTotal() === 0 ? qsTr("nessuno") : String(updatesTotal()) + detail: qsTr("di cui di sicurezza: ") + updatesSecurity() + progress: -1 + level: updatesSecurity() > 0 ? 1 : 0 + } + + MetricCard { + x: Theme.paddingLarge + width: parent.width - 2 * Theme.paddingLarge + title: qsTr("VPN") + value: vpnText() + detail: statusClient.fetchedAt !== "" ? qsTr("aggiornato alle ") + statusClient.fetchedAt : "" + progress: -1 + level: vpnText() === qsTr("nessuna") ? 2 : 0 + } + } + + VerticalScrollDecorator { } + } + + // Aggiornamento automatico: lo snapshot sul server è rigenerato ogni 60 s. + Timer { + interval: 60000 + running: true + repeat: true + onTriggered: statusClient.refresh() + } + + Component.onCompleted: statusClient.refresh() +} diff --git a/rpm/harbour-server.desktop b/rpm/harbour-server.desktop new file mode 100644 index 0000000..c86a188 --- /dev/null +++ b/rpm/harbour-server.desktop @@ -0,0 +1,20 @@ +[Desktop Entry] +Name=Server +Name[it_IT]=Server +Comment=Server parameters on one screen +Comment[it_IT]=Parametri del server in una schermata +Exec=harbour-server +Icon=harbour-server +Type=Application +X-Nemo-Application-Type=silica-qt5 +Categories=System;Monitor; + +# Profilo SailJail esplicito: senza X-Sailjail la sandbox di Sailfish 5.1 usa +# il profilo default, che nasconde ~/.config/harbour (config non persistente). +# Org/App dichiarati QUI (letti dalla sandbox) e nel main.cpp (letti da +# QStandardPaths): AppConfigLocation = ~/.config/harbour/server (persistente). +# Internet = collector statusd (LAN o VPN). +[X-Sailjail] +Permissions=Internet +OrganizationName=harbour +ApplicationName=server diff --git a/rpm/harbour-server.spec b/rpm/harbour-server.spec new file mode 100644 index 0000000..fa65b7b --- /dev/null +++ b/rpm/harbour-server.spec @@ -0,0 +1,62 @@ +Name: harbour-server +Summary: Parametri del server in una schermata +Version: 0.1.0 +Release: 1 +Group: Qt/Qt +License: MIT +URL: https://git.hackatoniclife.com/kaneda/harbour-server +Source0: %{name}-%{version}.tar.gz +Source1: %{name}.desktop + +Requires: sailfishsilica-qt5 >= 0.10.9 +BuildRequires: pkgconfig(sailfishapp) >= 1.0.2 +BuildRequires: pkgconfig(Qt5Core) +BuildRequires: pkgconfig(Qt5Qml) +BuildRequires: pkgconfig(Qt5Quick) +BuildRequires: pkgconfig(Qt5Network) +BuildRequires: desktop-file-utils + +%description +Client read-only per il collector statusd: CPU, memoria, disco, container, +backup, servizi in errore, tentativi SSH e aggiornamenti del server in una +schermata sola. Il formato consumato (schema status/1) non dipende dalla +macchina: qualunque host che serva lo stesso JSON funziona senza modifiche. + +%changelog +* Tue Oct 27 2026 Carlo Baratto - 0.1.0-1 +- Prima release: schermata unica con i parametri del server letti da + /v1/status (schema status/1), soglie giallo/rosso, aggiornamento + automatico ogni 60 s, copertina con la CPU e pull-to-refresh; + impostazioni con indirizzo e token, salvate in ~/.config/harbour/server + +%prep +%setup -q -n %{name}-%{version} + +%build +%qmake5 +make %{?_smp_mflags} + +%install +make install INSTALL_ROOT=%{buildroot} +mkdir -p %{buildroot}%{_datadir}/applications +# Desktop file cercato in modo robusto: sfdk usa i sorgenti live (shadow build) +# e la directory sorgente puo' chiamarsi %{name}-%{version} (tarball) o +# %{name} (clone); %{SOURCE1} e' il fallback. +DESKTOP=$(find %{_builddir}/.. -maxdepth 4 -name '%{name}.desktop' 2>/dev/null | head -1) +if [ -z "$DESKTOP" ] && [ -f %{SOURCE1} ]; then DESKTOP=%{SOURCE1}; fi +if [ -z "$DESKTOP" ]; then + echo "ERROR: %{name}.desktop not found" >&2 + exit 1 +fi +install -m 0644 "$DESKTOP" %{buildroot}%{_datadir}/applications/%{name}.desktop +desktop-file-validate %{buildroot}%{_datadir}/applications/%{name}.desktop || true + +%files +%defattr(-,root,root,-) +%{_bindir}/%{name} +%{_datadir}/applications/%{name}.desktop +%{_datadir}/icons/hicolor/86x86/apps/%{name}.png +%{_datadir}/icons/hicolor/108x108/apps/%{name}.png +%{_datadir}/icons/hicolor/128x128/apps/%{name}.png +%{_datadir}/icons/hicolor/172x172/apps/%{name}.png +%{_datadir}/%{name}/qml diff --git a/scripts/make_icons.py b/scripts/make_icons.py new file mode 100644 index 0000000..58cf9f9 --- /dev/null +++ b/scripts/make_icons.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Genera le icone di harbour-server (86/108/128/172 px). + +Motivo: piastrina scura con una traccia "battito" verde — lo stesso segno +che l'app mostra quando tutto è in ordine. +""" +from pathlib import Path + +from PIL import Image, ImageDraw + +ROOT = Path(__file__).resolve().parent.parent +SIZES = (86, 108, 128, 172) +BG = (20, 24, 28) +TRACE = (67, 160, 71) +DIM = (110, 120, 128) + +# Traccia in coordinate 0..100 (x, y): parte piatta, picco, coda piatta. +TRACE_POINTS = [ + (6, 52), (30, 52), (38, 30), (46, 74), (54, 44), (62, 52), (94, 52), +] + + +def draw(size: int) -> Image.Image: + scale = 4 # disegno in grande e riduco: linee pulite anche a 86 px + S = size * scale + img = Image.new("RGBA", (S, S), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + + radius = int(S * 0.22) + d.rounded_rectangle([0, 0, S - 1, S - 1], radius=radius, fill=BG) + + pts = [(int(x * S / 100), int(y * S / 100)) for x, y in TRACE_POINTS] + width = max(2, int(S * 0.045)) + d.line(pts, fill=TRACE, width=width, joint="curve") + + # Tre tacche in basso: i "parametri" sotto la traccia. + for i, x in enumerate((22, 50, 78)): + y0 = int(S * 0.78) + h = int(S * (0.10 + 0.04 * i)) + d.rounded_rectangle( + [int(x * S / 100) - width, y0 - h, int(x * S / 100) + width, y0], + radius=width, + fill=DIM, + ) + + return img.resize((size, size), Image.LANCZOS) + + +def main() -> None: + for size in SIZES: + out = ROOT / "icons" / f"{size}x{size}" + out.mkdir(parents=True, exist_ok=True) + path = out / "harbour-server.png" + draw(size).save(path) + print("scritto", path) + + +if __name__ == "__main__": + main() diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..6013672 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#include "settings.h" +#include "statusclient.h" + +Q_DECL_EXPORT int main(int argc, char *argv[]) +{ + QGuiApplication *app = SailfishApp::application(argc, argv); + + // Identita' allineata al profilo X-Sailjail del desktop file: + // AppConfigLocation = ~/.config/harbour/server (zona persistente). + app->setOrganizationName(QStringLiteral("harbour")); + app->setApplicationName(QStringLiteral("server")); + app->setApplicationVersion(QStringLiteral("0.1.0")); + + qDebug() << "harbour-server v0.1.0 build" << __DATE__ << __TIME__; + + Settings settings; + StatusClient status(&settings); + + QQuickView *view = SailfishApp::createView(); + view->rootContext()->setContextProperty(QStringLiteral("appSettings"), &settings); + view->rootContext()->setContextProperty(QStringLiteral("statusClient"), &status); + view->setSource(SailfishApp::pathTo(QStringLiteral("qml/harbour-server.qml"))); + view->show(); + + return app->exec(); +} diff --git a/src/settings.cpp b/src/settings.cpp new file mode 100644 index 0000000..f299dc7 --- /dev/null +++ b/src/settings.cpp @@ -0,0 +1,71 @@ +#include "settings.h" + +#include +#include +#include + +static const char *kKeyBaseUrl = "server/baseUrl"; +static const char *kKeyToken = "server/token"; + +QString Settings::configPath() +{ + // AppConfigLocation = ~/.config/harbour/server con org=harbour, + // app=server (vedi main.cpp e X-Sailjail nel desktop file). Il QSettings + // "di default" scriverebbe in ~/.config/harbour/server.conf, FUORI dalla + // directory persistente della sandbox: le impostazioni andrebbero perse a + // ogni riavvio (bug gia' visto in harbour-hermes). + const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); + QDir().mkpath(dir); + return dir + QStringLiteral("/server.conf"); +} + +Settings::Settings(QObject *parent) + : QObject(parent) + , m_settings(configPath(), QSettings::IniFormat) +{ + m_baseUrl = m_settings.value(QLatin1String(kKeyBaseUrl)).toString(); + m_token = m_settings.value(QLatin1String(kKeyToken)).toString(); + qDebug() << "Settings file:" << m_settings.fileName(); + qDebug() << "Settings baseUrl=[" << m_baseUrl << "] token set:" << !m_token.isEmpty(); +} + +QString Settings::baseUrl() const +{ + return m_baseUrl; +} + +QString Settings::token() const +{ + return m_token; +} + +void Settings::setBaseUrl(const QString &value) +{ + QString v = value.trimmed(); + while (v.endsWith(QLatin1Char('/'))) + v.chop(1); + if (v == m_baseUrl) + return; + m_baseUrl = v; + m_settings.setValue(QLatin1String(kKeyBaseUrl), m_baseUrl); + m_settings.sync(); + emit baseUrlChanged(); +} + +void Settings::setToken(const QString &value) +{ + const QString v = value.trimmed(); + if (v == m_token) + return; + m_token = v; + m_settings.setValue(QLatin1String(kKeyToken), m_token); + m_settings.sync(); + emit tokenChanged(); +} + +void Settings::save(const QString &baseUrl, const QString &token) +{ + setBaseUrl(baseUrl); + setToken(token); + m_settings.sync(); +} diff --git a/src/settings.h b/src/settings.h new file mode 100644 index 0000000..0ed5608 --- /dev/null +++ b/src/settings.h @@ -0,0 +1,43 @@ +#ifndef SETTINGS_H +#define SETTINGS_H + +#include +#include +#include + +// Impostazioni dell'app. Nessun indirizzo compilato nel binario: il server si +// configura la prima volta che si apre l'app. +// +// Il file vive in AppConfigLocation (~/.config/harbour/server/server.conf), +// l'unica zona che la sandbox SailJail rende persistente quando org/app sono +// dichiarati sia nel main.cpp sia in X-Sailjail del desktop file. +class Settings : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString baseUrl READ baseUrl WRITE setBaseUrl NOTIFY baseUrlChanged) + Q_PROPERTY(QString token READ token WRITE setToken NOTIFY tokenChanged) + +public: + explicit Settings(QObject *parent = nullptr); + + QString baseUrl() const; + QString token() const; + + void setBaseUrl(const QString &value); + void setToken(const QString &value); + + Q_INVOKABLE void save(const QString &baseUrl, const QString &token); + +signals: + void baseUrlChanged(); + void tokenChanged(); + +private: + static QString configPath(); + + QSettings m_settings; + QString m_baseUrl; + QString m_token; +}; + +#endif // SETTINGS_H diff --git a/src/statusclient.cpp b/src/statusclient.cpp new file mode 100644 index 0000000..5745c1b --- /dev/null +++ b/src/statusclient.cpp @@ -0,0 +1,189 @@ +#include "statusclient.h" +#include "settings.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +static const int kTimeoutMs = 8000; + +StatusClient::StatusClient(Settings *settings, QObject *parent) + : QObject(parent) + , m_settings(settings) + , m_busy(false) +{ + m_watchdog.setSingleShot(true); + connect(&m_watchdog, SIGNAL(timeout()), this, SLOT(onTimeout())); +} + +QVariantMap StatusClient::data() const { return m_data; } +bool StatusClient::busy() const { return m_busy; } +QString StatusClient::error() const { return m_error; } +QString StatusClient::fetchedAt() const { return m_fetchedAt; } + +bool StatusClient::configured() const +{ + return !m_settings->baseUrl().trimmed().isEmpty(); +} + +void StatusClient::setBusy(bool value) +{ + if (m_busy == value) + return; + m_busy = value; + emit busyChanged(); +} + +void StatusClient::setError(const QString &message) +{ + if (m_error == message) + return; + m_error = message; + emit errorChanged(); + emit changed(); +} + +void StatusClient::clearReply() +{ + if (m_reply) { + m_reply->disconnect(this); + m_reply->deleteLater(); + m_reply = nullptr; + } + m_watchdog.stop(); +} + +void StatusClient::refresh() +{ + if (m_busy) + return; + + const QString base = m_settings->baseUrl().trimmed(); + if (base.isEmpty()) { + setError(tr("Indica l'indirizzo del server nelle impostazioni")); + return; + } + + const QUrl url(base + QStringLiteral("/v1/status")); + if (!url.isValid() || url.scheme().isEmpty() || url.host().isEmpty()) { + setError(tr("Indirizzo non valido: serve schema e host (es. http://192.168.3.21:8792)")); + return; + } + + QNetworkRequest request(url); + request.setRawHeader("Accept", "application/json"); + const QString token = m_settings->token().trimmed(); + if (!token.isEmpty()) + request.setRawHeader("X-Status-Token", token.toUtf8()); + + setError(QString()); + setBusy(true); + + m_reply = m_nam.get(request); + connect(m_reply, SIGNAL(finished()), this, SLOT(onFinished())); + m_watchdog.start(kTimeoutMs); + qDebug() << "[status] GET" << url.toString(); +} + +void StatusClient::onTimeout() +{ + if (!m_reply) + return; + qDebug() << "[status] timeout"; + clearReply(); + setBusy(false); + setError(tr("Server non raggiungibile (timeout)")); +} + +void StatusClient::onFinished() +{ + if (!m_reply) + return; + + QNetworkReply *reply = m_reply; + m_watchdog.stop(); + m_reply = nullptr; + reply->disconnect(this); + reply->deleteLater(); + + const int httpStatus = + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + + if (reply->error() != QNetworkReply::NoError) { + setBusy(false); + if (httpStatus == 401) + setError(tr("Token non valido: controlla le impostazioni")); + else if (httpStatus == 0) + setError(tr("Server non raggiungibile: %1").arg(reply->errorString())); + else + setError(tr("Errore dal server (HTTP %1)").arg(httpStatus)); + return; + } + + QJsonParseError parseError; + const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &parseError); + if (parseError.error != QJsonParseError::NoError || !doc.isObject()) { + setBusy(false); + setError(tr("Risposta non leggibile dal server")); + return; + } + + const QJsonObject obj = doc.object(); + const QString schema = obj.value(QStringLiteral("schema")).toString(); + if (!schema.startsWith(QStringLiteral("status/"))) { + setBusy(false); + setError(tr("Il server non parla il formato status (schema assente)")); + return; + } + + m_data = obj.toVariantMap(); + m_fetchedAt = QLocale::system().toString(QDateTime::currentDateTime(), QStringLiteral("HH:mm:ss")); + setBusy(false); + emit changed(); + emit busyChanged(); + qDebug() << "[status] ok, schema" << schema; +} + +QString StatusClient::fmtBytes(qint64 bytes) const +{ + const double gb = double(bytes) / (1024.0 * 1024.0 * 1024.0); + if (gb >= 1.0) + return QLocale::system().toString(gb, 'f', 1) + QStringLiteral(" GB"); + const double mb = double(bytes) / (1024.0 * 1024.0); + return QLocale::system().toString(mb, 'f', 0) + QStringLiteral(" MB"); +} + +QString StatusClient::fmtUptime(qint64 seconds) const +{ + if (seconds <= 0) + return QString(); + const qint64 days = seconds / 86400; + const qint64 hours = (seconds % 86400) / 3600; + const qint64 minutes = (seconds % 3600) / 60; + if (days > 0) + return tr("%1 g %2 h").arg(days).arg(hours); + if (hours > 0) + return tr("%1 h %2 min").arg(hours).arg(minutes); + return tr("%1 min").arg(minutes); +} + +QString StatusClient::fmtAge(double hours) const +{ + if (hours < 0) + return QString(); + if (hours < 1.0) + return tr("%1 min fa").arg(qMax(1, int(hours * 60.0))); + if (hours < 48.0) + return tr("%1 h fa").arg(QLocale::system().toString(hours, 'f', 1)); + return tr("%1 giorni fa").arg(QLocale::system().toString(hours / 24.0, 'f', 1)); +} + +QString StatusClient::fmtNum(double value, int decimals) const +{ + return QLocale::system().toString(value, 'f', decimals); +} diff --git a/src/statusclient.h b/src/statusclient.h new file mode 100644 index 0000000..ca63dee --- /dev/null +++ b/src/statusclient.h @@ -0,0 +1,70 @@ +#ifndef STATUSCLIENT_H +#define STATUSCLIENT_H + +#include +#include +#include +#include +#include +#include +#include + +class Settings; + +// Scarica lo snapshot `status/1` dal collector e lo espone al QML. +// +// QNetworkAccessManager non applica timeout: una richiesta senza risposta +// lascerebbe la UI in attesa per sempre, quindi c'e' un watchdog che aborta +// dopo kTimeoutMs e riporta un errore visibile. +class StatusClient : public QObject +{ + Q_OBJECT + Q_PROPERTY(QVariantMap data READ data NOTIFY changed) + Q_PROPERTY(bool busy READ busy NOTIFY busyChanged) + Q_PROPERTY(QString error READ error NOTIFY errorChanged) + Q_PROPERTY(QString fetchedAt READ fetchedAt NOTIFY changed) + Q_PROPERTY(bool configured READ configured NOTIFY changed) + +public: + explicit StatusClient(Settings *settings, QObject *parent = nullptr); + + QVariantMap data() const; + bool busy() const; + QString error() const; + QString fetchedAt() const; + bool configured() const; + + Q_INVOKABLE void refresh(); + + // Formattazione lato C++: lo JS del QML di Qt 5.6 e' ES5 e le locale + // numeriche italiane (virgola decimale) qui sono affidabili. + Q_INVOKABLE QString fmtBytes(qint64 bytes) const; + Q_INVOKABLE QString fmtUptime(qint64 seconds) const; + Q_INVOKABLE QString fmtAge(double hours) const; + Q_INVOKABLE QString fmtNum(double value, int decimals) const; + +signals: + void changed(); + void busyChanged(); + void errorChanged(); + +private slots: + void onFinished(); + void onTimeout(); + +private: + void setBusy(bool value); + void setError(const QString &message); + void clearReply(); + + Settings *m_settings; + QNetworkAccessManager m_nam; + QPointer m_reply; + QTimer m_watchdog; + QVariantMap m_data; + QString m_error; + QString m_fetchedAt; + bool m_busy; +}; + +#endif // STATUSCLIENT_H