diff --git a/config.yaml b/config.yaml index b48994d..c72f321 100644 --- a/config.yaml +++ b/config.yaml @@ -1,6 +1,6 @@ server: - bind_address: "0.0.0.0:8080" - public_url: "http://localhost:8080" + bind_address: "0.0.0.0:14243" + public_url: "http://nxc.nx2.site" redaction_text: "[-]" default_class: "CONFIDENTIAL" @@ -12,30 +12,24 @@ users: password: "123" groups: - family - - klosterberg - parent - name: "diane" password: "123" groups: - family - - klosterberg - parent - name: "georg" password: "123" groups: - family - - kids - name: "lennart" password: "123" groups: - family - - kids - name: "tessa" password: "123" groups: - family - - kids - - klosterberg - name: "testuser" password: "123" - name: "shared" @@ -62,3 +56,4 @@ aggregates: access: - group: "family" mode: "read-only" + - ics: "future-only" diff --git a/internal/backend/db.go b/internal/backend/db.go index fada416..9bd7913 100644 --- a/internal/backend/db.go +++ b/internal/backend/db.go @@ -11,6 +11,7 @@ import ( "os/exec" "path" "strings" + "time" "github.com/emersion/go-ical" "github.com/emersion/go-webdav" @@ -21,6 +22,11 @@ import ( "nxcaldav/internal/config" ) +type publicInfo struct { + InternalPath string + Mode string // e.g., "future-only" +} + // DBBackend implements the caldav.Backend interface using a PostgreSQL database. // It manages users, calendars, and their events/tasks with built-in support for // access control, privacy redaction, and aggregate (virtual) calendars. @@ -30,6 +36,7 @@ type DBBackend struct { defaultClass string // Class assumed if non is set ("PUBLIC", "PRIVATE", "CONFIDENTIAL") aggregates map[string]*config.Aggregate // In-memory map of path -> virtual calendar definitions userAggs map[string][]string // In-memory map of user -> list of aggregate paths they can see + publicAccess map[string]publicInfo // In-memory map of public path -> internal info } // NewDBBackend creates a new database-backed CalDAV provider. @@ -48,6 +55,7 @@ func NewDBBackend(ctx context.Context, cfg *config.Config) (*DBBackend, error) { defaultClass: cfg.Server.DefaultClass, aggregates: make(map[string]*config.Aggregate), userAggs: make(map[string][]string), + publicAccess: make(map[string]publicInfo), } // Step 1: Ensure database tables are ready @@ -153,6 +161,7 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error { b.aggregates = make(map[string]*config.Aggregate) b.userAggs = make(map[string][]string) + b.publicAccess = make(map[string]publicInfo) // --- Phase 1: User Sync --- for _, u := range cfg.Users { @@ -230,6 +239,17 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error { return err } } + + // Check for public access (ICS) + for _, a := range c.Access { + if a.ICS != "" { + pubPath := fmt.Sprintf("/public/%s/%s.ics", c.Owner, c.ID) + b.publicAccess[pubPath] = publicInfo{ + InternalPath: path, + Mode: a.ICS, + } + } + } } // --- Phase 3: Aggregate Setup --- @@ -246,6 +266,14 @@ func (b *DBBackend) syncConfig(ctx context.Context, cfg *config.Config) error { aggAccess := make(map[string]bool) aggAccess[agg.Owner] = true for _, a := range agg.Access { + if a.ICS != "" { + pubPath := fmt.Sprintf("/public/%s/%s.ics", agg.Owner, agg.ID) + b.publicAccess[pubPath] = publicInfo{ + InternalPath: p_, + Mode: a.ICS, + } + } + var tUsers []string if a.User != "" { tUsers = append(tUsers, a.User) @@ -319,7 +347,7 @@ func (b *DBBackend) CurrentUserPrincipal(ctx context.Context) (string, error) { func (b *DBBackend) getUsername(ctx context.Context) (string, error) { principal, err := b.CurrentUserPrincipal(ctx) if err != nil { - return "", err + return "", nil // No principal means anonymous/public } return strings.Trim(principal, "/"), nil } @@ -441,6 +469,76 @@ func (b *DBBackend) filterCalendar(ctx context.Context, ownerName string, origin return filtered, nil } +// ServePublicICS handles public GET requests for .ics files. +// It applies privacy redaction and optional time-range filtering (e.g. "future-only"). +func (b *DBBackend) ServePublicICS(w http.ResponseWriter, r *http.Request) { + info, ok := b.publicAccess[r.URL.Path] + if !ok { + http.Error(w, "Not Found", http.StatusNotFound) + return + } + + // For public access, we use an empty context (no principal) + // which ensures filterCalendar applies full redaction. + ctx := r.Context() + + var objects []caldav.CalendarObject + var err error + + if agg, ok := b.aggregates[info.InternalPath]; ok { + objects, err = b.listAggregateObjects(ctx, info.InternalPath, agg) + } else { + var calID int + var ownerName string + err = b.pool.QueryRow(ctx, ` + SELECT c.id, u.name FROM calendars c + JOIN users u ON c.owner_id = u.id + WHERE c.path = $1`, info.InternalPath).Scan(&calID, &ownerName) + if err == nil { + objects, err = b.listCalendarObjectsRaw(ctx, calID, ownerName) + } + } + + if err != nil { + log.Printf("Error fetching public objects: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + outCal := ical.NewCalendar() + outCal.Props.SetText("PRODID", "-//nxcaldav//Public ICS//EN") + outCal.Props.SetText("VERSION", "2.0") + + now := time.Now() + + for _, obj := range objects { + for _, child := range obj.Data.Children { + if child.Name != "VEVENT" && child.Name != "VTODO" { + continue + } + + if info.Mode == "future-only" { + var end time.Time + if prop := child.Props.Get("DTEND"); prop != nil { + end, _ = prop.DateTime(time.UTC) + } else if prop := child.Props.Get("DTSTART"); prop != nil { + end, _ = prop.DateTime(time.UTC) + } + + if !end.IsZero() && end.Before(now) { + continue + } + } + outCal.Children = append(outCal.Children, child) + } + } + + w.Header().Set("Content-Type", "text/calendar; charset=utf-8") + if err := ical.NewEncoder(w).Encode(outCal); err != nil { + log.Printf("Error encoding public ICS: %v", err) + } +} + // --- CalDAV Backend Implementation --- // CalendarHomeSetPath returns the root path for a user's calendars (e.g., "/alice/calendars/"). @@ -561,6 +659,10 @@ func (b *DBBackend) ListCalendarObjects(ctx context.Context, p string, req *cald return nil, err } + return b.listCalendarObjectsRaw(ctx, calID, ownerName) +} + +func (b *DBBackend) listCalendarObjectsRaw(ctx context.Context, calID int, ownerName string) ([]caldav.CalendarObject, error) { rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID) if err != nil { return nil, err @@ -609,49 +711,29 @@ func (b *DBBackend) listAggregateObjects(ctx context.Context, aggPath string, ag continue } - rows, err := b.pool.Query(ctx, "SELECT path, data, etag FROM calendar_objects WHERE calendar_id = $1", calID) + objs, err := b.listCalendarObjectsRaw(ctx, calID, ownerName) if err != nil { continue } - for rows.Next() { - var obj caldav.CalendarObject - var dataStr string - if err := rows.Scan(&obj.Path, &dataStr, &obj.ETag); err != nil { - rows.Close() - return nil, err - } - - calData, err := ical.NewDecoder(strings.NewReader(dataStr)).Decode() - if err != nil { - continue - } - - // Apply Privacy rules for the aggregate viewer - filtered, err := b.filterCalendar(ctx, ownerName, calData) - if err != nil || filtered == nil { - continue - } - - // Prepend source name so Diane knows this is a "[school]" event - for _, child := range filtered.Children { + for _, obj := range objs { + // Prepend source name so Diane knows this is a "[calendar]" event + for _, child := range obj.Data.Children { if child.Name == "VEVENT" || child.Name == "VTODO" { - summary := child.Props.Get("SUMMARY") + descr := child.Props.Get("DESCRIPTION") val := "" - if summary != nil { - val = summary.Value + if descr != nil { + val = descr.Value } - child.Props.SetText("SUMMARY", fmt.Sprintf("[%s] %s", sourceID, val)) + child.Props.SetText("DESCRIPTION", fmt.Sprintf("[%s]\n%s", sourceID, val)) } } // Virtualize the path so Thunderbird doesn't reject the file fileName := path.Base(obj.Path) obj.Path = aggPath + sourceID + "__" + fileName - obj.Data = filtered res = append(res, obj) } - rows.Close() } return res, nil } diff --git a/internal/config/config.go b/internal/config/config.go index 604eaaf..95ac938 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -12,6 +12,7 @@ type Access struct { Group string `yaml:"group,omitempty"` Groups string `yaml:"groups,omitempty"` Mode string `yaml:"mode"` // "read-only" or "read-write" + ICS string `yaml:"ics,omitempty"` } type Calendar struct { diff --git a/main.go b/main.go index ac70170..969db37 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "net/http" + "strings" "time" "github.com/emersion/go-webdav/caldav" @@ -27,6 +28,11 @@ func main() { handler := &caldav.Handler{Backend: be} http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/public/") { + be.ServePublicICS(w, r) + return + } + user, password, ok := r.BasicAuth() if !ok { w.Header().Set("WWW-Authenticate", `Basic realm="CalDAV Server"`)