2020-05-13 12:07:44 +00:00
|
|
|
package alpscaldav
|
2020-02-05 17:08:00 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
|
2020-05-13 12:07:44 +00:00
|
|
|
"git.sr.ht/~emersion/alps"
|
2020-02-05 17:08:00 +00:00
|
|
|
"github.com/emersion/go-webdav/caldav"
|
|
|
|
)
|
|
|
|
|
|
|
|
var errNoCalendar = fmt.Errorf("caldav: no calendar found")
|
|
|
|
|
|
|
|
type authRoundTripper struct {
|
|
|
|
upstream http.RoundTripper
|
2020-05-13 12:07:44 +00:00
|
|
|
session *alps.Session
|
2020-02-05 17:08:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (rt *authRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
rt.session.SetHTTPBasicAuth(req)
|
|
|
|
return rt.upstream.RoundTrip(req)
|
|
|
|
}
|
|
|
|
|
2020-05-13 12:07:44 +00:00
|
|
|
func newClient(u *url.URL, session *alps.Session) (*caldav.Client, error) {
|
2020-02-05 17:08:00 +00:00
|
|
|
rt := authRoundTripper{
|
|
|
|
upstream: http.DefaultTransport,
|
|
|
|
session: session,
|
|
|
|
}
|
|
|
|
c, err := caldav.NewClient(&http.Client{Transport: &rt}, u.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to create CalDAV client: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
2020-05-13 12:07:44 +00:00
|
|
|
func getCalendar(u *url.URL, session *alps.Session) (*caldav.Client, *caldav.Calendar, error) {
|
2020-02-05 17:08:00 +00:00
|
|
|
c, err := newClient(u, session)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
principal, err := c.FindCurrentUserPrincipal()
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, fmt.Errorf("failed to query CalDAV principal: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
calendarHomeSet, err := c.FindCalendarHomeSet(principal)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, fmt.Errorf("failed to query CalDAV calendar home set: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
calendars, err := c.FindCalendars(calendarHomeSet)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, fmt.Errorf("failed to find calendars: %v", err)
|
|
|
|
}
|
|
|
|
if len(calendars) == 0 {
|
|
|
|
return nil, nil, errNoCalendar
|
|
|
|
}
|
|
|
|
return c, &calendars[0], nil
|
|
|
|
}
|