-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInMemoryBackend.go
110 lines (92 loc) · 2.17 KB
/
InMemoryBackend.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
package gospam
import (
"strings"
"sync"
"time"
"github.com/emersion/go-smtp"
)
type InMemoryBackend struct {
currentID int
emails []*EMail
MaxStoredMessage int
mailMutex sync.Mutex
AcceptedDomains []string
AcceptSubdomains bool
}
func (backend *InMemoryBackend) NewSession(c *smtp.Conn) (smtp.Session, error) {
return &Session{
remote: c.Conn().RemoteAddr(),
backend: backend,
}, nil
}
func (backend *InMemoryBackend) AnonymousLogin(c *smtp.Conn) (smtp.Session, error) {
return &Session{
remote: c.Conn().RemoteAddr(),
backend: backend,
}, nil
}
func (backend *InMemoryBackend) Login(_ *smtp.Conn, username, password string) (smtp.Session, error) {
return nil, smtp.ErrAuthUnsupported
}
func (b *InMemoryBackend) SaveEmail(email *EMail) {
b.mailMutex.Lock()
if b.emails == nil {
b.emails = make([]*EMail, 0)
}
if len(b.emails) >= b.MaxStoredMessage {
b.emails = b.emails[1:]
}
email.ID = b.currentID
b.currentID++
b.emails = append(b.emails, email)
b.mailMutex.Unlock()
}
func (b *InMemoryBackend) GetEmailsByAlias(alias string) []*EMail {
emails := make([]*EMail, 0)
for _, e := range b.emails {
for _, recipient := range e.To {
if strings.HasPrefix(recipient, alias+"@") {
emails = append(emails, e)
break
}
}
}
return emails
}
func (b *InMemoryBackend) GetEmailById(id int) *EMail {
for _, e := range b.emails {
if e.ID == id {
return e
}
}
return nil
}
func (b *InMemoryBackend) Cleanup(deadline time.Time) {
unexpiredMails := make([]*EMail, 0)
for _, e := range b.emails {
if !e.Time.Before(deadline) {
unexpiredMails = append(unexpiredMails, e)
}
}
b.mailMutex.Lock()
b.emails = unexpiredMails
b.mailMutex.Unlock()
}
func (b *InMemoryBackend) IsAcceptedDomain(email string) bool {
if len(b.AcceptedDomains) == 0 {
return true
}
emailParts := strings.Split(email, "@")
domain := emailParts[len(emailParts)-1]
for _, d := range b.AcceptedDomains {
if strings.EqualFold(d, domain) {
return true
} else if b.AcceptSubdomains && strings.HasSuffix(domain, "."+d) {
return true
}
}
return false
}
func (b *InMemoryBackend) GetProcessedEmails() int {
return b.currentID
}