Gotify Lite : réécriture complète en Rust natif

Service de fond minuscule (tray + WebSocket + toasts WinRT) et fenêtre egui
séparée lancée à la demande. Silence, heures calmes, seuils de priorité,
mute par appli, démarrage Windows, thème, token DPAPI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
linkatplugandClaude Opus 5.5 committed 2026-12-01 18:47:38 +01:00
commit 45581005fc
17 files changed
+6122

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
name: build
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo test --release
- run: cargo build --release
- uses: actions/upload-artifact@v4
with:
name: gotify-lite
path: target/release/gotify-lite.exe
- if: startsWith(github.ref, 'refs/tags/v')
uses: softprops/action-gh-release@v2
with:
files: target/release/gotify-lite.exe
+2
View File
@@ -0,0 +1,2 @@
/target
*.log
Generated
+3590
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "gotify-lite"
version = "2.0.0"
edition = "2024"
description = "Client Gotify léger pour Windows (tray + notifications natives)"
license = "MIT"
[dependencies]
eframe = { version = "0.38", default-features = false, features = ["glow", "default_fonts"] }
tray-icon = "0.27"
native-tls = "0.2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tungstenite = { version = "0.30", features = ["native-tls"] }
ureq = { version = "3", default-features = false, features = ["native-tls", "gzip", "json"] }
windows = { version = "0.61", features = [
"Win32_Foundation", "Win32_System_Registry", "Win32_Security_Cryptography",
"Win32_System_Threading", "Win32_UI_WindowsAndMessaging", "Win32_UI_Shell",
"Win32_System_LibraryLoader", "Win32_System_SystemInformation", "UI_Notifications", "Data_Xml_Dom", "Foundation",
] }
[profile.release]
opt-level = "s"
lto = true
codegen-units = 1
panic = "abort"
strip = true
[build-dependencies]
winresource = "0.1"
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+71
View File
@@ -0,0 +1,71 @@
# Gotify Lite
Client [Gotify](https://gotify.net) léger pour Windows 10/11 : icône dans la zone de notification,
notifications **natives** Windows, historique des messages, mode silence, thème clair/sombre.
Un seul `.exe` d'environ 5 Mo, sans runtime à installer (ni .NET ni Python).
![Messages](docs/ui_messages.png)
## Pourquoi c’est léger
| | Mémoire privée mesurée |
|---|---|
| Service de fond (icône + connexion temps réel) | **≈ 6 Mo**, ~0 % CPU au repos |
| Fenêtre messages/réglages | ≈ 130 Mo, **uniquement pendant qu'elle est ouverte** |
La fenêtre tourne dans un processus séparé, lancé au clic sur l'icône et libéré dès sa fermeture.
Le service ne charge aucun moteur graphique.
## Fonctions
- **Temps réel** par WebSocket, reconnexion automatique (backoff 1 s → 60 s), détection de la sortie de veille.
- **Messages manqués** : à la reconnexion, ils sont notifiés (un résumé s'il y en a plus de 3).
- **Notifications Windows natives** : centre de notifications, *Ne pas déranger*, réglages par appli dans
*Paramètres → Notifications → Gotify Lite*, icône de l'application Gotify d'origine, clic qui ouvre
l'URL `client::notification.click.url` (http/https uniquement) ou la fenêtre.
- **Priorités** : ignorer en dessous de *N*, bannière à partir de *N* (sinon discret dans le centre de
notifications), notification persistante à partir de *N*.
- **Silence** : 30 min / 1 h / 4 h / jusqu'à demain 8 h / indéfiniment (depuis le menu de l'icône),
**heures calmes** quotidiennes, seuil de priorité qui passe malgré le silence.
- **Par application** : couper les notifications d'une appli Gotify (clic droit dans la liste ou réglages).
- **Historique** : recherche, filtre par appli, suppression d'un message, d'une appli ou de tout (sur le serveur).
- **Démarrage avec Windows** (HKCU, sans droits admin), thème **Système / Clair / Sombre**.
- **Sécurité** : token chiffré avec DPAPI (lié à votre session Windows), TLS natif Windows (SChannel,
donc les autorités de certification installées dans Windows sont reconnues).
- Détecte quand Windows bloque les notifications et le signale, avec un bouton vers le bon réglage.
## Utilisation
1. Lancez `gotify-lite.exe`. Au premier lancement, les réglages s'ouvrent.
2. Dans Gotify (web) : **Clients → Créer un client**, copiez le token (*client*, pas *application*).
3. Collez l'URL et le token, puis **Enregistrer et connecter**.
Clic gauche sur l'icône : fenêtre. Clic droit : silence, activer/désactiver, reconnecter, quitter.
Données : `%APPDATA%\GotifyLite\config.json` (réglages), `%LOCALAPPDATA%\GotifyLite\` (état, icônes, journal).
## Compiler
```powershell
cargo build --release
```
L'exécutable est `target\release\gotify-lite.exe`. `cargo test` lance les tests unitaires
(décision de notification, heures calmes, dates, échappement XML, Markdown).
## Architecture
| Fichier | Rôle |
|---|---|
| `src/daemon.rs` | Icône, menu, boucle Win32, thread WebSocket, rattrapage |
| `src/ui.rs` | Fenêtre egui (messages + réglages) |
| `src/gotify.rs` | API REST (ureq) + flux WebSocket (tungstenite) |
| `src/notify.rs` | Toasts WinRT |
| `src/config.rs` | Réglages + règle de décision (`Config::decide`) |
| `src/sys.rs` | Registre, DPAPI, instance unique, dates |
| `src/icon.rs` | Icônes dessinées en code + encodeur PNG |
## Licence
MIT
+36
View File
@@ -0,0 +1,36 @@
// Génère l'icône .ico à partir du même code de dessin que l'icône de la barre des tâches,
// puis l'embarque dans l'exécutable (Explorateur, Gestionnaire des tâches, démarrage).
#[allow(dead_code)]
#[path = "src/icon.rs"]
mod icon;
fn main() {
println!("cargo:rerun-if-changed=src/icon.rs");
let out = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap());
let sizes = [16u32, 24, 32, 48, 64, 256];
let pngs: Vec<Vec<u8>> = sizes.iter().map(|&s| icon::png(s, &icon::render(s, icon::Look::Connected))).collect();
let mut ico = vec![0, 0, 1, 0];
ico.extend_from_slice(&(sizes.len() as u16).to_le_bytes());
let mut offset = 6 + 16 * sizes.len() as u32;
for (s, p) in sizes.iter().zip(&pngs) {
let d = if *s >= 256 { 0 } else { *s as u8 };
ico.extend_from_slice(&[d, d, 0, 0, 1, 0, 32, 0]);
ico.extend_from_slice(&(p.len() as u32).to_le_bytes());
ico.extend_from_slice(&offset.to_le_bytes());
offset += p.len() as u32;
}
for p in &pngs {
ico.extend_from_slice(p);
}
let ico_path = out.join("app.ico");
std::fs::write(&ico_path, ico).unwrap();
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let mut res = winresource::WindowsResource::new();
res.set_icon(ico_path.to_str().unwrap())
.set("FileDescription", "Gotify Lite")
.set("ProductName", "Gotify Lite")
.set("LegalCopyright", "MIT");
res.compile().unwrap();
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

+208
View File
@@ -0,0 +1,208 @@
//! Configuration persistante (%APPDATA%\GotifyLite\config.json) et état runtime
//! partagé entre le processus de fond et la fenêtre (%LOCALAPPDATA%\GotifyLite\state.json).
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::SystemTime;
use crate::sys;
pub const MUTE_FOREVER: u64 = u64::MAX;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub server_url: String,
/// Token client chiffré avec DPAPI (lié à la session Windows), encodé en hex.
pub token_enc: String,
#[serde(skip)]
pub token: String,
pub accept_invalid_certs: bool,
pub notifications: bool,
/// En dessous : message ignoré (aucune notification).
pub min_priority: u8,
/// En dessous : notification discrète (centre de notifications, sans bannière).
pub banner_min_priority: u8,
/// À partir de : la notification reste à l'écran jusqu'à fermeture.
pub sticky_min_priority: u8,
pub sound: bool,
/// Applications Gotify dont on ne veut pas de notification.
pub muted_apps: Vec<u64>,
/// Silence manuel jusqu'à ce timestamp unix (0 = inactif, MUTE_FOREVER = indéfini).
pub mute_until: u64,
pub quiet_enabled: bool,
/// Minutes depuis minuit (heure locale).
pub quiet_start: u16,
pub quiet_end: u16,
/// Pendant un silence, les priorités >= à ceci s'affichent quand même (11 = jamais).
pub silence_bypass_priority: u8,
pub catch_up: bool,
/// "system" | "light" | "dark"
pub theme: String,
}
impl Default for Config {
fn default() -> Self {
Self {
server_url: String::new(),
token_enc: String::new(),
token: String::new(),
accept_invalid_certs: false,
notifications: true,
min_priority: 0,
banner_min_priority: 4,
sticky_min_priority: 8,
sound: true,
muted_apps: Vec::new(),
mute_until: 0,
quiet_enabled: false,
quiet_start: 22 * 60,
quiet_end: 7 * 60,
silence_bypass_priority: 8,
catch_up: true,
theme: "system".into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Delivery {
pub popup: bool,
pub sound: bool,
pub sticky: bool,
}
impl Config {
pub fn path() -> PathBuf {
sys::roaming_dir().join("config.json")
}
pub fn is_configured(&self) -> bool {
!self.server_url.trim().is_empty() && !self.token.trim().is_empty()
}
pub fn load() -> Self {
let mut c: Config = std::fs::read_to_string(Self::path())
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
c.token = sys::unprotect(&c.token_enc).unwrap_or_default();
c
}
pub fn save(&mut self) -> std::io::Result<()> {
self.token_enc = sys::protect(&self.token).unwrap_or_default();
let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
sys::write_atomic(&Self::path(), json.as_bytes())
}
pub fn mtime() -> Option<SystemTime> {
std::fs::metadata(Self::path()).and_then(|m| m.modified()).ok()
}
/// Champs dont la modification impose une reconnexion.
pub fn connection_key(&self) -> (String, String, bool) {
(self.server_url.clone(), self.token.clone(), self.accept_invalid_certs)
}
pub fn manual_mute_active(&self, now_unix: u64) -> bool {
self.mute_until > now_unix
}
pub fn quiet_hours_active(&self, local_minutes: u16) -> bool {
if !self.quiet_enabled || self.quiet_start == self.quiet_end {
return false;
}
let (s, e, t) = (self.quiet_start, self.quiet_end, local_minutes);
if s < e { t >= s && t < e } else { t >= s || t < e }
}
pub fn silenced(&self, now_unix: u64, local_minutes: u16) -> bool {
self.manual_mute_active(now_unix) || self.quiet_hours_active(local_minutes)
}
/// Décide comment (et si) un message doit être notifié.
pub fn decide(&self, app_id: u64, priority: i64, now_unix: u64, local_minutes: u16) -> Option<Delivery> {
let p = priority.clamp(0, 10) as u8;
if !self.notifications || p < self.min_priority || self.muted_apps.contains(&app_id) {
return None;
}
let silenced = self.silenced(now_unix, local_minutes);
let bypass = p >= self.silence_bypass_priority;
let popup = p >= self.banner_min_priority && (!silenced || bypass);
Some(Delivery { popup, sound: self.sound && popup, sticky: popup && p >= self.sticky_min_priority })
}
}
/// État runtime écrit par le processus de fond, lu par la fenêtre.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct State {
pub last_id: u64,
/// "connected" | "connecting" | "unconfigured" | "error"
pub status: String,
pub detail: String,
pub daemon_pid: u32,
/// Non vide si Windows bloque l'affichage des notifications.
pub toasts_blocked: String,
}
impl State {
pub fn path() -> PathBuf {
sys::local_dir().join("state.json")
}
pub fn load() -> Self {
std::fs::read_to_string(Self::path())
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default()
}
pub fn save(&self) {
if let Ok(json) = serde_json::to_string(self) {
let _ = sys::write_atomic(&Self::path(), json.as_bytes());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quiet_hours_wrap_midnight() {
let c = Config { quiet_enabled: true, quiet_start: 22 * 60, quiet_end: 7 * 60, ..Default::default() };
assert!(c.quiet_hours_active(23 * 60));
assert!(c.quiet_hours_active(0));
assert!(c.quiet_hours_active(6 * 60 + 59));
assert!(!c.quiet_hours_active(7 * 60));
assert!(!c.quiet_hours_active(12 * 60));
let d = Config { quiet_enabled: true, quiet_start: 13 * 60, quiet_end: 14 * 60, ..Default::default() };
assert!(d.quiet_hours_active(13 * 60 + 30));
assert!(!d.quiet_hours_active(14 * 60));
}
#[test]
fn decide_priorities() {
let c = Config::default();
assert_eq!(c.decide(1, 2, 0, 600), Some(Delivery { popup: false, sound: false, sticky: false }));
assert_eq!(c.decide(1, 5, 0, 600), Some(Delivery { popup: true, sound: true, sticky: false }));
assert_eq!(c.decide(1, 9, 0, 600), Some(Delivery { popup: true, sound: true, sticky: true }));
let c = Config { min_priority: 3, muted_apps: vec![7], ..Default::default() };
assert_eq!(c.decide(1, 2, 0, 600), None);
assert_eq!(c.decide(7, 10, 0, 600), None);
}
#[test]
fn decide_silence_and_bypass() {
let c = Config { mute_until: MUTE_FOREVER, ..Default::default() };
assert_eq!(c.decide(1, 5, 100, 600).unwrap().popup, false);
assert_eq!(c.decide(1, 8, 100, 600).unwrap().popup, true);
let c = Config { mute_until: 50, ..Default::default() };
assert!(c.decide(1, 5, 100, 600).unwrap().popup, "silence expiré");
let c = Config { mute_until: MUTE_FOREVER, silence_bypass_priority: 11, ..Default::default() };
assert!(!c.decide(1, 10, 100, 600).unwrap().popup);
}
}
+558
View File
@@ -0,0 +1,558 @@
//! Processus de fond : icône de zone de notification + connexion temps réel + toasts.
//! Aucun moteur graphique chargé ici : la fenêtre (egui) vit dans un processus séparé,
//! lancé à la demande et fermé ensuite, pour garder ce processus minuscule.
use std::collections::HashMap;
use std::net::{Shutdown, TcpStream};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant, SystemTime};
use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use windows::Win32::System::Threading::GetCurrentThreadId;
use windows::Win32::UI::WindowsAndMessaging::*;
use crate::config::{Config, MUTE_FOREVER, State};
use crate::gotify::{self, Client, Message};
use crate::icon::{self, Look};
use crate::notify::{Notifier, Toast};
use crate::sys;
const READ_TIMEOUT: Duration = Duration::from_secs(100); // Gotify pingue toutes les 45 s par défaut
const OPEN_URL: &str = "gotify-lite:open";
#[derive(Clone, PartialEq)]
enum Status {
Unconfigured,
Connecting,
Connected(String),
Error(String),
}
struct Shared {
cfg: Mutex<Config>,
status: Mutex<Status>,
sock: Mutex<Option<TcpStream>>,
generation: AtomicU64,
quit: AtomicBool,
main_thread: u32,
}
impl Shared {
fn wake_main(&self) {
unsafe {
let _ = PostThreadMessageW(self.main_thread, WM_APP, Default::default(), Default::default());
}
}
fn set_status(&self, s: Status) {
let mut cur = self.status.lock().unwrap();
if *cur != s {
*cur = s;
drop(cur);
self.wake_main();
}
}
fn force_reconnect(&self) {
self.generation.fetch_add(1, Ordering::SeqCst);
if let Some(s) = self.sock.lock().unwrap().as_ref() {
let _ = s.shutdown(Shutdown::Both);
}
}
}
pub fn run() {
let _guard = match sys::single_instance("Local\\GotifyLite.Daemon") {
Some(h) => h,
None => {
// Déjà lancé : on ouvre simplement la fenêtre.
sys::spawn_ui();
return;
}
};
sys::log("démarrage");
let icon_path = sys::local_dir().join("icon.png");
let _ = std::fs::write(&icon_path, icon::png(64, &icon::render(64, Look::Connected)));
sys::register_app(&icon_path);
let cfg = Config::load();
let first_run = !cfg.is_configured();
let shared = Arc::new(Shared {
cfg: Mutex::new(cfg),
status: Mutex::new(Status::Connecting),
sock: Mutex::new(None),
generation: AtomicU64::new(0),
quit: AtomicBool::new(false),
main_thread: unsafe { GetCurrentThreadId() },
});
{
let shared = shared.clone();
std::thread::Builder::new().name("stream".into()).spawn(move || worker(shared)).ok();
}
if first_run {
sys::spawn_settings();
}
tray_loop(shared);
sys::log("arrêt");
}
// ---------------------------------------------------------------- tray
struct TrayUi {
tray: TrayIcon,
status_item: MenuItem,
unmute: MenuItem,
notif_toggle: CheckMenuItem,
look: Look,
tooltip: String,
notifier: Notifier,
blocked: Option<&'static str>,
ticks: u32,
}
enum Ev {
Menu(MenuEvent),
Tray(TrayIconEvent),
}
fn make_icon(look: Look) -> Icon {
Icon::from_rgba(icon::render(32, look), 32, 32).expect("icône")
}
fn tray_loop(shared: Arc<Shared>) {
let (tx, rx) = mpsc::channel::<Ev>();
let tid = shared.main_thread;
let post = move || unsafe {
let _ = PostThreadMessageW(tid, WM_APP, Default::default(), Default::default());
};
{
let (tx, post) = (tx.clone(), post);
MenuEvent::set_event_handler(Some(Arc::new(move |e: MenuEvent| {
let _ = tx.send(Ev::Menu(e));
post();
})));
}
TrayIconEvent::set_event_handler(Some(move |e: TrayIconEvent| {
let _ = tx.send(Ev::Tray(e));
post();
}));
let menu = Menu::new();
let status_item = MenuItem::with_id("status", "Connexion…", false, None);
let open = MenuItem::with_id("open", "Ouvrir Gotify Lite", true, None);
let notif_toggle = CheckMenuItem::with_id("toggle", "Notifications activées", true, shared.cfg.lock().unwrap().notifications, None);
let mute = Submenu::with_id_and_items(
"mute",
"Silence",
true,
&[
&MenuItem::with_id("mute:30", "30 minutes", true, None),
&MenuItem::with_id("mute:60", "1 heure", true, None),
&MenuItem::with_id("mute:240", "4 heures", true, None),
&MenuItem::with_id("mute:morning", "Jusqu'à demain 8 h", true, None),
&MenuItem::with_id("mute:forever", "Jusqu'à réactivation", true, None),
],
)
.expect("menu");
let unmute = MenuItem::with_id("unmute", "Réactiver le son et les bannières", false, None);
let settings = MenuItem::with_id("settings", "Paramètres…", true, None);
let reconnect = MenuItem::with_id("reconnect", "Reconnecter", true, None);
let quit = MenuItem::with_id("quit", "Quitter", true, None);
let _ = menu.append_items(&[
&status_item,
&PredefinedMenuItem::separator(),
&open,
&notif_toggle,
&mute,
&unmute,
&PredefinedMenuItem::separator(),
&settings,
&reconnect,
&quit,
]);
let tray = TrayIconBuilder::new()
.with_icon(make_icon(Look::Disconnected))
.with_tooltip(sys::APP_NAME)
.with_menu(Box::new(menu))
.with_menu_on_left_click(false)
.build()
.expect("tray");
let notifier = Notifier::new();
let blocked = notifier.blocked_reason();
let mut ui = TrayUi { tray, status_item, unmute, notif_toggle, look: Look::Disconnected, tooltip: String::new(), notifier, blocked, ticks: 0 };
let quit_ev = sys::quit_event();
unsafe { SetTimer(None, 0, 1000, None) };
let mut cfg_mtime = Config::mtime();
let mut last_tick = SystemTime::now();
let mut last_state = State::default();
refresh_tray(&shared, &mut ui, &mut last_state);
let mut msg = MSG::default();
loop {
let r = unsafe { GetMessageW(&mut msg, None, 0, 0) };
if r.0 <= 0 {
break;
}
unsafe {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
while let Ok(ev) = rx.try_recv() {
match ev {
Ev::Tray(TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. }) => sys::spawn_ui(),
Ev::Tray(_) => {}
Ev::Menu(e) => handle_menu(&shared, e.id.0.as_str()),
}
}
if shared.quit.load(Ordering::SeqCst) {
break;
}
if msg.message == WM_TIMER {
if quit_ev.is_some_and(sys::quit_requested) {
break;
}
// Sortie de veille : un tick de 1 s qui en a duré 20+ → la connexion est probablement morte.
let now = SystemTime::now();
if now.duration_since(last_tick).map(|d| d > Duration::from_secs(20)).unwrap_or(false) {
sys::log("reprise après veille : reconnexion");
shared.force_reconnect();
}
last_tick = now;
ui.ticks = ui.ticks.wrapping_add(1);
if ui.ticks.is_multiple_of(5) {
ui.blocked = ui.notifier.blocked_reason();
}
let m = Config::mtime();
if m != cfg_mtime {
cfg_mtime = m;
let new = Config::load();
let mut cur = shared.cfg.lock().unwrap();
let reconnect = new.connection_key() != cur.connection_key();
*cur = new;
drop(cur);
if reconnect {
shared.force_reconnect();
}
}
}
refresh_tray(&shared, &mut ui, &mut last_state);
}
shared.quit.store(true, Ordering::SeqCst);
shared.force_reconnect();
let mut st = State::load();
st.status = "stopped".into();
st.daemon_pid = 0;
st.save();
}
fn update_cfg(shared: &Shared, f: impl FnOnce(&mut Config)) {
let mut c = shared.cfg.lock().unwrap();
// Relire le disque d'abord : la fenêtre a pu modifier d'autres champs.
let mut fresh = Config::load();
f(&mut fresh);
if let Err(e) = fresh.save() {
sys::log(&format!("save config: {e}"));
}
*c = fresh;
}
fn handle_menu(shared: &Shared, id: &str) {
let now = sys::now_unix();
match id {
"open" => sys::spawn_ui(),
"settings" => sys::spawn_settings(),
"reconnect" => shared.force_reconnect(),
"quit" => {
shared.quit.store(true, Ordering::SeqCst);
unsafe { PostQuitMessage(0) };
}
"toggle" => update_cfg(shared, |c| c.notifications = !c.notifications),
"unmute" => update_cfg(shared, |c| c.mute_until = 0),
"mute:forever" => update_cfg(shared, |c| c.mute_until = MUTE_FOREVER),
"mute:morning" => {
let m = sys::local_minutes() as u64;
let until = if m < 8 * 60 { 8 * 60 - m } else { 24 * 60 - m + 8 * 60 };
update_cfg(shared, |c| c.mute_until = now + until * 60);
}
other => {
if let Some(mins) = other.strip_prefix("mute:").and_then(|s| s.parse::<u64>().ok()) {
update_cfg(shared, |c| c.mute_until = now + mins * 60);
}
}
}
}
pub fn describe_mute(cfg: &Config) -> Option<String> {
let now = sys::now_unix();
if cfg.mute_until == MUTE_FOREVER {
return Some("Silence activé".into());
}
if cfg.mute_until > now {
let mins = (cfg.mute_until - now).div_ceil(60);
return Some(if mins >= 60 { format!("Silence encore {} h {:02}", mins / 60, mins % 60) } else { format!("Silence encore {mins} min") });
}
if cfg.quiet_hours_active(sys::local_minutes()) {
return Some("Heures calmes".into());
}
None
}
fn refresh_tray(shared: &Shared, ui: &mut TrayUi, last_state: &mut State) {
let cfg = shared.cfg.lock().unwrap().clone();
let status = shared.status.lock().unwrap().clone();
let mute = describe_mute(&cfg);
let (status_text, connected) = match &status {
Status::Unconfigured => ("Non configuré — cliquez pour régler".to_string(), false),
Status::Connecting => ("Connexion…".to_string(), false),
Status::Connected(host) => (format!("Connecté à {host}"), true),
Status::Error(e) => (format!("Déconnecté : {e}"), false),
};
let look = if !connected {
Look::Disconnected
} else if mute.is_some() || !cfg.notifications || ui.blocked.is_some() {
Look::Muted
} else {
Look::Connected
};
if look != ui.look {
let _ = ui.tray.set_icon(Some(make_icon(look)));
ui.look = look;
}
let mut tooltip = format!("{}\n{}", sys::APP_NAME, status_text);
if !cfg.notifications {
tooltip.push_str("\nNotifications désactivées");
} else if let Some(m) = &mute {
tooltip.push('\n');
tooltip.push_str(m);
}
let tooltip: String = tooltip.chars().take(127).collect();
if tooltip != ui.tooltip {
let _ = ui.tray.set_tooltip(Some(&tooltip));
ui.status_item.set_text(status_text.chars().take(70).collect::<String>());
ui.tooltip = tooltip;
}
ui.unmute.set_enabled(cfg.manual_mute_active(sys::now_unix()));
ui.notif_toggle.set_checked(cfg.notifications);
// Publie l'état pour la fenêtre.
let (code, detail) = match &status {
Status::Unconfigured => ("unconfigured", String::new()),
Status::Connecting => ("connecting", String::new()),
Status::Connected(h) => ("connected", h.clone()),
Status::Error(e) => ("error", e.clone()),
};
let mut st = State::load();
st.status = code.into();
st.detail = detail;
st.daemon_pid = std::process::id();
st.toasts_blocked = ui.blocked.unwrap_or_default().to_string();
if st.status != last_state.status
|| st.detail != last_state.detail
|| st.daemon_pid != last_state.daemon_pid
|| st.toasts_blocked != last_state.toasts_blocked
{
st.save();
*last_state = st;
}
}
// ---------------------------------------------------------------- flux
struct AppInfo {
name: String,
icon: Option<PathBuf>,
}
fn worker(shared: Arc<Shared>) {
let notifier = Notifier::new();
let mut backoff = 1u64;
while !shared.quit.load(Ordering::SeqCst) {
let cfg = shared.cfg.lock().unwrap().clone();
let generation = shared.generation.load(Ordering::SeqCst);
if !cfg.is_configured() {
shared.set_status(Status::Unconfigured);
wait(&shared, generation, 3600);
continue;
}
shared.set_status(Status::Connecting);
let started = Instant::now();
let result = session(&shared, &cfg, &notifier);
*shared.sock.lock().unwrap() = None;
if shared.quit.load(Ordering::SeqCst) {
break;
}
if shared.generation.load(Ordering::SeqCst) != generation {
backoff = 1;
continue; // reconnexion demandée : immédiate
}
if let Err(e) = &result {
sys::log(&format!("flux : {e}"));
}
shared.set_status(Status::Error(result.err().unwrap_or_else(|| "connexion fermée par le serveur".into())));
if started.elapsed() > Duration::from_secs(60) {
backoff = 1;
}
wait(&shared, generation, backoff);
backoff = (backoff * 2).min(60);
}
}
/// Attend `secs` secondes, ou moins si on quitte / si une reconnexion est demandée.
fn wait(shared: &Shared, generation: u64, secs: u64) {
let end = Instant::now() + Duration::from_secs(secs);
while Instant::now() < end && !shared.quit.load(Ordering::SeqCst) && shared.generation.load(Ordering::SeqCst) == generation {
std::thread::sleep(Duration::from_millis(250));
}
}
fn session(shared: &Shared, cfg: &Config, notifier: &Notifier) -> Result<(), String> {
let (mut ws, handle) = gotify::connect_stream(cfg, READ_TIMEOUT)?;
*shared.sock.lock().unwrap() = Some(handle);
let client = Client::new(cfg);
let host = client.base().split("://").nth(1).unwrap_or(client.base()).to_string();
shared.set_status(Status::Connected(host));
sys::log("connecté");
let mut apps = load_apps(&client);
let mut last_id = State::load().last_id;
// Rattrapage des messages reçus pendant la déconnexion.
match client.messages(20, None) {
Ok(page) => {
let newest = page.messages.iter().map(|m| m.id).max().unwrap_or(0);
if last_id == 0 || newest < last_id {
// Premier lancement (ou base serveur réinitialisée) : on ne rejoue pas l'historique.
last_id = newest;
} else if cfg.catch_up {
let mut missed: Vec<&Message> = page.messages.iter().filter(|m| m.id > last_id).collect();
missed.sort_by_key(|m| m.id);
if missed.len() <= 3 {
for m in &missed {
deliver(shared, notifier, &apps, m);
}
} else {
summary(shared, notifier, &missed, page.paging.next.is_some() && missed.len() == page.messages.len());
}
last_id = newest.max(last_id);
} else {
last_id = newest.max(last_id);
}
save_last_id(last_id);
}
Err(e) => sys::log(&format!("rattrapage : {e}")),
}
loop {
let msg = ws.read().map_err(|e| match e {
tungstenite::Error::Io(io) if io.kind() == std::io::ErrorKind::TimedOut || io.kind() == std::io::ErrorKind::WouldBlock => {
"plus de nouvelles du serveur (timeout)".to_string()
}
other => other.to_string(),
})?;
match msg {
tungstenite::Message::Text(t) => {
let Ok(m) = serde_json::from_str::<Message>(&t) else { continue };
if m.id <= last_id {
continue;
}
if !apps.contains_key(&m.appid) {
apps = load_apps(&client);
}
deliver(shared, notifier, &apps, &m);
last_id = m.id;
save_last_id(last_id);
}
tungstenite::Message::Close(_) => return Err("connexion fermée par le serveur".into()),
_ => {}
}
}
}
fn save_last_id(id: u64) {
let mut st = State::load();
if st.last_id != id {
st.last_id = id;
st.save();
}
}
fn load_apps(client: &Client) -> HashMap<u64, AppInfo> {
let dir = sys::local_dir().join("icons");
let _ = std::fs::create_dir_all(&dir);
let list = client.applications().unwrap_or_else(|e| {
sys::log(&format!("applications : {e}"));
Vec::new()
});
list.into_iter()
.map(|a| {
let icon = (!a.image.is_empty()).then(|| {
// Nom de fichier dérivé du chemin serveur : change quand l'image change.
let h = a.image.bytes().fold(0xcbf29ce484222325u64, |h, b| (h ^ b as u64).wrapping_mul(0x100000001b3));
let p = dir.join(format!("{}-{h:016x}.png", a.id));
if !p.exists()
&& let Ok(bytes) = client.download(&a.image) {
let _ = std::fs::write(&p, bytes);
}
p
});
(a.id, AppInfo { name: a.name, icon: icon.filter(|p| p.exists()) })
})
.collect()
}
fn deliver(shared: &Shared, notifier: &Notifier, apps: &HashMap<u64, AppInfo>, m: &Message) {
let cfg = shared.cfg.lock().unwrap().clone();
let Some(delivery) = cfg.decide(m.appid, m.priority(), sys::now_unix(), sys::local_minutes()) else { return };
let app = apps.get(&m.appid);
let app_name = app.map(|a| a.name.as_str()).unwrap_or("Gotify");
let body = if m.is_markdown() { gotify::strip_markdown(&m.message) } else { m.message.clone() };
let title = m.title.as_deref().filter(|t| !t.trim().is_empty()).unwrap_or(app_name);
let launch = m.click_url().unwrap_or_else(|| OPEN_URL.to_string());
notifier.show(&Toast {
title,
body: &body,
app_name,
icon: app.and_then(|a| a.icon.as_deref()),
launch: &launch,
tag: &m.id.to_string(),
group: &m.appid.to_string(),
delivery,
});
}
fn summary(shared: &Shared, notifier: &Notifier, missed: &[&Message], more: bool) {
let cfg = shared.cfg.lock().unwrap().clone();
let top = missed.iter().map(|m| m.priority()).max().unwrap_or(0);
// Un résumé n'est soumis qu'aux seuils globaux, pas au filtre par appli.
let Some(delivery) = cfg.decide(u64::MAX, top, sys::now_unix(), sys::local_minutes()) else { return };
let visible: Vec<_> = missed.iter().filter(|m| !cfg.muted_apps.contains(&m.appid)).collect();
if visible.is_empty() {
return;
}
let lines: Vec<String> = visible
.iter()
.rev()
.take(4)
.map(|m| format!("• {}", m.title.clone().filter(|t| !t.is_empty()).unwrap_or_else(|| m.message.chars().take(60).collect())))
.collect();
let title = format!("{}{} messages reçus pendant votre absence", visible.len(), if more { "+" } else { "" });
notifier.show(&Toast {
title: &title,
body: &lines.join("\n"),
app_name: sys::APP_NAME,
icon: None,
launch: OPEN_URL,
tag: "summary",
group: "summary",
delivery: crate::config::Delivery { sticky: false, ..delivery },
});
}
+297
View File
@@ -0,0 +1,297 @@
//! Client Gotify : API REST (ureq) et flux WebSocket (tungstenite), TLS natif Windows (SChannel).
use serde::Deserialize;
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use tungstenite::client::IntoClientRequest;
use tungstenite::stream::MaybeTlsStream;
use tungstenite::{Connector, WebSocket};
use crate::config::Config;
#[derive(Clone, Debug, Deserialize)]
pub struct Message {
pub id: u64,
pub appid: u64,
#[serde(default)]
pub message: String,
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub priority: Option<i64>,
#[serde(default)]
pub date: String,
#[serde(default)]
pub extras: Option<serde_json::Value>,
}
impl Message {
pub fn priority(&self) -> i64 {
self.priority.unwrap_or(0)
}
/// URL à ouvrir au clic (`client::notification.click.url`), uniquement http(s).
pub fn click_url(&self) -> Option<String> {
let url = self.extras.as_ref()?.pointer("/client::notification/click/url")?.as_str()?;
let l = url.to_ascii_lowercase();
(l.starts_with("https://") || l.starts_with("http://")).then(|| url.to_string())
}
pub fn is_markdown(&self) -> bool {
self.extras
.as_ref()
.and_then(|e| e.pointer("/client::display/contentType"))
.and_then(|v| v.as_str())
== Some("text/markdown")
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct App {
pub id: u64,
pub name: String,
#[serde(default)]
pub image: String,
}
#[derive(Debug, Deserialize)]
pub struct Paging {
#[serde(default)]
pub since: u64,
#[serde(default)]
pub next: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct PagedMessages {
pub messages: Vec<Message>,
pub paging: Paging,
}
#[derive(Debug, Deserialize)]
pub struct User {
pub name: String,
}
#[derive(Debug, Deserialize)]
pub struct Version {
pub version: String,
}
pub type Result<T> = std::result::Result<T, String>;
pub fn normalize_url(url: &str) -> String {
let u = url.trim().trim_end_matches('/');
if u.is_empty() || u.contains("://") { u.to_string() } else { format!("https://{u}") }
}
pub struct Client {
base: String,
token: String,
agent: ureq::Agent,
}
impl Client {
pub fn new(cfg: &Config) -> Self {
let tls = ureq::tls::TlsConfig::builder()
.provider(ureq::tls::TlsProvider::NativeTls)
.disable_verification(cfg.accept_invalid_certs)
.build();
let agent: ureq::Agent = ureq::Agent::config_builder()
.tls_config(tls)
.timeout_global(Some(Duration::from_secs(15)))
.user_agent(concat!("gotify-lite/", env!("CARGO_PKG_VERSION")))
.build()
.into();
Self { base: normalize_url(&cfg.server_url), token: cfg.token.trim().to_string(), agent }
}
pub fn base(&self) -> &str {
&self.base
}
fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
self.agent
.get(format!("{}{}", self.base, path))
.header("X-Gotify-Key", &self.token)
.call()
.map_err(describe)?
.body_mut()
.read_json::<T>()
.map_err(|e| format!("Réponse invalide : {e}"))
}
fn delete(&self, path: &str) -> Result<()> {
self.agent
.delete(format!("{}{}", self.base, path))
.header("X-Gotify-Key", &self.token)
.call()
.map(|_| ())
.map_err(describe)
}
pub fn version(&self) -> Result<Version> {
self.get("/version")
}
pub fn current_user(&self) -> Result<User> {
self.get("/current/user")
}
pub fn applications(&self) -> Result<Vec<App>> {
self.get("/application")
}
/// Messages du plus récent au plus ancien ; `since` = pagination (ids < since).
pub fn messages(&self, limit: u32, since: Option<u64>) -> Result<PagedMessages> {
match since {
Some(s) => self.get(&format!("/message?limit={limit}&since={s}")),
None => self.get(&format!("/message?limit={limit}")),
}
}
pub fn delete_message(&self, id: u64) -> Result<()> {
self.delete(&format!("/message/{id}"))
}
pub fn delete_app_messages(&self, app: u64) -> Result<()> {
self.delete(&format!("/application/{app}/message"))
}
pub fn delete_all(&self) -> Result<()> {
self.delete("/message")
}
pub fn download(&self, path: &str) -> Result<Vec<u8>> {
self.agent
.get(format!("{}/{}", self.base, path.trim_start_matches('/')))
.header("X-Gotify-Key", &self.token)
.call()
.map_err(describe)?
.body_mut()
.with_config()
.limit(2 * 1024 * 1024)
.read_to_vec()
.map_err(|e| e.to_string())
}
}
fn describe(e: ureq::Error) -> String {
match e {
ureq::Error::StatusCode(401) | ureq::Error::StatusCode(403) => "Token refusé (401/403) : vérifiez qu'il s'agit d'un token *client*".into(),
ureq::Error::StatusCode(404) => "Introuvable (404) : vérifiez l'URL du serveur".into(),
ureq::Error::StatusCode(c) => format!("Erreur HTTP {c}"),
other => {
let s = other.to_string();
if s.to_lowercase().contains("certificate") || s.contains("0x800B") {
format!("Certificat TLS refusé : {s}")
} else {
s
}
}
}
}
pub type Stream = WebSocket<MaybeTlsStream<TcpStream>>;
/// Ouvre le flux temps réel. Retourne aussi un clone du socket TCP pour pouvoir
/// interrompre la lecture bloquante depuis un autre thread (shutdown).
pub fn connect_stream(cfg: &Config, read_timeout: Duration) -> Result<(Stream, TcpStream)> {
let base = normalize_url(&cfg.server_url);
let ws_url = if let Some(rest) = base.strip_prefix("https://") {
format!("wss://{rest}/stream")
} else if let Some(rest) = base.strip_prefix("http://") {
format!("ws://{rest}/stream")
} else {
return Err("L'URL doit commencer par http:// ou https://".into());
};
let mut req = ws_url.as_str().into_client_request().map_err(|e| e.to_string())?;
let token = tungstenite::http::HeaderValue::from_str(cfg.token.trim()).map_err(|_| "Token invalide".to_string())?;
req.headers_mut().insert("X-Gotify-Key", token);
let uri = req.uri().clone();
let host = uri.host().ok_or("URL sans hôte")?.trim_start_matches('[').trim_end_matches(']').to_string();
let port = uri.port_u16().unwrap_or(if uri.scheme_str() == Some("wss") { 443 } else { 80 });
let addrs: Vec<_> = (host.as_str(), port).to_socket_addrs().map_err(|e| format!("DNS : {e}"))?.collect();
let mut last_err = String::from("aucune adresse");
let tcp = addrs
.iter()
.find_map(|a| match TcpStream::connect_timeout(a, Duration::from_secs(10)) {
Ok(s) => Some(s),
Err(e) => {
last_err = e.to_string();
None
}
})
.ok_or_else(|| format!("Connexion impossible à {host}:{port} : {last_err}"))?;
tcp.set_nodelay(true).ok();
tcp.set_read_timeout(Some(Duration::from_secs(15))).ok(); // handshake
let handle = tcp.try_clone().map_err(|e| e.to_string())?;
let connector = if uri.scheme_str() == Some("wss") {
let tls = native_tls::TlsConnector::builder()
.danger_accept_invalid_certs(cfg.accept_invalid_certs)
.danger_accept_invalid_hostnames(cfg.accept_invalid_certs)
.build()
.map_err(|e| e.to_string())?;
Connector::NativeTls(tls)
} else {
Connector::Plain
};
let (mut ws, _resp) = tungstenite::client_tls_with_config(req, tcp, None, Some(connector)).map_err(|e| match e {
tungstenite::HandshakeError::Failure(tungstenite::Error::Http(r)) if r.status() == 401 => {
"Token refusé (401) : utilisez un token *client*".to_string()
}
other => other.to_string(),
})?;
// Sous Windows, SO_RCVTIMEO n'est pas partagé entre handles dupliqués : on règle le socket réellement lu.
match ws.get_mut() {
MaybeTlsStream::Plain(s) => s.set_read_timeout(Some(read_timeout)).ok(),
MaybeTlsStream::NativeTls(s) => s.get_ref().set_read_timeout(Some(read_timeout)).ok(),
_ => None,
};
Ok((ws, handle))
}
/// Retire le balisage Markdown le plus courant pour un affichage texte brut.
pub fn strip_markdown(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for line in s.lines() {
let l = line.trim_start_matches(['#', '>']).trim_start();
let l = l.strip_prefix("- ").or_else(|| l.strip_prefix("* ")).map(|r| format!("• {r}")).unwrap_or_else(|| l.to_string());
// [texte](url) -> texte ; ![alt](url) -> alt
let mut res = String::new();
let mut rest = l.as_str();
while let Some(start) = rest.find('[') {
let Some(mid) = rest[start..].find("](") else { break };
let Some(end) = rest[start + mid..].find(')') else { break };
let before = rest[..start].trim_end_matches('!');
res.push_str(before);
res.push_str(&rest[start + 1..start + mid]);
rest = &rest[start + mid + end + 1..];
}
res.push_str(rest);
out.push_str(&res.replace("**", "").replace("__", "").replace('`', ""));
out.push('\n');
}
out.trim_end().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn markdown() {
assert_eq!(strip_markdown("# Titre\n- **gras** et [lien](http://x)\n![img](a.png)"), "Titre\n• gras et lien\nimg");
}
#[test]
fn url() {
assert_eq!(normalize_url(" gotify.example.com/ "), "https://gotify.example.com");
assert_eq!(normalize_url("http://10.0.0.2:8080/gotify/"), "http://10.0.0.2:8080/gotify");
}
#[test]
fn click_url_only_http() {
let mk = |u: &str| Message {
id: 1, appid: 1, message: String::new(), title: None, priority: None, date: String::new(),
extras: Some(serde_json::json!({"client::notification": {"click": {"url": u}}})),
};
assert_eq!(mk("https://a.b").click_url().as_deref(), Some("https://a.b"));
assert_eq!(mk("file:///C:/Windows/calc.exe").click_url(), None);
}
}
+151
View File
@@ -0,0 +1,151 @@
//! Icônes dessinées en code (aucun fichier à embarquer) + encodeur PNG minimal.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Look {
Connected,
Disconnected,
Muted,
}
impl Look {
fn bg(self) -> [f32; 3] {
match self {
Look::Connected => [0.17, 0.42, 0.69], // bleu
Look::Disconnected => [0.45, 0.47, 0.50], // gris
Look::Muted => [0.80, 0.45, 0.10], // orange
}
}
}
fn rounded_rect(x: f32, y: f32, r: f32) -> bool {
let dx = (x - 0.5).abs() - (0.5 - r);
let dy = (y - 0.5).abs() - (0.5 - r);
let (ox, oy) = (dx.max(0.0), dy.max(0.0));
(ox * ox + oy * oy).sqrt() <= r && dx.max(dy) <= r
}
fn circle(x: f32, y: f32, cx: f32, cy: f32, r: f32) -> bool {
(x - cx).powi(2) + (y - cy).powi(2) <= r * r
}
fn bell(x: f32, y: f32) -> bool {
let cx = 0.5;
let dome = y <= 0.47 && circle(x, y, cx, 0.47, 0.21);
let body = (0.47..=0.68).contains(&y) && (x - cx).abs() <= 0.21 + (y - 0.47) * 0.35;
let rim = (0.66..=0.72).contains(&y) && (x - cx).abs() <= 0.30;
let knob = circle(x, y, cx, 0.25, 0.05);
let clapper = circle(x, y, cx, 0.78, 0.065);
dome || body || rim || knob || clapper
}
fn slash(x: f32, y: f32, w: f32) -> bool {
// segment (0.22,0.20) -> (0.80,0.80)
let (ax, ay, bx, by) = (0.22, 0.20, 0.80, 0.80);
let (vx, vy) = (bx - ax, by - ay);
let t = (((x - ax) * vx + (y - ay) * vy) / (vx * vx + vy * vy)).clamp(0.0, 1.0);
let (px, py) = (ax + t * vx - x, ay + t * vy - y);
(px * px + py * py).sqrt() <= w
}
/// RGBA `size`×`size`, anti-aliasé par sur-échantillonnage 4×4.
pub fn render(size: u32, look: Look) -> Vec<u8> {
let bg = look.bg();
let mut out = Vec::with_capacity((size * size * 4) as usize);
const SS: u32 = 4;
for py in 0..size {
for px in 0..size {
let (mut a, mut r, mut g, mut b) = (0.0f32, 0.0f32, 0.0f32, 0.0f32);
for sy in 0..SS {
for sx in 0..SS {
let x = (px as f32 + (sx as f32 + 0.5) / SS as f32) / size as f32;
let y = (py as f32 + (sy as f32 + 0.5) / SS as f32) / size as f32;
if !rounded_rect(x, y, 0.24) {
continue;
}
let mut c = bg;
if bell(x, y) {
c = [1.0, 1.0, 1.0];
}
if look == Look::Muted {
if slash(x, y, 0.075) {
c = bg;
}
if slash(x, y, 0.04) {
c = [1.0, 1.0, 1.0];
}
}
a += 1.0;
r += c[0];
g += c[1];
b += c[2];
}
}
let n = (SS * SS) as f32;
if a > 0.0 {
out.extend_from_slice(&[(r / a * 255.0) as u8, (g / a * 255.0) as u8, (b / a * 255.0) as u8, (a / n * 255.0) as u8]);
} else {
out.extend_from_slice(&[0, 0, 0, 0]);
}
}
}
out
}
fn crc32(data: &[u8]) -> u32 {
let mut c = 0xFFFF_FFFFu32;
for &b in data {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
/// PNG RGBA non compressé (blocs deflate « stored ») : suffisant pour une icône de 64 px.
pub fn png(size: u32, rgba: &[u8]) -> Vec<u8> {
let mut raw = Vec::with_capacity(rgba.len() + size as usize);
for row in rgba.chunks(size as usize * 4) {
raw.push(0);
raw.extend_from_slice(row);
}
let mut z = vec![0x78, 0x01];
let chunks: Vec<&[u8]> = raw.chunks(65535).collect();
for (i, ch) in chunks.iter().enumerate() {
z.push((i == chunks.len() - 1) as u8);
z.extend_from_slice(&(ch.len() as u16).to_le_bytes());
z.extend_from_slice(&(!(ch.len() as u16)).to_le_bytes());
z.extend_from_slice(ch);
}
let (mut a, mut b) = (1u32, 0u32);
for &x in &raw {
a = (a + x as u32) % 65521;
b = (b + a) % 65521;
}
z.extend_from_slice(&((b << 16) | a).to_be_bytes());
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
let mut chunk = |ty: &[u8; 4], data: &[u8]| {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
let mut c = ty.to_vec();
c.extend_from_slice(data);
out.extend_from_slice(&c);
out.extend_from_slice(&crc32(&c).to_be_bytes());
};
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&size.to_be_bytes());
ihdr.extend_from_slice(&size.to_be_bytes());
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]);
chunk(b"IHDR", &ihdr);
chunk(b"IDAT", &z);
chunk(b"IEND", &[]);
out
}
#[cfg(test)]
mod tests {
#[test]
fn crc() {
assert_eq!(super::crc32(b"123456789"), 0xCBF4_3926);
}
}
+24
View File
@@ -0,0 +1,24 @@
#![windows_subsystem = "windows"]
//! Gotify Lite — client Gotify léger pour Windows.
//!
//! Sans argument : processus de fond (icône + notifications).
//! `--ui` : fenêtre messages/réglages (processus séparé, fermé après usage).
mod config;
mod daemon;
mod gotify;
mod icon;
mod notify;
mod sys;
mod ui;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--settings") {
ui::run(true);
} else if args.iter().any(|a| a == "--ui" || a.starts_with("gotify-lite:")) {
ui::run(false);
} else {
daemon::run();
}
}
+134
View File
@@ -0,0 +1,134 @@
//! Notifications toast natives Windows (WinRT) : centre de notifications, Ne pas déranger,
//! réglages par appli dans Paramètres Windows > Notifications.
use std::path::Path;
use windows::Data::Xml::Dom::XmlDocument;
use windows::UI::Notifications::{ToastNotification, ToastNotificationManager, ToastNotifier};
use windows::core::HSTRING;
use crate::config::Delivery;
use crate::sys;
pub struct Notifier {
inner: Option<ToastNotifier>,
}
fn esc(s: &str) -> String {
let mut o = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => o.push_str("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
'\'' => o.push_str("&apos;"),
c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}
c => o.push(c),
}
}
o
}
fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max { s.to_string() } else { s.chars().take(max - 1).collect::<String>() + "…" }
}
pub struct Toast<'a> {
pub title: &'a str,
pub body: &'a str,
pub app_name: &'a str,
pub icon: Option<&'a Path>,
pub launch: &'a str,
pub tag: &'a str,
pub group: &'a str,
pub delivery: Delivery,
}
impl Notifier {
pub fn new() -> Self {
let inner = ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(sys::AUMID))
.map_err(|e| sys::log(&format!("notifier: {e}")))
.ok();
Self { inner }
}
/// `None` si Windows autorise l'affichage, sinon la raison du blocage.
pub fn blocked_reason(&self) -> Option<&'static str> {
use windows::UI::Notifications::NotificationSetting as S;
let setting = self.inner.as_ref()?.Setting().ok()?;
match setting {
S::Enabled => None,
S::DisabledForUser => Some("Les notifications Windows sont désactivées pour votre session"),
S::DisabledForApplication => Some("Les notifications de Gotify Lite sont désactivées dans Windows"),
S::DisabledByGroupPolicy => Some("Les notifications sont désactivées par une stratégie de groupe"),
S::DisabledByManifest => Some("Notifications refusées par Windows"),
_ => Some("Notifications bloquées par Windows"),
}
}
pub fn build_xml(t: &Toast) -> String {
let d = t.delivery;
let scenario = if d.sticky { r#" scenario="reminder""# } else { "" };
let image = t
.icon
.map(|p| format!(r#"<image placement="appLogoOverride" hint-crop="circle" src="{}"/>"#, esc(&p.display().to_string())))
.unwrap_or_default();
let audio = if d.sound { "" } else { r#"<audio silent="true"/>"# };
let actions = if d.sticky {
format!(
r#"<actions><action content="Ouvrir" activationType="protocol" arguments="{}"/><action content="Fermer" activationType="system" arguments="dismiss"/></actions>"#,
esc(t.launch)
)
} else {
String::new()
};
format!(
r#"<toast launch="{launch}" activationType="protocol"{scenario}><visual><binding template="ToastGeneric"><text hint-maxLines="2">{title}</text><text>{body}</text>{image}<text placement="attribution">{app}</text></binding></visual>{audio}{actions}</toast>"#,
launch = esc(t.launch),
title = esc(&truncate(t.title, 120)),
body = esc(&truncate(t.body, 600)),
app = esc(t.app_name),
)
}
pub fn show(&self, t: &Toast) {
let Some(notifier) = &self.inner else { return };
let r = (|| -> windows::core::Result<()> {
let xml = XmlDocument::new()?;
xml.LoadXml(&HSTRING::from(Self::build_xml(t)))?;
let toast = ToastNotification::CreateToastNotification(&xml)?;
toast.SetSuppressPopup(!t.delivery.popup)?;
toast.SetTag(&HSTRING::from(truncate(t.tag, 64)))?;
toast.SetGroup(&HSTRING::from(truncate(t.group, 64)))?;
notifier.Show(&toast)
})();
if let Err(e) = r {
sys::log(&format!("toast: {e}"));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xml_is_escaped() {
let t = Toast {
title: "a<b>&\"c\"",
body: "x\u{1}y",
app_name: "App",
icon: None,
launch: "gotify-lite:open",
tag: "1",
group: "1",
delivery: Delivery { popup: true, sound: false, sticky: true },
};
let x = Notifier::build_xml(&t);
assert!(x.contains("a&lt;b&gt;&amp;&quot;c&quot;"));
assert!(x.contains("<text>xy</text>"));
assert!(x.contains(r#"<audio silent="true"/>"#));
assert!(x.contains(r#"scenario="reminder""#));
}
}
+343
View File
@@ -0,0 +1,343 @@
//! Petites intégrations Windows : dossiers, DPAPI, registre, instance unique, shell.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use windows::Win32::Foundation::{ERROR_ALREADY_EXISTS, GetLastError, HANDLE, HLOCAL, LocalFree};
use windows::Win32::Security::Cryptography::{
CRYPT_INTEGER_BLOB, CRYPTPROTECT_UI_FORBIDDEN, CryptProtectData, CryptUnprotectData,
};
use windows::Win32::System::Registry::*;
use windows::Win32::System::SystemInformation::GetLocalTime;
use windows::Win32::System::Threading::CreateMutexW;
use windows::Win32::UI::Shell::ShellExecuteW;
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
use windows::core::{HSTRING, PCWSTR, w};
pub const APP_NAME: &str = "Gotify Lite";
pub const AUMID: &str = "GotifyLite.Client";
pub const URL_SCHEME: &str = "gotify-lite";
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE: &str = "GotifyLite";
fn env_dir(var: &str) -> PathBuf {
let base = std::env::var_os(var).map(PathBuf::from).unwrap_or_else(std::env::temp_dir);
let p = base.join("GotifyLite");
let _ = std::fs::create_dir_all(&p);
p
}
pub fn roaming_dir() -> PathBuf {
env_dir("APPDATA")
}
pub fn local_dir() -> PathBuf {
env_dir("LOCALAPPDATA")
}
pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, data)?;
std::fs::rename(&tmp, path)
}
pub fn now_unix() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Minutes écoulées depuis minuit, heure locale.
pub fn local_minutes() -> u16 {
let t = unsafe { GetLocalTime() };
t.wHour * 60 + t.wMinute
}
/// Journal minimal, borné à ~256 Ko.
pub fn log(msg: &str) {
let path = local_dir().join("gotify-lite.log");
if std::fs::metadata(&path).map(|m| m.len() > 256 * 1024).unwrap_or(false) {
let _ = std::fs::rename(&path, path.with_extension("log.old"));
}
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
let t = unsafe { GetLocalTime() };
let _ = writeln!(
f,
"{:04}-{:02}-{:02} {:02}:{:02}:{:02} [{}] {}",
t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, std::process::id(), msg
);
}
}
// ---------- DPAPI ----------
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
fn unhex(s: &str) -> Option<Vec<u8>> {
if !s.len().is_multiple_of(2) {
return None;
}
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()).collect()
}
pub fn protect(plain: &str) -> Option<String> {
if plain.is_empty() {
return Some(String::new());
}
unsafe {
let input = CRYPT_INTEGER_BLOB { cbData: plain.len() as u32, pbData: plain.as_ptr() as *mut u8 };
let mut out = CRYPT_INTEGER_BLOB::default();
CryptProtectData(&input, w!("Gotify token"), None, None, None, CRYPTPROTECT_UI_FORBIDDEN, &mut out).ok()?;
let v = std::slice::from_raw_parts(out.pbData, out.cbData as usize).to_vec();
LocalFree(Some(HLOCAL(out.pbData as _)));
Some(hex(&v))
}
}
pub fn unprotect(enc: &str) -> Option<String> {
if enc.is_empty() {
return Some(String::new());
}
let data = unhex(enc)?;
unsafe {
let input = CRYPT_INTEGER_BLOB { cbData: data.len() as u32, pbData: data.as_ptr() as *mut u8 };
let mut out = CRYPT_INTEGER_BLOB::default();
CryptUnprotectData(&input, None, None, None, None, CRYPTPROTECT_UI_FORBIDDEN, &mut out).ok()?;
let v = std::slice::from_raw_parts(out.pbData, out.cbData as usize).to_vec();
LocalFree(Some(HLOCAL(out.pbData as _)));
String::from_utf8(v).ok()
}
}
// ---------- Registre (HKCU uniquement, aucun droit admin requis) ----------
pub fn reg_set_str(subkey: &str, name: Option<&str>, value: &str) -> bool {
unsafe {
let mut key = HKEY::default();
let r = RegCreateKeyExW(
HKEY_CURRENT_USER,
&HSTRING::from(subkey),
None,
PCWSTR::null(),
REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE,
None,
&mut key,
None,
);
if r.is_err() {
return false;
}
let wide: Vec<u16> = value.encode_utf16().chain(std::iter::once(0)).collect();
let bytes = std::slice::from_raw_parts(wide.as_ptr() as *const u8, wide.len() * 2);
let name_h = name.map(HSTRING::from);
let name_p = name_h.as_ref().map(|h| PCWSTR(h.as_ptr())).unwrap_or(PCWSTR::null());
let ok = RegSetValueExW(key, name_p, None, REG_SZ, Some(bytes)).is_ok();
let _ = RegCloseKey(key);
ok
}
}
pub fn reg_get_str(subkey: &str, name: &str) -> Option<String> {
unsafe {
let mut buf = vec![0u16; 2048];
let mut size = (buf.len() * 2) as u32;
let r = RegGetValueW(
HKEY_CURRENT_USER,
&HSTRING::from(subkey),
&HSTRING::from(name),
RRF_RT_REG_SZ,
None,
Some(buf.as_mut_ptr() as _),
Some(&mut size),
);
if r.is_err() {
return None;
}
let len = (size as usize / 2).saturating_sub(1);
Some(String::from_utf16_lossy(&buf[..len]))
}
}
fn reg_delete_value(subkey: &str, name: &str) {
unsafe {
let mut key = HKEY::default();
if RegOpenKeyExW(HKEY_CURRENT_USER, &HSTRING::from(subkey), None, KEY_SET_VALUE, &mut key).is_ok() {
let _ = RegDeleteValueW(key, &HSTRING::from(name));
let _ = RegCloseKey(key);
}
}
}
pub fn exe_path() -> String {
std::env::current_exe().map(|p| p.display().to_string()).unwrap_or_default()
}
pub fn autostart_enabled() -> bool {
reg_get_str(RUN_KEY, RUN_VALUE).is_some_and(|v| v.contains(&exe_path()))
}
pub fn set_autostart(on: bool) {
if on {
reg_set_str(RUN_KEY, Some(RUN_VALUE), &format!("\"{}\"", exe_path()));
} else {
reg_delete_value(RUN_KEY, RUN_VALUE);
}
}
/// Inscrit l'appli auprès de Windows : identité de notification (nom + icône visibles
/// dans Paramètres > Notifications) et protocole `gotify-lite:` pour le clic sur un toast.
pub fn register_app(icon_png: &Path) {
let aumid_key = format!(r"Software\Classes\AppUserModelId\{AUMID}");
reg_set_str(&aumid_key, Some("DisplayName"), APP_NAME);
reg_set_str(&aumid_key, Some("IconUri"), &icon_png.display().to_string());
reg_set_str(&aumid_key, Some("IconBackgroundColor"), "FF2B6CB0");
let proto = format!(r"Software\Classes\{URL_SCHEME}");
reg_set_str(&proto, None, &format!("URL:{APP_NAME}"));
reg_set_str(&proto, Some("URL Protocol"), "");
reg_set_str(&format!(r"{proto}\shell\open\command"), None, &format!("\"{}\" --ui", exe_path()));
}
// ---------- Divers ----------
/// Retourne `None` si une autre instance détient déjà ce nom.
pub fn single_instance(name: &str) -> Option<HANDLE> {
unsafe {
let h = CreateMutexW(None, false, &HSTRING::from(name)).ok()?;
if GetLastError() == ERROR_ALREADY_EXISTS { None } else { Some(h) }
}
}
pub fn open_url(url: &str) {
unsafe {
ShellExecuteW(None, w!("open"), &HSTRING::from(url), PCWSTR::null(), PCWSTR::null(), SW_SHOWNORMAL);
}
}
pub fn spawn_ui() {
spawn_with("--ui");
}
pub fn spawn_settings() {
spawn_with("--settings");
}
fn spawn_with(arg: &str) {
use std::os::windows::process::CommandExt;
let _ = std::process::Command::new(std::env::current_exe().unwrap_or_default())
.arg(arg)
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
.spawn();
}
pub fn spawn_daemon() {
let _ = std::process::Command::new(std::env::current_exe().unwrap_or_default()).spawn();
}
// ---------- Dates ----------
/// Parse un horodatage RFC 3339 (format Gotify) en secondes unix.
pub fn parse_rfc3339(s: &str) -> Option<i64> {
let b = s.as_bytes();
let num = |a: usize, n: usize| -> Option<i64> { s.get(a..a + n)?.parse().ok() };
if b.len() < 19 {
return None;
}
let (y, mo, d, h, mi, se) = (num(0, 4)?, num(5, 2)?, num(8, 2)?, num(11, 2)?, num(14, 2)?, num(17, 2)?);
let mut i = 19;
if b.get(i) == Some(&b'.') {
i += 1;
while b.get(i).is_some_and(|c| c.is_ascii_digit()) {
i += 1;
}
}
let offset = match b.get(i) {
Some(b'Z') | Some(b'z') | None => 0,
Some(&c) if c == b'+' || c == b'-' => {
let sign = if c == b'-' { -1 } else { 1 };
sign * (num(i + 1, 2)? * 3600 + num(i + 4, 2)? * 60)
}
_ => return None,
};
// Jours depuis l'époque (algorithme de Howard Hinnant).
let (y2, m2) = if mo <= 2 { (y - 1, mo + 9) } else { (y, mo - 3) };
let era = y2.div_euclid(400);
let yoe = y2 - era * 400;
let doy = (153 * m2 + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146097 + doe - 719468;
Some(days * 86400 + h * 3600 + mi * 60 + se - offset)
}
pub fn relative_time(date: &str) -> String {
let Some(t) = parse_rfc3339(date) else { return String::new() };
let diff = now_unix() as i64 - t;
match diff {
i64::MIN..=44 => "à l'instant".into(),
45..=3599 => format!("il y a {} min", (diff + 30) / 60),
3600..=86399 => format!("il y a {} h", diff / 3600),
86400..=172799 => "hier".into(),
_ if diff < 30 * 86400 => format!("il y a {} j", diff / 86400),
_ => date.get(..10).map(|d| format!("{}/{}/{}", &d[8..10], &d[5..7], &d[..4])).unwrap_or_default(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc3339() {
assert_eq!(parse_rfc3339("1970-01-01T00:00:00Z"), Some(0));
assert_eq!(parse_rfc3339("2026-12-01T18:21:00Z"), Some(1796149260));
assert_eq!(parse_rfc3339("2026-12-01T19:21:00.123456789+01:00"), Some(1796149260));
assert_eq!(parse_rfc3339("2024-02-29T12:00:00-05:30"), Some(1709227800));
assert_eq!(parse_rfc3339("garbage"), None);
}
#[test]
fn hex_roundtrip() {
assert_eq!(unhex(&hex(&[0, 1, 254, 255])), Some(vec![0, 1, 254, 255]));
}
}
// ---------- Coordination fenêtre <-> service ----------
pub const DAEMON_MUTEX: &str = r"Local\GotifyLite.Daemon";
const QUIT_EVENT: &str = r"Local\GotifyLite.Quit";
pub fn daemon_running() -> bool {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Threading::{OpenMutexW, SYNCHRONIZATION_SYNCHRONIZE};
unsafe {
match OpenMutexW(SYNCHRONIZATION_SYNCHRONIZE, false, &HSTRING::from(DAEMON_MUTEX)) {
Ok(h) => {
let _ = CloseHandle(h);
true
}
Err(_) => false,
}
}
}
/// Événement nommé que le service surveille pour s'arrêter proprement.
pub fn quit_event() -> Option<HANDLE> {
use windows::Win32::System::Threading::CreateEventW;
unsafe { CreateEventW(None, true, false, &HSTRING::from(QUIT_EVENT)).ok() }
}
pub fn quit_requested(ev: HANDLE) -> bool {
use windows::Win32::Foundation::WAIT_OBJECT_0;
use windows::Win32::System::Threading::WaitForSingleObject;
unsafe { WaitForSingleObject(ev, 0) == WAIT_OBJECT_0 }
}
pub fn stop_daemon() {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Threading::{EVENT_MODIFY_STATE, OpenEventW, SetEvent};
unsafe {
if let Ok(h) = OpenEventW(EVENT_MODIFY_STATE, false, &HSTRING::from(QUIT_EVENT)) {
let _ = SetEvent(h);
let _ = CloseHandle(h);
}
}
}
+634
View File
@@ -0,0 +1,634 @@
//! Fenêtre (egui) : historique des messages + réglages. Processus séparé, lancé à la demande.
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant, SystemTime};
use eframe::egui::{self, Color32, RichText};
use crate::config::{Config, MUTE_FOREVER, State};
use crate::gotify::{self, App, Client, Message};
use crate::icon::{self, Look};
use crate::sys;
const PAGE: u32 = 100;
pub fn run(settings: bool) {
let Some(_guard) = sys::single_instance("Local\\GotifyLite.UI") else {
focus_existing();
return;
};
let rgba = icon::render(64, Look::Connected);
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title(sys::APP_NAME)
.with_inner_size([820.0, 600.0])
.with_min_inner_size([560.0, 420.0])
.with_icon(Arc::new(egui::IconData { rgba, width: 64, height: 64 })),
..Default::default()
};
if let Err(e) = eframe::run_native(sys::APP_NAME, options, Box::new(move |cc| Ok(Box::new(Gui::new(&cc.egui_ctx, settings))))) {
sys::log(&format!("ui: {e}"));
}
}
fn focus_existing() {
use windows::Win32::UI::WindowsAndMessaging::*;
use windows::core::{HSTRING, PCWSTR};
unsafe {
if let Ok(h) = FindWindowW(PCWSTR::null(), &HSTRING::from(sys::APP_NAME)) {
let _ = ShowWindow(h, SW_RESTORE);
let _ = SetForegroundWindow(h);
}
}
}
#[derive(PartialEq, Clone, Copy)]
enum Tab {
Messages,
Settings,
}
enum Done {
Loaded { apps: Vec<App>, messages: Vec<Message>, next: Option<u64>, append: bool },
Deleted(u64),
DeletedMany(Option<u64>),
Test(Result<String, String>),
Error(String),
}
struct Gui {
cfg: Config,
saved: Config,
cfg_mtime: Option<SystemTime>,
url_edit: String,
token_edit: String,
show_token: bool,
autostart: bool,
tab: Tab,
state: State,
daemon_running: bool,
last_poll: Instant,
apps: Vec<App>,
messages: Vec<Message>,
next_since: Option<u64>,
filter: Option<u64>,
search: String,
confirm_delete: bool,
loading: bool,
error: Option<String>,
test: Option<Result<String, String>>,
testing: bool,
tx: mpsc::Sender<Done>,
rx: mpsc::Receiver<Done>,
ctx: egui::Context,
}
impl Gui {
fn new(ctx: &egui::Context, settings: bool) -> Self {
let cfg = Config::load();
let (tx, rx) = mpsc::channel();
let mut g = Self {
url_edit: cfg.server_url.clone(),
token_edit: cfg.token.clone(),
show_token: false,
autostart: sys::autostart_enabled(),
tab: if cfg.is_configured() && !settings { Tab::Messages } else { Tab::Settings },
saved: cfg.clone(),
cfg,
cfg_mtime: Config::mtime(),
state: State::load(),
daemon_running: sys::daemon_running(),
last_poll: Instant::now(),
apps: Vec::new(),
messages: Vec::new(),
next_since: None,
filter: None,
search: String::new(),
confirm_delete: false,
loading: false,
error: None,
test: None,
testing: false,
tx,
rx,
ctx: ctx.clone(),
};
g.apply_theme();
install_system_fonts(ctx);
let mut style = (*ctx.global_style()).clone();
style.spacing.item_spacing = egui::vec2(8.0, 6.0);
style.spacing.button_padding = egui::vec2(10.0, 4.0);
ctx.set_global_style(style);
if g.cfg.is_configured() {
g.reload(false);
}
g
}
fn apply_theme(&self) {
self.ctx.set_theme(match self.cfg.theme.as_str() {
"light" => egui::ThemePreference::Light,
"dark" => egui::ThemePreference::Dark,
_ => egui::ThemePreference::System,
});
}
fn job(&self, f: impl FnOnce(Client) -> Done + Send + 'static) {
let client = Client::new(&self.cfg);
let (tx, ctx) = (self.tx.clone(), self.ctx.clone());
std::thread::spawn(move || {
let _ = tx.send(f(client));
ctx.request_repaint();
});
}
fn reload(&mut self, append: bool) {
if !self.cfg.is_configured() || self.loading {
return;
}
self.loading = true;
let since = if append { self.next_since } else { None };
self.job(move |c| {
let apps = if append { Ok(Vec::new()) } else { c.applications() };
match (apps, c.messages(PAGE, since)) {
(Ok(apps), Ok(p)) => Done::Loaded {
apps,
next: p.paging.next.as_ref().map(|_| p.paging.since),
messages: p.messages,
append,
},
(Err(e), _) | (_, Err(e)) => Done::Error(e),
}
});
}
fn poll(&mut self) {
while let Ok(d) = self.rx.try_recv() {
match d {
Done::Loaded { apps, messages, next, append } => {
self.loading = false;
self.error = None;
if append {
self.messages.extend(messages);
} else {
self.apps = apps;
self.messages = messages;
}
self.next_since = next.filter(|&s| s > 0);
}
Done::Deleted(id) => self.messages.retain(|m| m.id != id),
Done::DeletedMany(app) => match app {
Some(a) => self.messages.retain(|m| m.appid != a),
None => self.messages.clear(),
},
Done::Test(r) => {
self.testing = false;
let ok = r.is_ok();
self.test = Some(r);
if ok {
self.reload(false);
}
}
Done::Error(e) => {
self.loading = false;
self.error = Some(e);
}
}
}
// État du service + modifications externes (menu de l'icône) toutes les secondes.
if self.last_poll.elapsed() >= Duration::from_secs(1) {
self.last_poll = Instant::now();
self.state = State::load();
self.daemon_running = sys::daemon_running();
let m = Config::mtime();
if m != self.cfg_mtime {
self.cfg_mtime = m;
if self.cfg == self.saved {
self.cfg = Config::load();
self.saved = self.cfg.clone();
self.apply_theme();
}
}
}
self.ctx.request_repaint_after(Duration::from_secs(1));
// Sauvegarde automatique des réglages.
if self.cfg != self.saved {
if self.cfg.theme != self.saved.theme {
self.apply_theme();
}
match self.cfg.save() {
Ok(()) => {
self.saved = self.cfg.clone();
self.cfg_mtime = Config::mtime();
}
Err(e) => self.error = Some(format!("Impossible d'enregistrer : {e}")),
}
}
}
fn app_name(&self, id: u64) -> &str {
self.apps.iter().find(|a| a.id == id).map(|a| a.name.as_str()).unwrap_or("?")
}
// ------------------------------------------------------------ en-tête
fn header(&mut self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.heading(RichText::new("🔔 Gotify Lite").strong());
ui.add_space(12.0);
ui.selectable_value(&mut self.tab, Tab::Messages, "Messages");
ui.selectable_value(&mut self.tab, Tab::Settings, "Paramètres");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (dot, text) = if !self.daemon_running {
(Color32::from_rgb(200, 60, 60), "Service arrêté".to_string())
} else {
match self.state.status.as_str() {
"connected" => (Color32::from_rgb(40, 170, 90), format!("Connecté · {}", self.state.detail)),
"connecting" => (Color32::from_rgb(220, 160, 30), "Connexion…".into()),
"unconfigured" => (Color32::GRAY, "Non configuré".into()),
_ => (Color32::from_rgb(200, 60, 60), "Déconnecté".into()),
}
};
if !self.daemon_running && ui.button("Démarrer").clicked() {
sys::spawn_daemon();
}
let r = ui.label(text);
if self.state.status == "error" && !self.state.detail.is_empty() {
r.on_hover_text(&self.state.detail);
}
ui.colored_label(dot, "●");
if let Some(m) = crate::daemon::describe_mute(&self.cfg) {
ui.separator();
ui.colored_label(Color32::from_rgb(220, 130, 40), format!("🔕 {m}"));
}
});
});
}
// ------------------------------------------------------------ messages
fn messages_tab(&mut self, ui: &mut egui::Ui) {
if !self.cfg.is_configured() {
ui.add_space(40.0);
ui.vertical_centered(|ui| {
ui.label("Aucun serveur configuré.");
if ui.button("Configurer le serveur").clicked() {
self.tab = Tab::Settings;
}
});
return;
}
egui::Panel::left("apps").resizable(false).exact_size(180.0).show(ui, |ui| {
ui.add_space(6.0);
let total = self.messages.len();
if ui.selectable_label(self.filter.is_none(), format!("Toutes ({total})")).clicked() {
self.filter = None;
self.confirm_delete = false;
}
ui.separator();
let apps: Vec<(u64, String)> = self.apps.iter().map(|a| (a.id, a.name.clone())).collect();
egui::ScrollArea::vertical().show(ui, |ui| {
for (id, name) in apps {
let n = self.messages.iter().filter(|m| m.appid == id).count();
let muted = self.cfg.muted_apps.contains(&id);
let label = format!("{}{} ({n})", if muted { "🔕 " } else { "" }, name);
let r = ui.selectable_label(self.filter == Some(id), label);
if r.clicked() {
self.filter = Some(id);
self.confirm_delete = false;
}
r.context_menu(|ui| {
let txt = if muted { "Réactiver les notifications" } else { "Couper les notifications" };
if ui.button(txt).clicked() {
if muted {
self.cfg.muted_apps.retain(|a| *a != id);
} else {
self.cfg.muted_apps.push(id);
}
ui.close();
}
});
}
});
});
egui::CentralPanel::default().show(ui, |ui| {
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.search).hint_text("🔍 Rechercher…").desired_width(220.0));
if ui.add_enabled(!self.loading, egui::Button::new("⟳ Actualiser")).clicked() {
self.reload(false);
}
if self.loading {
ui.spinner();
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let what = match self.filter {
Some(a) => format!("les messages de {}", self.app_name(a)),
None => "tous les messages".into(),
};
if self.confirm_delete {
if ui.button("Annuler").clicked() {
self.confirm_delete = false;
}
if ui.button(RichText::new("Supprimer").color(Color32::from_rgb(220, 70, 70))).clicked() {
self.confirm_delete = false;
let app = self.filter;
self.job(move |c| match app {
Some(a) => c.delete_app_messages(a).map(|_| Done::DeletedMany(Some(a))).unwrap_or_else(Done::Error),
None => c.delete_all().map(|_| Done::DeletedMany(None)).unwrap_or_else(Done::Error),
});
}
ui.label(format!("Supprimer {what} du serveur ?"));
} else if ui.button("🗑 Tout supprimer").on_hover_text(format!("Supprime {what} du serveur")).clicked() {
self.confirm_delete = true;
}
});
});
if let Some(e) = &self.error {
ui.colored_label(Color32::from_rgb(220, 70, 70), format!("⚠ {e}"));
}
ui.separator();
let q = self.search.to_lowercase();
let list: Vec<Message> = self
.messages
.iter()
.filter(|m| self.filter.is_none_or(|a| m.appid == a))
.filter(|m| {
q.is_empty()
|| m.message.to_lowercase().contains(&q)
|| m.title.as_deref().unwrap_or("").to_lowercase().contains(&q)
})
.cloned()
.collect();
egui::ScrollArea::vertical().auto_shrink(false).show(ui, |ui| {
if list.is_empty() && !self.loading {
ui.add_space(30.0);
ui.vertical_centered(|ui| ui.weak("Aucun message"));
}
for m in &list {
self.message_card(ui, m);
}
if self.next_since.is_some() && self.search.is_empty() {
ui.vertical_centered(|ui| {
if ui.add_enabled(!self.loading, egui::Button::new("Charger plus")).clicked() {
self.reload(true);
}
});
}
});
});
}
fn message_card(&mut self, ui: &mut egui::Ui, m: &Message) {
let p = m.priority();
let accent = match p {
8.. => Color32::from_rgb(220, 70, 70),
4..=7 => Color32::from_rgb(230, 150, 40),
1..=3 => Color32::from_rgb(70, 140, 220),
_ => Color32::GRAY,
};
egui::Frame::group(ui.style()).inner_margin(egui::Margin::same(10)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.colored_label(accent, "▍");
ui.label(RichText::new(self.app_name(m.appid).to_string()).strong());
ui.label(RichText::new(format!("P{p}")).small().color(accent)).on_hover_text("Priorité");
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("🗑").on_hover_text("Supprimer du serveur").clicked() {
let id = m.id;
self.job(move |c| c.delete_message(id).map(|_| Done::Deleted(id)).unwrap_or_else(Done::Error));
}
if let Some(url) = m.click_url()
&& ui.small_button("🔗").on_hover_text(&url).clicked() {
sys::open_url(&url);
}
ui.weak(sys::relative_time(&m.date)).on_hover_text(&m.date);
});
});
if let Some(t) = m.title.as_deref().filter(|t| !t.is_empty()) {
ui.label(RichText::new(t).strong().size(15.0));
}
let body = if m.is_markdown() { gotify::strip_markdown(&m.message) } else { m.message.clone() };
ui.add(egui::Label::new(body).selectable(true).wrap());
});
ui.add_space(4.0);
}
// ------------------------------------------------------------ réglages
fn settings_tab(&mut self, ui: &mut egui::Ui) {
egui::CentralPanel::default().show(ui, |ui| {
egui::ScrollArea::vertical().auto_shrink(false).show(ui, |ui| {
ui.set_max_width(640.0);
section(ui, "Serveur");
egui::Grid::new("srv").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
ui.label("URL");
ui.add(egui::TextEdit::singleline(&mut self.url_edit).hint_text("https://gotify.exemple.fr").desired_width(360.0));
ui.end_row();
ui.label("Token client");
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut self.token_edit).password(!self.show_token).desired_width(320.0));
if ui.small_button(if self.show_token { "🙈" } else { "👁" }).clicked() {
self.show_token = !self.show_token;
}
});
ui.end_row();
});
ui.weak("Dans l'interface web Gotify : Clients → Créer un client, puis copiez son token (pas un token d'application).");
ui.horizontal(|ui| {
let changed = gotify::normalize_url(&self.url_edit) != self.cfg.server_url || self.token_edit.trim() != self.cfg.token;
if ui.add_enabled(!self.testing, egui::Button::new(if changed { "Enregistrer et connecter" } else { "Tester la connexion" })).clicked() {
self.cfg.server_url = gotify::normalize_url(&self.url_edit);
self.url_edit = self.cfg.server_url.clone();
self.cfg.token = self.token_edit.trim().to_string();
self.testing = true;
self.test = None;
self.job(|c| {
Done::Test(c.version().and_then(|v| c.current_user().map(|u| format!("Connecté en tant que « {} » — Gotify {}", u.name, v.version))))
});
}
if self.testing {
ui.spinner();
}
});
match &self.test {
Some(Ok(s)) => {
ui.colored_label(Color32::from_rgb(40, 170, 90), format!("✔ {s}"));
}
Some(Err(e)) => {
ui.colored_label(Color32::from_rgb(220, 70, 70), format!("✖ {e}"));
}
None => {}
}
ui.checkbox(&mut self.cfg.accept_invalid_certs, "Accepter les certificats non valides (auto-signés)")
.on_hover_text("À éviter : préférez installer votre autorité de certification dans Windows.");
section(ui, "Notifications");
ui.checkbox(&mut self.cfg.notifications, "Afficher les notifications Windows");
ui.add_enabled_ui(self.cfg.notifications, |ui| {
ui.checkbox(&mut self.cfg.sound, "Jouer un son");
egui::Grid::new("prio").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| {
ui.label("Ignorer en dessous de la priorité");
ui.add(egui::Slider::new(&mut self.cfg.min_priority, 0..=10));
ui.end_row();
ui.label("Bannière à partir de la priorité")
.on_hover_text("En dessous : discret, directement dans le centre de notifications.");
ui.add(egui::Slider::new(&mut self.cfg.banner_min_priority, 0..=10));
ui.end_row();
ui.label("Reste affichée à partir de la priorité")
.on_hover_text("La notification reste à l'écran jusqu'à ce que vous la fermiez.");
ui.add(egui::Slider::new(&mut self.cfg.sticky_min_priority, 0..=11).custom_formatter(|v, _| if v > 10.0 { "jamais".into() } else { format!("{v}") }));
ui.end_row();
});
ui.checkbox(&mut self.cfg.catch_up, "Afficher les messages manqués à la reconnexion");
if !self.apps.is_empty() {
ui.collapsing("Notifications par application", |ui| {
for a in &self.apps {
let mut on = !self.cfg.muted_apps.contains(&a.id);
if ui.checkbox(&mut on, &a.name).changed() {
if on {
self.cfg.muted_apps.retain(|x| *x != a.id);
} else {
self.cfg.muted_apps.push(a.id);
}
}
}
});
}
});
if ui.button("Paramètres de notification Windows…").on_hover_text("Style des bannières, écran de verrouillage, Ne pas déranger…").clicked() {
sys::open_url("ms-settings:notifications");
}
section(ui, "Silence");
ui.horizontal_wrapped(|ui| {
let now = sys::now_unix();
for (label, mins) in [("30 min", 30u64), ("1 h", 60), ("4 h", 240), ("8 h", 480)] {
if ui.button(label).clicked() {
self.cfg.mute_until = now + mins * 60;
}
}
if ui.button("Indéfiniment").clicked() {
self.cfg.mute_until = MUTE_FOREVER;
}
if ui.add_enabled(self.cfg.manual_mute_active(now), egui::Button::new("Réactiver")).clicked() {
self.cfg.mute_until = 0;
}
});
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.checkbox(&mut self.cfg.quiet_enabled, "Heures calmes chaque jour de");
ui.add_enabled_ui(self.cfg.quiet_enabled, |ui| {
time_edit(ui, &mut self.cfg.quiet_start);
ui.label("à");
time_edit(ui, &mut self.cfg.quiet_end);
});
});
ui.horizontal(|ui| {
ui.label("Pendant un silence, laisser passer à partir de la priorité");
ui.add(egui::Slider::new(&mut self.cfg.silence_bypass_priority, 0..=11).custom_formatter(|v, _| if v > 10.0 { "jamais".into() } else { format!("{v}") }));
});
ui.weak("En silence, les messages arrivent quand même dans le centre de notifications, sans son ni bannière.");
section(ui, "Général");
if ui.checkbox(&mut self.autostart, "Lancer au démarrage de Windows").changed() {
sys::set_autostart(self.autostart);
self.autostart = sys::autostart_enabled();
}
ui.horizontal(|ui| {
ui.label("Thème");
ui.selectable_value(&mut self.cfg.theme, "system".to_string(), "Système");
ui.selectable_value(&mut self.cfg.theme, "light".to_string(), "☀ Clair");
ui.selectable_value(&mut self.cfg.theme, "dark".to_string(), "🌙 Sombre");
});
ui.horizontal(|ui| {
if ui.button("Dossier des données").clicked() {
sys::open_url(&sys::local_dir().display().to_string());
}
if self.daemon_running && ui.button("Arrêter le service de fond").clicked() {
sys::stop_daemon();
}
});
ui.add_space(8.0);
ui.weak(format!("Gotify Lite {} · réglages enregistrés automatiquement", env!("CARGO_PKG_VERSION")));
});
});
}
}
/// Utilise les polices de Windows (Segoe UI + symboles/emoji) : rendu natif, binaire inchangé.
fn install_system_fonts(ctx: &egui::Context) {
let dir = std::env::var_os("WINDIR").map(std::path::PathBuf::from).unwrap_or_else(|| r"C:\Windows".into()).join("Fonts");
let mut fonts = egui::FontDefinitions::default();
let mut added = Vec::new();
for (name, file) in [("segoe", "segoeui.ttf"), ("segoe-sym", "seguisym.ttf"), ("segoe-emoji", "seguiemj.ttf")] {
if let Ok(bytes) = std::fs::read(dir.join(file)) {
fonts.font_data.insert(name.into(), Arc::new(egui::FontData::from_owned(bytes)));
added.push(name.to_string());
}
}
if added.is_empty() {
return;
}
let prop = fonts.families.entry(egui::FontFamily::Proportional).or_default();
if added[0] == "segoe" {
prop.insert(0, "segoe".into());
}
prop.extend(added.iter().filter(|n| *n != "segoe").cloned());
let mono = fonts.families.entry(egui::FontFamily::Monospace).or_default();
mono.extend(added.iter().filter(|n| *n != "segoe").cloned());
ctx.set_fonts(fonts);
}
fn section(ui: &mut egui::Ui, title: &str) {
ui.add_space(14.0);
ui.label(RichText::new(title).strong().size(16.0));
ui.separator();
}
fn time_edit(ui: &mut egui::Ui, minutes: &mut u16) {
let mut h = *minutes / 60;
let mut m = *minutes % 60;
ui.add(egui::DragValue::new(&mut h).range(0..=23).custom_formatter(|v, _| format!("{v:02}")));
ui.label(":");
ui.add(egui::DragValue::new(&mut m).range(0..=59).speed(0.5).custom_formatter(|v, _| format!("{v:02}")));
*minutes = h * 60 + m;
}
impl eframe::App for Gui {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.poll();
egui::Panel::top("top").show(ui, |ui| {
ui.add_space(6.0);
self.header(ui);
ui.add_space(4.0);
if self.daemon_running && !self.state.toasts_blocked.is_empty() {
egui::Frame::new()
.fill(Color32::from_rgba_unmultiplied(230, 150, 40, 40))
.corner_radius(6.0)
.inner_margin(egui::Margin::symmetric(10, 6))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(format!("⚠ {} : aucune bannière ne peut s'afficher.", self.state.toasts_blocked));
if ui.button("Ouvrir les paramètres Windows").clicked() {
sys::open_url("ms-settings:notifications");
}
});
});
ui.add_space(4.0);
}
});
match self.tab {
Tab::Messages => self.messages_tab(ui),
Tab::Settings => self.settings_tab(ui),
}
}
}