aboutsummaryrefslogtreecommitdiff
path: root/plugins/carddav/routes.go
blob: ccc053c05082ebf31bea6c49774a23c1de8205f4 (plain) (blame)
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package koushincarddav

import (
	"fmt"
	"net/http"
	"net/url"
	"path"
	"strings"

	"git.sr.ht/~emersion/koushin"
	"github.com/emersion/go-vcard"
	"github.com/emersion/go-webdav/carddav"
	"github.com/google/uuid"
	"github.com/labstack/echo/v4"
)

type AddressBookRenderData struct {
	koushin.BaseRenderData
	AddressBook    *carddav.AddressBook
	AddressObjects []AddressObject
	Query          string
}

type AddressObjectRenderData struct {
	koushin.BaseRenderData
	AddressObject AddressObject
}

type UpdateAddressObjectRenderData struct {
	koushin.BaseRenderData
	AddressObject *carddav.AddressObject // nil if creating a new contact
	Card          vcard.Card
}

func parseObjectPath(s string) (string, error) {
	p, err := url.PathUnescape(s)
	if err != nil {
		err = fmt.Errorf("failed to parse path: %v", err)
		return "", echo.NewHTTPError(http.StatusBadRequest, err)
	}
	return string(p), nil
}

func registerRoutes(p *plugin) {
	p.GET("/contacts", func(ctx *koushin.Context) error {
		queryText := ctx.QueryParam("query")

		c, addressBook, err := p.clientWithAddressBook(ctx.Session)
		if err != nil {
			return err
		}

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

		if queryText != "" {
			query.PropFilters = []carddav.PropFilter{
				{
					Name:        vcard.FieldFormattedName,
					TextMatches: []carddav.TextMatch{{Text: queryText}},
				},
				{
					Name:        vcard.FieldEmail,
					TextMatches: []carddav.TextMatch{{Text: queryText}},
				},
			}
		}

		aos, err := c.QueryAddressBook(addressBook.Path, &query)
		if err != nil {
			return fmt.Errorf("failed to query CardDAV addresses: %v", err)
		}

		return ctx.Render(http.StatusOK, "address-book.html", &AddressBookRenderData{
			BaseRenderData: *koushin.NewBaseRenderData(ctx),
			AddressBook:    addressBook,
			AddressObjects: newAddressObjectList(aos),
			Query:          queryText,
		})
	})

	p.GET("/contacts/:path", func(ctx *koushin.Context) error {
		path, err := parseObjectPath(ctx.Param("path"))
		if err != nil {
			return err
		}

		c, err := p.client(ctx.Session)
		if err != nil {
			return err
		}

		multiGet := carddav.AddressBookMultiGet{
			DataRequest: carddav.AddressDataRequest{
				Props: []string{
					vcard.FieldFormattedName,
					vcard.FieldEmail,
					vcard.FieldUID,
				},
			},
		}
		aos, err := c.MultiGetAddressBook(path, &multiGet)
		if err != nil {
			return fmt.Errorf("failed to query CardDAV address: %v", err)
		}
		if len(aos) != 1 {
			return fmt.Errorf("expected exactly one address object with path %q, got %v", path, len(aos))
		}
		ao := &aos[0]

		return ctx.Render(http.StatusOK, "address-object.html", &AddressObjectRenderData{
			BaseRenderData: *koushin.NewBaseRenderData(ctx),
			AddressObject:  AddressObject{ao},
		})
	})

	updateContact := func(ctx *koushin.Context) error {
		addressObjectPath, err := parseObjectPath(ctx.Param("path"))
		if err != nil {
			return err
		}

		c, addressBook, err := p.clientWithAddressBook(ctx.Session)
		if err != nil {
			return err
		}

		var ao *carddav.AddressObject
		var card vcard.Card
		if addressObjectPath != "" {
			ao, err := c.GetAddressObject(addressObjectPath)
			if err != nil {
				return fmt.Errorf("failed to query CardDAV address: %v", err)
			}
			card = ao.Card
		} else {
			card = make(vcard.Card)
		}

		if ctx.Request().Method == "POST" {
			fn := ctx.FormValue("fn")
			emails := strings.Split(ctx.FormValue("emails"), ",")

			if _, ok := card[vcard.FieldVersion]; !ok {
				// Some CardDAV servers (e.g. Google) don't support vCard 4.0
				var version = "4.0"
				if !addressBook.SupportsAddressData(vcard.MIMEType, version) {
					version = "3.0"
				}
				if !addressBook.SupportsAddressData(vcard.MIMEType, version) {
					return fmt.Errorf("upstream CardDAV server doesn't support vCard %v", version)
				}
				card.SetValue(vcard.FieldVersion, version)
			}

			if field := card.Preferred(vcard.FieldFormattedName); field != nil {
				field.Value = fn
			} else {
				card.Add(vcard.FieldFormattedName, &vcard.Field{Value: fn})
			}

			// TODO: Google wants a "N" field, fails with a 400 otherwise

			// TODO: params are lost here
			var emailFields []*vcard.Field
			for _, email := range emails {
				emailFields = append(emailFields, &vcard.Field{
					Value: strings.TrimSpace(email),
				})
			}
			card[vcard.FieldEmail] = emailFields

			id := uuid.New()
			if _, ok := card[vcard.FieldUID]; !ok {
				card.SetValue(vcard.FieldUID, id.URN())
			}

			var p string
			if ao != nil {
				p = ao.Path
			} else {
				p = path.Join(addressBook.Path, id.String()+".vcf")
			}
			ao, err = c.PutAddressObject(p, card)
			if err != nil {
				return fmt.Errorf("failed to put address object: %v", err)
			}

			return ctx.Redirect(http.StatusFound, AddressObject{ao}.URL())
		}

		return ctx.Render(http.StatusOK, "update-address-object.html", &UpdateAddressObjectRenderData{
			BaseRenderData: *koushin.NewBaseRenderData(ctx),
			AddressObject:  ao,
			Card:           card,
		})
	}

	p.GET("/contacts/create", updateContact)
	p.POST("/contacts/create", updateContact)

	p.GET("/contacts/:path/edit", updateContact)
	p.POST("/contacts/:path/edit", updateContact)
}