-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdispatcher.go
93 lines (79 loc) · 2.37 KB
/
dispatcher.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
package bart
import (
"errors"
"fmt"
"io/ioutil"
"regexp"
"github.com/hashicorp/go-multierror"
)
// Matches an underscore at the beginning of the string
var underscoreRegex = regexp.MustCompile(`^\_`)
// mergeMaps merges two maps. Key-value pairs from `secondary` are added to primary.
// If a key is present in both maps, the `primary`'s value is retained.
func mergeMaps(primary map[string]string, secondary map[string]string) {
for k, v := range secondary {
if _, present := primary[k]; !present {
primary[k] = v
}
}
}
/// Verify a context. Key 'subject' must be present.
func checkForSubject(context map[string]string) error {
if _, ok := context["subject"]; ok {
return nil
}
return errors.New("no 'subject' tag found. It must be contained in the context")
}
/// Verify a context. No keys beginning with an underscore are allowed.
func checkForNoUnderscores(context map[string]string) error {
for k := range context {
if underscoreRegex.MatchString(k) {
return errors.New("tags beginning with an underscore are not allowed")
}
}
return nil
}
func ProcessFile(templateFilename string, send bool, c *Config) error {
data, err := ioutil.ReadFile(templateFilename)
if err != nil {
return err
}
dataAsString := string(data)
ap := new(authPair)
if send {
fmt.Printf("Please enter your credentials for \"%s\"\n", c.EmailServer.Hostname)
ap.prompt()
}
var emails []Email
for recipient, localContext := range c.Recipients {
// Add global context to local context
mergeMaps(localContext, c.GlobalContext)
if err := checkForSubject(localContext); err != nil {
return err
}
if err := checkForNoUnderscores(localContext); err != nil {
return err
}
localContext["__subject_encoded__"] = EncodeRfc1342(localContext["subject"])
em, err := NewEmail().AddAuthor(&c.Author).AddRecipient(recipient).AddContent(dataAsString).Build(localContext)
if err != nil {
return err
}
emails = append(emails, em)
}
var result error
for _, em := range emails {
if send {
fmt.Printf("Will send to %v\n", em.GetRecipients())
if err := em.Send(&c.EmailServer, ap); err != nil {
result = multierror.Append(result, err)
}
} else {
fmt.Printf("Send flag not set: opening preview in \"%s\"\n", c.Author.Browser)
if err := em.OpenInBrowser(c.Author.Browser); err != nil {
result = multierror.Append(result, err)
}
}
}
return result
}