Files
date-wizard/main.go
T

351 lines
9.6 KiB
Go

package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/smtp"
"os"
"strings"
"time"
)
type Activity struct {
Name string `json:"name"`
Icon string `json:"icon"`
Type string `json:"type"`
CustomDescription string `json:"customDescription,omitempty"`
}
type SurveyPayload struct {
Activity string `json:"activity"`
Activities []Activity `json:"activities"`
Date string `json:"date"`
DateType string `json:"dateType"`
Name string `json:"name"`
}
type Response struct {
Success bool `json:"success"`
Message string `json:"message"`
}
func main() {
loadEnv(".env")
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
webDir := os.Getenv("WEB_DIR")
if webDir == "" {
webDir = "public"
}
http.HandleFunc("/api/submit", handleSubmit)
http.HandleFunc("/api/booked-dates", handleBookedDates)
// Serve static files from webDir directory
fs := http.FileServer(http.Dir(webDir))
http.Handle("/", fs)
log.Printf("Server starting on port %s (serving static files from %s)...", port, webDir)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}
func handleSubmit(w http.ResponseWriter, r *http.Request) {
if enableCORS(w, r) {
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var payload SurveyPayload
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(Response{
Success: false,
Message: "Ungültige Anfragedaten.",
})
return
}
log.Printf("Received survey submission from %s for date %s (%s)", payload.Name, payload.Date, payload.Activity)
if err := recordBookedDate(payload.Date); err != nil {
log.Printf("Error recording booked date: %v", err)
}
err = sendEmail(payload)
if err != nil {
log.Printf("Warning: Email could not be sent: %v", err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(Response{
Success: true,
Message: "Reservierung erfolgreich übermittelt!",
})
}
func handleBookedDates(w http.ResponseWriter, r *http.Request) {
if enableCORS(w, r) {
return
}
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
dates, err := getBookedDates()
if err != nil {
log.Printf("Error reading booked dates: %v", err)
dates = []string{}
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(dates)
}
func getBookedDatesFilePath() string {
path := os.Getenv("BOOKED_DATES_FILE")
if path == "" {
path = "booked_dates.json"
}
return path
}
func getBookedDates() ([]string, error) {
filePath := getBookedDatesFilePath()
file, err := os.Open(filePath)
if err != nil {
if os.IsNotExist(err) {
return []string{}, nil
}
return nil, err
}
defer file.Close()
var rawDates []string
if err := json.NewDecoder(file).Decode(&rawDates); err != nil {
return []string{}, nil
}
dates := make([]string, 0, len(rawDates))
for _, d := range rawDates {
trimmed := strings.TrimSpace(d)
if trimmed != "" {
dates = append(dates, trimmed)
}
}
return dates, nil
}
func recordBookedDate(dateStr string) error {
trimmedDate := strings.TrimSpace(dateStr)
if trimmedDate == "" {
return nil
}
dates, err := getBookedDates()
if err != nil {
dates = []string{}
}
for _, d := range dates {
if d == trimmedDate {
return nil
}
}
dates = append(dates, trimmedDate)
filePath := getBookedDatesFilePath()
data, err := json.MarshalIndent(dates, "", " ")
if err != nil {
return err
}
return os.WriteFile(filePath, data, 0644)
}
func enableCORS(w http.ResponseWriter, r *http.Request) bool {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return true
}
return false
}
func sendEmail(payload SurveyPayload) error {
smtpHost := os.Getenv("SMTP_HOST")
smtpPort := os.Getenv("SMTP_PORT")
if smtpPort == "" {
smtpPort = "587"
}
smtpUser := os.Getenv("SMTP_USER")
smtpPass := os.Getenv("SMTP_PASS")
toEmail := os.Getenv("TO_EMAIL")
fromEmail := os.Getenv("FROM_EMAIL")
if fromEmail == "" {
fromEmail = smtpUser
}
if smtpHost == "" || toEmail == "" {
log.Println("HINWEIS: SMTP_HOST oder TO_EMAIL nicht konfiguriert. E-Mail-Versand übersprungen.")
return nil
}
boundary := fmt.Sprintf("BOUNDARY_%d", time.Now().UnixNano())
var bodyBuilder bytes.Buffer
bodyBuilder.WriteString(fmt.Sprintf("From: %s\r\n", fromEmail))
bodyBuilder.WriteString(fmt.Sprintf("To: %s\r\n", toEmail))
bodyBuilder.WriteString(fmt.Sprintf("Subject: Neue Date-Reservierung von %s! 💕\r\n", payload.Name))
bodyBuilder.WriteString("MIME-Version: 1.0\r\n")
bodyBuilder.WriteString(fmt.Sprintf("Content-Type: multipart/mixed; boundary=\"%s\"\r\n\r\n", boundary))
// Text-Teil der E-Mail
bodyBuilder.WriteString(fmt.Sprintf("--%s\r\n", boundary))
bodyBuilder.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
bodyBuilder.WriteString("Content-Transfer-Encoding: 8bit\r\n\r\n")
bodyBuilder.WriteString("Hallo!\r\n\r\n")
bodyBuilder.WriteString("Es gibt eine neue Date-Reservierung über deinen Date-Planer:\r\n\r\n")
bodyBuilder.WriteString(fmt.Sprintf("👤 Name: %s\r\n", payload.Name))
bodyBuilder.WriteString(fmt.Sprintf("📅 Datum: %s (%s)\r\n", payload.Date, payload.DateType))
bodyBuilder.WriteString(fmt.Sprintf("💌 Aktivität(en): %s\r\n\r\n", cleanActivityName(payload.Activity)))
if len(payload.Activities) > 0 {
bodyBuilder.WriteString("Details der Aktivitäten:\r\n")
for _, act := range payload.Activities {
actName := cleanActivityName(act.Name)
if act.CustomDescription != "" {
cleanDesc := cleanActivityName(act.CustomDescription)
if !strings.Contains(actName, cleanDesc) {
actName = cleanDesc
}
}
bodyBuilder.WriteString(fmt.Sprintf(" - %s %s (%s)\r\n", act.Icon, actName, act.Type))
}
bodyBuilder.WriteString("\r\n")
}
bodyBuilder.WriteString("Im Anhang findest du einen Kalendereintrag (.ics), den du direkt auf deinem Smartphone/Kalender importieren kannst. 💕\r\n\r\n")
// iCalendar-Anhang (.ics)
icsData := generateICS(payload)
bodyBuilder.WriteString(fmt.Sprintf("--%s\r\n", boundary))
bodyBuilder.WriteString("Content-Type: text/calendar; charset=UTF-8; method=REQUEST; name=\"date-event.ics\"\r\n")
bodyBuilder.WriteString("Content-Disposition: attachment; filename=\"date-event.ics\"\r\n")
bodyBuilder.WriteString("Content-Transfer-Encoding: 8bit\r\n\r\n")
bodyBuilder.WriteString(icsData)
bodyBuilder.WriteString("\r\n")
// Abschluss-Boundary
bodyBuilder.WriteString(fmt.Sprintf("--%s--\r\n", boundary))
auth := smtp.PlainAuth("", smtpUser, smtpPass, smtpHost)
addr := fmt.Sprintf("%s:%s", smtpHost, smtpPort)
return smtp.SendMail(addr, auth, fromEmail, []string{toEmail}, bodyBuilder.Bytes())
}
func cleanActivityName(s string) string {
s = strings.TrimPrefix(s, "Etwas eigenes: ")
s = strings.TrimPrefix(s, "Etwas eigenes:")
s = strings.TrimPrefix(s, "Sonstiges: ")
s = strings.TrimPrefix(s, "Sonstiges:")
return strings.TrimSpace(s)
}
func generateICS(payload SurveyPayload) string {
parsedDate, err := time.Parse("2006-01-02", payload.Date)
dtStart := strings.ReplaceAll(payload.Date, "-", "")
dtEnd := dtStart
if err == nil {
dtStart = parsedDate.Format("20060102")
dtEnd = parsedDate.AddDate(0, 0, 1).Format("20060102")
}
dtStamp := time.Now().UTC().Format("20060102T150405Z")
uid := fmt.Sprintf("date-wizard-%s-%d@date-wizard", dtStart, time.Now().UnixNano())
activityText := cleanActivityName(payload.Activity)
for _, act := range payload.Activities {
if act.CustomDescription != "" {
cleanDesc := cleanActivityName(act.CustomDescription)
if !strings.Contains(activityText, cleanDesc) {
activityText = cleanDesc
}
}
}
summary := fmt.Sprintf("Date: %s", activityText)
description := fmt.Sprintf("Date mit %s\\nAktivität(en): %s", payload.Name, activityText)
var sb strings.Builder
sb.WriteString("BEGIN:VCALENDAR\r\n")
sb.WriteString("VERSION:2.0\r\n")
sb.WriteString("PRODID:-//Date-Wizard//DE\r\n")
sb.WriteString("CALSCALE:GREGORIAN\r\n")
sb.WriteString("METHOD:REQUEST\r\n")
sb.WriteString("BEGIN:VEVENT\r\n")
sb.WriteString(fmt.Sprintf("UID:%s\r\n", uid))
sb.WriteString(fmt.Sprintf("DTSTAMP:%s\r\n", dtStamp))
sb.WriteString(fmt.Sprintf("DTSTART;VALUE=DATE:%s\r\n", dtStart))
sb.WriteString(fmt.Sprintf("DTEND;VALUE=DATE:%s\r\n", dtEnd))
sb.WriteString(fmt.Sprintf("SUMMARY:%s\r\n", summary))
sb.WriteString(fmt.Sprintf("DESCRIPTION:%s\r\n", description))
sb.WriteString("STATUS:CONFIRMED\r\n")
sb.WriteString("END:VEVENT\r\n")
sb.WriteString("END:VCALENDAR\r\n")
return sb.String()
}
func loadEnv(filename string) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.SplitN(line, "=", 2)
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
val := strings.TrimSpace(parts[1])
val = strings.Trim(val, `"'`)
if os.Getenv(key) == "" {
os.Setenv(key, val)
}
}
}
}