1125 lines
45 KiB
Go
1125 lines
45 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"regexp"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type apiBaseContextKey struct{}
|
|
|
|
type mobileAPIDependencies struct {
|
|
data PageData
|
|
database *postgresStore
|
|
rss *rssEngine
|
|
editorial *editorialStore
|
|
events *eventStore
|
|
team *teamStore
|
|
charts *chartStore
|
|
playlist *playlistStore
|
|
programs *programStore
|
|
settings *settingsStore
|
|
nowPlaying *nowPlayingService
|
|
}
|
|
|
|
func registerExternalV1Alias(mux *http.ServeMux) {
|
|
alias := func(w http.ResponseWriter, r *http.Request) {
|
|
clone := r.Clone(context.WithValue(r.Context(), apiBaseContextKey{}, "/v1"))
|
|
clone.URL.Path = "/api" + r.URL.Path
|
|
mux.ServeHTTP(w, clone)
|
|
}
|
|
mux.HandleFunc("/v1", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/v1" {
|
|
writeAPIError(w, http.StatusNotFound, "not_found", "Der angeforderte API-Endpunkt wurde nicht gefunden.")
|
|
return
|
|
}
|
|
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: map[string]any{
|
|
"name": applicationName,
|
|
"api_version": apiVersion,
|
|
"contract": apiContractVersion,
|
|
"bootstrap_url": "/v1/app/bootstrap",
|
|
}, Meta: apiMeta()})
|
|
})
|
|
mux.HandleFunc("/v1/", alias)
|
|
}
|
|
|
|
func apiRequestBase(r *http.Request) string {
|
|
if value, ok := r.Context().Value(apiBaseContextKey{}).(string); ok && value != "" {
|
|
return value
|
|
}
|
|
return "/api/" + apiVersion
|
|
}
|
|
|
|
func mobileAPIFeatures(database *postgresStore) map[string]bool {
|
|
dbEnabled := database != nil && database.Enabled()
|
|
return map[string]bool{
|
|
"radio": true,
|
|
"background_audio": true,
|
|
"now_playing": true,
|
|
"playlist_history": true,
|
|
"news": true,
|
|
"news_details": true,
|
|
"events": true,
|
|
"event_details": true,
|
|
"program": true,
|
|
"team": true,
|
|
"charts": true,
|
|
"chart_voting": dbEnabled,
|
|
"weather": true,
|
|
"traffic": true,
|
|
"speed_cameras": true,
|
|
"excursions": true,
|
|
"regional_preferences": dbEnabled,
|
|
"installation_identity": dbEnabled,
|
|
"push_registration": dbEnabled && appPushEncryptionConfigured(),
|
|
"push_topics": dbEnabled,
|
|
"usage_analytics": dbEnabled && envBool("LANDWELLE_APP_ANALYTICS_ENABLED", false),
|
|
"android_sideload": envBool("LANDWELLE_APP_ANDROID_SIDELOAD_ENABLED", false),
|
|
"google_play": envBool("LANDWELLE_APP_GOOGLE_PLAY_ENABLED", false),
|
|
"ios_app": envBool("LANDWELLE_APP_IOS_ENABLED", false),
|
|
"store_release_checks": true,
|
|
}
|
|
}
|
|
|
|
func registerMobileAppAPI(mux *http.ServeMux, deps mobileAPIDependencies) {
|
|
base := "/api/" + apiVersion
|
|
|
|
mux.HandleFunc(base+"/station", getOnly(func(w http.ResponseWriter, r *http.Request) {
|
|
streamURL := deps.data.StreamURL
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: map[string]any{
|
|
"name": applicationName, "version": displayVersion(), "timezone": "Europe/Berlin",
|
|
"slogan": "Sound & Infos aus Niedersachsen",
|
|
"stream": map[string]any{"url": streamURL, "mime_type": "audio/mpeg", "autoplay": false},
|
|
"website_url": "https://landwelle.de", "support_url": "https://landwelle.de/kontakt",
|
|
"privacy_url": "https://landwelle.de/datenschutz", "legal_url": "https://landwelle.de/impressum",
|
|
}, Meta: apiMeta()})
|
|
}))
|
|
|
|
mux.HandleFunc(base+"/playlist/history", getOnly(func(w http.ResponseWriter, r *http.Request) {
|
|
limit := queryLimit(r, 30, 100)
|
|
entries, total, err := deps.playlist.List(r.Context(), 1, limit, PlaylistFilter{})
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "playlist_unavailable", "Die Playlist-Historie konnte nicht geladen werden.")
|
|
return
|
|
}
|
|
for i := range entries {
|
|
entries[i].CoverURL = publicURL(r, entries[i].CoverURL)
|
|
}
|
|
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: entries, Meta: map[string]any{"count": len(entries), "total": total, "api_version": apiVersion}})
|
|
}))
|
|
|
|
mux.HandleFunc(base+"/team", getOnly(func(w http.ResponseWriter, r *http.Request) {
|
|
members, err := deps.team.List(r.Context(), false)
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "team_unavailable", "Das Landwelle-Team konnte nicht geladen werden.")
|
|
return
|
|
}
|
|
for i := range members {
|
|
members[i].Image = publicURL(r, members[i].Image)
|
|
}
|
|
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: members, Meta: map[string]any{"count": len(members), "api_version": apiVersion}})
|
|
}))
|
|
|
|
mux.HandleFunc(base+"/charts", getOnly(func(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: []map[string]any{
|
|
{"id": "listener", "name": "Landwelle Zuhörer Charts", "url": apiRequestBase(r) + "/charts/listener"},
|
|
{"id": "schlager", "name": "Landwelle Schlager Charts", "url": apiRequestBase(r) + "/charts/schlager"},
|
|
{"id": "annual", "name": "Landwelle Jahrescharts", "url": apiRequestBase(r) + "/charts/annual"},
|
|
}, Meta: apiMeta()})
|
|
}))
|
|
mux.HandleFunc(base+"/charts/", func(w http.ResponseWriter, r *http.Request) {
|
|
handleMobileCharts(w, r, base, deps)
|
|
})
|
|
|
|
mux.HandleFunc(base+"/news/", func(w http.ResponseWriter, r *http.Request) {
|
|
handleMobileNewsDetail(w, r, base, deps)
|
|
})
|
|
mux.HandleFunc(base+"/events/", func(w http.ResponseWriter, r *http.Request) {
|
|
handleMobileEventDetail(w, r, base, deps)
|
|
})
|
|
|
|
mux.HandleFunc(base+"/app/compatibility", getOnly(func(w http.ResponseWriter, r *http.Request) {
|
|
handleCompatibility(w, r, deps.database)
|
|
}))
|
|
|
|
mux.HandleFunc(base+"/installations", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != base+"/installations" {
|
|
writeAPIError(w, http.StatusNotFound, "not_found", "Der angeforderte API-Endpunkt wurde nicht gefunden.")
|
|
return
|
|
}
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Nur POST ist erlaubt.")
|
|
return
|
|
}
|
|
handleInstallationRegistration(w, r, deps.database)
|
|
})
|
|
mux.HandleFunc(base+"/installations/", func(w http.ResponseWriter, r *http.Request) {
|
|
handleInstallationResource(w, r, base, deps.database)
|
|
})
|
|
mux.HandleFunc(base+"/usage-events", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Nur POST ist erlaubt.")
|
|
return
|
|
}
|
|
handleUsageEvents(w, r, deps.database)
|
|
})
|
|
mux.HandleFunc(base+"/push/opened", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Nur POST ist erlaubt.")
|
|
return
|
|
}
|
|
handlePushOpened(w, r, deps.database)
|
|
})
|
|
|
|
// JSON-Fallback für unbekannte v1-Endpunkte. Spezifischere Routen gewinnen im ServeMux.
|
|
mux.HandleFunc(base+"/", func(w http.ResponseWriter, r *http.Request) {
|
|
writeAPIError(w, http.StatusNotFound, "not_found", "Der angeforderte API-Endpunkt wurde nicht gefunden.")
|
|
})
|
|
}
|
|
|
|
func handleMobileCharts(w http.ResponseWriter, r *http.Request, base string, deps mobileAPIDependencies) {
|
|
tail := strings.Trim(strings.TrimPrefix(r.URL.Path, base+"/charts/"), "/")
|
|
parts := strings.Split(tail, "/")
|
|
if len(parts) == 0 || parts[0] == "" {
|
|
writeAPIError(w, http.StatusNotFound, "not_found", "Charts wurden nicht gefunden.")
|
|
return
|
|
}
|
|
chartKey := parts[0]
|
|
if chartKey != "listener" && chartKey != "schlager" && chartKey != "annual" {
|
|
writeAPIError(w, http.StatusNotFound, "chart_not_found", "Diese Chartliste existiert nicht.")
|
|
return
|
|
}
|
|
if len(parts) == 1 && r.Method == http.MethodGet {
|
|
entries, err := deps.charts.Chart(r.Context(), chartKey)
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "charts_unavailable", "Die Charts konnten nicht geladen werden.")
|
|
return
|
|
}
|
|
for i := range entries {
|
|
entries[i].CoverURL = publicURL(r, entries[i].CoverURL)
|
|
entries[i].PreviewURL = publicURL(r, entries[i].PreviewURL)
|
|
}
|
|
writeETagJSON(w, r, http.StatusOK, apiEnvelope{Data: entries, Meta: map[string]any{"chart": chartKey, "count": len(entries), "api_version": apiVersion}})
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "votes" && r.Method == http.MethodPost {
|
|
installation, ok := authorizeInstallation(w, r, deps.database, "")
|
|
if !ok {
|
|
return
|
|
}
|
|
var in struct {
|
|
EntryID int `json:"entry_id"`
|
|
Rating int `json:"rating"`
|
|
}
|
|
if err := decodeStrictJSON(r, &in, 8<<10); err != nil {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
result, err := deps.charts.Vote(r.Context(), chartKey, in.EntryID, in.Rating, installation.ID)
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "vote_rejected", err.Error())
|
|
return
|
|
}
|
|
status := http.StatusCreated
|
|
if !result.Accepted {
|
|
status = http.StatusTooManyRequests
|
|
}
|
|
writeJSON(w, status, apiEnvelope{Data: result, Meta: apiMeta()})
|
|
return
|
|
}
|
|
w.Header().Set("Allow", "GET, POST")
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
}
|
|
|
|
func handleMobileNewsDetail(w http.ResponseWriter, r *http.Request, base string, deps mobileAPIDependencies) {
|
|
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
w.Header().Set("Allow", "GET, HEAD")
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
return
|
|
}
|
|
tail := strings.Trim(strings.TrimPrefix(r.URL.Path, base+"/news/"), "/")
|
|
parts := strings.SplitN(tail, "/", 2)
|
|
if len(parts) != 2 || parts[1] == "" {
|
|
writeAPIError(w, http.StatusNotFound, "news_not_found", "Die Meldung wurde nicht gefunden.")
|
|
return
|
|
}
|
|
switch parts[0] {
|
|
case "editorial":
|
|
entry, found, err := deps.editorial.GetBySlug(r.Context(), parts[1])
|
|
if err != nil || !found || entry.Status != "published" || entry.ContentType != "news" {
|
|
writeAPIError(w, http.StatusNotFound, "news_not_found", "Die Meldung wurde nicht gefunden.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: map[string]any{
|
|
"id": "editorial:" + entry.Slug, "content_type": "editorial", "title": entry.Title,
|
|
"summary": entry.Teaser, "body": entry.Body, "location": entry.Location,
|
|
"image_url": publicURL(r, entry.MediaURL), "image_alt": entry.MediaAlt,
|
|
"published_at": entry.UpdatedAt, "source": map[string]any{"name": "Landwelle Redaktion"},
|
|
"ai_transparency": editorialAITransparencyPayload(entry),
|
|
}, Meta: apiMeta()})
|
|
case "rss":
|
|
id, err := strconv.ParseInt(parts[1], 10, 64)
|
|
if err != nil || id < 1 {
|
|
writeAPIError(w, http.StatusNotFound, "news_not_found", "Die Meldung wurde nicht gefunden.")
|
|
return
|
|
}
|
|
item, found, err := deps.rss.PublicItemByID(r.Context(), id)
|
|
if err != nil || !found {
|
|
writeAPIError(w, http.StatusNotFound, "news_not_found", "Die Meldung wurde nicht gefunden.")
|
|
return
|
|
}
|
|
data := feedRecordJSON(r, item)
|
|
data["id"] = "rss:" + strconv.FormatInt(item.ID, 10)
|
|
data["body"] = nil
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: data, Meta: apiMeta()})
|
|
default:
|
|
writeAPIError(w, http.StatusNotFound, "news_not_found", "Die Meldung wurde nicht gefunden.")
|
|
}
|
|
}
|
|
|
|
func handleMobileEventDetail(w http.ResponseWriter, r *http.Request, base string, deps mobileAPIDependencies) {
|
|
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
w.Header().Set("Allow", "GET, HEAD")
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
return
|
|
}
|
|
id, err := strconv.ParseInt(strings.Trim(strings.TrimPrefix(r.URL.Path, base+"/events/"), "/"), 10, 64)
|
|
if err != nil || id < 1 {
|
|
writeAPIError(w, http.StatusNotFound, "event_not_found", "Die Veranstaltung wurde nicht gefunden.")
|
|
return
|
|
}
|
|
items, err := deps.events.ListPublished(r.Context(), "")
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "events_unavailable", "Veranstaltungen konnten nicht geladen werden.")
|
|
return
|
|
}
|
|
for _, item := range items {
|
|
if item.ID == id {
|
|
item.ImageURL = publicURL(r, item.ImageURL)
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: mobileEventJSON(r, item), Meta: apiMeta()})
|
|
return
|
|
}
|
|
}
|
|
writeAPIError(w, http.StatusNotFound, "event_not_found", "Die Veranstaltung wurde nicht gefunden.")
|
|
}
|
|
|
|
func mobileEventJSON(r *http.Request, item CalendarEvent) map[string]any {
|
|
imageURL := ""
|
|
if strings.TrimSpace(item.ImageURL) != "" {
|
|
imageURL = publicURL(r, item.ImageURL)
|
|
}
|
|
return map[string]any{
|
|
"id": item.ID, "title": item.Title, "category": item.Category,
|
|
"start_at": item.StartAt, "end_at": item.EndAt, "date_label": item.DateLabel(),
|
|
"venue": item.Venue, "city": item.City, "postal_code": item.PostalCode,
|
|
"organizer": item.Organizer, "description": item.Description, "website": item.Website,
|
|
"image_url": imageURL, "source_name": item.SourceName, "source_url": item.SourceURL,
|
|
"calendar_url": publicURL(r, "/veranstaltungen/kalender.ics"),
|
|
"detail_url": apiRequestBase(r) + "/events/" + strconv.FormatInt(item.ID, 10),
|
|
}
|
|
}
|
|
|
|
func handleCompatibility(w http.ResponseWriter, r *http.Request, db *postgresStore) {
|
|
platform := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("platform")))
|
|
channel := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("channel")))
|
|
version := strings.TrimSpace(r.URL.Query().Get("version"))
|
|
build := strings.TrimSpace(r.URL.Query().Get("build"))
|
|
if platform != "android" && platform != "ios" {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_platform", "platform muss android oder ios sein.")
|
|
return
|
|
}
|
|
if channel == "" {
|
|
if platform == "android" {
|
|
channel = "google_play"
|
|
} else {
|
|
channel = "app_store"
|
|
}
|
|
}
|
|
if channel == "development" {
|
|
channel = "beta"
|
|
}
|
|
if (platform == "android" && !allowedValue(channel, "sideload", "google_play", "beta")) ||
|
|
(platform == "ios" && !allowedValue(channel, "app_store", "beta")) {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_channel", "channel ist für die gewählte Plattform ungültig.")
|
|
return
|
|
}
|
|
latest, found, err := latestAppRelease(r.Context(), db, platform, channel)
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "release_check_failed", "Die Versionsprüfung ist momentan nicht verfügbar.")
|
|
return
|
|
}
|
|
data := map[string]any{
|
|
"platform": platform, "channel": channel, "current_version": version, "current_build": build,
|
|
"supported": true, "update_available": false, "mandatory": false, "latest_release": nil,
|
|
}
|
|
if found {
|
|
data["latest_release"] = latest
|
|
data["update_available"] = appUpdateAvailable(version, build, fmt.Sprint(latest["version"]), fmt.Sprint(latest["build_number"]))
|
|
data["mandatory"] = latest["mandatory"]
|
|
}
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: data, Meta: apiMeta()})
|
|
}
|
|
|
|
func latestAppRelease(ctx context.Context, db *postgresStore, platform, channel string) (map[string]any, bool, error) {
|
|
if db == nil || !db.Enabled() {
|
|
return nil, false, nil
|
|
}
|
|
var items []map[string]any
|
|
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 published=true AND platform=` + sqlText(platform) + ` AND channel=` + sqlText(channel) + ` ORDER BY published_at DESC,id DESC LIMIT 1) x;`
|
|
if err := db.queryJSON(ctx, q, &items); err != nil {
|
|
return nil, false, err
|
|
}
|
|
if len(items) == 0 {
|
|
return nil, false, nil
|
|
}
|
|
return items[0], true, nil
|
|
}
|
|
|
|
func appUpdateAvailable(currentVersion, currentBuild, latestVersion, latestBuild string) bool {
|
|
versionComparison := compareVersions(currentVersion, latestVersion)
|
|
return versionComparison < 0 || (versionComparison == 0 && compareBuilds(currentBuild, latestBuild) < 0)
|
|
}
|
|
|
|
func compareVersions(a, b string) int {
|
|
parse := func(raw string) []int {
|
|
raw = strings.TrimPrefix(strings.TrimSpace(raw), "v")
|
|
parts := strings.Split(raw, ".")
|
|
out := make([]int, 3)
|
|
for i := 0; i < len(parts) && i < len(out); i++ {
|
|
n, _ := strconv.Atoi(regexp.MustCompile(`[^0-9].*$`).ReplaceAllString(parts[i], ""))
|
|
out[i] = n
|
|
}
|
|
return out
|
|
}
|
|
x, y := parse(a), parse(b)
|
|
for i := range x {
|
|
if x[i] < y[i] {
|
|
return -1
|
|
}
|
|
if x[i] > y[i] {
|
|
return 1
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func compareBuilds(a, b string) int {
|
|
x, errX := strconv.ParseInt(strings.TrimSpace(a), 10, 64)
|
|
y, errY := strconv.ParseInt(strings.TrimSpace(b), 10, 64)
|
|
if errX != nil || errY != nil {
|
|
return 0
|
|
}
|
|
if x < y {
|
|
return -1
|
|
}
|
|
if x > y {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// Installation API
|
|
|
|
type installationRecord struct {
|
|
ID string `json:"id"`
|
|
Platform string `json:"platform"`
|
|
AppVersion string `json:"app_version"`
|
|
AppBuild string `json:"app_build"`
|
|
PreferredRegionSlug string `json:"preferred_region_slug"`
|
|
NotificationsEnabled bool `json:"notifications_enabled"`
|
|
AnalyticsConsent bool `json:"analytics_consent"`
|
|
Status string `json:"status"`
|
|
}
|
|
|
|
type installationRegistration struct {
|
|
InstallationID string `json:"installation_id"`
|
|
Platform string `json:"platform"`
|
|
DeviceClass string `json:"device_class"`
|
|
DistributionChannel string `json:"distribution_channel"`
|
|
AppVersion string `json:"app_version"`
|
|
AppBuild string `json:"app_build"`
|
|
OSVersion string `json:"os_version"`
|
|
Locale string `json:"locale"`
|
|
Timezone string `json:"timezone"`
|
|
}
|
|
|
|
var uuidPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)
|
|
|
|
func handleInstallationRegistration(w http.ResponseWriter, r *http.Request, db *postgresStore) {
|
|
if db == nil || !db.Enabled() {
|
|
writeAPIError(w, http.StatusServiceUnavailable, "database_unavailable", "Die App-Registrierung ist derzeit nicht verfügbar.")
|
|
return
|
|
}
|
|
var in installationRegistration
|
|
if err := decodeStrictJSON(r, &in, 32<<10); err != nil {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
in.Platform = strings.ToLower(strings.TrimSpace(in.Platform))
|
|
in.DeviceClass = strings.ToLower(strings.TrimSpace(in.DeviceClass))
|
|
in.DistributionChannel = strings.ToLower(strings.TrimSpace(in.DistributionChannel))
|
|
if in.InstallationID == "" {
|
|
in.InstallationID = newUUID()
|
|
}
|
|
if !uuidPattern.MatchString(in.InstallationID) {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_installation_id", "installation_id ist keine gültige UUID.")
|
|
return
|
|
}
|
|
if !allowedValue(in.Platform, "android", "ios") || !allowedValue(in.DeviceClass, "phone", "tablet", "unknown") || !allowedValue(in.DistributionChannel, "sideload", "google_play", "app_store", "development") || strings.TrimSpace(in.AppVersion) == "" {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_installation", "Plattform, Geräteklasse, Vertriebsweg oder App-Version sind ungültig.")
|
|
return
|
|
}
|
|
secret, err := randomToken(32)
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "token_generation_failed", "Das Installation-Secret konnte nicht erzeugt werden.")
|
|
return
|
|
}
|
|
hash := sha256.Sum256([]byte(secret))
|
|
q := `INSERT INTO app_installations(id,installation_token_hash,platform,device_class,distribution_channel,app_version,app_build,os_version,locale,timezone,last_seen_at) VALUES (` +
|
|
sqlText(strings.ToLower(in.InstallationID)) + `::uuid,decode(` + sqlText(hex.EncodeToString(hash[:])) + `,'hex'),` + sqlText(in.Platform) + `,` + sqlText(in.DeviceClass) + `,` + sqlText(in.DistributionChannel) + `,` + sqlText(limitString(in.AppVersion, 50)) + `,` + sqlText(limitString(in.AppBuild, 50)) + `,` + sqlText(limitString(in.OSVersion, 100)) + `,` + sqlText(limitString(in.Locale, 20)) + `,` + sqlText(limitString(in.Timezone, 100)) + `,now());`
|
|
if _, err := db.exec(r.Context(), q); err != nil {
|
|
if strings.Contains(strings.ToLower(err.Error()), "duplicate") {
|
|
writeAPIError(w, http.StatusConflict, "installation_exists", "Diese installation_id ist bereits registriert.")
|
|
return
|
|
}
|
|
writeAPIError(w, http.StatusInternalServerError, "registration_failed", "Die App-Installation konnte nicht registriert werden.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusCreated, apiEnvelope{Data: map[string]any{
|
|
"installation_id": strings.ToLower(in.InstallationID), "installation_token": secret,
|
|
"authorization_scheme": "Installation", "created_at": time.Now().UTC().Format(time.RFC3339),
|
|
}, Meta: apiMeta()})
|
|
}
|
|
|
|
func handleInstallationResource(w http.ResponseWriter, r *http.Request, base string, db *postgresStore) {
|
|
tail := strings.Trim(strings.TrimPrefix(r.URL.Path, base+"/installations/"), "/")
|
|
parts := strings.Split(tail, "/")
|
|
if len(parts) < 1 || !uuidPattern.MatchString(parts[0]) {
|
|
writeAPIError(w, http.StatusNotFound, "installation_not_found", "Die App-Installation wurde nicht gefunden.")
|
|
return
|
|
}
|
|
id := strings.ToLower(parts[0])
|
|
installation, ok := authorizeInstallation(w, r, db, id)
|
|
if !ok {
|
|
return
|
|
}
|
|
if len(parts) == 1 {
|
|
switch r.Method {
|
|
case http.MethodPatch:
|
|
handleInstallationUpdate(w, r, db, installation)
|
|
case http.MethodDelete:
|
|
handleInstallationDelete(w, r, db, installation)
|
|
default:
|
|
w.Header().Set("Allow", "PATCH, DELETE")
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
}
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "push-token" {
|
|
switch r.Method {
|
|
case http.MethodPut:
|
|
handlePushTokenUpsert(w, r, db, installation)
|
|
case http.MethodDelete:
|
|
handlePushTokenDelete(w, r, db, installation)
|
|
default:
|
|
w.Header().Set("Allow", "PUT, DELETE")
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
}
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "topics" {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
handleTopicsGet(w, r, db, installation)
|
|
case http.MethodPut:
|
|
handleTopicsReplace(w, r, db, installation)
|
|
default:
|
|
w.Header().Set("Allow", "GET, PUT")
|
|
writeAPIError(w, http.StatusMethodNotAllowed, "method_not_allowed", "Diese HTTP-Methode ist nicht erlaubt.")
|
|
}
|
|
return
|
|
}
|
|
writeAPIError(w, http.StatusNotFound, "not_found", "Der angeforderte API-Endpunkt wurde nicht gefunden.")
|
|
}
|
|
|
|
func authorizeInstallation(w http.ResponseWriter, r *http.Request, db *postgresStore, expectedID string) (installationRecord, bool) {
|
|
if db == nil || !db.Enabled() {
|
|
writeAPIError(w, http.StatusServiceUnavailable, "database_unavailable", "Die App-Registrierung ist derzeit nicht verfügbar.")
|
|
return installationRecord{}, false
|
|
}
|
|
token := installationToken(r.Header.Get("Authorization"))
|
|
if token == "" {
|
|
writeAPIError(w, http.StatusUnauthorized, "installation_auth_required", "Ein gültiges Installation-Secret wird benötigt.")
|
|
return installationRecord{}, false
|
|
}
|
|
hash := sha256.Sum256([]byte(token))
|
|
var rows []installationRecord
|
|
where := "installation_token_hash=decode(" + sqlText(hex.EncodeToString(hash[:])) + ",'hex') AND status='active'"
|
|
if expectedID != "" {
|
|
where += " AND id=" + sqlText(expectedID) + "::uuid"
|
|
}
|
|
q := `SELECT COALESCE(json_agg(row_to_json(x)),'[]'::json)::text FROM (SELECT id::text,platform,app_version,COALESCE(app_build,'') app_build,COALESCE(preferred_region_slug,'') preferred_region_slug,notifications_enabled,analytics_consent,status FROM app_installations WHERE ` + where + ` LIMIT 1) x;`
|
|
if err := db.queryJSON(r.Context(), q, &rows); err != nil || len(rows) == 0 {
|
|
writeAPIError(w, http.StatusUnauthorized, "invalid_installation_token", "Das Installation-Secret ist ungültig.")
|
|
return installationRecord{}, false
|
|
}
|
|
_, _ = db.exec(r.Context(), "UPDATE app_installations SET last_seen_at=now() WHERE id="+sqlText(rows[0].ID)+"::uuid;")
|
|
return rows[0], true
|
|
}
|
|
|
|
func installationToken(header string) string {
|
|
parts := strings.Fields(strings.TrimSpace(header))
|
|
if len(parts) != 2 {
|
|
return ""
|
|
}
|
|
if !strings.EqualFold(parts[0], "Installation") && !strings.EqualFold(parts[0], "Bearer") {
|
|
return ""
|
|
}
|
|
return parts[1]
|
|
}
|
|
|
|
func handleInstallationUpdate(w http.ResponseWriter, r *http.Request, db *postgresStore, installation installationRecord) {
|
|
var in struct {
|
|
AppVersion *string `json:"app_version"`
|
|
AppBuild *string `json:"app_build"`
|
|
OSVersion *string `json:"os_version"`
|
|
Locale *string `json:"locale"`
|
|
Timezone *string `json:"timezone"`
|
|
PreferredRegionSlug *string `json:"preferred_region_slug"`
|
|
NotificationsEnabled *bool `json:"notifications_enabled"`
|
|
AnalyticsConsent *bool `json:"analytics_consent"`
|
|
}
|
|
if err := decodeStrictJSON(r, &in, 16<<10); err != nil {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
sets := []string{"last_seen_at=now()"}
|
|
if in.AppVersion != nil {
|
|
sets = append(sets, "app_version="+sqlText(limitString(*in.AppVersion, 50)))
|
|
}
|
|
if in.AppBuild != nil {
|
|
sets = append(sets, "app_build="+sqlText(limitString(*in.AppBuild, 50)))
|
|
}
|
|
if in.OSVersion != nil {
|
|
sets = append(sets, "os_version="+sqlText(limitString(*in.OSVersion, 100)))
|
|
}
|
|
if in.Locale != nil {
|
|
sets = append(sets, "locale="+sqlText(limitString(*in.Locale, 20)))
|
|
}
|
|
if in.Timezone != nil {
|
|
sets = append(sets, "timezone="+sqlText(limitString(*in.Timezone, 100)))
|
|
}
|
|
if in.PreferredRegionSlug != nil {
|
|
if strings.TrimSpace(*in.PreferredRegionSlug) == "" {
|
|
sets = append(sets, "preferred_region_slug=NULL")
|
|
} else {
|
|
sets = append(sets, "preferred_region_slug="+sqlText(limitString(*in.PreferredRegionSlug, 100)))
|
|
}
|
|
}
|
|
if in.NotificationsEnabled != nil {
|
|
sets = append(sets, "notifications_enabled="+sqlBool(*in.NotificationsEnabled))
|
|
}
|
|
if in.AnalyticsConsent != nil {
|
|
sets = append(sets, "analytics_consent="+sqlBool(*in.AnalyticsConsent))
|
|
}
|
|
if _, err := db.exec(r.Context(), "UPDATE app_installations SET "+strings.Join(sets, ",")+" WHERE id="+sqlText(installation.ID)+"::uuid;"); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "update_failed", "Die App-Installation konnte nicht aktualisiert werden.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: map[string]any{"installation_id": installation.ID, "updated": true}, Meta: apiMeta()})
|
|
}
|
|
|
|
func handleInstallationDelete(w http.ResponseWriter, r *http.Request, db *postgresStore, installation installationRecord) {
|
|
q := `UPDATE app_installations SET status='deleted',deleted_at=now(),notifications_enabled=false,analytics_consent=false WHERE id=` + sqlText(installation.ID) + `::uuid; UPDATE app_push_tokens SET active=false,invalidated_at=now() WHERE installation_id=` + sqlText(installation.ID) + `::uuid;`
|
|
if _, err := db.exec(r.Context(), q); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "delete_failed", "Die App-Installation konnte nicht gelöscht werden.")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func handlePushTokenUpsert(w http.ResponseWriter, r *http.Request, db *postgresStore, installation installationRecord) {
|
|
key, err := appPushEncryptionKey()
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusServiceUnavailable, "push_not_configured", "Push-Registrierung ist serverseitig noch nicht konfiguriert.")
|
|
return
|
|
}
|
|
var in struct{ Provider, Token, Environment string }
|
|
if err := decodeStrictJSON(r, &in, 16<<10); err != nil {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
in.Provider = strings.ToLower(strings.TrimSpace(in.Provider))
|
|
in.Environment = strings.ToLower(strings.TrimSpace(in.Environment))
|
|
if in.Environment == "" {
|
|
in.Environment = "production"
|
|
}
|
|
if !allowedValue(in.Provider, "fcm", "native") || !allowedValue(in.Environment, "development", "staging", "production") || len(strings.TrimSpace(in.Token)) < 20 || len(in.Token) > 8192 {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_push_token", "Provider, Umgebung oder Push-Token sind ungültig.")
|
|
return
|
|
}
|
|
ciphertext, err := encryptToken(key, []byte(in.Token))
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "push_encryption_failed", "Der Push-Token konnte nicht geschützt gespeichert werden.")
|
|
return
|
|
}
|
|
fp := sha256.Sum256([]byte(in.Token))
|
|
q := `INSERT INTO app_push_tokens(installation_id,provider,token_ciphertext,token_fingerprint,environment,active,last_confirmed_at) VALUES (` + sqlText(installation.ID) + `::uuid,` + sqlText(in.Provider) + `,decode(` + sqlText(hex.EncodeToString(ciphertext)) + `,'hex'),` + sqlText(hex.EncodeToString(fp[:])) + `,` + sqlText(in.Environment) + `,true,now()) ON CONFLICT(token_fingerprint) DO UPDATE SET installation_id=excluded.installation_id,provider=excluded.provider,token_ciphertext=excluded.token_ciphertext,environment=excluded.environment,active=true,last_confirmed_at=now(),invalidated_at=NULL,last_error_code=NULL; UPDATE app_installations SET notifications_enabled=true,last_seen_at=now() WHERE id=` + sqlText(installation.ID) + `::uuid;`
|
|
if _, err := db.exec(r.Context(), q); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "push_registration_failed", "Der Push-Token konnte nicht gespeichert werden.")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func handlePushTokenDelete(w http.ResponseWriter, r *http.Request, db *postgresStore, installation installationRecord) {
|
|
q := `UPDATE app_push_tokens SET active=false,invalidated_at=now() WHERE installation_id=` + sqlText(installation.ID) + `::uuid; UPDATE app_installations SET notifications_enabled=false WHERE id=` + sqlText(installation.ID) + `::uuid;`
|
|
if _, err := db.exec(r.Context(), q); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "push_delete_failed", "Der Push-Token konnte nicht entfernt werden.")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func handleTopicsGet(w http.ResponseWriter, r *http.Request, db *postgresStore, installation installationRecord) {
|
|
var topics []map[string]any
|
|
q := `SELECT COALESCE(json_agg(row_to_json(x)),'[]'::json)::text FROM (SELECT t.slug,t.name,t.description,t.kind,(it.installation_id IS NOT NULL) subscribed FROM push_topics t LEFT JOIN app_installation_topics it ON it.topic_id=t.id AND it.installation_id=` + sqlText(installation.ID) + `::uuid WHERE t.active=true ORDER BY t.kind,t.name) x;`
|
|
if err := db.queryJSON(r.Context(), q, &topics); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "topics_unavailable", "Push-Themen konnten nicht geladen werden.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, apiEnvelope{Data: topics, Meta: map[string]any{"count": len(topics), "api_version": apiVersion}})
|
|
}
|
|
|
|
func handleTopicsReplace(w http.ResponseWriter, r *http.Request, db *postgresStore, installation installationRecord) {
|
|
var in struct {
|
|
Topics []string `json:"topics"`
|
|
}
|
|
if err := decodeStrictJSON(r, &in, 16<<10); err != nil {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
if len(in.Topics) > 50 {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "too_many_topics", "Es dürfen höchstens 50 Push-Themen gewählt werden.")
|
|
return
|
|
}
|
|
seen := map[string]bool{}
|
|
values := make([]string, 0, len(in.Topics))
|
|
for _, topic := range in.Topics {
|
|
topic = strings.ToLower(strings.TrimSpace(topic))
|
|
if topic == "" || seen[topic] {
|
|
continue
|
|
}
|
|
seen[topic] = true
|
|
values = append(values, topic)
|
|
}
|
|
valueSQL := "NULL"
|
|
if len(values) > 0 {
|
|
quoted := make([]string, len(values))
|
|
for i, value := range values {
|
|
quoted[i] = sqlText(value)
|
|
}
|
|
valueSQL = strings.Join(quoted, ",")
|
|
}
|
|
q := `DELETE FROM app_installation_topics WHERE installation_id=` + sqlText(installation.ID) + `::uuid;`
|
|
if len(values) > 0 {
|
|
q += ` INSERT INTO app_installation_topics(installation_id,topic_id) SELECT ` + sqlText(installation.ID) + `::uuid,id FROM push_topics WHERE active=true AND slug IN (` + valueSQL + `) ON CONFLICT DO NOTHING;`
|
|
}
|
|
if _, err := db.exec(r.Context(), q); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "topics_update_failed", "Push-Themen konnten nicht aktualisiert werden.")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func handleUsageEvents(w http.ResponseWriter, r *http.Request, db *postgresStore) {
|
|
installation, ok := authorizeInstallation(w, r, db, "")
|
|
if !ok {
|
|
return
|
|
}
|
|
if !envBool("LANDWELLE_APP_ANALYTICS_ENABLED", false) {
|
|
writeAPIError(w, http.StatusForbidden, "analytics_disabled", "Nutzungsstatistik ist serverseitig deaktiviert.")
|
|
return
|
|
}
|
|
if !installation.AnalyticsConsent {
|
|
writeAPIError(w, http.StatusForbidden, "analytics_consent_required", "Für Nutzungsereignisse liegt keine Einwilligung vor.")
|
|
return
|
|
}
|
|
var in struct {
|
|
Events []usageEventInput `json:"events"`
|
|
}
|
|
if err := decodeStrictJSON(r, &in, 128<<10); err != nil {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", err.Error())
|
|
return
|
|
}
|
|
if len(in.Events) == 0 || len(in.Events) > 50 {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_event_count", "Pro Anfrage sind 1 bis 50 Ereignisse erlaubt.")
|
|
return
|
|
}
|
|
allowed := map[string]bool{"app_open": true, "session_start": true, "session_end": true, "stream_start": true, "stream_stop": true, "news_open": true, "event_open": true, "program_open": true, "push_open": true, "download_open": true}
|
|
statements := make([]string, 0, len(in.Events))
|
|
for _, event := range in.Events {
|
|
if !uuidPattern.MatchString(event.EventID) || !allowed[event.EventName] || event.Platform != installation.Platform || event.AppVersion == "" {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_usage_event", "Mindestens ein Nutzungsereignis ist ungültig.")
|
|
return
|
|
}
|
|
occurred, err := time.Parse(time.RFC3339, event.OccurredAt)
|
|
if err != nil || occurred.Before(time.Now().Add(-7*24*time.Hour)) || occurred.After(time.Now().Add(10*time.Minute)) {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_event_time", "Der Ereigniszeitpunkt ist ungültig.")
|
|
return
|
|
}
|
|
properties, err := validateUsageProperties(event.EventName, event.Properties)
|
|
if err != nil {
|
|
writeAPIError(w, http.StatusUnprocessableEntity, "invalid_event_properties", err.Error())
|
|
return
|
|
}
|
|
regionSQL := "NULL"
|
|
if strings.TrimSpace(event.RegionSlug) != "" {
|
|
regionSQL = sqlText(limitString(event.RegionSlug, 100))
|
|
}
|
|
statements = append(statements, `INSERT INTO app_usage_events(event_id,installation_id,event_name,occurred_at,app_version,platform,region_slug,properties) VALUES (`+sqlText(strings.ToLower(event.EventID))+`::uuid,`+sqlText(installation.ID)+`::uuid,`+sqlText(event.EventName)+`,`+sqlText(occurred.UTC().Format(time.RFC3339))+`::timestamptz,`+sqlText(limitString(event.AppVersion, 50))+`,`+sqlText(event.Platform)+`,`+regionSQL+`,`+sqlText(string(properties))+`::jsonb) ON CONFLICT(event_id) DO NOTHING;`)
|
|
}
|
|
if _, err := db.exec(r.Context(), strings.Join(statements, "\n")); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "usage_events_failed", "Nutzungsereignisse konnten nicht gespeichert werden.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusAccepted, apiEnvelope{Data: map[string]any{"accepted": len(in.Events)}, Meta: apiMeta()})
|
|
}
|
|
|
|
func validateUsageProperties(eventName string, properties map[string]any) ([]byte, error) {
|
|
allowed := map[string]map[string]string{
|
|
"app_open": {},
|
|
"session_start": {},
|
|
"session_end": {"duration_seconds": "number", "reason": "string"},
|
|
"stream_start": {},
|
|
"stream_stop": {"duration_seconds": "number", "reason": "string"},
|
|
"news_open": {"content_id": "string"},
|
|
"event_open": {"event_id": "id"},
|
|
"program_open": {"program_id": "id"},
|
|
"push_open": {"campaign_id": "id"},
|
|
"download_open": {"release_id": "id"},
|
|
}
|
|
rules, ok := allowed[eventName]
|
|
if !ok {
|
|
return nil, errors.New("Der Ereignistyp ist nicht erlaubt.")
|
|
}
|
|
if properties == nil {
|
|
properties = map[string]any{}
|
|
}
|
|
for key, value := range properties {
|
|
typeName, permitted := rules[key]
|
|
if !permitted {
|
|
return nil, fmt.Errorf("Die Eigenschaft %q ist für %s nicht erlaubt.", key, eventName)
|
|
}
|
|
switch typeName {
|
|
case "string":
|
|
text, valid := value.(string)
|
|
if !valid || strings.TrimSpace(text) == "" || len([]rune(text)) > 200 {
|
|
return nil, fmt.Errorf("Die Eigenschaft %q muss ein kurzer Text sein.", key)
|
|
}
|
|
case "number":
|
|
number, valid := value.(float64)
|
|
if !valid || number < 0 || number > 86400 {
|
|
return nil, fmt.Errorf("Die Eigenschaft %q muss eine Zahl zwischen 0 und 86400 sein.", key)
|
|
}
|
|
case "id":
|
|
switch typed := value.(type) {
|
|
case string:
|
|
if strings.TrimSpace(typed) == "" || len([]rune(typed)) > 100 {
|
|
return nil, fmt.Errorf("Die Eigenschaft %q enthält keine gültige ID.", key)
|
|
}
|
|
case float64:
|
|
if typed < 1 || typed != float64(int64(typed)) {
|
|
return nil, fmt.Errorf("Die Eigenschaft %q enthält keine gültige ID.", key)
|
|
}
|
|
default:
|
|
return nil, fmt.Errorf("Die Eigenschaft %q enthält keine gültige ID.", key)
|
|
}
|
|
}
|
|
}
|
|
encoded, err := json.Marshal(properties)
|
|
if err != nil || len(encoded) > 2048 {
|
|
return nil, errors.New("Die Ereigniseigenschaften sind ungültig oder zu groß.")
|
|
}
|
|
return encoded, nil
|
|
}
|
|
|
|
type usageEventInput struct {
|
|
EventID, EventName, OccurredAt, AppVersion, Platform, RegionSlug string
|
|
Properties map[string]any `json:"properties"`
|
|
}
|
|
|
|
func (u *usageEventInput) UnmarshalJSON(data []byte) error {
|
|
type alias struct {
|
|
EventID string `json:"event_id"`
|
|
EventName string `json:"event_name"`
|
|
OccurredAt string `json:"occurred_at"`
|
|
AppVersion string `json:"app_version"`
|
|
Platform string `json:"platform"`
|
|
RegionSlug string `json:"region_slug"`
|
|
Properties map[string]any `json:"properties"`
|
|
}
|
|
var a alias
|
|
if err := json.Unmarshal(data, &a); err != nil {
|
|
return err
|
|
}
|
|
u.EventID, u.EventName, u.OccurredAt, u.AppVersion, u.Platform, u.RegionSlug, u.Properties = a.EventID, a.EventName, a.OccurredAt, a.AppVersion, strings.ToLower(a.Platform), a.RegionSlug, a.Properties
|
|
return nil
|
|
}
|
|
|
|
func handlePushOpened(w http.ResponseWriter, r *http.Request, db *postgresStore) {
|
|
installation, ok := authorizeInstallation(w, r, db, "")
|
|
if !ok {
|
|
return
|
|
}
|
|
var in struct {
|
|
CampaignID int64 `json:"campaign_id"`
|
|
OpenedAt string `json:"opened_at"`
|
|
}
|
|
if err := decodeStrictJSON(r, &in, 8<<10); err != nil || in.CampaignID < 1 {
|
|
writeAPIError(w, http.StatusBadRequest, "invalid_json", "campaign_id und opened_at sind erforderlich.")
|
|
return
|
|
}
|
|
opened, err := time.Parse(time.RFC3339, in.OpenedAt)
|
|
if err != nil {
|
|
opened = time.Now().UTC()
|
|
}
|
|
q := `UPDATE push_deliveries SET status='opened',opened_at=` + sqlText(opened.UTC().Format(time.RFC3339)) + `::timestamptz WHERE campaign_id=` + strconv.FormatInt(in.CampaignID, 10) + ` AND installation_id=` + sqlText(installation.ID) + `::uuid; UPDATE push_campaigns SET opened_count=(SELECT count(*) FROM push_deliveries WHERE campaign_id=` + strconv.FormatInt(in.CampaignID, 10) + ` AND status='opened') WHERE id=` + strconv.FormatInt(in.CampaignID, 10) + `;`
|
|
if _, err := db.exec(r.Context(), q); err != nil {
|
|
writeAPIError(w, http.StatusInternalServerError, "push_open_failed", "Das Öffnen der Push-Mitteilung konnte nicht gespeichert werden.")
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusAccepted, apiEnvelope{Data: map[string]any{"accepted": true}, Meta: apiMeta()})
|
|
}
|
|
|
|
func decodeStrictJSON(r *http.Request, dest any, limit int64) error {
|
|
body, err := io.ReadAll(io.LimitReader(r.Body, limit+1))
|
|
if err != nil {
|
|
return errors.New("Die Anfrage konnte nicht gelesen werden.")
|
|
}
|
|
if int64(len(body)) > limit {
|
|
return errors.New("Die JSON-Anfrage ist zu groß.")
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewReader(body))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(dest); err != nil {
|
|
return fmt.Errorf("Ungültige JSON-Anfrage: %v", err)
|
|
}
|
|
if err := decoder.Decode(&struct{}{}); err != io.EOF {
|
|
return errors.New("Die Anfrage darf nur ein JSON-Objekt enthalten.")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func appPushEncryptionConfigured() bool {
|
|
_, err := appPushEncryptionKey()
|
|
return err == nil
|
|
}
|
|
|
|
func appPushEncryptionKey() ([]byte, error) {
|
|
raw := strings.TrimSpace(os.Getenv("LANDWELLE_APP_PUSH_ENCRYPTION_KEY"))
|
|
if raw == "" {
|
|
return nil, errors.New("LANDWELLE_APP_PUSH_ENCRYPTION_KEY fehlt")
|
|
}
|
|
if decoded, err := base64.StdEncoding.DecodeString(raw); err == nil && len(decoded) == 32 {
|
|
return decoded, nil
|
|
}
|
|
if decoded, err := hex.DecodeString(raw); err == nil && len(decoded) == 32 {
|
|
return decoded, nil
|
|
}
|
|
return nil, errors.New("LANDWELLE_APP_PUSH_ENCRYPTION_KEY muss 32 Byte als Base64 oder Hex enthalten")
|
|
}
|
|
|
|
func encryptToken(key, plaintext []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := rand.Read(nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
return gcm.Seal(nonce, nonce, plaintext, nil), nil
|
|
}
|
|
|
|
func decryptToken(key, ciphertext []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(ciphertext) < gcm.NonceSize() {
|
|
return nil, errors.New("verschlüsselter Push-Token ist unvollständig")
|
|
}
|
|
nonce := ciphertext[:gcm.NonceSize()]
|
|
payload := ciphertext[gcm.NonceSize():]
|
|
return gcm.Open(nil, nonce, payload, nil)
|
|
}
|
|
|
|
func newUUID() string {
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
panic(err)
|
|
}
|
|
b[6] = (b[6] & 0x0f) | 0x40
|
|
b[8] = (b[8] & 0x3f) | 0x80
|
|
return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
|
}
|
|
|
|
func allowedValue(value string, allowed ...string) bool {
|
|
for _, candidate := range allowed {
|
|
if value == candidate {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func limitString(value string, max int) string {
|
|
value = strings.TrimSpace(value)
|
|
runes := []rune(value)
|
|
if len(runes) > max {
|
|
runes = runes[:max]
|
|
}
|
|
return string(runes)
|
|
}
|
|
|
|
// constantTimeEqual is kept for future token rotation support and tested now.
|
|
func constantTimeEqual(a, b []byte) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
return subtle.ConstantTimeCompare(a, b) == 1
|
|
}
|
|
|
|
func sortedUnique(values []string) []string {
|
|
seen := map[string]bool{}
|
|
out := make([]string, 0, len(values))
|
|
for _, value := range values {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" || seen[value] {
|
|
continue
|
|
}
|
|
seen[value] = true
|
|
out = append(out, value)
|
|
}
|
|
sort.Strings(out)
|
|
return out
|
|
}
|
|
|
|
type mobileNewsItem struct {
|
|
SortTime time.Time
|
|
Payload map[string]any
|
|
}
|
|
|
|
func mobileNewsList(r *http.Request, deps mobileAPIDependencies, limit, offset int, region string) ([]map[string]any, int, error) {
|
|
if limit < 1 || limit > 100 {
|
|
limit = 20
|
|
}
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
fetchLimit := limit + offset + 20
|
|
items := make([]mobileNewsItem, 0, fetchLimit*2)
|
|
|
|
if deps.editorial != nil {
|
|
entries, err := deps.editorial.PublishedNews(r.Context(), fetchLimit)
|
|
if err != nil && deps.editorial.Enabled() {
|
|
return nil, 0, err
|
|
}
|
|
for _, entry := range entries {
|
|
regions := []string{"niedersachsen"}
|
|
if slug := slugify(entry.Location); strings.TrimSpace(entry.Location) != "" {
|
|
regions = []string{slug}
|
|
}
|
|
if region != "" && !containsString(regions, region) && region != "niedersachsen" {
|
|
continue
|
|
}
|
|
imageURL := strings.TrimSpace(entry.MediaURL)
|
|
if imageURL == "" {
|
|
imageURL = "/assets/news-region-v14.jpg"
|
|
}
|
|
items = append(items, mobileNewsItem{SortTime: entry.UpdatedAt, Payload: map[string]any{
|
|
"id": "editorial:" + entry.Slug, "numeric_id": entry.ID, "content_type": "editorial",
|
|
"title": entry.Title, "summary": entry.Teaser, "location": entry.Location,
|
|
"image_url": publicURL(r, imageURL), "image_alt": entry.MediaAlt,
|
|
"published_at": entry.UpdatedAt, "regions": regions,
|
|
"detail_url": apiRequestBase(r) + "/news/editorial/" + entry.Slug,
|
|
"web_url": publicURL(r, "/aktuelles/"+entry.Slug), "external_url": nil,
|
|
"source": map[string]any{"name": "Landwelle Redaktion", "website_url": "https://landwelle.de"},
|
|
"ai_transparency": editorialAITransparencyPayload(entry),
|
|
}})
|
|
}
|
|
}
|
|
|
|
if deps.rss != nil {
|
|
records, _, err := deps.rss.PublicItems(r.Context(), fetchLimit, "", region)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
for _, record := range records {
|
|
payload := feedRecordJSON(r, record)
|
|
payload["id"] = "rss:" + strconv.FormatInt(record.ID, 10)
|
|
payload["numeric_id"] = record.ID
|
|
payload["detail_url"] = apiRequestBase(r) + "/news/rss/" + strconv.FormatInt(record.ID, 10)
|
|
items = append(items, mobileNewsItem{SortTime: record.PublishedAt, Payload: payload})
|
|
}
|
|
}
|
|
|
|
sort.SliceStable(items, func(i, j int) bool { return items[i].SortTime.After(items[j].SortTime) })
|
|
total := len(items)
|
|
if offset >= total {
|
|
return []map[string]any{}, total, nil
|
|
}
|
|
end := offset + limit
|
|
if end > total {
|
|
end = total
|
|
}
|
|
result := make([]map[string]any, 0, end-offset)
|
|
for _, item := range items[offset:end] {
|
|
result = append(result, item.Payload)
|
|
}
|
|
return result, total, nil
|
|
}
|
|
|
|
func containsString(values []string, candidate string) bool {
|
|
candidate = strings.ToLower(strings.TrimSpace(candidate))
|
|
for _, value := range values {
|
|
if strings.ToLower(strings.TrimSpace(value)) == candidate {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|