477 lines
13 KiB
Go
477 lines
13 KiB
Go
package server
|
||
|
||
import (
|
||
"context"
|
||
"encoding/base64"
|
||
"encoding/json"
|
||
"errors"
|
||
"net/http"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
"pageswiki/internal/calendar"
|
||
)
|
||
|
||
const calendarAPI = "/_/api/v1/extension/organizer.calendar/"
|
||
const calendarDAV = "/_/api/v1/caldav/"
|
||
const davCredentialsAPI = "/_/api/v1/caldav-credentials"
|
||
|
||
func calendarRoute(path string) bool {
|
||
return path == "/v/plan" || strings.HasPrefix(path, "/v/plan/") || strings.HasPrefix(path, "/v/event/") || path == "/v/calendar" || strings.HasPrefix(path, calendarAPI) || strings.HasPrefix(path, calendarDAV) || path == strings.TrimSuffix(calendarDAV, "/") || path == davCredentialsAPI || strings.HasPrefix(path, davCredentialsAPI+"/")
|
||
}
|
||
func (s *Server) registerCalendarRoutes() {
|
||
for _, p := range []string{"/v/plan", "/v/plan/", "/v/event/", "/v/calendar"} {
|
||
s.mux.HandleFunc(p, s.handleCalendarPage)
|
||
}
|
||
s.mux.HandleFunc(calendarAPI, s.handleCalendarAPI)
|
||
s.mux.HandleFunc(calendarDAV, s.handleCalendarDAV)
|
||
s.mux.HandleFunc(strings.TrimSuffix(calendarDAV, "/"), s.handleCalendarDAV)
|
||
s.mux.HandleFunc(davCredentialsAPI, s.handleDAVCredentials)
|
||
s.mux.HandleFunc(davCredentialsAPI+"/", s.handleDAVCredentials)
|
||
}
|
||
func (s *Server) calendars() (*calendar.Repository, error) {
|
||
s.calendarOnce.Do(func() {
|
||
if s.store.DocumentRoot == "" {
|
||
s.calendarErr = errors.New("calendar storage unavailable")
|
||
return
|
||
}
|
||
s.calendarRepo, s.calendarErr = s.store.NewCalendarRepository(context.Background())
|
||
})
|
||
return s.calendarRepo, s.calendarErr
|
||
}
|
||
func (s *Server) calendarActor(r *http.Request) (string, bool) {
|
||
p, e := s.store.PrincipalForSession(s.domainUUIDForRequest(r), s.authTokenFromRequest(r))
|
||
if e != nil {
|
||
return "", false
|
||
}
|
||
return p.UUID, p.State == "active"
|
||
}
|
||
func (s *Server) calendarReady(w http.ResponseWriter, r *http.Request) (*calendar.Repository, bool) {
|
||
if !s.systemExtensionEnabled(s.domainUUIDForRequest(r), "organizer.calendar") {
|
||
http.NotFound(w, r)
|
||
return nil, false
|
||
}
|
||
repo, e := s.calendars()
|
||
if e != nil {
|
||
http.Error(w, "calendar storage unavailable", 503)
|
||
return nil, false
|
||
}
|
||
return repo, true
|
||
}
|
||
func calendarError(w http.ResponseWriter, e error) {
|
||
status := 500
|
||
message := "calendar operation failed"
|
||
switch {
|
||
case errors.Is(e, calendar.ErrMissing):
|
||
status = 404
|
||
message = "calendar or event not found"
|
||
case errors.Is(e, calendar.ErrForbidden):
|
||
status = 403
|
||
message = e.Error()
|
||
case errors.Is(e, calendar.ErrConflict):
|
||
status = 412
|
||
message = "The calendar changed. Reload before saving."
|
||
case errors.Is(e, calendar.ErrPreconditionRequired):
|
||
status = 428
|
||
message = "If-Match required"
|
||
case errors.Is(e, calendar.ErrNameTaken):
|
||
status = 409
|
||
message = e.Error()
|
||
case errors.Is(e, calendar.ErrInvalid):
|
||
status = 422
|
||
message = e.Error()
|
||
case errors.Is(e, calendar.ErrLimit):
|
||
status = 507
|
||
message = e.Error()
|
||
}
|
||
writeEventJSON(w, status, map[string]string{"error": message})
|
||
}
|
||
func calendarHref(id, uid string) string {
|
||
return calendarDAV + id + "/" + base64.RawURLEncoding.EncodeToString([]byte(uid)) + ".ics"
|
||
}
|
||
func calendarUID(filename string) (string, error) {
|
||
if !strings.HasSuffix(filename, ".ics") {
|
||
return "", calendar.ErrMissing
|
||
}
|
||
b, e := base64.RawURLEncoding.DecodeString(strings.TrimSuffix(filename, ".ics"))
|
||
if e != nil || len(b) == 0 || len(b) > 512 {
|
||
return "", calendar.ErrMissing
|
||
}
|
||
return string(b), nil
|
||
}
|
||
func decodeCalendarJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
|
||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, calendar.MaxResource))
|
||
d.DisallowUnknownFields()
|
||
if e := d.Decode(dst); e != nil {
|
||
http.Error(w, "invalid JSON", 400)
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
func (s *Server) handleCalendarAPI(w http.ResponseWriter, r *http.Request) {
|
||
repo, ok := s.calendarReady(w, r)
|
||
if !ok {
|
||
return
|
||
}
|
||
domain := s.domainUUIDForRequest(r)
|
||
actor, active := s.calendarActor(r)
|
||
path := strings.Trim(strings.TrimPrefix(r.URL.Path, calendarAPI), "/")
|
||
parts := strings.Split(path, "/")
|
||
if path == "upcoming" {
|
||
s.handleCalendarUpcoming(w, r, repo, domain, actor)
|
||
return
|
||
}
|
||
if len(parts) == 3 && parts[0] == "calendars" && parts[2] == "source" {
|
||
s.handleCalendarSource(w, r, repo, domain, parts[1], actor, active)
|
||
return
|
||
}
|
||
if path == "preferences" {
|
||
if actor == "" {
|
||
calendarError(w, calendar.ErrForbidden)
|
||
return
|
||
}
|
||
if r.Method != "PUT" {
|
||
w.WriteHeader(405)
|
||
return
|
||
}
|
||
var body struct {
|
||
Calendars []string `json:"calendars"`
|
||
}
|
||
if !decodeCalendarJSON(w, r, &body) {
|
||
return
|
||
}
|
||
if err := repo.SaveDefaults(r.Context(), domain, actor, body.Calendars); err != nil {
|
||
calendarError(w, err)
|
||
return
|
||
}
|
||
writeEventJSON(w, 200, map[string]any{"calendars": body.Calendars})
|
||
return
|
||
}
|
||
if path == "event" && r.Method == "GET" {
|
||
cs, e := repo.List(domain, actor)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
if len(cs) > 256 {
|
||
calendarError(w, calendar.ErrLimit)
|
||
return
|
||
}
|
||
var found *calendar.Event
|
||
id := ""
|
||
for _, c := range cs {
|
||
v, e := repo.Event(r.Context(), domain, c.ID, actor, r.URL.Query().Get("uid"))
|
||
if errors.Is(e, calendar.ErrMissing) {
|
||
continue
|
||
}
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
if found != nil {
|
||
writeEventJSON(w, 409, map[string]string{"error": "UID exists in multiple calendars; select a calendar"})
|
||
return
|
||
}
|
||
found = &v
|
||
id = c.ID
|
||
}
|
||
if found == nil {
|
||
calendarError(w, calendar.ErrMissing)
|
||
return
|
||
}
|
||
writeEventJSON(w, 200, map[string]any{"calendar": id, "event": found})
|
||
return
|
||
}
|
||
if path == "calendars" {
|
||
switch r.Method {
|
||
case "GET":
|
||
cs, e := repo.List(domain, actor)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
for i := range cs {
|
||
cs[i].Months = nil
|
||
if cs[i].Source != nil {
|
||
source := *cs[i].Source
|
||
source.HasCredential = source.Credential != ""
|
||
source.Credential = ""
|
||
source.Resources = nil
|
||
cs[i].Source = &source
|
||
}
|
||
if cs[i].Owner != actor {
|
||
cs[i].Source = nil // source URLs may contain private subscription tokens
|
||
role := cs[i].Members[actor]
|
||
cs[i].Members = map[string]string{}
|
||
if actor != "" && role != "" {
|
||
cs[i].Members[actor] = role
|
||
}
|
||
}
|
||
}
|
||
defaults, e := repo.Defaults(domain, actor)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
writeEventJSON(w, 200, map[string]any{"calendars": cs, "actor": actor, "active": active, "public_allowed": repo.PublicAllowed(domain), "defaults": defaults})
|
||
case "POST":
|
||
if !active {
|
||
calendarError(w, calendar.ErrForbidden)
|
||
return
|
||
}
|
||
var body struct {
|
||
Name string `json:"name"`
|
||
PrettyName *string `json:"pretty_name"`
|
||
}
|
||
if !decodeCalendarJSON(w, r, &body) {
|
||
return
|
||
}
|
||
var pretty []string
|
||
if body.PrettyName != nil {
|
||
if !calendar.ValidPrettyName(*body.PrettyName) {
|
||
writeEventJSON(w, 422, map[string]string{"error": "pretty_name: use letters, numbers, - or _ (1–120 UTF-8 bytes; no commas, spaces or UUIDs)"})
|
||
return
|
||
}
|
||
pretty = []string{*body.PrettyName}
|
||
}
|
||
c, e := repo.Create(r.Context(), domain, actor, body.Name, pretty...)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
writeEventJSON(w, 201, c)
|
||
default:
|
||
w.Header().Set("Allow", "GET, POST")
|
||
w.WriteHeader(405)
|
||
}
|
||
return
|
||
}
|
||
if len(parts) == 3 && parts[0] == "calendars" && parts[2] == "settings" {
|
||
if r.Method != "PUT" && r.Method != "DELETE" {
|
||
w.Header().Set("Allow", "PUT, DELETE")
|
||
w.WriteHeader(405)
|
||
return
|
||
}
|
||
if !active {
|
||
calendarError(w, calendar.ErrForbidden)
|
||
return
|
||
}
|
||
c, err := repo.Get(domain, parts[1], actor)
|
||
if err != nil {
|
||
calendarError(w, err)
|
||
return
|
||
}
|
||
if c.Owner != actor {
|
||
calendarError(w, calendar.ErrForbidden)
|
||
return
|
||
}
|
||
if r.Method == "DELETE" {
|
||
var body struct {
|
||
Version string `json:"version"`
|
||
}
|
||
if !decodeCalendarJSON(w, r, &body) {
|
||
return
|
||
}
|
||
if body.Version == "" || body.Version != c.Version {
|
||
calendarError(w, calendar.ErrConflict)
|
||
return
|
||
}
|
||
if err := s.store.CancelEventJobsByTypeKey(calendarSyncType, domain+":"+c.ID); err != nil {
|
||
calendarError(w, err)
|
||
return
|
||
}
|
||
if err := repo.Delete(r.Context(), domain, c.ID, actor, body.Version); err != nil {
|
||
calendarError(w, err)
|
||
return
|
||
}
|
||
w.WriteHeader(http.StatusNoContent)
|
||
return
|
||
}
|
||
var body struct {
|
||
Name string `json:"name"`
|
||
Public bool `json:"public"`
|
||
Members map[string]string `json:"members"`
|
||
Version string `json:"version"`
|
||
PrettyName *string `json:"pretty_name"`
|
||
}
|
||
if !decodeCalendarJSON(w, r, &body) {
|
||
return
|
||
}
|
||
// Only existing local-domain users may be collaborators.
|
||
members := map[string]string{}
|
||
for id, role := range body.Members {
|
||
if _, e := uuid.Parse(id); e != nil {
|
||
p, e := s.store.PrincipalByUsername(domain, id)
|
||
if e != nil {
|
||
http.Error(w, "unknown collaborator", 400)
|
||
return
|
||
}
|
||
id = p.UUID
|
||
}
|
||
active, e := s.store.ActiveDomainMember(r.Context(), domain, id)
|
||
if e != nil || !active {
|
||
http.Error(w, "unknown collaborator", 400)
|
||
return
|
||
}
|
||
members[id] = role
|
||
}
|
||
body.Members = members
|
||
var pretty []string
|
||
if body.PrettyName != nil {
|
||
if !calendar.ValidPrettyName(*body.PrettyName) {
|
||
writeEventJSON(w, 422, map[string]string{"error": "pretty_name: use letters, numbers, - or _ (1–120 UTF-8 bytes; no commas, spaces or UUIDs)"})
|
||
return
|
||
}
|
||
pretty = []string{*body.PrettyName}
|
||
}
|
||
c, e := repo.Settings(r.Context(), domain, parts[1], actor, body.Version, body.Name, body.Public, body.Members, pretty...)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
c.Months = nil
|
||
if c.Source != nil {
|
||
c.Source.HasCredential = c.Source.Credential != ""
|
||
c.Source.Credential = ""
|
||
c.Source.Resources = nil
|
||
}
|
||
writeEventJSON(w, 200, c)
|
||
return
|
||
}
|
||
if len(parts) == 3 && parts[0] == "calendars" && parts[2] == "events" {
|
||
if r.Method == "GET" {
|
||
uid := r.URL.Query().Get("uid")
|
||
if resource := r.URL.Query().Get("resource"); resource != "" {
|
||
c, err := repo.Get(domain, parts[1], actor)
|
||
if err != nil {
|
||
calendarError(w, err)
|
||
return
|
||
}
|
||
uid, err = calendar.DAVUID(c, resource)
|
||
if err != nil {
|
||
calendarError(w, err)
|
||
return
|
||
}
|
||
}
|
||
v, e := repo.Event(r.Context(), domain, parts[1], actor, uid)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
writeEventJSON(w, 200, v)
|
||
return
|
||
}
|
||
if r.Method != "POST" {
|
||
w.WriteHeader(405)
|
||
return
|
||
}
|
||
if !active {
|
||
calendarError(w, calendar.ErrForbidden)
|
||
return
|
||
}
|
||
var body struct {
|
||
UID string `json:"uid"`
|
||
Summary string `json:"summary"`
|
||
Description string `json:"description"`
|
||
Location string `json:"location"`
|
||
Start time.Time `json:"start"`
|
||
End time.Time `json:"end"`
|
||
AllDay bool `json:"all_day"`
|
||
ETag string `json:"etag"`
|
||
}
|
||
if !decodeCalendarJSON(w, r, &body) {
|
||
return
|
||
}
|
||
old := ""
|
||
match := "*"
|
||
status := 201
|
||
if body.UID != "" {
|
||
v, e := repo.Event(r.Context(), domain, parts[1], actor, body.UID)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
old = v.Data
|
||
match = body.ETag
|
||
status = 200
|
||
} else {
|
||
body.UID = uuid.NewString()
|
||
}
|
||
v, e := calendar.Build(old, calendar.Event{UID: body.UID, Summary: body.Summary, Description: body.Description, Location: body.Location, Start: body.Start, End: body.End, AllDay: body.AllDay})
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
v, e = repo.Change(r.Context(), domain, parts[1], actor, body.UID, match, &v)
|
||
if e != nil {
|
||
calendarError(w, e)
|
||
return
|
||
}
|
||
w.Header().Set("Location", calendarHref(parts[1], v.UID))
|
||
w.Header().Set("ETag", v.ETag)
|
||
writeEventJSON(w, status, v)
|
||
return
|
||
}
|
||
http.NotFound(w, r)
|
||
}
|
||
|
||
func (s *Server) handleCalendarPage(w http.ResponseWriter, r *http.Request) {
|
||
if r.Method != "GET" && r.Method != "HEAD" {
|
||
w.WriteHeader(405)
|
||
return
|
||
}
|
||
if _, ok := s.calendarReady(w, r); !ok {
|
||
return
|
||
}
|
||
if r.URL.Path == "/v/calendar" {
|
||
http.Redirect(w, r, "/v/plan", 302)
|
||
return
|
||
}
|
||
actor, _ := s.calendarActor(r)
|
||
edit := strings.HasPrefix(r.URL.Path, "/v/event/") || strings.HasSuffix(r.URL.Path, "/new")
|
||
if edit && actor == "" {
|
||
s.authRequired(w, r)
|
||
return
|
||
}
|
||
// The client parses only these URI shapes; malformed dates must be real 404s.
|
||
if !validCalendarViewPath(r.URL.Path) {
|
||
http.NotFound(w, r)
|
||
return
|
||
}
|
||
s.renderWithContext(w, r, "calendar.gohtml", map[string]any{"Title": "Calendar", "CalendarActor": actor, "CalendarTimezone": s.getTimezoneName(s.domainUUIDForRequest(r)), "Path": r.URL.Path})
|
||
}
|
||
func validCalendarViewPath(path string) bool {
|
||
if path == "/v/plan" || path == "/v/plan/" || path == "/v/event/new" {
|
||
return true
|
||
}
|
||
if strings.HasPrefix(path, "/v/plan/event/") {
|
||
return len(strings.TrimPrefix(path, "/v/plan/event/")) > 0
|
||
}
|
||
if strings.HasPrefix(path, "/v/event/") {
|
||
return strings.HasSuffix(path, "/edit") && len(strings.TrimSuffix(strings.TrimPrefix(path, "/v/event/"), "/edit")) > 0
|
||
}
|
||
if !strings.HasPrefix(path, "/v/plan/cal/") {
|
||
return false
|
||
}
|
||
p := strings.Split(strings.TrimPrefix(path, "/v/plan/cal/"), "/")
|
||
if len(p) == 5 && p[3] == "week" && p[4] == "list" {
|
||
p = p[:3]
|
||
}
|
||
if len(p) > 4 || len(p) < 1 {
|
||
return false
|
||
}
|
||
if len(p) == 4 {
|
||
switch p[3] {
|
||
case "week", "timeline", "events", "new":
|
||
default:
|
||
return false
|
||
}
|
||
p = p[:3]
|
||
}
|
||
layout := []string{"2006", "2006/01", "2006/01/02"}[len(p)-1]
|
||
v := strings.Join(p, "/")
|
||
t, e := time.Parse(layout, v)
|
||
return e == nil && t.Year() > 0 && t.Year() < 9999 && t.Format(layout) == v
|
||
}
|