-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcompose.go
285 lines (256 loc) · 8.75 KB
/
compose.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package main
import (
"bytes"
"context"
"fmt"
htmltemplate "html/template"
"log/slog"
"net"
"net/url"
"regexp"
"sort"
"strings"
texttemplate "text/template"
"time"
"golang.org/x/mod/module"
"golang.org/x/mod/semver"
)
// sendCan returns whether it is likely the ratelimiter won't block on a subsequent call.
func sendCan() bool {
return ratelimitEmail.CanAdd(net.IPv6zero, time.Now(), 1)
}
// sendTake consumes from the rate limiter, blocking until sending is allowed.
func sendTake() {
for !ratelimitEmail.Add(net.IPv6zero, time.Now(), 1) {
slog.Info("slowing down outgoing messages")
time.Sleep(time.Second)
}
}
// send sends a message, either by composing itself and submitting over smtp, or
// through a mox webapi request.
// Caller must have checked the rate limiter.
func send(ctx context.Context, meta bool, user User, origMessageID, subject, text, html string) (sendID string, rerr error) {
if config.Mox != nil {
sendID, _, _, rerr = webapiSend(ctx, meta, user, origMessageID, subject, text, html)
return sendID, rerr
}
// Compose ourselves and submit over SMTP.
mailFrom, sendID, msg, eightbit, smtputf8, err := compose(meta, user, origMessageID, subject, text, html)
if err != nil {
return "", fmt.Errorf("composing message: %v", err)
}
conn, err := smtpGet(ctx)
if err != nil {
return sendID, fmt.Errorf("dial submission: %v", err)
}
defer func() {
if rerr == nil {
smtpPut(conn)
} else {
err := conn.Close()
logCheck(err, "closing submission connection")
}
}()
err = smtpSubmit(ctx, conn, meta, mailFrom, user.Email, msg, eightbit, smtputf8)
if err != nil {
return sendID, fmt.Errorf("submitting message to queue: %v", err)
}
return sendID, nil
}
func composeRender(templText *texttemplate.Template, templHTML *htmltemplate.Template, args any) (text, html string, rerr error) {
var textBuf, htmlBuf bytes.Buffer
if err := templText.Execute(&textBuf, args); err != nil {
return "", "", err
}
if err := templHTML.Execute(&htmlBuf, args); err != nil {
return "", "", err
}
var pageBuf bytes.Buffer
if err := templateHTML.Execute(&pageBuf, htmltemplate.HTML(htmlBuf.String())); err != nil {
return "", "", err
}
return textBuf.String(), pageBuf.String(), nil
}
func composeSignup(u User, fromWebsite bool) (subject, text, html string, err error) {
subject = config.SubjectPrefix + "Verify new account"
if !fromWebsite {
subject = "re: signup for " + config.ServiceName
}
args := struct {
BaseURL string
Subject string
User User
}{config.BaseURL, subject, u}
text, html, err = composeRender(templSignupText, templSignupHTML, args)
return subject, text, html, err
}
func composePasswordReset(u User, fromWebsite bool) (subject, text, html string, err error) {
subject = config.SubjectPrefix + "Password reset requested"
if !fromWebsite {
subject = "re: signup for " + config.ServiceName
}
args := struct {
BaseURL string
Subject string
User User
}{config.BaseURL, subject, u}
text, html, err = composeRender(templPasswordResetText, templPasswordResetHTML, args)
return subject, text, html, err
}
var pseudolikeRegexp = regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+-.*[0-9]{14}-[0-9a-f]{12}.*$`)
func guessURLs(module, version string) (repoURL, tagURL, docURL string) {
baseVersion, _, _ := strings.Cut(version, "+")
t := strings.Split(module, "/")
host := t[0]
if strings.Contains(host, "github") && len(t) >= 3 {
repoURL = "https://" + strings.Join(t[:3], "/")
tagURL = repoURL + "/releases/tag/" + url.QueryEscape(strings.Join(append(t[3:], baseVersion), "/"))
} else if strings.Contains(host, "gitlab") && len(t) >= 3 {
repoURL = "https://" + strings.Join(t[:3], "/")
tagURL = repoURL + "/-/tags/" + baseVersion
} else if strings.Contains(host, "codeberg") {
repoURL = "https://" + strings.Join(t[:3], "/")
tagURL = repoURL + "/releases/tag/" + baseVersion
} else if strings.Contains(host, "sr.ht") {
repoURL = "https://" + strings.Join(t[:3], "/")
tagURL = repoURL + "/refs/" + baseVersion
} else if host == "golang.org" && len(t) >= 3 && t[1] == "x" {
repoURL = "https://github.com/golang/" + t[2]
tagURL = repoURL + "/releases/tag/" + url.QueryEscape(strings.Join(append(t[3:], baseVersion), "/"))
}
// bitbucket doesn't seem to have a URL for just the tag (and the message associated), only trees or commits.
// e.g. v0.0.10-0.20240216191305-fd359d597383 and variants
if pseudolikeRegexp.MatchString(baseVersion) {
tagURL = ""
}
if host != "gopkg.in" {
docURL = "https://pkg.go.dev/" + module + "@" + version
}
return
}
func guessDiffURL(module, prevVersion, curVersion string) (diffURL string) {
t := strings.Split(module, "/")
if len(t) < 3 || strings.HasSuffix(prevVersion, "+incompatible") || strings.HasSuffix(curVersion, "+incompatible") {
return ""
}
// All recognized sites have paths of the form "$host/$dir1/$dir2", so everything
// after that should be part of the version.
host := t[0]
repoURL := "https://" + strings.Join(t[:3], "/")
oldVersion := strings.Join(append(t[3:], prevVersion), "/")
newVersion := strings.Join(append(t[3:], curVersion), "/")
if strings.Contains(host, "github") && len(t) >= 3 {
oldVersion = url.QueryEscape(oldVersion)
newVersion = url.QueryEscape(newVersion)
return repoURL + "/compare/" + oldVersion + "..." + newVersion
} else if strings.Contains(host, "gitlab") && len(t) >= 3 {
return repoURL + "/-/compare/" + oldVersion + "..." + newVersion
} else if strings.Contains(host, "codeberg") {
oldVersion = url.QueryEscape(oldVersion)
newVersion = url.QueryEscape(newVersion)
return repoURL + "/compare/" + oldVersion + "..." + newVersion
} else if host == "golang.org" && len(t) >= 3 && t[1] == "x" {
repoURL = "https://github.com/golang/" + t[2]
oldVersion = url.QueryEscape(oldVersion)
newVersion = url.QueryEscape(newVersion)
return repoURL + "/compare/" + oldVersion + "..." + newVersion
} else if strings.Contains(host, "bitbucket") && len(t) >= 3 {
oldVersion = url.PathEscape(oldVersion)
newVersion = url.PathEscape(newVersion)
// Versions in reverse, tags treated as "branch", and CR as separator...
return repoURL + "/branches/compare/" + newVersion + "%0D" + oldVersion
}
return ""
}
func composeModuleUpdates(u User, loginToken string, updates []ModuleUpdate, prevModuleVersions map[string]string) (subject, text, html string, err error) {
type version struct {
Version string
DocURL string
TagURL string
}
type moduleVersion struct {
Module string
RepoURL string
Versions []version
DiffURL string
DiffVersion string
}
modVersions := map[string]moduleVersion{}
for _, up := range updates {
mv, ok := modVersions[up.Module]
if !ok {
mv = moduleVersion{up.Module, "", nil, "", ""}
}
repoURL, tagURL, docURL := guessURLs(up.Module, up.Version)
mv.RepoURL = repoURL
mv.Versions = append(mv.Versions, version{up.Version, docURL, tagURL})
modVersions[up.Module] = mv
}
var l []moduleVersion
for _, mv := range modVersions {
sort.Slice(mv.Versions, func(i, j int) bool {
return semver.Compare(mv.Versions[i].Version, mv.Versions[j].Version) < 0
})
if curVersion := mv.Versions[len(mv.Versions)-1]; !module.IsPseudoVersion(curVersion.Version) {
if prevVersion, ok := prevModuleVersions[mv.Module]; ok {
mv.DiffVersion = prevVersion
mv.DiffURL = guessDiffURL(mv.Module, prevVersion, curVersion.Version)
}
}
l = append(l, mv)
}
sort.Slice(l, func(i, j int) bool {
return l[i].Module < l[j].Module
})
smod := "s"
if len(l) == 1 {
smod = ""
}
sup := "s"
if len(updates) == 1 {
sup = ""
}
subject = fmt.Sprintf("%s%d module%s with %d new version%s", config.SubjectPrefix, len(l), smod, len(updates), sup)
var truncated bool
if len(l) > 1100 {
l = l[:1000]
}
var args = struct {
BaseURL string
Subject string
User User
UpdatesTruncated bool
ModuleVersions []moduleVersion
LoginToken string
}{config.BaseURL, subject, u, truncated, l, loginToken}
text, html, err = composeRender(templModuleUpdatesText, templModuleUpdatesHTML, args)
return subject, text, html, err
}
func composeSample(kind string, user User, loginToken string) (subject, text, html string, err error) {
switch kind {
case "signup":
return composeSignup(user, true)
case "passwordreset":
return composePasswordReset(user, true)
case "moduleupdates":
updates := []ModuleUpdate{
{
Module: "github.com/mjl-/gopherwatch",
Version: "v0.0.1",
},
{
Module: "github.com/mjl-/gopherwatch",
Version: "v0.0.2",
},
{
Module: "github.com/mjl-/mox",
Version: "v0.0.9",
},
}
prevModuleVersions := map[string]string{
"github.com/mjl-/mox": "v0.0.8",
}
return composeModuleUpdates(user, loginToken, updates, prevModuleVersions)
}
return "", "", "", fmt.Errorf("unknown message kind %q", kind)
}