refactor mappings getter

This commit is contained in:
Aine
2022-08-22 23:24:51 +03:00
parent 0decd4fad6
commit 848d6a7187
4 changed files with 14 additions and 18 deletions

View File

@@ -76,8 +76,8 @@ func (b *Bot) Start() error {
// Send email to matrix room
func (b *Bot) Send(ctx context.Context, from, to, subject, body string, files []*utils.File) error {
roomID, ok := b.rooms[utils.Mailbox(to)]
if !ok || roomID == "" {
roomID, ok := b.GetMapping(ctx, utils.Mailbox(to))
if !ok {
return errors.New("room not found")
}
@@ -117,15 +117,16 @@ func (b *Bot) Send(ctx context.Context, from, to, subject, body string, files []
}
// GetMappings returns mapping of mailbox = room
func (b *Bot) GetMappings(ctx context.Context) (map[string]id.RoomID, error) {
func (b *Bot) GetMapping(ctx context.Context, mailbox string) (id.RoomID, bool) {
if len(b.rooms) == 0 {
err := b.syncRooms(ctx)
if err != nil {
return nil, err
return "", false
}
}
return b.rooms, nil
roomID, ok := b.rooms[mailbox]
return roomID, ok
}
// Stop the bot

View File

@@ -70,7 +70,7 @@ func (b *Bot) setMailbox(ctx context.Context, evt *event.Event, mailbox string)
defer span.Finish()
mailbox = utils.Mailbox(mailbox)
existingID, ok := b.rooms[mailbox]
existingID, ok := b.GetMapping(ctx, mailbox)
if ok && existingID != "" && existingID != evt.RoomID {
content := format.RenderMarkdown("Mailbox "+mailbox+"@"+b.domain+" already taken", true, true)
content.MsgType = event.MsgNotice

View File

@@ -30,23 +30,18 @@ func (s *session) Mail(from string, opts smtp.MailOptions) error {
func (s *session) Rcpt(to string) error {
sentry.GetHubFromContext(s.ctx).Scope().SetTag("to", to)
mappings, err := s.client.GetMappings(s.ctx)
if err != nil {
s.log.Error("cannot get mappings: %v", err)
return err
}
s.log.Debug("mappings: %v", mappings)
_, ok := mappings[utils.Mailbox(to)]
if !ok {
s.log.Debug("mapping for %s not found", to)
return smtp.ErrAuthRequired
}
if utils.Hostname(to) != s.domain {
s.log.Debug("wrong domain of %s", to)
return smtp.ErrAuthRequired
}
_, ok := s.client.GetMapping(s.ctx, utils.Mailbox(to))
if !ok {
s.log.Debug("mapping for %s not found", to)
return smtp.ErrAuthRequired
}
s.to = to
s.log.Debug("mail to %s", to)
return nil

View File

@@ -9,6 +9,6 @@ import (
// Client interface to send emails
type Client interface {
GetMappings(context.Context) (map[string]id.RoomID, error)
GetMapping(context.Context, string) (id.RoomID, bool)
Send(ctx context.Context, from, mailbox, subject, body string, files []*utils.File) error
}