~sbinet/episto

ref: c5da42852daa episto/episto.go -rw-r--r-- 4.3 KiB
c5da4285Sebastien Binet all: add vanity import clause 5 months ago
                                                                                
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Copyright ©2021 The episto Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package episto // import "sbinet.org/x/episto"

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/emersion/go-message/mail"
	"github.com/emersion/go-vcard"
	"github.com/emersion/go-webdav"
	"github.com/emersion/go-webdav/carddav"
	uuid "github.com/hashicorp/go-uuid"
	"gopkg.in/ini.v1"
)

type Account struct {
	Name string
	User string `ini:"user"`
	Cred string `ini:"cred-cmd"`
	URL  string `ini:"url"`

	cli *carddav.Client
}

func LoadAccounts() ([]Account, error) {
	dir, err := os.UserConfigDir()
	if err != nil {
		return nil, fmt.Errorf("could not find user config directory: %w", err)
	}

	f, err := ini.Load(filepath.Join(dir, "episto", "accounts.conf"))
	if err != nil {
		return nil, fmt.Errorf("could not find config file: %w", err)
	}

	var cfg []Account
	for _, name := range f.SectionStrings() {
		if name == "DEFAULT" {
			continue
		}
		sec := f.Section(name)
		var acc Account
		err := sec.MapTo(&acc)
		if err != nil {
			return nil, fmt.Errorf("could not read section %q: %w", name, err)
		}
		acc.Name = name
		acc.Cred, err = loadCreds(acc.Cred)
		if err != nil {
			return nil, fmt.Errorf("could not load credentials for section %q: %w", name, err)
		}
		cfg = append(cfg, acc)
	}

	return cfg, nil
}

func loadCreds(c string) (string, error) {
	cmd := exec.Command("sh", "-c", c)
	cmd.Stdin = os.Stdin
	out, err := cmd.Output()
	if err != nil {
		return "", fmt.Errorf("could not read password: %w", err)
	}
	return strings.TrimSpace(string(out)), nil
}

func (acc *Account) dial() error {
	cli, err := carddav.NewClient(
		webdav.HTTPClientWithBasicAuth(http.DefaultClient, acc.User, acc.Cred),
		acc.URL,
	)
	if err != nil {
		return fmt.Errorf("could not create CardDAV client: %w", err)
	}
	acc.cli = cli

	return nil
}

func (acc *Account) List(qry string) ([]mail.Address, error) {
	if acc.cli == nil {
		err := acc.dial()
		if err != nil {
			return nil, fmt.Errorf("could not dial CardDAV server: %w", err)
		}
	}

	principal, err := acc.cli.FindCurrentUserPrincipal()
	if err != nil {
		return nil, fmt.Errorf("could not find principal: %w", err)
	}

	homeSet, err := acc.cli.FindAddressBookHomeSet(principal)
	if err != nil {
		return nil, fmt.Errorf("failed to query CardDAV address book home set: %w", err)
	}

	addressBooks, err := acc.cli.FindAddressBooks(homeSet)
	if err != nil {
		return nil, fmt.Errorf("failed to query CardDAV address books: %w", err)
	}

	query := &carddav.AddressBookQuery{
		DataRequest: carddav.AddressDataRequest{
			Props: []string{
				vcard.FieldFormattedName,
				vcard.FieldEmail,
				vcard.FieldUID,
			},
		},
		PropFilters: []carddav.PropFilter{{
			Name:        vcard.FieldFormattedName,
			TextMatches: []carddav.TextMatch{{Text: ""}},
		}},
	}

	query.PropFilters = nil
	query.PropFilters = append(query.PropFilters, []carddav.PropFilter{
		{
			Name:        vcard.FieldFormattedName,
			TextMatches: []carddav.TextMatch{{Text: qry}},
		},
		{
			Name:        vcard.FieldEmail,
			TextMatches: []carddav.TextMatch{{Text: qry}},
		},
	}...)

	var results []mail.Address
	for _, addrBook := range addressBooks {
		addrs, err := acc.cli.QueryAddressBook(addrBook.Path, query)
		if err != nil {
			return nil, fmt.Errorf("failed to query CardDAV addresses: %w", err)
		}

		for _, addr := range addrs {
			name := addr.Card.Value(vcard.FieldFormattedName)
			cardEmails := addr.Card.Values(vcard.FieldEmail)
			for _, v := range cardEmails {
				results = append(results, mail.Address{
					Name:    name,
					Address: v,
				})
			}
		}
	}

	return results, nil
}

func (acc *Account) Push(card vcard.Card) (*carddav.AddressObject, error) {
	if acc.cli == nil {
		err := acc.dial()
		if err != nil {
			return nil, fmt.Errorf("could not dial CardDAV server: %w", err)
		}
	}

	var (
		id  string
		err error
	)
	switch field := card.Get(vcard.FieldUID); field {
	case nil:
		id, err = uuid.GenerateUUID()
		if err != nil {
			return nil, fmt.Errorf("could not generate UUID: %w", err)
		}
	default:
		id = field.Value
	}

	path := filepath.ToSlash(id + ".vcf")

	addrObj, err := acc.cli.PutAddressObject(path, card)
	if err != nil {
		return nil, fmt.Errorf("could not put address object to %q: %w", path, err)
	}

	return addrObj, nil
}