-
Notifications
You must be signed in to change notification settings - Fork 10
/
handlers.go
170 lines (146 loc) · 4.58 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/textproto"
"github.com/go-chi/chi"
"github.com/joeirimpan/listmonk-messenger/messenger"
"github.com/knadh/listmonk/models"
)
type postback struct {
Subject string `json:"subject"`
FromEmail string `json:"from_email"`
ContentType string `json:"content_type"`
Body string `json:"body"`
Recipients []recipient `json:"recipients"`
Campaign *campaign `json:"campaign"`
Attachments []attachment `json:"attachments"`
}
type campaign struct {
FromEmail string `json:"from_email"`
UUID string `json:"uuid"`
Name string `json:"name"`
Tags []string `json:"tags"`
}
type recipient struct {
UUID string `json:"uuid"`
Email string `json:"email"`
Name string `json:"name"`
Attribs models.SubscriberAttribs `json:"attribs"`
Status string `json:"status"`
}
type attachment struct {
Name string `json:"name"`
Header textproto.MIMEHeader `json:"header"`
Content []byte `json:"content"`
}
type httpResp struct {
Status string `json:"status"`
Message string `json:"message,omitempty"`
Data interface{} `json:"data,omitempty"`
}
// handlePostback picks the messager based on url params and pushes message using it.
func handlePostback(w http.ResponseWriter, r *http.Request) {
var (
app = r.Context().Value("app").(*App)
provider = chi.URLParam(r, "provider")
)
// Decode body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
app.logger.ErrorWith("error reading request body").Err("err", err).Write()
sendErrorResponse(w, "invalid body", http.StatusBadRequest, nil)
return
}
defer r.Body.Close()
data := &postback{}
if err := json.Unmarshal(body, &data); err != nil {
app.logger.ErrorWith("error unmarshalling request body").Err("err", err).Write()
sendErrorResponse(w, "invalid body", http.StatusBadRequest, nil)
return
}
// Get the provider.
p, ok := app.messengers[provider]
if !ok {
sendErrorResponse(w, "unknown provider", http.StatusBadRequest, nil)
return
}
if len(data.Recipients) > 1 {
sendErrorResponse(w, "invalid recipients", http.StatusBadRequest, nil)
return
}
rec := data.Recipients[0]
message := messenger.Message{
From: data.FromEmail,
Subject: data.Subject,
ContentType: data.ContentType,
Body: []byte(data.Body),
Subscriber: models.Subscriber{
UUID: rec.UUID,
Email: rec.Email,
Name: rec.Name,
Status: rec.Status,
Attribs: rec.Attribs,
},
}
if data.Campaign != nil {
message.Campaign = &models.Campaign{
FromEmail: data.Campaign.FromEmail,
UUID: data.Campaign.UUID,
Name: data.Campaign.Name,
Tags: data.Campaign.Tags,
}
}
if len(data.Attachments) > 0 {
files := make([]messenger.Attachment, 0, len(data.Attachments))
for _, f := range data.Attachments {
a := messenger.Attachment{
Name: f.Name,
Header: f.Header,
Content: make([]byte, len(f.Content)),
}
copy(a.Content, f.Content)
files = append(files, a)
}
message.Attachments = files
}
app.logger.DebugWith("sending message").String("provider", provider).String("message", fmt.Sprintf("%#+v", message)).Write()
// Send message.
if err := p.Push(message); err != nil {
app.logger.ErrorWith("error sending message").Err("err", err).Write()
sendErrorResponse(w, "error sending message", http.StatusInternalServerError, nil)
return
}
sendResponse(w, "OK")
return
}
// wrap is a middleware that wraps HTTP handlers and injects the "app" context.
func wrap(app *App, next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "app", app)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// sendResponse sends a JSON envelope to the HTTP response.
func sendResponse(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
out, err := json.Marshal(httpResp{Status: "success", Data: data})
if err != nil {
sendErrorResponse(w, "Internal Server Error", http.StatusInternalServerError, nil)
return
}
w.Write(out)
}
// sendErrorResponse sends a JSON error envelope to the HTTP response.
func sendErrorResponse(w http.ResponseWriter, message string, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
resp := httpResp{Status: "error",
Message: message,
Data: data}
out, _ := json.Marshal(resp)
w.Write(out)
}