summaryrefslogtreecommitdiff
path: root/internal/imap/url.go
blob: 6ffea7283fd2992dbf80e8408ac950187df08cb5 (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
71
72
73
74
75
76
package imap

import (
	"net"
	"net/url"

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

// Our own convenience wrapper
type URL struct {
	*url.URL
	// url.URL has no port field and splits it everytime from Host
	port *string
}

const (
	imapsPort   = "993"
	imapPort    = "143"
	imapsSchema = "imaps"
	imapSchema  = "imap"
)

func (url *URL) Port() string {
	if url.port == nil {
		port := url.URL.Port()
		url.port = &port
	}
	return *url.port
}

func (url *URL) ForceTLS() bool {
	return url.Scheme == imapsSchema || url.Port() == imapsPort
}

func (url *URL) setDefaultScheme() {
	switch url.Scheme {
	case imapSchema, imapsSchema:
		return
	default:
		oldScheme := url.Scheme
		if url.Port() == imapsPort {
			url.Scheme = imapsSchema
		} else {
			url.Scheme = imapSchema
		}

		if oldScheme != "" {
			log.Warnf("Unknown scheme '%s', defaulting to '%s'", oldScheme, url.Scheme)
		}
	}
}

func (url *URL) setDefaultPort() {
	if url.Port() == "" {
		var port string
		if url.Scheme == imapsSchema {
			port = imapsPort
		} else {
			port = imapPort
		}
		url.port = &port
		url.Host = net.JoinHostPort(url.Host, port)
	}
}

func (url *URL) sanitizeUrl() {
	url.setDefaultScheme()
	url.setDefaultPort()
}

func NewUrl(url *url.URL) *URL {
	u := URL{URL: url}
	u.sanitizeUrl()
	return &u
}