Files
landwelle/main.go
T
OpenGenesis (MPL 2.0) fda6501439 fix: exclude legacy Niedersachsen Hub events in Landwelle v1.5.76
* fix(events): exclude legacy tourism hub sources in events.go

* fix(events): exclude legacy tourism hub sources in admin_management.go

* test(events): prevent reintroduction of legacy tourism hub entries

* chore: bump Landwelle to v1.5.76

* chore: bump Landwelle to v1.5.76

* docs(events): clarify v1.5.76 external-event hardening and server checks

* docs(events): clarify v1.5.76 external-event hardening and server checks

* docs(events): clarify v1.5.76 external-event hardening and server checks

* docs: release notes for Landwelle v1.5.76

* fix(events): escape ILIKE percent signs inside fmt.Sprintf SQL

* test(events): normalize escaped SQL wildcards in fmt.Sprintf queries

* ci: compare container version to source instead of hardcoding 1.5.75
2026-11-10 17:07:27 +01:00

1370 lines
60 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.
package main
import (
"bytes"
"context"
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/fs"
"log"
"math/rand"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
//go:embed web
var webFS embed.FS
var (
buildCommit = "unknown"
buildTime = "unknown"
)
const (
defaultStreamURL = "https://stream.slmm.de:10443/listen/landwelle/landwelle"
apiVersion = "v1"
apiContractVersion = "1.0.0"
applicationName = "Landwelle Radio"
applicationVersion = "1.5.76"
)
var publicTemplateFiles = []string{
"web/index.html",
"web/player.html",
"web/partials.html",
"web/page.html",
"web/excursions.html",
"web/traffic.html",
"web/program.html",
"web/mitmachen.html",
"web/team.html",
"web/downloads.html",
"web/empfangen.html",
"web/mobile-app.html",
"web/livestudio.html",
"web/playlist.html",
"web/404.html",
"web/forum.html",
"web/forum-topic.html",
"web/forum-new.html",
"web/charts-listener.html",
"web/news.html",
"web/news-article.html",
"web/editorial-story.html",
"web/landwelle-vor-ort.html",
"web/events.html",
"web/advertising.html",
"web/directory.html",
"web/ontour.html",
"web/jobs.html",
"web/managed-page.html",
"web/faq.html",
"web/contact.html",
"web/mediathek.html",
"web/landwelle-zuhause.html",
}
func displayVersion() string {
return "Landwelle v" + applicationVersion
}
type NewsItem struct {
Category string
Title string
Age string
Image string
URL string
Source string
}
type Event struct {
ID int64
Day string
Month string
Title string
DateTime string
Place string
Image string
URL string
}
type Story struct {
Title string
Age string
Image string
URL string
Teaser string
Location string
AIUsage string
AIHumanReviewed bool
AIEditorialResponsible string
AIDisclosure string
MediaAIUsage string
MediaAIDisclosure string
MediaWatermarkEnabled bool
MediaWatermarkText string
}
func (s Story) HasAITransparency() bool { return normalizeAIUsage(s.AIUsage) != "none" }
func (s Story) AIShortLabel() string { return aiUsageShortLabel(s.AIUsage) }
func (s Story) AITransparencyText() string {
if text := strings.TrimSpace(s.AIDisclosure); text != "" {
return text
}
return defaultAIDisclosure(s.AIUsage)
}
func (s Story) AIReviewLabel() string {
if !s.HasAITransparency() {
return ""
}
if s.AIHumanReviewed {
if responsible := strings.TrimSpace(s.AIEditorialResponsible); responsible != "" {
return "Redaktionell geprüft · Verantwortlich: " + responsible
}
return "Redaktionell geprüft"
}
return "Keine redaktionelle Prüfung dokumentiert"
}
func (s Story) HasMediaAITransparency() bool { return normalizeMediaAIUsage(s.MediaAIUsage) != "none" }
func (s Story) MediaAITransparencyText() string {
if text := strings.TrimSpace(s.MediaAIDisclosure); text != "" {
return text
}
switch normalizeMediaAIUsage(s.MediaAIUsage) {
case "generated":
return "Dieses Bild wurde mithilfe künstlicher Intelligenz erstellt."
case "manipulated":
return "Dieses Bild wurde mithilfe künstlicher Intelligenz wesentlich bearbeitet."
default:
return ""
}
}
func (s Story) HasMediaWatermark() bool {
return s.MediaWatermarkEnabled && normalizeMediaAIUsage(s.MediaAIUsage) != "none"
}
func (s Story) MediaWatermarkLabel() string {
if !s.HasMediaWatermark() {
return ""
}
if text := strings.TrimSpace(s.MediaWatermarkText); text != "" {
return text
}
if normalizeMediaAIUsage(s.MediaAIUsage) == "manipulated" {
return "Mit KI bearbeitet"
}
return "Mit KI erstellt"
}
type PageData struct {
StreamURL string
News []NewsItem
Events []Event
Stories []Story
Program []ProgramItem
AppBetaEnabled bool
AppBetaGroupURL string
AppBetaGroupEmail string
}
type apiEnvelope struct {
Data any `json:"data"`
Meta map[string]any `json:"meta,omitempty"`
}
type apiErrorEnvelope struct {
Error apiError `json:"error"`
}
type apiError struct {
Code string `json:"code"`
Message string `json:"message"`
Fields map[string]any `json:"fields,omitempty"`
}
func main() {
if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "version") {
_, _ = os.Stdout.WriteString(displayVersion() + "\n")
return
}
logger := log.New(os.Stdout, "landwelle: ", log.LstdFlags|log.LUTC)
var publicNavigationStore *navigationStore
tmpl, err := template.New("landwelle").Funcs(template.FuncMap{
"year": func() int { return time.Now().Year() },
"seoHead": seoHead,
"playlistURL": playlistPageURL,
"paragraphs": managedParagraphs,
"publicNavigation": func() template.HTML {
if publicNavigationStore == nil {
return navigationHTML(defaultNavigationItems())
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return navigationHTML(publicNavigationStore.Public(ctx))
},
"seq": func(a, b int) []int {
out := make([]int, 0, b-a+1)
for i := a; i <= b; i++ {
out = append(out, i)
}
return out
}}).ParseFS(webFS, publicTemplateFiles...)
if err != nil {
logger.Fatal(err)
}
assets, err := fs.Sub(webFS, "web/assets")
if err != nil {
logger.Fatal(err)
}
data := pageData()
database, err := newPostgresStore()
if err != nil {
logger.Fatal(err)
}
weather := NewWeatherService()
traffic := newTrafficService(logger)
programs, err := newProgramStore(database)
if err != nil {
logger.Fatal(err)
}
downloads, err := newDownloadStore()
if err != nil {
logger.Fatal(err)
}
wishes, err := newWishStore(database)
if err != nil {
logger.Fatal(err)
}
settings, err := newSettingsStore(data.StreamURL)
if err != nil {
logger.Fatal(err)
}
playlist := newPlaylistStore(database)
nowPlayingService := newNowPlayingService(settings, logger, playlist)
charts := newChartStore(database)
ai, err := newAIService(settings)
if err != nil {
logger.Fatal(err)
}
editorial := newEditorialStore(database)
media, err := newMediaStore(database)
if err != nil {
logger.Fatal(err)
}
siteContent := newSiteContentStore(database, media)
analytics := newSiteAnalyticsStore(database)
emailTemplates := newEmailTemplateStore(database)
events := newEventStore(database)
excursions := newExcursionStore(database)
eventAutomation := newEventWorkflow(settings, emailTemplates)
navigation := newNavigationStore(database)
publicNavigationStore = navigation
advertising := newAdvertisingStore(database)
advertisingAutomation := newAdvertisingWorkflow(settings, emailTemplates)
directory := newDirectoryStore(database)
directoryAutomation := newDirectoryWorkflow(settings, emailTemplates)
youtube := newYouTubeFeedService()
jobs := newJobsService()
team := newTeamStore(database)
forum := newForumStore(database)
accounts := newPublicAuth(database, settings, emailTemplates, logger)
wishAutomation := newWishWorkflow(settings, ai, wishes, emailTemplates)
wishes.onAdded = func(item ListenerWish) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := wishAutomation.NotifyNewWish(ctx, item); err != nil {
logger.Printf("Musikwunsch-E-Mail: %v", err)
}
}()
}
admin, err := newAdminHandler(logger, weather, data, settings, nowPlayingService, programs, downloads, ai, editorial, wishes, emailTemplates, wishAutomation, media, database, team, forum, navigation, directory)
if err != nil {
logger.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/assets/", cacheControl(http.StripPrefix("/assets/", http.FileServer(http.FS(assets)))))
mux.HandleFunc("/media/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "Methode nicht erlaubt", http.StatusMethodNotAllowed)
return
}
key := strings.TrimPrefix(r.URL.Path, "/media/")
path, ok := media.PathForKey(key)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Header().Set("X-Content-Type-Options", "nosniff")
http.ServeFile(w, r, path)
})
// Backwards-compatible endpoint used by older website clients.
mux.HandleFunc("/api/now", getOnly(func(w http.ResponseWriter, r *http.Request) {
snapshot, _ := nowPlayingService.Get(r.Context(), false)
writeJSON(w, http.StatusOK, publicNowPlaying(r, snapshot))
}))
mux.HandleFunc("/api/site-analytics/pageview", siteAnalyticsPageviewHandler(analytics))
rss := newRSSEngine(database, logger)
rss.Start()
registerPublicAPI(mux, data, weather, nowPlayingService, traffic, programs, database, rss, editorial, events, team, charts, playlist)
registerMobileAppAPI(mux, mobileAPIDependencies{data: data, database: database, rss: rss, editorial: editorial, events: events, team: team, charts: charts, playlist: playlist, programs: programs, settings: settings, nowPlaying: nowPlayingService})
registerExternalV1Alias(mux)
admin.register(mux)
registerPublicForum(mux, tmpl, logger, data.StreamURL, forum, accounts)
go admin.warmWeather()
go func() { _, _ = traffic.Get(context.Background(), false) }()
nowPlayingService.Start()
registerSEOEndpoints(mux)
mux.HandleFunc("/api/info", getOnly(renderAPIInfo))
mux.HandleFunc("/api", getOnly(renderAPIInfo))
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/" {
getOnly(renderAPIInfo)(w, r)
return
}
writeAPIError(w, http.StatusNotFound, "not_found", "Der angeforderte API-Endpunkt wurde nicht gefunden.")
})
mux.HandleFunc("/health", getOnly(func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "service": applicationName, "version": displayVersion()})
}))
mux.HandleFunc("/ready", getOnly(func(w http.ResponseWriter, r *http.Request) {
checks := map[string]any{"http": "ok", "database": "not_configured"}
ready := true
if database.Enabled() {
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
if err := database.Ping(ctx); err != nil {
checks["database"] = "unavailable"
logger.Printf("readiness postgres: %v", err)
ready = false
} else {
checks["database"] = "ok"
}
}
status := http.StatusOK
state := "ready"
if !ready {
status = http.StatusServiceUnavailable
state = "not_ready"
}
writeJSON(w, status, map[string]any{"status": state, "checks": checks, "version": displayVersion()})
}))
mux.HandleFunc("/version", getOnly(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write([]byte(displayVersion() + "\n"))
}))
mux.HandleFunc("/build", getOnly(func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"version": displayVersion(), "commit": buildCommit, "build_time": buildTime})
}))
mux.HandleFunc("/internal/status", getOnly(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Internal-Token") != envOr("LANDWELLE_INTERNAL_TOKEN", "") || envOr("LANDWELLE_INTERNAL_TOKEN", "") == "" {
writeAPIError(w, http.StatusUnauthorized, "unauthorized", "Interner Zugriff verweigert.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
dbStatus := "not_configured"
if database.Enabled() {
if err := database.Ping(ctx); err != nil {
dbStatus = err.Error()
} else {
dbStatus = "ok"
}
}
writeJSON(w, http.StatusOK, map[string]any{"version": displayVersion(), "commit": buildCommit, "build_time": buildTime, "database": dbStatus, "rss": rss.Status(ctx)})
}))
livestudioHandler := func(w http.ResponseWriter, r *http.Request) {
// Both variants are accepted because some reverse proxies append a trailing slash.
if r.URL.Path != "/livestudio" && r.URL.Path != "/livestudio/" {
renderNotFound(w, r, tmpl, logger, data)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", http.MethodGet+", "+http.MethodHead)
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
if err := tmpl.ExecuteTemplate(w, "livestudio.html", data); err != nil {
logger.Printf("livestudio template: %v", err)
}
}
mux.HandleFunc("/livestudio", livestudioHandler)
mux.HandleFunc("/livestudio/", livestudioHandler)
mux.HandleFunc("/player", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/player" {
http.NotFound(w, r)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
if err := tmpl.ExecuteTemplate(w, "player.html", data); err != nil {
logger.Printf("player template: %v", err)
}
})
mux.HandleFunc("/ausflugstipps", publicTemplateHandler(tmpl, logger, "excursions.html", func(r *http.Request) any {
items, err := excursions.ListPublic(r.Context())
if err != nil {
logger.Printf("ausflugstipps laden: %v", err)
}
categories, err := excursions.PublicCategories(r.Context())
if err != nil {
logger.Printf("ausflugstipps rubriken laden: %v", err)
}
return ExcursionPageData{StreamURL: data.StreamURL, Excursions: items, Categories: categories}
}))
mux.HandleFunc("/verkehr", publicTemplateHandler(tmpl, logger, "traffic.html", func(r *http.Request) any {
return TrafficPageData{StreamURL: data.StreamURL}
}))
mux.HandleFunc("/programm", publicTemplateHandler(tmpl, logger, "program.html", func(r *http.Request) any {
now := time.Now()
current, hasCurrent := programs.Current(now)
return ProgramPageData{StreamURL: data.StreamURL, Days: programs.Grouped(now), Updated: now.Format("02.01.2006 · 15:04 Uhr"), Current: current, HasCurrent: hasCurrent, TodayName: ProgramItem{Weekday: int(now.Weekday())}.WeekdayName()}
}))
mux.HandleFunc("/playlist", publicTemplateHandler(tmpl, logger, "playlist.html", func(r *http.Request) any {
const perPage = 15
page := playlistPageNumber(r.URL.Query().Get("page"))
filter := playlistFilterFromQuery(r.URL.Query())
entries, total, err := playlist.List(r.Context(), page, perPage, filter)
if err != nil {
logger.Printf("playlist laden: %v", err)
}
totalPages := (total + perPage - 1) / perPage
if totalPages < 1 {
totalPages = 1
}
if page > totalPages {
page = totalPages
}
return PlaylistPageData{
StreamURL: data.StreamURL, Days: groupPlaylistEntries(entries), Entries: entries,
Filter: filter, Page: page, Pages: playlistPages(page, totalPages), TotalPages: totalPages,
HasPrev: page > 1, HasNext: page < totalPages,
PrevURL: playlistPageURL(page-1, filter), NextURL: playlistPageURL(page+1, filter),
Total: total, Filtered: filter.Query != "" || filter.DateFrom != "" || filter.DateTo != "" || filter.TimeFrom != "" || filter.TimeTo != "",
}
}))
mux.HandleFunc("/mitmachen", wishPageHandler(tmpl, logger, data.StreamURL, wishes))
mux.HandleFunc("/team", publicTemplateHandler(tmpl, logger, "team.html", func(r *http.Request) any {
members, _ := team.List(r.Context(), false)
return TeamPageData{StreamURL: data.StreamURL, Members: members}
}))
mux.HandleFunc("/downloads", publicTemplateHandler(tmpl, logger, "downloads.html", func(r *http.Request) any { return DownloadsPageData{PageData: data, Platforms: downloads.List()} }))
mux.HandleFunc("/download/t/", getOnly(func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.URL.Path, "/download/t/")
path, meta, ok := downloads.FileByToken(token)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Disposition", `attachment; filename="`+strings.ReplaceAll(meta.OriginalName, `"`, "")+`"`)
w.Header().Set("Cache-Control", "private, no-store")
http.ServeFile(w, r, path)
}))
mux.HandleFunc("/download-preview/", getOnly(func(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.URL.Path, "/download-preview/")
path, ok := downloads.PreviewByToken(token)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Cache-Control", "public, max-age=3600")
http.ServeFile(w, r, path)
}))
mux.HandleFunc("/download/", getOnly(func(w http.ResponseWriter, r *http.Request) {
platform := strings.TrimPrefix(r.URL.Path, "/download/")
path, meta, ok := downloads.File(platform)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Disposition", `attachment; filename="`+strings.ReplaceAll(meta.OriginalName, `"`, "")+`"`)
w.Header().Set("Cache-Control", "private, no-store")
http.ServeFile(w, r, path)
}))
mux.HandleFunc("/veranstaltungen", eventsPageHandler(tmpl, logger, data, events))
mux.HandleFunc("/veranstaltungen/kalender.ics", eventsICalHandler(events, logger))
mux.HandleFunc("/veranstaltungen/einsenden", eventSubmissionHandler(events, eventAutomation, logger))
mux.HandleFunc("/api/events/search", eventSearchAPIHandler(events))
mux.HandleFunc("/api/events/", eventDetailAPIHandler(events))
mux.HandleFunc("/event-media/", eventMediaHandler())
mux.HandleFunc("/werbung", advertisingPageHandler(tmpl, logger, data, advertising, advertisingAutomation))
mux.HandleFunc("/branchenbuch", directoryPageHandler(tmpl, logger, data, directory, directoryAutomation))
mux.HandleFunc("/api/directory/search", directorySearchAPI(directory))
mux.HandleFunc("/ontour", onTourPageHandler(tmpl, logger, data, youtube))
mux.HandleFunc("/landwelle-vor-ort", editorialStoriesHandler(tmpl, logger, data, editorial))
mux.HandleFunc("/landwelle-vor-ort/", editorialStoryHandler(tmpl, logger, data, editorial))
mux.HandleFunc("/ontour/thumbnail/", onTourThumbnailHandler(youtube))
mux.HandleFunc("/service/stellenboerse", jobsPageHandler(tmpl, logger, data, jobs))
mux.HandleFunc("/api/jobs/details", jobDetailAPIHandler(jobs))
mux.HandleFunc("/charts/zuhoerer", chartsPageHandler(tmpl, logger, data, charts, chartPageConfig{ChartKey: "listener", RoutePath: "/charts/zuhoerer", VoteAPIPath: "/api/charts/zuhoerer/vote", VoteStatusAPIPath: "/api/charts/zuhoerer/vote-status", SEODescription: "Die beliebtesten Titel der Landwelle-Hörer mit Voting, Trend und Hörprobe.", HeroClass: "charts-wish-hero", HeroKicker: "Deine Musik. Deine Charts.", HeroTitle: "Landwelle Zuhörer Charts", HeroLead: "Hier entscheidet ihr, welche Titel bei Landwelle ganz oben stehen.", IntroKicker: "Von euch gewählt", IntroTitle: "Die Top 3 der Woche", IntroLead: "Gib deinen Lieblingstiteln 1 bis 5 Punkte. Nach 24 Stunden kannst du denselben Titel erneut bewerten.", SidebarKicker: "Ganz einfach mitmachen", SidebarTitle: "Hören, bewerten, mitentscheiden.", SidebarText: "Wähle bei jedem Titel 1 bis 5 Punkte. Nach deiner Stimme zeigen wir dir gut sichtbar, wann du wieder abstimmen kannst.", ListKicker: "Eure Rangliste", ListTitle: "Platz 4 bis 32", EmptyTopTitle: "Die Charts warten auf ihre ersten Titel", EmptyTopText: "Sobald die Redaktion die neue Runde freigibt, geht es hier los.", EmptyListTitle: "Hier ist noch Platz für mehr Musik", EmptyListText: "Weitere Titel kommen mit der nächsten Chart-Runde dazu.", MainEnd: 32, TotalEnd: 45, NewEntriesTitle: "Neu für euch: Platz 33 bis 45", VotingEnabled: true}))
mux.HandleFunc("/api/charts/zuhoerer/vote", chartVoteHandler(charts, "listener"))
mux.HandleFunc("/api/charts/zuhoerer/vote-status", chartVoteStatusHandler(charts, "listener"))
mux.HandleFunc("/charts/docx", chartsPageHandler(tmpl, logger, data, charts, chartPageConfig{ChartKey: "dockx", RoutePath: "/charts/docx", VoteAPIPath: "/api/charts/docx/vote", VoteStatusAPIPath: "/api/charts/docx/vote-status", SEODescription: "Die Landwelle docX Charts mit Alternative, Rock, Indie und neuen Sounds.", HeroClass: "charts-docx-hero", HeroKicker: "Andere Sounds. Eure Wahl.", HeroTitle: "Landwelle docX Charts", HeroLead: "Alternative, Rock, Indie und spannende Neuentdeckungen – von euch nach vorn gewählt.", IntroKicker: "Diese Woche ganz vorn", IntroTitle: "Die docX Top 3", IntroLead: "Hör rein und vergib 1 bis 5 Punkte. Für denselben Titel ist nach 24 Stunden wieder eine Stimme möglich.", SidebarKicker: "Dein docX Voting", SidebarTitle: "Mach aus deinem Favoriten einen Spitzenreiter.", SidebarText: "Ein Klick auf 1 bis 5 Punkte genügt. Danach zeigt der Countdown, wann du den Titel erneut unterstützen kannst.", ListKicker: "Die aktuelle Reihenfolge", ListTitle: "Platz 4 bis 30", EmptyTopTitle: "Noch keine docX-Titel im Rennen", EmptyTopText: "Die nächste Runde wird von der Redaktion vorbereitet.", EmptyListTitle: "Weitere Sounds folgen", EmptyListText: "Neue Titel ziehen mit der nächsten Auswertung ein.", MainEnd: 30, TotalEnd: 40, NewEntriesTitle: "Frisch dabei: Platz 31 bis 40", VotingEnabled: true}))
mux.HandleFunc("/api/charts/docx/vote", chartVoteHandler(charts, "dockx"))
mux.HandleFunc("/api/charts/docx/vote-status", chartVoteStatusHandler(charts, "dockx"))
mux.HandleFunc("/charts/schlager", chartsPageHandler(tmpl, logger, data, charts, chartPageConfig{ChartKey: "schlager", RoutePath: "/charts/schlager", VoteAPIPath: "/api/charts/schlager/vote", VoteStatusAPIPath: "/api/charts/schlager/vote-status", SEODescription: "Die Landwelle Schlager Charts mit Voting, Trend und Hörprobe.", HeroClass: "charts-schlager-hero", HeroKicker: "Schlager, die euch bewegen", HeroTitle: "Landwelle Schlager Charts", HeroLead: "Herz, Gefühl und gute Laune – ihr wählt eure Schlagerlieblinge nach oben.", IntroKicker: "Eure Favoriten", IntroTitle: "Die Schlager Top 3", IntroLead: "Vergib 1 bis 5 Punkte und unterstütze deine Lieblingsschlager. Nach 24 Stunden kannst du wieder mitmachen.", SidebarKicker: "Deine Stimme zählt", SidebarTitle: "Welcher Schlager gehört nach ganz oben?", SidebarText: "Bewerte jeden Titel mit 1 bis 5 Punkten. Nach deiner Stimme siehst du sofort, wann die nächste Bewertung möglich ist.", ListKicker: "Die aktuelle Hitparade", ListTitle: "Platz 4 bis 25", EmptyTopTitle: "Die Schlagerbühne ist noch leer", EmptyTopText: "Sobald die neue Runde startet, erscheinen hier die ersten Favoriten.", EmptyListTitle: "Mehr Schlager kommen bald", EmptyListText: "Mit der nächsten Runde wächst die Rangliste weiter.", MainEnd: 25, TotalEnd: 35, NewEntriesTitle: "Neu auf der Bühne: Platz 26 bis 35", VotingEnabled: true}))
mux.HandleFunc("/api/charts/schlager/vote", chartVoteHandler(charts, "schlager"))
mux.HandleFunc("/api/charts/schlager/vote-status", chartVoteStatusHandler(charts, "schlager"))
mux.HandleFunc("/charts/jahrescharts", chartsPageHandler(tmpl, logger, data, charts, chartPageConfig{ChartKey: "annual", RoutePath: "/charts/jahrescharts", SEODescription: "Das Landwelle-Musikarchiv mit den größten Titeln vergangener Jahre.", HeroClass: "charts-annual-hero", HeroKicker: "Erinnerst du dich noch?", HeroTitle: "Landwelle Jahrescharts", HeroLead: "Eine musikalische Zeitreise durch große Hits, alte Favoriten und fast vergessene Schätze.", IntroKicker: "Ein Jahr voller Musik", IntroTitle: "Die Top 3 des Jahres", IntroLead: "Wähle einen Jahrgang, blättere durch seine Erinnerungen und höre alte Lieblingslieder wieder.", SidebarKicker: "Das Landwelle-Musikarchiv", SidebarTitle: "Jedes Jahr erzählt seine eigene Geschichte.", SidebarText: "Zu vielen Titeln findest du Hintergrundwissen über Künstler, Song und damalige Musikzeit.", ListKicker: "Zurück in dieses Musikjahr", ListTitle: "Die komplette Jahresrangliste", EmptyTopTitle: "Dieser Jahrgang wartet noch auf seine Charts", EmptyTopText: "Sobald die Jahresliste veröffentlicht ist, beginnt hier die Zeitreise.", EmptyListTitle: "Noch keine weiteren Erinnerungen", EmptyListText: "Weitere Titel aus diesem Musikjahr folgen.", MainEnd: 100, TotalEnd: 100, Annual: true}))
mux.HandleFunc("/api/charts/jahrescharts/vote", chartVoteHandler(charts, "annual"))
mux.HandleFunc("/api/charts/jahrescharts/info", chartSongInfoAPI(charts))
mux.HandleFunc("/aktuelles", newsPageHandler(tmpl, logger, data, editorial, rss))
mux.HandleFunc("/aktuelles/", newsArticleHandler(tmpl, logger, data, editorial))
mux.HandleFunc("/empfangen", publicTemplateHandler(tmpl, logger, "empfangen.html", func(r *http.Request) any { return data }))
mux.HandleFunc("/mobile-app", publicTemplateHandler(tmpl, logger, "mobile-app.html", func(r *http.Request) any { return data }))
mux.HandleFunc("/zuhause/landwelle", publicTemplateHandler(tmpl, logger, "landwelle-zuhause.html", func(r *http.Request) any { return data }))
mux.HandleFunc("/ueber-landwelle", managedPublicPageHandler(tmpl, logger, data.StreamURL, siteContent, "ueber-landwelle", "managed-page.html"))
mux.HandleFunc("/presse", managedPublicPageHandler(tmpl, logger, data.StreamURL, siteContent, "presse", "managed-page.html"))
mux.HandleFunc("/karriere", managedPublicPageHandler(tmpl, logger, data.StreamURL, siteContent, "karriere", "managed-page.html"))
mux.HandleFunc("/faq", managedPublicPageHandler(tmpl, logger, data.StreamURL, siteContent, "faq", "faq.html"))
mux.HandleFunc("/kontakt", contactPageHandler(tmpl, logger, data.StreamURL, siteContent))
mux.HandleFunc("/mediathek", mediathekPageHandler(tmpl, logger, data.StreamURL, siteContent))
for slug, page := range contentPages() {
slug, page := slug, page
mux.HandleFunc("/"+slug, publicTemplateHandler(tmpl, logger, "page.html", func(r *http.Request) any {
return StaticPageData{StreamURL: data.StreamURL, Page: page}
}))
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" && isAPIHostname(r.Host) {
renderAPIInfo(w, r)
return
}
if r.URL.Path != "/" {
renderNotFound(w, r, tmpl, logger, data)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
homeData := data
homeData.Program = programs.Highlights(time.Now(), 4)
if mixedNews, _, _, err := loadMixedPublicNews(r.Context(), editorial, rss, 12); err != nil {
logger.Printf("startseite nachrichten laden: %v", err)
} else if len(mixedNews) > 0 {
limit := 3
if len(mixedNews) < limit {
limit = len(mixedNews)
}
homeData.News = make([]NewsItem, 0, limit)
for _, item := range mixedNews[:limit] {
image := strings.TrimSpace(item.ImageURL)
if image == "" {
image = "/assets/news-region-v14.jpg"
}
url := strings.TrimSpace(item.ArticleURL)
if url == "" {
url = "/aktuelles"
}
homeData.News = append(homeData.News, NewsItem{Category: item.Category(), Title: item.Title, Age: relativeNewsAge(item.PublishedAt), Image: image, URL: url, Source: item.Source})
}
}
if calendarEvents, err := events.ListPublished(r.Context(), ""); err != nil {
logger.Printf("startseite veranstaltungen laden: %v", err)
} else if len(calendarEvents) > 0 {
selectedEvents := selectHomepageCalendarEvents(calendarEvents, 3, time.Now().UnixNano())
homeData.Events = make([]Event, 0, len(selectedEvents))
for _, item := range selectedEvents {
imageURL := strings.TrimSpace(item.ImageURL)
if imageURL == "" {
imageURL = "/assets/events-hero-v2.png"
}
place := strings.TrimSpace(strings.Join([]string{item.PostalCode, item.City}, " "))
if item.Venue != "" {
if place != "" {
place = item.Venue + " · " + place
} else {
place = item.Venue
}
}
homeData.Events = append(homeData.Events, Event{
ID: item.ID, Day: item.Day(), Month: item.MonthShort(), Title: item.Title,
DateTime: item.DateLabel(), Place: place, Image: imageURL,
URL: "/veranstaltungen#kalender",
})
}
}
homeData.Stories = nil
if stories, err := editorial.HomepageStories(r.Context(), 3); err != nil {
logger.Printf("startseite landwelle-vor-ort laden: %v", err)
} else if len(stories) > 0 {
homeData.Stories = make([]Story, 0, len(stories))
for _, item := range stories {
image := strings.TrimSpace(item.MediaURL)
if image == "" {
image = "/assets/story-land.jpg"
}
homeData.Stories = append(homeData.Stories, Story{Title: item.Title, Age: relativeNewsAge(item.PublishedAt), Image: image, URL: item.PublicPath(), Teaser: item.Teaser, Location: item.Location, AIUsage: item.EffectiveAIUsage(), AIHumanReviewed: item.AIHumanReviewed, AIEditorialResponsible: item.AIEditorialResponsible, AIDisclosure: item.AIDisclosure, MediaAIUsage: item.MediaAIUsage, MediaAIDisclosure: item.MediaAIDisclosure, MediaWatermarkEnabled: item.MediaWatermarkEnabled, MediaWatermarkText: item.MediaWatermarkText})
}
}
if err := tmpl.ExecuteTemplate(w, "index.html", homeData); err != nil {
logger.Printf("template: %v", err)
}
})
server := &http.Server{
Addr: envOr("ADDR", ":2200"),
Handler: requestLog(logger, securityHeaders(rateLimitMiddleware(mux))),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 4 * time.Minute,
IdleTimeout: 60 * time.Second,
}
logger.Printf("Portal läuft auf %s", listenURL(server.Addr))
logger.Printf("Livestream: %s", data.StreamURL)
logger.Printf("App-API: /api/%s/app/bootstrap", apiVersion)
logger.Printf("Eigenständiger Liveplayer: /player")
logger.Printf("Adminbereich: /admin")
logger.Printf("AzuraCast-Einstellungen: %s", settings.Path())
if !admin.configured() {
logger.Printf("WARNUNG: Adminbereich ist gesperrt, da kein Admin-Passwort konfiguriert ist")
} else if admin.passwordHash == "" {
logger.Printf("WARNUNG: LANDWELLE_ADMIN_PASSWORD wird im Klartext verwendet; bitte auf LANDWELLE_ADMIN_PASSWORD_HASH umstellen")
}
errCh := make(chan error, 1)
go func() { errCh <- server.ListenAndServe() }()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-sigCh:
logger.Printf("Shutdown-Signal empfangen: %s", sig)
case err := <-errCh:
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatal(err)
}
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
rss.Stop(ctx)
nowPlayingService.Stop(ctx)
if err := server.Shutdown(ctx); err != nil {
logger.Printf("Graceful Shutdown: %v", err)
}
logger.Printf("Portal sauber beendet")
}
func registerPublicAPI(mux *http.ServeMux, data PageData, weather *WeatherService, nowPlayingService *nowPlayingService, traffic *trafficService, programs *programStore, database *postgresStore, rss *rssEngine, editorial *editorialStore, events *eventStore, team *teamStore, charts *chartStore, playlist *playlistStore) {
excursionAPIStore := newExcursionStore(database)
base := "/api/" + apiVersion
mux.HandleFunc(base+"/app/bootstrap", getOnly(func(w http.ResponseWriter, r *http.Request) {
clientBase := apiRequestBase(r)
writeJSON(w, http.StatusOK, apiEnvelope{
Data: map[string]any{
"api_version": apiVersion,
"brand": map[string]any{
"name": applicationName,
"slogan": "Sound & Infos aus Niedersachsen",
"primary_color": "#19a64a",
"logo_url": publicURL(r, "/assets/landwelle-logo.png"),
},
"stream": map[string]any{
"url": data.StreamURL,
"mime_type": "audio/mpeg",
"autoplay": false,
},
"now": func() NowPlayingSnapshot {
snapshot, _ := nowPlayingService.Get(r.Context(), false)
return publicNowPlaying(r, snapshot)
}(),
"features": mobileAPIFeatures(database),
"endpoints": map[string]string{
"bootstrap": clientBase + "/app/bootstrap",
"compatibility": clientBase + "/app/compatibility",
"station": clientBase + "/station",
"now": clientBase + "/now",
"livestudio": clientBase + "/livestudio",
"playlist": clientBase + "/playlist/history",
"current_program": clientBase + "/program/current",
"news": clientBase + "/news",
"events": clientBase + "/events",
"program": clientBase + "/program",
"team": clientBase + "/team",
"charts": clientBase + "/charts",
"regions": clientBase + "/regions",
"releases": clientBase + "/releases",
"installations": clientBase + "/installations",
"usage_events": clientBase + "/usage-events",
"weather": clientBase + "/weather",
"traffic": clientBase + "/traffic",
"speed_cameras": clientBase + "/speed-cameras",
"excursions": clientBase + "/excursions",
},
},
Meta: apiMeta(),
})
}))
mux.HandleFunc(base+"/livestudio", getOnly(func(w http.ResponseWriter, r *http.Request) {
now := time.Now()
snapshot, _ := nowPlayingService.Get(r.Context(), false)
current, currentOK := programs.Current(now)
next, nextOK := nextProgram(programs.List(now), now)
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
defer cancel()
weatherSnapshot, weatherErr := weather.Get(ctx, false)
var weatherData any
if weatherErr == nil {
weatherData = map[string]any{"location": weatherSnapshot.Location, "temperature": weatherSnapshot.Current.Temperature, "description": weatherSnapshot.Current.Description, "icon": weatherSnapshot.Current.Icon, "wind_speed": weatherSnapshot.Current.WindSpeed, "wind_direction": weatherSnapshot.Current.WindDirectionText, "stale": weatherSnapshot.Stale}
}
var currentData, nextData any
if currentOK {
currentData = studioProgramItem(current)
}
if nextOK {
nextData = studioProgramItem(next)
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: map[string]any{
"generated_at": now.UTC().Format(time.RFC3339), "timezone": "Europe/Berlin",
"now_playing": publicNowPlaying(r, snapshot),
"program": map[string]any{"current": currentData, "next": nextData},
"weather": weatherData,
"station": map[string]any{"name": applicationName, "stream_url": data.StreamURL, "version": displayVersion()},
}, Meta: apiMeta()})
}))
mux.HandleFunc(base+"/now", getOnly(func(w http.ResponseWriter, r *http.Request) {
snapshot, err := nowPlayingService.Get(r.Context(), false)
meta := apiMeta()
meta["azuracast_available"] = err == nil && snapshot.Source == "azuracast"
if err != nil {
meta["warning"] = "AzuraCast ist momentan nicht erreichbar; es werden zwischengespeicherte Daten angezeigt."
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: publicNowPlaying(r, snapshot), Meta: meta})
}))
mux.HandleFunc(base+"/covers/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", http.MethodGet)
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
return
}
id := strings.TrimPrefix(r.URL.Path, base+"/covers/")
if id == "" || strings.Contains(id, "/") {
http.NotFound(w, r)
return
}
nowPlayingService.covers.ServeHTTP(w, r, id)
})
mux.HandleFunc(base+"/weather", getOnly(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
snapshot, err := weather.Get(ctx, false)
if err != nil {
writeAPIError(w, http.StatusBadGateway, "weather_unavailable", "Die Wetterdaten für Visselhövede sind momentan nicht erreichbar.")
return
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: snapshot, Meta: apiMeta()})
}))
mux.HandleFunc(base+"/news", getOnly(func(w http.ResponseWriter, r *http.Request) {
limit := queryLimit(r, 20, 100)
offset := 0
if raw := strings.TrimSpace(r.URL.Query().Get("cursor")); raw != "" {
parsed, err := strconv.Atoi(raw)
if err != nil || parsed < 0 {
writeAPIError(w, http.StatusBadRequest, "invalid_cursor", "Der Nachrichten-Cursor ist ungültig.")
return
}
offset = parsed
}
region := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("region")))
items, total, err := mobileNewsList(r, mobileAPIDependencies{data: data, database: database, rss: rss, editorial: editorial}, limit, offset, region)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "news_unavailable", "Nachrichten konnten nicht geladen werden.")
return
}
if len(items) == 0 && !database.Enabled() {
for i, item := range data.News {
items = append(items, map[string]any{"id": fmt.Sprintf("demo:%d", i+1), "content_type": "demo", "category": strings.ToLower(item.Category), "category_label": item.Category, "title": item.Title, "summary": "Demonstrationsinhalt, bis freigegebene Nachrichten verfügbar sind.", "image_url": publicURL(r, item.Image), "published_at": time.Now().UTC().Add(-time.Duration(i+2) * time.Hour).Format(time.RFC3339), "regions": []string{"niedersachsen"}, "external_url": nil})
}
total = len(items)
if len(items) > limit {
items = items[:limit]
}
}
next := ""
if offset+len(items) < total {
next = strconv.Itoa(offset + len(items))
}
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: items, Meta: map[string]any{"count": len(items), "total": total, "next_cursor": next, "region": region, "api_version": apiVersion}})
}))
mux.HandleFunc(base+"/events", getOnly(func(w http.ResponseWriter, r *http.Request) {
limit := queryLimit(r, 30, 100)
category := strings.TrimSpace(r.URL.Query().Get("category"))
calendarEvents, err := events.ListPublished(r.Context(), category)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "events_unavailable", "Veranstaltungen konnten nicht geladen werden.")
return
}
items := make([]map[string]any, 0, len(calendarEvents))
for _, item := range calendarEvents {
items = append(items, mobileEventJSON(r, item))
if len(items) >= limit {
break
}
}
if len(items) == 0 && !database.Enabled() {
for i, item := range data.Events {
items = append(items, map[string]any{"id": i + 1, "title": item.Title, "date_label": item.DateTime, "place": item.Place, "image_url": publicURL(r, item.Image), "regions": []string{"niedersachsen"}})
}
}
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: items, Meta: map[string]any{"count": len(items), "category": category, "api_version": apiVersion}})
}))
mux.HandleFunc(base+"/program/current", getOnly(func(w http.ResponseWriter, r *http.Request) {
item, ok := programs.Current(time.Now())
if !ok {
writeJSON(w, http.StatusOK, apiEnvelope{Data: nil, Meta: apiMeta()})
return
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: map[string]any{
"id": item.ID, "weekday": item.Weekday, "weekday_label": item.WeekdayName(),
"start": item.Start, "end": item.End, "time_label": item.Time,
"show": item.Show, "presenter": item.Presenter, "program_type": item.ProgramType,
"description": item.Description, "image_url": publicURL(r, item.Image), "live": true,
}, Meta: apiMeta()})
}))
mux.HandleFunc(base+"/program", getOnly(func(w http.ResponseWriter, r *http.Request) {
programItems := programs.List(time.Now())
items := make([]map[string]any, 0, len(programItems))
for _, item := range programItems {
if !item.Active {
continue
}
items = append(items, map[string]any{
"id": item.ID, "weekday": item.Weekday, "weekday_label": item.WeekdayName(),
"start": item.Start, "end": item.End, "time_label": item.Time,
"show": item.Show, "presenter": item.Presenter, "program_type": item.ProgramType,
"description": item.Description, "image_url": publicURL(r, item.Image), "live": item.Live,
})
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: items, Meta: map[string]any{"count": len(items), "api_version": apiVersion}})
}))
mux.HandleFunc(base+"/traffic", getOnly(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
snapshot, err := traffic.Get(ctx, r.URL.Query().Get("refresh") == "1")
if err != nil && snapshot.FetchedAt.IsZero() {
writeAPIError(w, http.StatusBadGateway, "traffic_unavailable", "Verkehrs- und Blitzerdaten sind momentan nicht erreichbar.")
return
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: snapshot, Meta: apiMeta()})
}))
mux.HandleFunc(base+"/speed-cameras", getOnly(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
snapshot, err := traffic.Get(ctx, false)
if err != nil && snapshot.FetchedAt.IsZero() {
writeAPIError(w, http.StatusBadGateway, "speed_cameras_unavailable", "Blitzermeldungen sind momentan nicht erreichbar.")
return
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: snapshot.SpeedCameras, Meta: map[string]any{"count": len(snapshot.SpeedCameras), "api_version": apiVersion}})
}))
mux.HandleFunc(base+"/excursions", getOnly(func(w http.ResponseWriter, r *http.Request) {
items, err := excursionAPIStore.ListPublic(r.Context())
if err != nil {
log.Printf("app api excursions: %v", err)
}
writeJSON(w, http.StatusOK, apiEnvelope{Data: items, Meta: map[string]any{"count": len(items), "api_version": apiVersion}})
}))
mux.HandleFunc(base+"/regions", getOnly(func(w http.ResponseWriter, r *http.Request) {
regions := []map[string]any{}
if database.Enabled() {
_ = database.queryJSON(r.Context(), `SELECT COALESCE(json_agg(row_to_json(x)), '[]'::json)::text FROM (SELECT id,slug,name,kind,official_code,parent_id FROM regions WHERE active=true ORDER BY sort_order,name) x;`, &regions)
}
if len(regions) == 0 {
regions = []map[string]any{{"slug": "niedersachsen", "name": "Ganz Niedersachsen", "kind": "state"}, {"slug": "nordwest", "name": "Nordwest", "kind": "editorial_area"}, {"slug": "nordost", "name": "Nordost", "kind": "editorial_area"}, {"slug": "hannover", "name": "Hannover und Umland", "kind": "editorial_area"}, {"slug": "weser-ems", "name": "Weser-Ems", "kind": "editorial_area"}, {"slug": "braunschweiger-land", "name": "Braunschweiger Land", "kind": "editorial_area"}, {"slug": "suedniedersachsen", "name": "Südniedersachsen", "kind": "editorial_area"}}
}
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: regions, Meta: map[string]any{"count": len(regions), "api_version": apiVersion}})
}))
mux.HandleFunc(base+"/releases", getOnly(func(w http.ResponseWriter, r *http.Request) {
platform := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("platform")))
channel := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("channel")))
architecture := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("architecture")))
allowedPlatforms := map[string]bool{"": true, "android": true, "ios": true, "windows": true, "linux": true, "macos": true}
allowedChannels := map[string]bool{"": true, "sideload": true, "google_play": true, "app_store": true, "direct": true, "package_repository": true, "beta": true}
if !allowedPlatforms[platform] {
writeAPIError(w, http.StatusBadRequest, "invalid_platform", "Unbekannte Plattform.")
return
}
if !allowedChannels[channel] {
writeAPIError(w, http.StatusBadRequest, "invalid_channel", "Unbekannter Veröffentlichungskanal.")
return
}
if len(architecture) > 40 {
writeAPIError(w, http.StatusBadRequest, "invalid_architecture", "Die Architekturangabe ist ungültig.")
return
}
items := []map[string]any{}
if database.Enabled() {
where := "published=true"
if platform != "" {
where += " AND platform=" + sqlText(platform)
}
if channel != "" {
where += " AND channel=" + sqlText(channel)
}
if architecture != "" {
where += " AND architecture=" + sqlText(architecture)
}
q := `SELECT COALESCE(json_agg(row_to_json(x)), '[]'::json)::text FROM (SELECT id,platform,architecture,channel,version,build_number,minimum_os_version,download_url,store_url,sha256,file_size_bytes,release_notes,mandatory,published_at FROM app_releases WHERE ` + where + ` ORDER BY published_at DESC,id DESC LIMIT 50) x;`
if err := database.queryJSON(r.Context(), q, &items); err != nil {
writeAPIError(w, http.StatusInternalServerError, "releases_unavailable", "App-Releases konnten nicht geladen werden.")
return
}
}
meta := map[string]any{"api_version": apiVersion, "platform": platform, "channel": channel, "architecture": architecture, "count": len(items)}
if len(items) == 0 {
meta["message"] = "Noch keine passenden Client-Releases veröffentlicht."
}
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: items, Meta: meta})
}))
}
func publicTemplateHandler(tmpl *template.Template, logger *log.Logger, name string, data func(*http.Request) any) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", http.MethodGet)
http.Error(w, "Methode nicht erlaubt", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
var rendered bytes.Buffer
if err := tmpl.ExecuteTemplate(&rendered, name, data(r)); err != nil {
logger.Printf("template %s: %v", name, err)
http.Error(w, "Die Seite konnte nicht vollständig dargestellt werden.", http.StatusInternalServerError)
return
}
_, _ = w.Write(rendered.Bytes())
}
}
func listenURL(addr string) string {
if strings.HasPrefix(addr, ":") {
return "http://localhost" + addr
}
return "http://" + addr
}
func selectHomepageCalendarEvents(items []CalendarEvent, limit int, seed int64) []CalendarEvent {
if limit < 1 || len(items) == 0 {
return nil
}
random := rand.New(rand.NewSource(seed))
favorites := make([]CalendarEvent, 0)
for _, item := range items {
if item.HomepageFavorite {
favorites = append(favorites, item)
}
}
result := make([]CalendarEvent, 0, minInt(limit, len(items)))
var pinnedID int64
if len(favorites) > 0 {
random.Shuffle(len(favorites), func(i, j int) { favorites[i], favorites[j] = favorites[j], favorites[i] })
result = append(result, favorites[0])
pinnedID = favorites[0].ID
}
remaining := make([]CalendarEvent, 0, len(items)-len(result))
for _, item := range items {
if pinnedID != 0 && item.ID == pinnedID {
continue
}
remaining = append(remaining, item)
}
random.Shuffle(len(remaining), func(i, j int) { remaining[i], remaining[j] = remaining[j], remaining[i] })
needed := limit - len(result)
if needed > len(remaining) {
needed = len(remaining)
}
result = append(result, remaining[:needed]...)
return result
}
func selectRandomCalendarEvents(items []CalendarEvent, limit int, seed int64) []CalendarEvent {
if limit < 1 || len(items) == 0 {
return nil
}
shuffled := append([]CalendarEvent(nil), items...)
random := rand.New(rand.NewSource(seed))
random.Shuffle(len(shuffled), func(i, j int) {
shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
})
if limit > len(shuffled) {
limit = len(shuffled)
}
return shuffled[:limit]
}
func normalizeStreamURL(value string) string {
value = strings.TrimSpace(value)
switch value {
case "", "https://stream.slmm.de/listen/landwelle/landwelle", "http://stream.slmm.de:8010/landwelle", "https://stream.slmm.de:8010/landwelle":
return defaultStreamURL
default:
return value
}
}
func pageData() PageData {
return PageData{
StreamURL: normalizeStreamURL(envOr("LANDWELLE_STREAM_URL", defaultStreamURL)),
AppBetaEnabled: envBool("LANDWELLE_APP_BETA_ENABLED", true),
AppBetaGroupURL: envOr("LANDWELLE_APP_BETA_GROUP_URL", "https://groups.google.com/g/landwelle-betatest"),
AppBetaGroupEmail: envOr("LANDWELLE_APP_BETA_GROUP_EMAIL", "landwelle-betatest@googlegroups.com"),
News: []NewsItem{
{Category: "Landwirtschaft", Title: "Ernte 2026: Gute Aussichten für viele Betriebe in NDS", Age: "vor 2 Stunden", Image: "/assets/news-landwirtschaft-v14.jpg"},
{Category: "Politik", Title: "Niedersachsen investiert in ländliche Entwicklung", Age: "vor 5 Stunden", Image: "/assets/news-region-v14.jpg"},
{Category: "Verkehr", Title: "Neue Straßenprojekte für den ländlichen Raum", Age: "vor 7 Stunden", Image: "/assets/news-verkehr-v14.jpg"},
},
Events: []Event{
{Day: "25", Month: "MAI", Title: "Schützenfest in Bissendorf", DateTime: "25. Mai 2026 · ab 14:00 Uhr", Place: "Bissendorf", Image: "/assets/event-schuetzen-v14.jpg"},
{Day: "01", Month: "JUN", Title: "Bauernmarkt in Bruchhausen-Vilsen", DateTime: "1. Juni 2026 · ab 08:00 Uhr", Place: "Bruchhausen-Vilsen", Image: "/assets/event-market-v14.jpg"},
{Day: "08", Month: "JUN", Title: "Open-Air-Konzert mit LineUp", DateTime: "8. Juni 2026 · ab 19:00 Uhr", Place: "Nienburg/Weser", Image: "/assets/event-concert-v14.jpg"},
},
Stories: []Story{
{Title: "Wir waren beim Treckertreffen in Vechta", Age: "vor 1 Tag", Image: "/assets/story-treffen.jpg", URL: "/kontakt"},
{Title: "Mühle in Mühlhausen: Ein Stück Geschichte lebt", Age: "vor 2 Tagen", Image: "/assets/story-muehle.jpg", URL: "/kontakt"},
{Title: "Unser Landwelle-Team im Einsatz für euch", Age: "vor 3 Tagen", Image: "/assets/story-team-new.jpg", URL: "/kontakt"},
},
}
}
func publicNowPlaying(r *http.Request, snapshot NowPlayingSnapshot) NowPlayingSnapshot {
if strings.HasPrefix(snapshot.CoverURL, "/api/"+apiVersion+"/") {
snapshot.CoverURL = apiRequestBase(r) + strings.TrimPrefix(snapshot.CoverURL, "/api/"+apiVersion)
}
if snapshot.CoverURL != "" && !strings.HasPrefix(snapshot.CoverURL, "http://") && !strings.HasPrefix(snapshot.CoverURL, "https://") {
snapshot.CoverURL = publicURL(r, snapshot.CoverURL)
}
return snapshot
}
func apiMeta() map[string]any {
return map[string]any{
"api_version": apiVersion,
"contract_version": apiContractVersion,
"server_time": time.Now().UTC().Format(time.RFC3339),
}
}
func publicURL(r *http.Request, path string) string {
if strings.HasPrefix(path, "http://") || strings.HasPrefix(path, "https://") {
return path
}
if configured := strings.TrimRight(strings.TrimSpace(os.Getenv("LANDWELLE_PUBLIC_BASE_URL")), "/"); configured != "" {
return configured + "/" + strings.TrimLeft(path, "/")
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
} else if forwarded := strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0]); forwarded == "https" {
scheme = "https"
}
return scheme + "://" + r.Host + "/" + strings.TrimLeft(path, "/")
}
func getOnly(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", http.MethodGet)
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
return
}
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
handler(w, r)
}
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Landwelle-API-Version", apiVersion)
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(value); err != nil {
// The response has already started. Logging is handled by the HTTP layer in later versions.
return
}
}
func writeAPIError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, apiErrorEnvelope{Error: apiError{Code: code, Message: message}})
}
func queryLimit(r *http.Request, fallback, max int) int {
v, err := strconv.Atoi(r.URL.Query().Get("limit"))
if err != nil || v < 1 {
return fallback
}
if v > max {
return max
}
return v
}
func writeETagJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
b, err := json.Marshal(value)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "encoding_error", "Antwort konnte nicht erzeugt werden.")
return
}
sum := sha256.Sum256(b)
etag := "\"" + hex.EncodeToString(sum[:12]) + "\""
w.Header().Set("ETag", etag)
w.Header().Set("Cache-Control", "public, max-age=30, stale-while-revalidate=120")
if r.Header.Get("If-None-Match") == etag {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Landwelle-API-Version", apiVersion)
w.WriteHeader(status)
_, _ = w.Write(append(b, '\n'))
}
func envOr(key, fallback string) string {
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func cacheControl(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := strings.ToLower(r.URL.Path)
switch {
case strings.HasSuffix(path, ".css"), strings.HasSuffix(path, ".js"):
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
case strings.HasSuffix(path, ".mp4"):
w.Header().Set("Cache-Control", "public, max-age=86400")
default:
w.Header().Set("Cache-Control", "public, max-age=3600")
}
next.ServeHTTP(w, r)
})
}
type ipRateEntry struct {
Count int
Reset time.Time
}
var publicRateMu sync.Mutex
var publicRate = map[string]ipRateEntry{}
var publicRateLastSweep time.Time
func rateLimitMiddleware(next http.Handler) http.Handler {
limit, _ := strconv.Atoi(envOr("LANDWELLE_PUBLIC_RATE_LIMIT_PER_MINUTE", "600"))
if limit < 30 {
limit = 30
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/assets/") || r.URL.Path == "/health" || r.URL.Path == "/ready" {
next.ServeHTTP(w, r)
return
}
ip := requestClientIP(r)
now := time.Now()
publicRateMu.Lock()
if now.Sub(publicRateLastSweep) >= time.Minute {
for key, expired := range publicRate {
if !now.Before(expired.Reset) { delete(publicRate,key) }
}
publicRateLastSweep=now
}
entry := publicRate[ip]
if now.After(entry.Reset) {
entry = ipRateEntry{Reset: now.Add(time.Minute)}
}
entry.Count++
publicRate[ip] = entry
blocked := entry.Count > limit
remaining := limit - entry.Count
publicRateMu.Unlock()
w.Header().Set("X-RateLimit-Limit", strconv.Itoa(limit))
if remaining < 0 {
remaining = 0
}
w.Header().Set("X-RateLimit-Remaining", strconv.Itoa(remaining))
if blocked {
w.Header().Set("Retry-After", "60")
writeAPIError(w, http.StatusTooManyRequests, "rate_limited", "Zu viele Anfragen. Bitte später erneut versuchen.")
return
}
next.ServeHTTP(w, r)
})
}
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
restricted := strings.HasPrefix(r.URL.Path, "/admin") || strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/v1/") || strings.HasPrefix(r.URL.Path, "/internal/") || r.URL.Path == "/player" || strings.HasPrefix(r.URL.Path, "/livestudio") || r.URL.Path == "/health" || r.URL.Path == "/ready" || r.URL.Path == "/version" || r.URL.Path == "/build"
contentSecurityPolicy := "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; media-src 'self' https:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; object-src 'none'"
if !restricted {
contentSecurityPolicy = "default-src 'self' https: data: blob:; img-src 'self' data: https:; style-src 'self' 'unsafe-inline' https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; media-src 'self' https:; connect-src 'self' https:; frame-src https://*.googlesyndication.com https://*.doubleclick.net https://fundingchoicesmessages.google.com; worker-src 'self' blob: https:; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"
if r.URL.Path == "/ontour" || strings.HasPrefix(r.URL.Path, "/ontour/") || strings.HasPrefix(r.URL.Path, "/charts/") {
contentSecurityPolicy += "; frame-src https://www.youtube-nocookie.com https://www.youtube.com https://*.googlesyndication.com https://*.doubleclick.net https://fundingchoicesmessages.google.com"
}
}
w.Header().Set("Content-Security-Policy", contentSecurityPolicy)
if restricted {
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
}
next.ServeHTTP(w, r)
})
}
func requestLog(logger *log.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
started := time.Now()
next.ServeHTTP(w, r)
logger.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(started).Round(time.Millisecond))
})
}
func studioProgramItem(item ProgramItem) map[string]any {
return map[string]any{"id": item.ID, "show": item.Show, "presenter": item.Presenter, "start": item.Start, "end": item.End, "program_type": item.ProgramType}
}
func nextProgram(items []ProgramItem, now time.Time) (ProgramItem, bool) {
currentMinutes := now.Hour()*60 + now.Minute()
weekday := int(now.Weekday())
var best ProgramItem
bestDistance := 8 * 24 * 60
for _, item := range items {
if !item.Active {
continue
}
parts := strings.Split(item.Start, ":")
if len(parts) != 2 {
continue
}
hour, errHour := strconv.Atoi(parts[0])
minute, errMinute := strconv.Atoi(parts[1])
if errHour != nil || errMinute != nil || hour < 0 || hour > 23 || minute < 0 || minute > 59 {
continue
}
itemDay := item.Weekday
if itemDay == -1 {
itemDay = weekday
}
days := (itemDay - weekday + 7) % 7
distance := days*24*60 + hour*60 + minute - currentMinutes
if distance <= 0 {
distance += 7 * 24 * 60
}
if distance < bestDistance {
bestDistance, best = distance, item
}
}
return best, bestDistance < 8*24*60
}
func isAPIHostname(host string) bool {
host = strings.ToLower(strings.TrimSpace(host))
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
return host == "api.landwelle.de"
}
func renderAPIInfo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Robots-Tag", "noindex, nofollow, noarchive")
if r.Method == http.MethodHead {
w.WriteHeader(http.StatusOK)
return
}
_, _ = w.Write([]byte(`<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow,noarchive"><title>Landwelle API</title><style>:root{color-scheme:dark}*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;background:radial-gradient(circle at top,#294534 0,#13251b 44%,#0b1510 100%);font-family:system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#f7f4e8}.card{width:min(620px,100%);padding:42px;border:1px solid rgba(255,255,255,.14);border-radius:24px;background:rgba(13,29,20,.88);box-shadow:0 24px 80px rgba(0,0,0,.35);text-align:center}.mark{display:inline-grid;place-items:center;width:58px;height:58px;margin-bottom:18px;border-radius:18px;background:#cddd45;color:#172418;font-size:30px;font-weight:800}h1{margin:0 0 14px;font-size:clamp(30px,6vw,48px);line-height:1.05}p{margin:0 auto;max-width:480px;color:#d8dfd5;font-size:18px;line-height:1.65}.note{margin-top:22px;color:#9eab9f;font-size:14px}</style></head><body><main class="card"><div class="mark" aria-hidden="true">L</div><h1>Landwelle API</h1><p>Dieser Dienst ist ausschließlich für autorisierte Anwendungen vorgesehen. Hier gibt es keine öffentliche Benutzeroberfläche.</p><div class="note">Landwelle Radio</div></main></body></html>`))
}
func renderNotFound(w http.ResponseWriter, r *http.Request, tmpl *template.Template, logger *log.Logger, data PageData) {
if strings.HasPrefix(r.URL.Path, "/api/") || strings.HasPrefix(r.URL.Path, "/v1/") {
writeAPIError(w, http.StatusNotFound, "not_found", "Der angeforderte API-Endpunkt wurde nicht gefunden.")
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Robots-Tag", "noindex, nofollow")
w.WriteHeader(http.StatusNotFound)
if r.Method == http.MethodHead {
return
}
if err := tmpl.ExecuteTemplate(w, "404.html", data); err != nil {
logger.Printf("404 template: %v", err)
}
}