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
|
|
|
)
|
|
|
|
|
2020-05-20 17:32:53 +00:00
|
|
|
const (
|
|
|
|
inputDateLayout = "2006-01-02"
|
|
|
|
inputTimeLayout = "15:04"
|
|
|
|
)
|
|
|
|
|
2020-02-05 17:08:00 +00:00
|
|
|
func sanityCheckURL(u *url.URL) error {
|
|
|
|
req, err := http.NewRequest(http.MethodOptions, u.String(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
resp.Body.Close()
|
|
|
|
|
|
|
|
// Servers might require authentication to perform an OPTIONS request
|
|
|
|
if resp.StatusCode/100 != 2 && resp.StatusCode != http.StatusUnauthorized {
|
|
|
|
return fmt.Errorf("HTTP request failed: %v %v", resp.StatusCode, resp.Status)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-05-13 12:07:44 +00:00
|
|
|
func newPlugin(srv *alps.Server) (alps.Plugin, error) {
|
2020-02-05 17:08:00 +00:00
|
|
|
u, err := srv.Upstream("caldavs", "caldav+insecure", "https", "http+insecure")
|
2020-05-13 12:07:44 +00:00
|
|
|
if _, ok := err.(*alps.NoUpstreamError); ok {
|
2020-02-05 17:08:00 +00:00
|
|
|
return nil, nil
|
|
|
|
} else if err != nil {
|
|
|
|
return nil, fmt.Errorf("caldav: failed to parse upstream caldav server: %v", err)
|
|
|
|
}
|
|
|
|
switch u.Scheme {
|
|
|
|
case "caldavs":
|
|
|
|
u.Scheme = "https"
|
|
|
|
case "caldav+insecure", "http+insecure":
|
|
|
|
u.Scheme = "http"
|
|
|
|
}
|
|
|
|
if u.Scheme == "" {
|
2020-02-19 15:35:47 +00:00
|
|
|
// TODO
|
|
|
|
err := fmt.Errorf("discovery not yet implemented")
|
|
|
|
srv.Logger().Printf("caldav: failed to discover CalDAV server: %v", err)
|
|
|
|
return nil, nil
|
2020-02-05 17:08:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := sanityCheckURL(u); err != nil {
|
|
|
|
return nil, fmt.Errorf("caldav: failed to connect to CalDAV server %q: %v", u, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
srv.Logger().Printf("Configured upstream CalDAV server: %v", u)
|
|
|
|
|
2020-05-13 12:07:44 +00:00
|
|
|
p := alps.GoPlugin{Name: "caldav"}
|
2020-02-05 17:08:00 +00:00
|
|
|
|
|
|
|
registerRoutes(&p, u)
|
|
|
|
|
|
|
|
return p.Plugin(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
2020-05-13 12:07:44 +00:00
|
|
|
alps.RegisterPluginLoader(func(s *alps.Server) ([]alps.Plugin, error) {
|
2020-02-05 17:08:00 +00:00
|
|
|
p, err := newPlugin(s)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if p == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
2020-05-13 12:07:44 +00:00
|
|
|
return []alps.Plugin{p}, err
|
2020-02-05 17:08:00 +00:00
|
|
|
})
|
|
|
|
}
|