aboutsummaryrefslogtreecommitdiff
path: root/internal/imap/client.go
blob: c916a642dc3d4b1ef31b0d31fee207a69beebdfb (plain)
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
package imap

import (
	"sync/atomic"

	uidplus "github.com/emersion/go-imap-uidplus"
	imapClient "github.com/emersion/go-imap/client"

	"github.com/Necoro/feed2imap-go/pkg/log"
)

const numberConns = 5

type connConf struct {
	host      string
	delimiter string
	toplevel  Folder
}

type Client struct {
	connConf
	mailboxes   *mailboxes
	commander   *commander
	connections [numberConns]*connection
	idxCounter  int32
	connChannel chan *connection
}

func (cl *Client) Disconnect() {
	if cl != nil {
		cl.stopCommander()
		close(cl.connChannel)

		connected := false
		for _, conn := range cl.connections {
			connected = conn.disconnect() || connected
		}

		if connected {
			log.Print("Disconnected from ", cl.host)
		}
	}
}

func (cl *Client) createConnection(c *imapClient.Client) *connection {
	nextIndex := int(atomic.AddInt32(&cl.idxCounter, 1)) - 1

	if nextIndex >= len(cl.connections) {
		panic("Too many connections")
	}

	client := &client{c, uidplus.NewClient(c)}

	conn := &connection{
		connConf:  &cl.connConf,
		mailboxes: cl.mailboxes,
		c:         client,
	}

	cl.connections[nextIndex] = conn

	return conn
}

func NewClient() *Client {
	return &Client{
		mailboxes:   NewMailboxes(),
		connChannel: make(chan *connection, 0),
	}
}