aboutsummaryrefslogtreecommitdiff
path: root/internal/imap/imap.go
blob: 1179f3d2cbe7aa8c915a22ac93b642c3c8c8c7bb (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
package imap

import (
	"fmt"

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

func Connect(url config.Url, numConnections int) (*Client, error) {
	var err error

	client := newClient()
	client.host = url.Host
	defer func() {
		if err != nil {
			client.Disconnect()
		}
	}()
	client.startCommander()

	var conn *connection // the main connection
	if conn, err = client.connect(url); err != nil {
		return nil, err
	}

	delim, err := conn.fetchDelimiter()
	if err != nil {
		return nil, fmt.Errorf("fetching delimiter: %w", err)
	}
	client.delimiter = delim

	client.toplevel = client.folderName(url.RootPath())

	log.Printf("Determined '%s' as toplevel, with '%s' as delimiter", client.toplevel, client.delimiter)

	if !client.toplevel.IsBlank() {
		if err = conn.ensureFolder(client.toplevel); err != nil {
			return nil, err
		}
	}

	// the other connections
	for i := 1; i < numConnections; i++ {
		go func(id int) {
			if _, err := client.connect(url); err != nil { // explicitly new var 'err', b/c these are now harmless
				log.Warnf("connecting #%d: %s", id, err)
			}
		}(i)
	}

	return client, nil
}