Files
landwelle/workflow.go
T

523 lines
23 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 (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"html/template"
"io"
"mime"
"net"
"net/mail"
"net/smtp"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type SMTPSettings struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
FromName string `json:"from_name"`
FromEmail string `json:"from_email"`
AdminEmail string `json:"admin_email"`
TLSMode string `json:"tls_mode"`
}
type FTPSettings struct {
Enabled bool `json:"enabled"`
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
TLS bool `json:"tls"`
Passive bool `json:"passive"`
TimeoutSeconds int `json:"timeout_seconds"`
}
type WishAutomationSettings struct {
Enabled bool `json:"enabled"`
Prompt string `json:"prompt"`
Model string `json:"model"`
Temperature float64 `json:"temperature"`
VoiceID string `json:"voice_id"`
BackgroundID string `json:"background_id"`
TTSVolume float64 `json:"tts_gain_db"`
BackgroundVolume float64 `json:"background_gain_db"`
RemoteDirectory string `json:"remote_directory"`
FileNamePattern string `json:"file_name_pattern"`
PublicBaseURL string `json:"public_base_url"`
AutoProcessOnApprove bool `json:"auto_process_on_approve"`
DeleteLocalAfterUpload bool `json:"delete_local_after_upload"`
DisableAIDisclosure bool `json:"disable_ai_disclosure"`
}
type EmailTemplate struct {
Key string `json:"key"`
Name string `json:"name"`
Subject string `json:"subject"`
HTMLBody string `json:"html_body"`
TextBody string `json:"text_body"`
Enabled bool `json:"enabled"`
}
type emailTemplateStore struct {
db *postgresStore
fallback map[string]EmailTemplate
}
func newEmailTemplateStore(db *postgresStore) *emailTemplateStore {
t := EmailTemplate{Key: "new_wish_admin", Name: "Neuer Musikwunsch – Administrator", Subject: "Neuer Musikwunsch von {{name}} aus {{place}}", Enabled: true,
HTMLBody: `<h1>Neuer Musikwunsch</h1><p>Bei Landwelle ist ein neuer Musikwunsch eingegangen.</p><p><strong>Name:</strong> {{name}}<br><strong>Ort:</strong> {{place}}<br><strong>Musikwunsch:</strong> {{artist}} – {{song}}</p><p><strong>Gruß:</strong><br>{{message}}</p><p><a href="{{admin_url}}">Musikwunsch prüfen und freigeben</a></p>`,
TextBody: `Neuer Musikwunsch von {{name}} aus {{place}}. Wunsch: {{artist}} – {{song}}. Gruß: {{message}}. Admin: {{admin_url}}`}
welcome := EmailTemplate{Key: "user_registered_welcome", Name: "Willkommen nach Registrierung", Subject: "Willkommen bei der Landwelle Community, {{display_name}}", Enabled: true,
HTMLBody: `<div style="text-align:center"><img src="{{logo_url}}" alt="Landwelle Radio" style="max-width:240px;height:auto;margin-bottom:20px"></div><h1>Willkommen bei Landwelle</h1><p>Hallo {{display_name}},</p><p>dein Benutzerkonto wurde erfolgreich angelegt.</p><p><strong>Benutzername:</strong> {{username}}<br><strong>E-Mail:</strong> {{email}}</p><p>Im Landwelle Forum kannst du dich über Musik, Sendungen, Niedersachsen, Technik und Rezepte austauschen.</p><p><a href="{{forum_url}}" style="display:inline-block;background:#74b82a;color:#fff;text-decoration:none;padding:12px 18px;border-radius:8px;font-weight:bold">Zum Landwelle Forum</a></p><p>Viele Grüße<br>dein Landwelle Team</p>`,
TextBody: `Hallo {{display_name}}, dein Landwelle-Benutzerkonto wurde erfolgreich angelegt. Benutzername: {{username}}. Forum: {{forum_url}}`}
eventConfirmation := EmailTemplate{Key: "event_submission_confirmation", Name: "Veranstaltungseinsendung – Bestätigung", Subject: "Danke für deine Veranstaltung: {{title}}", Enabled: true,
HTMLBody: `<h1>Danke für deine Einsendung</h1><p>Hallo {{contact_name}},</p><p>wir haben deine Veranstaltung <strong>{{title}}</strong> erhalten und schauen sie uns zeitnah an.</p><p><strong>Termin:</strong> {{date_time}}<br><strong>Ort:</strong> {{venue}}, {{postal_code}} {{city}}<br><strong>Kategorie:</strong> {{category}}</p><p>Nach der Prüfung kann der Termin im Landwelle-Veranstaltungskalender erscheinen.</p>`,
TextBody: `Hallo {{contact_name}}, wir haben deine Veranstaltung „{{title}}“ erhalten. Termin: {{date_time}}. Ort: {{venue}}, {{postal_code}} {{city}}.`}
eventAdmin := EmailTemplate{Key: "event_submission_admin", Name: "Neue Veranstaltung – Redaktion", Subject: "Neue Veranstaltung: {{title}} am {{date_time}}", Enabled: true,
HTMLBody: `<h1>Neue Veranstaltung</h1><p><strong>Titel:</strong> {{title}}<br><strong>Kategorie:</strong> {{category}}<br><strong>Termin:</strong> {{date_time}}<br><strong>Ort:</strong> {{venue}}, {{postal_code}} {{city}}<br><strong>Veranstalter:</strong> {{organizer}}</p><p><strong>Beschreibung:</strong><br>{{description}}</p><p><strong>Kontakt:</strong> {{contact_name}} · {{contact_email}} · {{contact_phone}}<br><strong>Webseite:</strong> {{website}}</p>`,
TextBody: `Neue Veranstaltung: {{title}}. Termin: {{date_time}}. Ort: {{venue}}, {{postal_code}} {{city}}. Kontakt: {{contact_name}}, {{contact_email}}.`}
advertisingConfirmation := EmailTemplate{Key: "advertising_inquiry_confirmation", Name: "Werbeanfrage – Bestätigung", Subject: "Deine Werbeanfrage bei Landwelle", Enabled: true, HTMLBody: `<h1>Danke für deine Werbeanfrage</h1><p>Hallo {{contact_name}},</p><p>wir haben die Anfrage für <strong>{{company}}</strong> erhalten.</p><p><strong>Ausgewählte Möglichkeiten:</strong><br>{{formats}}</p><p>Wir melden uns persönlich. Anfragenummer: {{inquiry_id}}</p>`, TextBody: `Hallo {{contact_name}}, wir haben die Werbeanfrage für {{company}} erhalten. Möglichkeiten: {{formats}}. Anfragenummer: {{inquiry_id}}.`}
advertisingAdmin := EmailTemplate{Key: "advertising_inquiry_admin", Name: "Werbeanfrage – Landwelle", Subject: "Neue Werbeanfrage: {{company}} · {{formats}}", Enabled: true, HTMLBody: `<h1>Neue Werbeanfrage</h1><p><strong>Nr.:</strong> {{inquiry_id}}<br><strong>Unternehmen:</strong> {{company}}<br><strong>Kontakt:</strong> {{contact_name}} · {{email}} · {{phone}}</p><p><strong>Formate:</strong> {{formats}}<br><strong>Region:</strong> {{region}}<br><strong>Budget:</strong> {{budget}}<br><strong>Start:</strong> {{campaign_start}}<br><strong>Laufzeit:</strong> {{duration}}</p><p>{{message}}</p>`, TextBody: `Neue Werbeanfrage {{inquiry_id}} von {{company}}. Kontakt: {{contact_name}}, {{email}}, {{phone}}. Formate: {{formats}}. Nachricht: {{message}}.`}
directoryConfirmation := EmailTemplate{Key: "directory_submission_confirmation", Name: "Branchenbuch – Bestätigung", Subject: "Dein Eintrag im Landwelle Branchenbuch", Enabled: true, HTMLBody: `<h1>Danke für deinen Eintrag</h1><p>Hallo {{contact_name}},</p><p>wir haben den kostenlosen Eintrag für <strong>{{name}}</strong> erhalten und prüfen ihn vor der Veröffentlichung.</p><p>Eintragsnummer: {{entry_id}}</p>`, TextBody: `Hallo {{contact_name}}, wir haben den Branchenbucheintrag für {{name}} erhalten. Eintragsnummer: {{entry_id}}.`}
directoryAdmin := EmailTemplate{Key: "directory_submission_admin", Name: "Branchenbuch – neuer Eintrag", Subject: "Neuer Branchenbucheintrag: {{name}} · {{category}}", Enabled: true, HTMLBody: `<h1>Neuer Branchenbucheintrag</h1><p><strong>Nr.:</strong> {{entry_id}}<br><strong>Name:</strong> {{name}}<br><strong>Kategorie:</strong> {{category}}<br><strong>Ort:</strong> {{postal_code}} {{city}}</p><p>{{description}}</p><p>Kontakt: {{contact_name}} · {{email}} · {{phone}}</p>`, TextBody: `Neuer Branchenbucheintrag {{entry_id}}: {{name}}, {{category}}, {{postal_code}} {{city}}. Kontakt: {{contact_name}}, {{email}}.`}
return &emailTemplateStore{db: db, fallback: map[string]EmailTemplate{t.Key: t, welcome.Key: welcome, eventConfirmation.Key: eventConfirmation, eventAdmin.Key: eventAdmin, advertisingConfirmation.Key: advertisingConfirmation, advertisingAdmin.Key: advertisingAdmin, directoryConfirmation.Key: directoryConfirmation, directoryAdmin.Key: directoryAdmin}}
}
func (s *emailTemplateStore) List() ([]EmailTemplate, error) {
if s.db != nil && s.db.Enabled() {
var out []EmailTemplate
q := `SELECT COALESCE(json_agg(json_build_object('key',template_key,'name',name,'subject',subject,'html_body',html_body,'text_body',text_body,'enabled',enabled) ORDER BY name),'[]'::json)::text FROM landwelle.email_templates;`
if err := s.db.queryJSON(context.Background(), q, &out); err != nil {
return nil, err
}
return out, nil
}
out := make([]EmailTemplate, 0, len(s.fallback))
for _, v := range s.fallback {
out = append(out, v)
}
return out, nil
}
func (s *emailTemplateStore) Get(key string) (EmailTemplate, bool) {
items, err := s.List()
if err != nil {
return EmailTemplate{}, false
}
for _, v := range items {
if v.Key == key {
return v, true
}
}
return EmailTemplate{}, false
}
func (s *emailTemplateStore) Save(t EmailTemplate) error {
t.Key = strings.TrimSpace(t.Key)
t.Name = strings.TrimSpace(t.Name)
if t.Key == "" || t.Name == "" || strings.TrimSpace(t.Subject) == "" {
return errors.New("Template-Key, Name und Betreff werden benötigt")
}
if s.db != nil && s.db.Enabled() {
q := `INSERT INTO landwelle.email_templates(template_key,name,subject,html_body,text_body,enabled,updated_at) VALUES (` + sqlText(t.Key) + `,` + sqlText(t.Name) + `,` + sqlText(t.Subject) + `,` + sqlText(t.HTMLBody) + `,` + sqlText(t.TextBody) + `,` + sqlBool(t.Enabled) + `,now()) ON CONFLICT(template_key) DO UPDATE SET name=excluded.name,subject=excluded.subject,html_body=excluded.html_body,text_body=excluded.text_body,enabled=excluded.enabled,updated_at=now();`
_, err := s.db.exec(context.Background(), q)
return err
}
s.fallback[t.Key] = t
return nil
}
type wishWorkflow struct {
settings *settingsStore
ai *aiService
wishes *wishStore
templates *emailTemplateStore
}
func newWishWorkflow(settings *settingsStore, ai *aiService, wishes *wishStore, templates *emailTemplateStore) *wishWorkflow {
return &wishWorkflow{settings: settings, ai: ai, wishes: wishes, templates: templates}
}
func (w *wishWorkflow) NotifyNewWish(ctx context.Context, wish ListenerWish) error {
cfg := w.settings.Get().SMTP
if !cfg.Enabled {
return nil
}
tpl, ok := w.templates.Get("new_wish_admin")
if !ok || !tpl.Enabled {
return nil
}
vars := map[string]string{"name": wish.Name, "place": wish.Place, "artist": wish.Artist, "song": wish.Song, "message": wish.Message, "admin_url": strings.TrimRight(w.settings.Get().WishAutomation.PublicBaseURL, "/") + "/admin/wishes"}
subject := renderTokens(tpl.Subject, vars)
html := renderTokens(tpl.HTMLBody, vars)
text := renderTokens(tpl.TextBody, vars)
return sendSMTP(ctx, cfg, cfg.AdminEmail, subject, html, text)
}
func wishDateToken(at time.Time) string {
return at.In(berlinLocation()).Format("2006-01-02")
}
func wishOutputFilenameAt(pattern string, wish ListenerWish, at time.Time) string {
pattern = strings.TrimSpace(pattern)
if pattern == "" {
pattern = "musikwunsch-{{id}}.mp3"
}
vars := map[string]string{
"id": wish.ID,
"name": wish.Name,
"place": wish.Place,
"artist": wish.Artist,
"song": wish.Song,
"datum": wishDateToken(at),
}
out := renderTokens(pattern, vars)
out = filepath.Base(strings.TrimSpace(out))
if out == "." || out == "" {
out = "musikwunsch-" + wish.ID + ".mp3"
}
// Keep the configured structure, but prevent path/control characters in FTP filenames.
replacer := strings.NewReplacer("/", "-", "\\\\", "-", "\\x00", "")
out = replacer.Replace(out)
if !strings.HasSuffix(strings.ToLower(out), ".mp3") {
out += ".mp3"
}
return out
}
func wishOutputFilename(pattern string, wish ListenerWish) string {
return wishOutputFilenameAt(pattern, wish, time.Now())
}
func (w *wishWorkflow) Process(ctx context.Context, wish ListenerWish) (ListenerWish, error) {
return w.process(ctx, wish, true)
}
func (w *wishWorkflow) ProcessManual(ctx context.Context, wish ListenerWish) (ListenerWish, error) {
return w.process(ctx, wish, false)
}
func (w *wishWorkflow) process(ctx context.Context, wish ListenerWish, requireEnabled bool) (ListenerWish, error) {
cfg := w.settings.Get()
wishCfg := cfg.WishAutomation
if requireEnabled && !wishCfg.Enabled {
return wish, errors.New("Musikwunsch-Automation ist deaktiviert")
}
if strings.TrimSpace(wishCfg.VoiceID) == "" {
return wish, errors.New("keine ElevenLabs Voice ID für Musikwünsche konfiguriert")
}
_ = w.wishes.SetProcessing(wish.ID, "processing", "")
source := fmt.Sprintf("Name: %s\nOrt: %s\nInterpret: %s\nTitel: %s\nGruß: %s", wish.Name, wish.Place, wish.Artist, wish.Song, wish.Message)
prompt := wishCfg.Prompt
if strings.TrimSpace(prompt) == "" {
prompt = "Formuliere eine natürliche, freundliche Radio-Anmoderation für diesen Musikwunsch. Verwende nur die gelieferten Fakten. Der Text soll 20 bis 35 Sekunden lang sein und direkt sprechbar sein."
}
generated, err := w.ai.GenerateText(ctx, prompt, source)
if err != nil {
_ = w.wishes.SetProcessing(wish.ID, "error", err.Error())
return wish, err
}
audio, err := w.ai.GenerateSpeechWithDisclosure(ctx, generated, wishCfg.VoiceID, !wishCfg.DisableAIDisclosure)
if err != nil {
_ = w.wishes.SetGenerated(wish.ID, generated, "", "", "error", err.Error())
return wish, err
}
local, ok := w.ai.AudioPath(audio)
if !ok {
return wish, errors.New("erzeugte MP3-Datei wurde nicht gefunden")
}
outputName := wishOutputFilename(wishCfg.FileNamePattern, wish)
remote := strings.TrimRight(wishCfg.RemoteDirectory, "/") + "/" + outputName
if cfg.FTP.Enabled {
if err := uploadFTP(ctx, cfg.FTP, local, remote); err != nil {
_ = w.wishes.SetGenerated(wish.ID, generated, audio, remote, "error", err.Error())
return wish, err
}
if wishCfg.DeleteLocalAfterUpload {
_ = os.Remove(local)
}
}
if err := w.wishes.SetGenerated(wish.ID, generated, audio, remote, "done", ""); err != nil {
return wish, err
}
updated, _ := w.wishes.Get(wish.ID)
return updated, nil
}
func renderTokens(s string, vars map[string]string) string {
for k, v := range vars {
s = strings.ReplaceAll(s, "{{"+k+"}}", v)
}
return s
}
type SMTPAttachment struct {
Filename string
ContentType string
Data []byte
}
func sendSMTPWithAttachments(ctx context.Context, c SMTPSettings, to, subject, htmlBody, textBody string, attachments []SMTPAttachment) error {
if len(attachments) == 0 {
return sendSMTP(ctx, c, to, subject, htmlBody, textBody)
}
if _, err := mail.ParseAddress(to); err != nil {
return fmt.Errorf("Empfängeradresse ungültig: %w", err)
}
from := mail.Address{Name: c.FromName, Address: c.FromEmail}
mixed := "landwelle-mixed-" + strconv.FormatInt(time.Now().UnixNano(), 36)
alt := "landwelle-alt-" + strconv.FormatInt(time.Now().UnixNano(), 36)
var b strings.Builder
b.WriteString("From: " + from.String() + "\r\nTo: " + to + "\r\nSubject: " + mime.QEncoding.Encode("utf-8", subject) + "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=" + mixed + "\r\n\r\n")
b.WriteString("--" + mixed + "\r\nContent-Type: multipart/alternative; boundary=" + alt + "\r\n\r\n")
b.WriteString("--" + alt + "\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n" + textBody + "\r\n")
b.WriteString("--" + alt + "\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<div style=\"font-family:Arial,sans-serif;background:#0b0e0c;color:#f5f7f4;padding:28px\"><div style=\"max-width:680px;margin:auto;background:#151a17;border:1px solid #72b62b;border-radius:18px;padding:28px\">" + htmlBody + "<p style=\"color:#8f9a92;margin-top:30px\">Landwelle Radio · Sound & Infos aus Niedersachsen</p></div></div>\r\n--" + alt + "--\r\n")
for _, a := range attachments {
name := mime.QEncoding.Encode("utf-8", filepath.Base(a.Filename))
ct := a.ContentType
if ct == "" {
ct = "application/octet-stream"
}
b.WriteString("--" + mixed + "\r\nContent-Type: " + ct + "; name=\"" + name + "\"\r\nContent-Disposition: attachment; filename=\"" + name + "\"\r\nContent-Transfer-Encoding: base64\r\n\r\n")
encoded := base64.StdEncoding.EncodeToString(a.Data)
for len(encoded) > 76 {
b.WriteString(encoded[:76] + "\r\n")
encoded = encoded[76:]
}
b.WriteString(encoded + "\r\n")
}
b.WriteString("--" + mixed + "--\r\n")
return sendSMTPMessage(ctx, c, to, b.String())
}
func sendSMTPMessage(ctx context.Context, c SMTPSettings, to, message string) error {
addr := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
dialer := net.Dialer{Timeout: 15 * time.Second}
var conn net.Conn
var err error
if c.TLSMode == "implicit" {
conn, err = tls.DialWithDialer(&dialer, "tcp", addr, &tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12})
} else {
conn, err = dialer.DialContext(ctx, "tcp", addr)
}
if err != nil {
return err
}
client, err := smtp.NewClient(conn, c.Host)
if err != nil {
return err
}
defer client.Close()
if c.TLSMode == "starttls" {
if err := client.StartTLS(&tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12}); err != nil {
return err
}
}
if c.Username != "" {
if err := client.Auth(smtp.PlainAuth("", c.Username, c.Password, c.Host)); err != nil {
return err
}
}
if err := client.Mail(c.FromEmail); err != nil {
return err
}
if err := client.Rcpt(to); err != nil {
return err
}
wc, err := client.Data()
if err != nil {
return err
}
if _, err = io.WriteString(wc, message); err != nil {
return err
}
if err = wc.Close(); err != nil {
return err
}
return client.Quit()
}
func sendSMTP(ctx context.Context, c SMTPSettings, to, subject, htmlBody, textBody string) error {
if _, err := mail.ParseAddress(to); err != nil {
return fmt.Errorf("Empfängeradresse ungültig: %w", err)
}
from := mail.Address{Name: c.FromName, Address: c.FromEmail}
boundary := "landwelle-" + strconv.FormatInt(time.Now().UnixNano(), 36)
var b strings.Builder
b.WriteString("From: " + from.String() + "\r\nTo: " + to + "\r\nSubject: " + mime.QEncoding.Encode("utf-8", subject) + "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/alternative; boundary=" + boundary + "\r\n\r\n")
b.WriteString("--" + boundary + "\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n" + textBody + "\r\n")
b.WriteString("--" + boundary + "\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<div style=\"font-family:Arial,sans-serif;background:#0b0e0c;color:#f5f7f4;padding:28px\"><div style=\"max-width:680px;margin:auto;background:#151a17;border:1px solid #72b62b;border-radius:18px;padding:28px\"><img src=\"" + strings.TrimRight(c.FromEmail, "/") + "\" alt=\"\" style=\"display:none\">" + htmlBody + "<p style=\"color:#8f9a92;margin-top:30px\">Landwelle Radio · Sound & Infos aus Niedersachsen</p></div></div>\r\n--" + boundary + "--\r\n")
addr := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
dialer := net.Dialer{Timeout: 15 * time.Second}
var conn net.Conn
var err error
if c.TLSMode == "implicit" {
conn, err = tls.DialWithDialer(&dialer, "tcp", addr, &tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12})
} else {
conn, err = dialer.DialContext(ctx, "tcp", addr)
}
if err != nil {
return err
}
client, err := smtp.NewClient(conn, c.Host)
if err != nil {
return err
}
defer client.Close()
if c.TLSMode == "starttls" {
if err := client.StartTLS(&tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12}); err != nil {
return err
}
}
if c.Username != "" {
if err := client.Auth(smtp.PlainAuth("", c.Username, c.Password, c.Host)); err != nil {
return err
}
}
if err := client.Mail(c.FromEmail); err != nil {
return err
}
if err := client.Rcpt(to); err != nil {
return err
}
wc, err := client.Data()
if err != nil {
return err
}
if _, err = io.WriteString(wc, b.String()); err != nil {
return err
}
if err = wc.Close(); err != nil {
return err
}
return client.Quit()
}
func uploadFTP(ctx context.Context, c FTPSettings, localPath, remotePath string) error {
timeout := time.Duration(c.TimeoutSeconds) * time.Second
if timeout <= 0 {
timeout = 20 * time.Second
}
d := net.Dialer{Timeout: timeout}
addr := net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return err
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(timeout))
r := bufio.NewReader(conn)
read := func() (int, string, error) {
line, err := r.ReadString('\n')
if err != nil {
return 0, "", err
}
if len(line) < 3 {
return 0, line, errors.New("ungültige FTP-Antwort")
}
code, _ := strconv.Atoi(line[:3])
return code, strings.TrimSpace(line), nil
}
cmd := func(s string, okCodes ...int) (string, error) {
if _, err := fmt.Fprintf(conn, "%s\r\n", s); err != nil {
return "", err
}
code, line, err := read()
if err != nil {
return line, err
}
for _, ok := range okCodes {
if code == ok {
return line, nil
}
}
return line, fmt.Errorf("FTP %s: %s", s, line)
}
if _, _, err = read(); err != nil {
return err
}
if c.TLS {
if _, err = cmd("AUTH TLS", 234); err != nil {
return err
}
tc := tls.Client(conn, &tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12})
if err = tc.HandshakeContext(ctx); err != nil {
return err
}
conn = tc
r = bufio.NewReader(conn)
_, _ = cmd("PBSZ 0", 200)
_, _ = cmd("PROT P", 200)
}
if _, err = cmd("USER "+c.Username, 230, 331); err != nil {
return err
}
if _, err = cmd("PASS "+c.Password, 230); err != nil {
return err
}
if _, err = cmd("TYPE I", 200); err != nil {
return err
}
dir, file := filepath.ToSlash(filepath.Dir(remotePath)), filepath.Base(remotePath)
if dir != "." && dir != "/" {
parts := strings.Split(strings.Trim(dir, "/"), "/")
for _, part := range parts {
_, _ = cmd("MKD "+part, 257, 550)
if _, err = cmd("CWD "+part, 250); err != nil {
return err
}
}
}
line, err := cmd("PASV", 227)
if err != nil {
return err
}
l := strings.Index(line, "(")
rr := strings.Index(line, ")")
if l < 0 || rr < l {
return errors.New("PASV-Antwort ungültig")
}
nums := strings.Split(line[l+1:rr], ",")
if len(nums) != 6 {
return errors.New("PASV-Adresse ungültig")
}
p1, _ := strconv.Atoi(nums[4])
p2, _ := strconv.Atoi(nums[5])
dataAddr := strings.Join(nums[:4], ".") + ":" + strconv.Itoa(p1*256+p2)
dataConn, err := d.DialContext(ctx, "tcp", dataAddr)
if err != nil {
return err
}
defer dataConn.Close()
if _, err = fmt.Fprintf(conn, "STOR %s\r\n", file); err != nil {
return err
}
if code, msg, err := read(); err != nil || !(code == 125 || code == 150) {
return fmt.Errorf("FTP STOR: %s %v", msg, err)
}
f, err := os.Open(localPath)
if err != nil {
return err
}
_, err = io.Copy(dataConn, f)
_ = f.Close()
_ = dataConn.Close()
if err != nil {
return err
}
code, msg, err := read()
if err != nil || !(code == 226 || code == 250) {
return fmt.Errorf("FTP Abschluss: %s %v", msg, err)
}
_, _ = cmd("QUIT", 221)
return nil
}
var _ = template.HTMLEscapeString