212 lines
7.3 KiB
Go
212 lines
7.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type adminPushTopic struct {
|
|
Slug string `json:"slug"`
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Kind string `json:"kind"`
|
|
}
|
|
|
|
type adminPushCampaignRow struct {
|
|
ID int64 `json:"id"`
|
|
Title string `json:"title"`
|
|
Body string `json:"body"`
|
|
Topic string `json:"topic"`
|
|
DeepLink string `json:"deep_link"`
|
|
Status string `json:"status"`
|
|
SentCount int `json:"sent_count"`
|
|
FailedCount int `json:"failed_count"`
|
|
OpenedCount int `json:"opened_count"`
|
|
CreatedAt string `json:"created_at"`
|
|
}
|
|
|
|
type adminPushStats struct {
|
|
Installations int `json:"installations"`
|
|
PushEnabled int `json:"push_enabled"`
|
|
ActiveTokens int `json:"active_tokens"`
|
|
Campaigns int `json:"campaigns"`
|
|
Sent int `json:"sent"`
|
|
Failed int `json:"failed"`
|
|
Opened int `json:"opened"`
|
|
}
|
|
|
|
type adminPushData struct {
|
|
Username string
|
|
CSRFToken string
|
|
DatabaseReady bool
|
|
FirebaseReady bool
|
|
FirebaseState string
|
|
EncryptionOK bool
|
|
Topics []adminPushTopic
|
|
Campaigns []adminPushCampaignRow
|
|
Stats adminPushStats
|
|
Title string
|
|
Body string
|
|
Topic string
|
|
DeepLink string
|
|
Error string
|
|
Success string
|
|
}
|
|
|
|
func (a *adminHandler) adminAppPush(w http.ResponseWriter, r *http.Request) {
|
|
_, session, ok := a.sessionFromRequest(r)
|
|
if !ok {
|
|
http.Redirect(w, r, "/admin/login", http.StatusSeeOther)
|
|
return
|
|
}
|
|
data := adminPushData{
|
|
Username: session.Username,
|
|
CSRFToken: session.CSRFToken,
|
|
DatabaseReady: a.database != nil && a.database.Enabled(),
|
|
EncryptionOK: appPushEncryptionConfigured(),
|
|
Topic: "breaking-news",
|
|
DeepLink: "landwelle://aktuelles",
|
|
}
|
|
if a.firebasePush != nil {
|
|
data.FirebaseReady = a.firebasePush.Ready()
|
|
data.FirebaseState = a.firebasePush.Status()
|
|
} else {
|
|
data.FirebaseState = "Nicht initialisiert"
|
|
}
|
|
|
|
if r.Method == http.MethodPost {
|
|
r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
|
|
if err := r.ParseForm(); err != nil {
|
|
data.Error = "Das Push-Formular konnte nicht gelesen werden."
|
|
a.renderAdminAppPush(w, data)
|
|
return
|
|
}
|
|
if !validAdminCSRF(r, session) {
|
|
http.Error(w, "Ungültige Sicherheitsprüfung", http.StatusForbidden)
|
|
return
|
|
}
|
|
data.Title = strings.TrimSpace(r.FormValue("title"))
|
|
data.Body = strings.TrimSpace(r.FormValue("body"))
|
|
data.Topic = strings.ToLower(strings.TrimSpace(r.FormValue("topic")))
|
|
data.DeepLink = strings.TrimSpace(r.FormValue("deep_link"))
|
|
if data.Topic == "" {
|
|
data.Topic = "breaking-news"
|
|
}
|
|
if data.DeepLink == "" {
|
|
data.DeepLink = "landwelle://aktuelles"
|
|
}
|
|
if data.Title == "" || data.Body == "" {
|
|
data.Error = "Titel und Nachricht sind erforderlich."
|
|
} else if len([]rune(data.Title)) > 160 || len([]rune(data.Body)) > 500 {
|
|
data.Error = "Titel oder Nachricht ist zu lang."
|
|
} else if !data.DatabaseReady {
|
|
data.Error = "PostgreSQL ist für App-Push nicht verfügbar."
|
|
} else if !data.EncryptionOK {
|
|
data.Error = "LANDWELLE_APP_PUSH_ENCRYPTION_KEY ist nicht korrekt konfiguriert."
|
|
} else if a.firebasePush == nil || !a.firebasePush.Ready() {
|
|
data.Error = "Firebase Push ist nicht bereit: " + data.FirebaseState
|
|
} else {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
|
result, err := a.firebasePush.SendAppCampaign(ctx, appPushCampaignInput{
|
|
Title: data.Title,
|
|
Body: data.Body,
|
|
Topic: data.Topic,
|
|
DeepLink: data.DeepLink,
|
|
Priority: "high",
|
|
CreatedBy: session.UserID,
|
|
Data: map[string]string{
|
|
"type": "news",
|
|
"title": data.Title,
|
|
"body": data.Body,
|
|
},
|
|
})
|
|
cancel()
|
|
if err != nil {
|
|
data.Error = "Push konnte nicht vollständig versendet werden: " + err.Error()
|
|
a.audit(r.Context(), session, r, "app_push.send", "push_campaign", result.CampaignID, data.Error, false)
|
|
} else {
|
|
data.Success = fmt.Sprintf("Push-Kampagne #%d abgeschlossen: %d Empfänger, %d erfolgreich, %d fehlgeschlagen.", result.CampaignID, result.Recipients, result.Sent, result.Failed)
|
|
a.audit(r.Context(), session, r, "app_push.send", "push_campaign", result.CampaignID, data.Success, true)
|
|
data.Title, data.Body = "", ""
|
|
}
|
|
}
|
|
} else if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
w.Header().Set("Allow", "GET, HEAD, POST")
|
|
http.Error(w, "Methode nicht erlaubt", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
a.renderAdminAppPush(w, data)
|
|
}
|
|
|
|
func (a *adminHandler) renderAdminAppPush(w http.ResponseWriter, data adminPushData) {
|
|
if data.DatabaseReady {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
|
defer cancel()
|
|
if topics, err := a.loadAdminPushTopics(ctx); err == nil {
|
|
data.Topics = topics
|
|
} else if data.Error == "" {
|
|
data.Error = "Push-Themen konnten nicht geladen werden: " + err.Error()
|
|
}
|
|
if campaigns, err := a.loadAdminPushCampaigns(ctx, 50); err == nil {
|
|
data.Campaigns = campaigns
|
|
} else if data.Error == "" {
|
|
data.Error = "Push-Historie konnte nicht geladen werden: " + err.Error()
|
|
}
|
|
if stats, err := a.loadAdminPushStats(ctx); err == nil {
|
|
data.Stats = stats
|
|
}
|
|
}
|
|
setAdminHTMLHeaders(w)
|
|
if err := a.pushTemplate.ExecuteTemplate(w, "push-admin.html", data); err != nil {
|
|
a.logger.Printf("admin push template: %v", err)
|
|
}
|
|
}
|
|
|
|
func (a *adminHandler) loadAdminPushTopics(ctx context.Context) ([]adminPushTopic, error) {
|
|
var rows []adminPushTopic
|
|
q := `SELECT COALESCE(json_agg(row_to_json(x)),'[]'::json)::text FROM (` +
|
|
`SELECT slug,name,COALESCE(description,'') description,kind FROM push_topics WHERE active=true ORDER BY kind,name) x;`
|
|
if err := a.database.queryJSON(ctx, q, &rows); err != nil {
|
|
return nil, err
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
func (a *adminHandler) loadAdminPushCampaigns(ctx context.Context, limit int) ([]adminPushCampaignRow, error) {
|
|
if limit < 1 || limit > 200 {
|
|
limit = 50
|
|
}
|
|
var rows []adminPushCampaignRow
|
|
q := `SELECT COALESCE(json_agg(row_to_json(x)),'[]'::json)::text FROM (` +
|
|
`SELECT id,title,body,COALESCE(target->'topics'->>0,'') topic,COALESCE(deep_link,'') deep_link,status,sent_count,failed_count,opened_count,to_char(created_at AT TIME ZONE 'Europe/Berlin','DD.MM.YYYY HH24:MI') created_at ` +
|
|
`FROM push_campaigns ORDER BY created_at DESC LIMIT ` + strconv.Itoa(limit) + `) x;`
|
|
if err := a.database.queryJSON(ctx, q, &rows); err != nil {
|
|
return nil, err
|
|
}
|
|
return rows, nil
|
|
}
|
|
|
|
func (a *adminHandler) loadAdminPushStats(ctx context.Context) (adminPushStats, error) {
|
|
var rows []adminPushStats
|
|
q := `SELECT json_build_array(json_build_object(` +
|
|
`'installations',(SELECT count(*)::int FROM app_installations WHERE status='active'),` +
|
|
`'push_enabled',(SELECT count(*)::int FROM app_installations WHERE status='active' AND notifications_enabled=true),` +
|
|
`'active_tokens',(SELECT count(*)::int FROM app_push_tokens WHERE active=true AND provider='fcm'),` +
|
|
`'campaigns',(SELECT count(*)::int FROM push_campaigns),` +
|
|
`'sent',(SELECT COALESCE(sum(sent_count),0)::int FROM push_campaigns),` +
|
|
`'failed',(SELECT COALESCE(sum(failed_count),0)::int FROM push_campaigns),` +
|
|
`'opened',(SELECT COALESCE(sum(opened_count),0)::int FROM push_campaigns)))::text;`
|
|
if err := a.database.queryJSON(ctx, q, &rows); err != nil {
|
|
return adminPushStats{}, err
|
|
}
|
|
if len(rows) == 0 {
|
|
return adminPushStats{}, nil
|
|
}
|
|
return rows[0], nil
|
|
}
|