Files
lan-clipboard/agent/cmd/lc-agent/main.go
T
dbildhauerandClaude Opus 5.5 4aebac5336 feat: desktop-agent für windows, macos und linux
Go-Programm lc-agent: sendet neu kopierten Text als Clip ins Projekt
"Zwischenablage" und übernimmt eigene Clips anderer Geräte live in die
Zwischenablage. Von Passwort-Managern markierte Inhalte werden nie
gesendet; Größengrenze, Ausschlussmuster, nur die letzten 50 eigenen
Clips. Wiederholt beim Start, bis der Server erreichbar ist; beendet sich
bei widerrufenem Token mit Exit-Code 3. Build für alle Plattformen per
build.sh im Container, Autostart-Vorlagen für alle drei Systeme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:11:40 +01:00

214 lines
5.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// lc-agent syncs the clipboard of this computer with LAN-Clipboard.
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
"golang.org/x/term"
"lan-clipboard/agent/internal/agent"
"lan-clipboard/agent/internal/api"
"lan-clipboard/agent/internal/clipboard"
"lan-clipboard/agent/internal/config"
)
// Set at build time with -ldflags "-X main.version=…"
var version = "dev"
// Exit code for a rejected token, so autostart (systemd) does not restart in a loop
const exitUnauthorized = 3
const usage = `lc-agent – Zwischenablage mit LAN-Clipboard synchronisieren
Befehle:
lc-agent setup Server und Token eingeben, Verbindung prüfen, Konfiguration speichern
lc-agent run Synchronisieren (läuft, bis er beendet wird)
lc-agent version Version anzeigen
Optionen:
-config DATEI Konfigurationsdatei (Standard: %s)
-log DATEI Protokoll in eine Datei statt auf die Konsole schreiben
`
func main() {
defaultPath, _ := config.DefaultPath()
flags := flag.NewFlagSet("lc-agent", flag.ExitOnError)
configPath := flags.String("config", defaultPath, "")
logPath := flags.String("log", "", "")
flags.Usage = func() { fmt.Fprintf(os.Stderr, usage, defaultPath) }
if len(os.Args) < 2 {
flags.Usage()
os.Exit(2)
}
command := os.Args[1]
flags.Parse(os.Args[2:])
var err error
switch command {
case "setup":
err = setup(*configPath)
case "run":
err = run(*configPath, *logPath)
case "version":
fmt.Println("lc-agent", version)
default:
flags.Usage()
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "Fehler:", err)
if errors.Is(err, api.ErrUnauthorized) {
os.Exit(exitUnauthorized)
}
os.Exit(1)
}
}
func run(configPath, logPath string) error {
cfg, err := config.Load(configPath)
if err != nil {
return err
}
out := io.Writer(os.Stderr)
if logPath != "" {
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return err
}
defer file.Close()
out = file
}
logger := log.New(out, "", log.LstdFlags)
cb, err := clipboard.New()
if err != nil {
return err
}
client, err := api.New(cfg.Server, cfg.Token, version)
if err != nil {
return err
}
a, err := agent.New(cfg, client, cb, logger, config.StatePath(configPath))
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := setupWithRetry(ctx, a, logger); err != nil {
return explain(err)
}
err = a.Run(ctx)
if err != nil {
return explain(err)
}
logger.Print("Beendet")
return nil
}
func explain(err error) error {
if errors.Is(err, api.ErrUnauthorized) {
return fmt.Errorf("%w – neuen Token erstellen und \"lc-agent setup\" ausführen", err)
}
return err
}
// setupWithRetry waits for the server, e.g. when the computer starts before the network.
// Only a rejected token ends the agent.
func setupWithRetry(ctx context.Context, a *agent.Agent, logger *log.Logger) error {
delay := 2 * time.Second
for {
err := a.Setup(ctx)
if ctx.Err() != nil {
return nil // stopped while waiting (Ctrl+C, shutdown)
}
if err == nil || errors.Is(err, api.ErrUnauthorized) {
return err
}
logger.Printf("Server nicht erreichbar (%v), neuer Versuch in %s", err, delay)
select {
case <-ctx.Done():
return nil
case <-time.After(delay):
}
delay = min(delay*2, time.Minute)
}
}
func setup(configPath string) error {
in := bufio.NewReader(os.Stdin)
cfg := config.Defaults()
if existing, err := config.Load(configPath); err == nil {
cfg = existing
}
cfg.Server = ask(in, "Server-Adresse", cfg.Server)
fmt.Print("Token (unter \"Konto\" → \"Geräte-Tokens\" erstellen): ")
token, err := readSecret(in)
if err != nil {
return err
}
if token != "" {
cfg.Token = token
}
cfg.Direction = config.Direction(ask(in, "Richtung: both (senden und empfangen), send oder receive", string(cfg.Direction)))
cfg.Project = ask(in, "Projekt für gesendete Clips (leer: keins)", cfg.Project)
if err := cfg.Validate(); err != nil {
return err
}
client, err := api.New(cfg.Server, cfg.Token, version)
if err != nil {
return err
}
user, err := client.Me(context.Background())
if err != nil {
return fmt.Errorf("Verbindung fehlgeschlagen: %w", err)
}
if err := config.Save(configPath, cfg); err != nil {
return err
}
fmt.Printf("Verbunden als %s. Konfiguration gespeichert in %s\n", user.Username, configPath)
fmt.Println("Starten mit: lc-agent run")
return nil
}
func ask(in *bufio.Reader, prompt, current string) string {
if current != "" {
fmt.Printf("%s [%s]: ", prompt, current)
} else {
fmt.Printf("%s: ", prompt)
}
line, _ := in.ReadString('\n')
if line = strings.TrimSpace(line); line != "" {
return line
}
return current
}
// readSecret reads without echo when attached to a terminal.
func readSecret(in *bufio.Reader) (string, error) {
if term.IsTerminal(int(os.Stdin.Fd())) {
data, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
return strings.TrimSpace(string(data)), err
}
line, err := in.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
return "", err
}
return strings.TrimSpace(line), nil
}