Web Variante in Go V0.1

This commit is contained in:
concierge committed 2026-11-12 20:00:33 +01:00
1 parent f9e3e94629
commit 692b9b6ef8
60 files changed
+13140

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
// Command lektorenplan serves the browser version of LektorenPlan.
package main
import (
"context"
"crypto/rand"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"syscall"
"time"
"lektorenplan/domain"
"lektorenplan/store"
"lektorenplan/web"
)
// version can be overridden at build time with
// -ldflags "-X main.version=1.2.3".
var version = "1.0.0"
func main() {
if err := run(); err != nil {
log.Fatalf("lektorenplan: %v", err)
}
}
func run() error {
var (
addr string
dbPath string
seedDemo bool
adminUser string
adminPassword string
secureCookies bool
demoMode bool
syncLiturgy bool
)
flag.StringVar(&addr, "addr", env("LP_ADDR", ":8080"), "HTTP listen address")
flag.StringVar(&dbPath, "db", env("LP_DB", "lektorenplan.db"), "path to the SQLite database")
flag.BoolVar(&seedDemo, "seed-demo", envBool("LP_SEED_DEMO", false), "create demo tenants and accounts on an empty database")
flag.StringVar(&adminUser, "admin-user", env("LP_ADMIN_USER", "admin"), "initial administrator username")
flag.StringVar(&adminPassword, "admin-password", env("LP_ADMIN_PASSWORD", ""), "initial administrator password (generated when empty)")
flag.BoolVar(&secureCookies, "secure-cookies", envBool("LP_SECURE_COOKIES", false), "mark session cookies Secure (enable behind HTTPS)")
flag.BoolVar(&demoMode, "demo", envBool("LP_DEMO_MODE", false), "show the demo badge in the interface")
flag.BoolVar(&syncLiturgy, "sync-liturgy", envBool("LP_SYNC_LITURGY", true), "refresh the liturgical calendar daily in the background")
flag.Parse()
if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil && filepath.Dir(dbPath) != "." {
return fmt.Errorf("create database directory: %w", err)
}
st, err := store.Open(dbPath)
if err != nil {
return err
}
defer st.Close()
ctx := context.Background()
if err := bootstrap(ctx, st, seedDemo, adminUser, adminPassword); err != nil {
return err
}
server, err := web.New(st, web.Options{
SecureCookies: secureCookies,
Version: version,
DemoMode: demoMode,
})
if err != nil {
return err
}
if syncLiturgy {
go liturgyLoop(st)
}
httpServer := &http.Server{
Addr: addr,
Handler: server.Handler(),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 120 * time.Second,
IdleTimeout: 120 * time.Second,
}
errc := make(chan error, 1)
go func() {
log.Printf("LektorenPlan %s lauscht auf %s (Datenbank: %s)", version, addr, dbPath)
if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errc <- err
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
select {
case err := <-errc:
return err
case sig := <-stop:
log.Printf("%s empfangen, beende Server …", sig)
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
return httpServer.Shutdown(shutdownCtx)
}
func bootstrap(ctx context.Context, st *store.Store, seedDemo bool, adminUser, adminPassword string) error {
if seedDemo {
if err := st.SeedDemo(ctx); err != nil {
return fmt.Errorf("seed demo data: %w", err)
}
log.Printf("Demo-Daten und Demo-Konten sind vorhanden.")
}
count, err := st.CountUsers(ctx)
if err != nil {
return fmt.Errorf("count users: %w", err)
}
if count == 0 {
password := adminPassword
generated := false
if password == "" {
password, err = randomPassword()
if err != nil {
return fmt.Errorf("generate administrator password: %w", err)
}
generated = true
}
created, err := st.EnsureAdmin(ctx, adminUser, password)
if err != nil {
return fmt.Errorf("create administrator: %w", err)
}
if created && generated {
log.Printf("Administrator %q angelegt. Einmaliges Passwort: %s", adminUser, password)
log.Printf("Bitte nach der ersten Anmeldung ändern.")
} else if created {
log.Printf("Administrator %q angelegt.", adminUser)
}
}
return nil
}
// liturgyLoop refreshes the liturgical calendar once a day. Failures are
// non-fatal: the bundled snapshot and local computation keep the app usable.
func liturgyLoop(st *store.Store) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
syncYears(ctx, st)
ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop()
for range ticker.C {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
syncYears(ctx, st)
cancel()
}
}
func syncYears(ctx context.Context, st *store.Store) {
if st.Setting(ctx, "autoSyncLiturgy") == "0" {
return
}
year := domain.Year(domain.Today())
for _, target := range []int{year, year + 1} {
if err := web.SyncLiturgyYear(ctx, st, target); err != nil {
log.Printf("Liturgie-Synchronisierung %d: %v", target, err)
continue
}
log.Printf("Liturgischer Kalender %d aktualisiert.", target)
}
}
func randomPassword() (string, error) {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"
buf := make([]byte, 20)
if _, err := rand.Read(buf); err != nil {
return "", err
}
for i := range buf {
buf[i] = alphabet[int(buf[i])%len(alphabet)]
}
return string(buf), nil
}
func env(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
func envBool(key string, fallback bool) bool {
value := os.Getenv(key)
if value == "" {
return fallback
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return fallback
}
return parsed
}