Skip to content

Commit

Permalink
Chore: Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
axllent committed Oct 12, 2024
1 parent 073ddd3 commit a56fd1f
Show file tree
Hide file tree
Showing 17 changed files with 78 additions and 54 deletions.
1 change: 1 addition & 0 deletions internal/html2text/html2text.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,6 @@ func clean(text string) string {
}, text)

text = re.ReplaceAllString(text, " ")

return strings.TrimSpace(text)
}
25 changes: 15 additions & 10 deletions internal/pop3client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,17 @@ type Conn struct {

// Opt represents the client configuration.
type Opt struct {
// Host name
Host string `json:"host"`
Port int `json:"port"`

// Default is 3 seconds.
// Port number
Port int `json:"port"`
// DialTimeout default is 3 seconds.
DialTimeout time.Duration `json:"dial_timeout"`
Dialer Dialer `json:"-"`

TLSEnabled bool `json:"tls_enabled"`
// Dialer
Dialer Dialer `json:"-"`
// TLSEnabled sets whether SLS is enabled
TLSEnabled bool `json:"tls_enabled"`
// TLSSkipVerify skips TLS verification (ie: self-signed)
TLSSkipVerify bool `json:"tls_skip_verify"`
}

Expand All @@ -49,16 +52,15 @@ type Dialer interface {
// MessageID contains the ID and size of an individual message.
type MessageID struct {
// ID is the numerical index (non-unique) of the message.
ID int
ID int
// Size in bytes
Size int

// UID is only present if the response is to the UIDL command.
UID string
}

var (
lineBreak = []byte("\r\n")

lineBreak = []byte("\r\n")
respOK = []byte("+OK") // `+OK` without additional info
respOKInfo = []byte("+OK ") // `+OK <info>`
respErr = []byte("-ERR") // `-ERR` without additional info
Expand Down Expand Up @@ -126,6 +128,7 @@ func (c *Conn) Send(b string) error {
if _, err := c.w.WriteString(b + "\r\n"); err != nil {
return err
}

return c.w.Flush()
}

Expand Down Expand Up @@ -223,12 +226,14 @@ func (c *Conn) Auth(user, password string) error {
// User sends the username to the server.
func (c *Conn) User(s string) error {
_, err := c.Cmd("USER", false, s)

return err
}

// Pass sends the password to the server.
func (c *Conn) Pass(s string) error {
_, err := c.Cmd("PASS", false, s)

return err
}

Expand Down
37 changes: 21 additions & 16 deletions internal/spamassassin/spamc/spamc.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"strconv"
"strings"
"time"

"github.com/axllent/mailpit/internal/tools"
)

// ProtoVersion is the protocol version
Expand Down Expand Up @@ -81,6 +83,7 @@ func (c *Client) dial() (connection, error) {
}
return net.DialUnix("unix", nil, unixAddr)
}

panic("Client.net must be either \"tcp\" or \"unix\"")
}

Expand All @@ -107,33 +110,33 @@ func (c *Client) report(email []byte) ([]string, error) {
}

bw := bufio.NewWriter(conn)
_, err = bw.WriteString("REPORT SPAMC/" + ProtoVersion + "\r\n")
if err != nil {
if _, err := bw.WriteString("REPORT SPAMC/" + ProtoVersion + "\r\n"); err != nil {
return nil, err
}
_, err = bw.WriteString("Content-length: " + strconv.Itoa(len(email)) + "\r\n\r\n")
if err != nil {

if _, err := bw.WriteString("Content-length: " + strconv.Itoa(len(email)) + "\r\n\r\n"); err != nil {
return nil, err
}
_, err = bw.Write(email)
if err != nil {

if _, err := bw.Write(email); err != nil {
return nil, err
}
err = bw.Flush()
if err != nil {

if err := bw.Flush(); err != nil {
return nil, err
}

// Client is supposed to close its writing side of the connection
// after sending its request.
err = conn.CloseWrite()
if err != nil {
if err := conn.CloseWrite(); err != nil {
return nil, err
}

var (
lines []string
br = bufio.NewReader(conn)
)

for {
line, err := br.ReadString('\n')
if err == io.EOF {
Expand Down Expand Up @@ -171,11 +174,12 @@ func (c *Client) parseOutput(output []string) Result {
continue
}
}

// summary
if spamMainRe.MatchString(row) {
res := spamMainRe.FindStringSubmatch(row)
if len(res) == 4 {
if strings.ToLower(res[1]) == "true" || strings.ToLower(res[1]) == "yes" {
if tools.InArray(res[1], []string{"true", "yes"}) {
result.Spam = true
} else {
result.Spam = false
Expand All @@ -197,8 +201,8 @@ func (c *Client) parseOutput(output []string) Result {
reachedRules = true
continue
}

// details
// row = strings.Trim(row, " \t\r\n")
if reachedRules && spamDetailsRe.MatchString(row) {
res := spamDetailsRe.FindStringSubmatch(row)
if len(res) == 5 {
Expand All @@ -207,6 +211,7 @@ func (c *Client) parseOutput(output []string) Result {
}
}
}

return result
}

Expand All @@ -222,12 +227,11 @@ func (c *Client) Ping() error {
return err
}

_, err = io.WriteString(conn, fmt.Sprintf("PING SPAMC/%s\r\n\r\n", ProtoVersion))
if err != nil {
if _, err := io.WriteString(conn, fmt.Sprintf("PING SPAMC/%s\r\n\r\n", ProtoVersion)); err != nil {
return err
}
err = conn.CloseWrite()
if err != nil {

if err := conn.CloseWrite(); err != nil {
return err
}

Expand All @@ -241,5 +245,6 @@ func (c *Client) Ping() error {
return err
}
}

return nil
}
8 changes: 5 additions & 3 deletions internal/storage/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,12 @@ var (

// InitDB will initialise the database
func InitDB() error {
var (
dsn string
err error
)

p := config.Database
var dsn string

if p == "" {
// when no path is provided then we create a temporary file
Expand Down Expand Up @@ -74,8 +78,6 @@ func InitDB() error {
}
}

var err error

db, err = sql.Open(sqlDriver, dsn)
if err != nil {
return err
Expand Down
15 changes: 15 additions & 0 deletions internal/storage/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,21 @@ func GetAttachmentPart(id, partID string) (*enmime.Part, error) {
return nil, errors.New("attachment not found")
}

// AttachmentSummary returns a summary of the attachment without any binary data
func AttachmentSummary(a *enmime.Part) Attachment {
o := Attachment{}
o.PartID = a.PartID
o.FileName = a.FileName
if o.FileName == "" {
o.FileName = a.ContentID
}
o.ContentType = a.ContentType
o.ContentID = a.ContentID
o.Size = float64(len(a.Content))

return o
}

// LatestID returns the latest message ID
//
// If a query argument is set in the request the function will return the
Expand Down
11 changes: 8 additions & 3 deletions internal/storage/reindex.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,14 @@ func ReindexAll() {
logger.Log().Infof("reindexing %d messages", total)

type updateStruct struct {
ID string
// ID in database
ID string
// SearchText for searching
SearchText string
Snippet string
Metadata string
// Snippet for UI
Snippet string
// Metadata info
Metadata string
}

parser := enmime.NewParser(enmime.DisableCharacterDetection(true))
Expand Down Expand Up @@ -137,5 +141,6 @@ func chunkBy[T any](items []T, chunkSize int) (chunks [][]T) {
for chunkSize < len(items) {
items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])
}

return append(chunks, items)
}
1 change: 1 addition & 0 deletions internal/storage/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ func DeleteSearch(search, timezone string) error {
}

dbLastAction = time.Now()

addDeletedSize(int64(deleteSize))

logMessagesDeleted(total)
Expand Down
17 changes: 0 additions & 17 deletions internal/storage/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package storage
import (
"net/mail"
"time"

"github.com/jhillyerd/enmime"
)

// Message data excluding physical attachments
Expand Down Expand Up @@ -114,21 +112,6 @@ type DBMailSummary struct {
ReplyTo []*mail.Address
}

// AttachmentSummary returns a summary of the attachment without any binary data
func AttachmentSummary(a *enmime.Part) Attachment {
o := Attachment{}
o.PartID = a.PartID
o.FileName = a.FileName
if o.FileName == "" {
o.FileName = a.ContentID
}
o.ContentType = a.ContentType
o.ContentID = a.ContentID
o.Size = float64(len(a.Content))

return o
}

// ListUnsubscribe contains a summary of List-Unsubscribe & List-Unsubscribe-Post headers
// including validation of the link structure
type ListUnsubscribe struct {
Expand Down
7 changes: 5 additions & 2 deletions internal/storage/tagfilters.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ import (

// TagFilter struct
type TagFilter struct {
// Match is the user-defined match
Match string
SQL *sqlf.Stmt
Tags []string
// SQL represents the SQL equivalent of Match
SQL *sqlf.Stmt
// Tags to add on match
Tags []string
}

var tagFilters = []TagFilter{}
Expand Down
1 change: 1 addition & 0 deletions internal/storage/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ func addMessageTag(id, name string) (string, error) {
Set("ID", id).
Set("TagID", tagID).
ExecAndClose(context.TODO(), db)

return foundName.String, err
}

Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions internal/tools/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ func Plural(total int, singular, plural string) string {
if total == 1 {
return fmt.Sprintf("%d %s", total, singular)
}

return fmt.Sprintf("%d %s", total, plural)
}

// InArray tests if a string is within an array. It is not case sensitive.
func InArray(k string, arr []string) bool {
k = strings.ToLower(k)
for _, v := range arr {
if strings.ToLower(v) == k {
if strings.EqualFold(v, k) {
return true
}
}
Expand Down
1 change: 1 addition & 0 deletions internal/updater/unzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,6 @@ func Unzip(src string, dest string) ([]string, error) {
return filenames, err
}
}

return filenames, nil
}
1 change: 1 addition & 0 deletions internal/updater/updater.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var (
// AllowPrereleases defines whether pre-releases may be included
AllowPrereleases = false

// temporary directory
tempDir string
)

Expand Down
1 change: 0 additions & 1 deletion sendmail/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ var (
SMTPAddr = "localhost:1025"
// FromAddr email address
FromAddr string

// UseB - used to set from `-bs`
UseB bool
// UseS - used to set from `-bs`
Expand Down
1 change: 1 addition & 0 deletions server/pop3/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,6 @@ func getSafeArg(args []string, nr int) (string, error) {
if nr < len(args) {
return args[nr], nil
}

return "", errors.New("-ERR out of range")
}
1 change: 1 addition & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ func middleWareFunc(fn http.HandlerFunc) http.HandlerFunc {
fn(w, r)
return
}

w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
Expand Down

0 comments on commit a56fd1f

Please sign in to comment.