papero/imaputils/connection.go

60 lines
1.1 KiB
Go
Raw Normal View History

2021-01-31 01:14:37 +01:00
package imaputils
import (
"crypto/tls"
"errors"
"fmt"
"os"
2021-04-01 18:09:04 +02:00
"git.sr.ht/~blallo/papero/config"
2021-01-31 01:14:37 +01:00
"github.com/emersion/go-imap/client"
)
var ErrUnencrypted = errors.New("the connection is unencrypted")
type IMAPConnection struct {
config *config.AccountData
client *client.Client
}
func NewConnection(conf *config.AccountData) *IMAPConnection {
conn := &IMAPConnection{}
conn.config = conf
return conn
}
func (c *IMAPConnection) Start(debug bool) error {
var err error
c.client, err = tryConnection(c.config.Host, c.config.Port)
if err != nil {
// TODO: allow unencrypted connections
return err
}
if debug {
c.client.SetDebug(os.Stderr)
}
return c.client.Login(c.config.Username, c.config.Password)
}
func (c *IMAPConnection) Close() {
c.client.Logout()
}
func tryConnection(host string, port int) (*client.Client, error) {
connString := fmt.Sprintf("%s:%d", host, port)
c, err := client.DialTLS(connString, nil)
if err == nil {
return c, err
}
c, err = client.Dial(connString)
if err != nil {
return c, err
}
err = c.StartTLS(&tls.Config{ServerName: host})
if err != nil {
err = ErrUnencrypted
}
return c, err
}