refactor email2content

This commit is contained in:
Aine
2022-09-06 18:39:35 +03:00
parent 1f896d1b26
commit 085cdf5dbf
4 changed files with 76 additions and 44 deletions

View File

@@ -8,6 +8,9 @@ import (
"time"
"github.com/emersion/go-msgauth/dkim"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
)
// MTA is mail transfer agent
@@ -30,6 +33,21 @@ type Email struct {
Files []*File
}
// ContentOptions used to convert email to matrix event content
type ContentOptions struct {
// On/Off
Sender bool
Subject bool
HTML bool
Threads bool
// Keys
MessageIDKey string
InReplyToKey string
SubjectKey string
FromKey string
}
// NewEmail constructs Email object
func NewEmail(messageID, inReplyTo, subject, from, to, text, html string, files []*File) *Email {
email := &Email{
@@ -55,6 +73,40 @@ func NewEmail(messageID, inReplyTo, subject, from, to, text, html string, files
return email
}
// Content converts email to matrix event content
func (e *Email) Content(threadID id.EventID, options *ContentOptions) *event.Content {
var text strings.Builder
if options.Sender {
text.WriteString("From: ")
text.WriteString(e.From)
text.WriteString("\n\n")
}
if options.Subject {
text.WriteString("# ")
text.WriteString(e.Subject)
text.WriteString("\n\n")
}
if e.HTML != "" && options.HTML {
text.WriteString(format.HTMLToMarkdown(e.HTML))
} else {
text.WriteString(e.Text)
}
parsed := format.RenderMarkdown(text.String(), true, true)
parsed.RelatesTo = RelatesTo(options.Threads, threadID)
content := event.Content{
Raw: map[string]interface{}{
options.MessageIDKey: e.MessageID,
options.InReplyToKey: e.InReplyTo,
options.SubjectKey: e.Subject,
options.FromKey: e.From,
},
Parsed: parsed,
}
return &content
}
// Compose converts email object to string and (optionally) signs it
func (e *Email) Compose(privkey string) string {
domain := strings.SplitN(e.From, "@", 2)[0]

View File

@@ -7,22 +7,22 @@ import (
)
// RelatesTo block of matrix event content
func RelatesTo(noThreads bool, parentID id.EventID) *event.RelatesTo {
func RelatesTo(threads bool, parentID id.EventID) *event.RelatesTo {
if parentID == "" {
return nil
}
if noThreads {
if threads {
return &event.RelatesTo{
InReplyTo: &event.InReplyTo{
EventID: parentID,
},
Type: event.RelThread,
EventID: parentID,
}
}
return &event.RelatesTo{
Type: event.RelThread,
EventID: parentID,
InReplyTo: &event.InReplyTo{
EventID: parentID,
},
}
}