email kinda working
This commit is contained in:
@@ -34,8 +34,11 @@ type publicInfo struct {
|
||||
type DBBackend struct {
|
||||
pool *pgxpool.Pool // Connection pool to PostgreSQL
|
||||
prefix string // Public URL base path prefix
|
||||
publicURL string // Full public URL base (e.g. http://nxc.nx2.site/)
|
||||
redactionText string // Text used to hide confidential event details (e.g. "[REDACED]")
|
||||
defaultClass string // Class assumed if non is set ("PUBLIC", "PRIVATE", "CONFIDENTIAL")
|
||||
defaultClass string // Class assumed if non is set ("PUBLIC", "PRIVATE", "CONFIDENTIAL")
|
||||
emailDomain string // Domain for email addresses (e.g., "nx2.site")
|
||||
smtp config.SMTPConfig // SMTP server configuration
|
||||
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
|
||||
@@ -54,8 +57,11 @@ func NewDBBackend(ctx context.Context, cfg *config.Config) (*DBBackend, error) {
|
||||
b := &DBBackend{
|
||||
pool: pool,
|
||||
prefix: cfg.Server.BasePath(),
|
||||
publicURL: cfg.Server.PublicURL,
|
||||
redactionText: cfg.Server.Redaction,
|
||||
defaultClass: cfg.Server.DefaultClass,
|
||||
emailDomain: cfg.Server.EmailDomain,
|
||||
smtp: cfg.SMTP,
|
||||
aggregates: make(map[string]*config.Aggregate),
|
||||
userAggs: make(map[string][]string),
|
||||
publicAccess: make(map[string]publicInfo),
|
||||
@@ -912,6 +918,88 @@ func (b *DBBackend) PutCalendarObject(ctx context.Context, p string, calendar *i
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Step 3: Handle Status Propagation & Invitations
|
||||
username, _ := b.getUsername(ctx)
|
||||
userEmail := strings.ToLower(username + "@" + b.emailDomain)
|
||||
|
||||
for _, event := range calendar.Events() {
|
||||
organizer := event.Props.Get("ORGANIZER")
|
||||
orgEmail := ""
|
||||
if organizer != nil {
|
||||
orgEmail = strings.TrimPrefix(strings.ToLower(organizer.Value), "mailto:")
|
||||
}
|
||||
|
||||
// --- Case A: User is the ATTENDEE updating their status ---
|
||||
// If the user is NOT the organizer, but is an attendee, find the organizer's
|
||||
// original event and update the status there.
|
||||
if orgEmail != "" && orgEmail != userEmail {
|
||||
log.Printf("[scheduling] Attendee %s updated event. Propagating to organizer %s", userEmail, orgEmail)
|
||||
|
||||
// Find the attendee's status in this version
|
||||
myStatus := "NEEDS-ACTION"
|
||||
for _, att := range event.Props["ATTENDEE"] {
|
||||
if strings.TrimPrefix(strings.ToLower(att.Value), "mailto:") == userEmail {
|
||||
if stat := att.Params.Get("PARTSTAT"); stat != "" {
|
||||
myStatus = stat
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Find the UID of this event to locate the organizer's copy
|
||||
uid := ""
|
||||
if u := event.Props.Get("UID"); u != nil {
|
||||
uid = u.Value
|
||||
}
|
||||
|
||||
if uid != "" {
|
||||
// Search for the organizer's copy in their calendars
|
||||
go b.propagateStatusToOrganizer(orgEmail, userEmail, uid, myStatus)
|
||||
}
|
||||
continue // Don't send invitations from an attendee's PUT
|
||||
}
|
||||
|
||||
// --- Case B: User is the ORGANIZER (Sending Invitations) ---
|
||||
// Only send invites if the user is the organizer and we are in the owner's calendar
|
||||
isOwnerCalendar := strings.Contains(p, "/"+username+"/")
|
||||
if !isOwnerCalendar || (orgEmail != "" && orgEmail != userEmail) {
|
||||
continue
|
||||
}
|
||||
|
||||
attendees := event.Props["ATTENDEE"]
|
||||
if len(attendees) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
summary := ""
|
||||
if s := event.Props.Get("SUMMARY"); s != nil {
|
||||
summary = s.Value
|
||||
}
|
||||
description := ""
|
||||
if d := event.Props.Get("DESCRIPTION"); d != nil {
|
||||
description = d.Value
|
||||
}
|
||||
start := ""
|
||||
if dtstart, err := event.DateTimeStart(time.UTC); err == nil {
|
||||
start = dtstart.Format(time.RFC1123)
|
||||
}
|
||||
end := ""
|
||||
if dtend, err := event.DateTimeEnd(time.UTC); err == nil {
|
||||
end = dtend.Format(time.RFC1123)
|
||||
}
|
||||
|
||||
for _, attendee := range attendees {
|
||||
recipientEmail := strings.TrimPrefix(attendee.Value, "mailto:")
|
||||
if recipientEmail == "" {
|
||||
continue
|
||||
}
|
||||
// Only send if it's a valid looking email and not the sender themselves
|
||||
if strings.Contains(recipientEmail, "@") && !strings.HasPrefix(recipientEmail, username+"@") {
|
||||
go b.sendInvitation(username, recipientEmail, summary, description, start, end, p, dataStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &caldav.CalendarObject{
|
||||
Path: p,
|
||||
Data: calendar,
|
||||
@@ -942,6 +1030,125 @@ func (b *DBBackend) DeleteCalendarObject(ctx context.Context, p string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// propagateStatusToOrganizer finds the original event in the organizer's calendar
|
||||
// and updates the attendee's status.
|
||||
func (b *DBBackend) propagateStatusToOrganizer(orgEmail, attendeeEmail, uid, status string) {
|
||||
ctx := context.Background()
|
||||
log.Printf("[scheduling] Searching for original event UID %s for organizer %s", uid, orgEmail)
|
||||
|
||||
// 1. Find the organizer's user ID
|
||||
var orgUserID int
|
||||
err := b.pool.QueryRow(ctx, "SELECT id FROM users WHERE name = $1 OR name = $2",
|
||||
strings.Split(orgEmail, "@")[0], orgEmail).Scan(&orgUserID)
|
||||
if err != nil {
|
||||
log.Printf("[scheduling] Could not find organizer user %s: %v", orgEmail, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Find the calendar object by UID within organizer's calendars
|
||||
rows, err := b.pool.Query(ctx, `
|
||||
SELECT co.path, co.data, co.calendar_id
|
||||
FROM calendar_objects co
|
||||
JOIN calendars c ON co.calendar_id = c.id
|
||||
WHERE c.owner_id = $1 AND co.data LIKE '%' || $2 || '%'`,
|
||||
orgUserID, uid)
|
||||
if err != nil {
|
||||
log.Printf("[scheduling] Error searching for organizer's copy: %v", err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var p, dataStr string
|
||||
var calID int
|
||||
if err := rows.Scan(&p, &dataStr, &calID); err != nil { continue }
|
||||
|
||||
// Verify UID (LIKE is just a hint)
|
||||
calendar, err := ical.NewDecoder(strings.NewReader(dataStr)).Decode()
|
||||
if err != nil { continue }
|
||||
|
||||
found := false
|
||||
for _, event := range calendar.Events() {
|
||||
if u := event.Props.Get("UID"); u != nil && u.Value == uid {
|
||||
// Update attendee status
|
||||
for _, att := range event.Props["ATTENDEE"] {
|
||||
if strings.TrimPrefix(strings.ToLower(att.Value), "mailto:") == attendeeEmail {
|
||||
log.Printf("[scheduling] Updating %s status to %s in organizer's copy %s", attendeeEmail, status, p)
|
||||
att.Params.Set("PARTSTAT", status)
|
||||
found = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if found {
|
||||
var buf bytes.Buffer
|
||||
if err := ical.NewEncoder(&buf).Encode(calendar); err == nil {
|
||||
newEtag := fmt.Sprintf(`"%d-%d"`, time.Now().Unix(), buf.Len())
|
||||
b.pool.Exec(ctx, "UPDATE calendar_objects SET data = $1, etag = $2 WHERE calendar_id = $3 AND path = $4",
|
||||
buf.String(), newEtag, calID, p)
|
||||
log.Printf("[scheduling] Organizer's copy %s updated successfully", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RespondToInvitation handles an attendee's Accept/Decline response.
|
||||
func (b *DBBackend) RespondToInvitation(ctx context.Context, p, attendeeEmail, status string) error {
|
||||
log.Printf("[email] Response for %s from %s: %s", p, attendeeEmail, status)
|
||||
|
||||
// 1. Fetch the calendar object
|
||||
var dataStr string
|
||||
var calID int
|
||||
err := b.pool.QueryRow(ctx, "SELECT calendar_id, data FROM calendar_objects WHERE path = $1", p).Scan(&calID, &dataStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to find calendar object: %v", err)
|
||||
}
|
||||
|
||||
calendar, err := ical.NewDecoder(strings.NewReader(dataStr)).Decode()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode calendar data: %v", err)
|
||||
}
|
||||
|
||||
// 2. Update PARTSTAT for the attendee
|
||||
modified := false
|
||||
status = strings.ToUpper(status)
|
||||
attendeeEmail = strings.ToLower(strings.TrimSpace(attendeeEmail))
|
||||
|
||||
for _, event := range calendar.Events() {
|
||||
attendees := event.Props["ATTENDEE"]
|
||||
for _, attendee := range attendees {
|
||||
email := strings.TrimPrefix(strings.ToLower(attendee.Value), "mailto:")
|
||||
if email == attendeeEmail {
|
||||
attendee.Params.Set("PARTSTAT", status)
|
||||
modified = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !modified {
|
||||
return fmt.Errorf("attendee %s not found in event", attendeeEmail)
|
||||
}
|
||||
|
||||
// 3. Save back to DB
|
||||
var buf bytes.Buffer
|
||||
if err := ical.NewEncoder(&buf).Encode(calendar); err != nil {
|
||||
return err
|
||||
}
|
||||
newDataStr := buf.String()
|
||||
// Use a timestamp + length for a unique ETag
|
||||
newEtag := fmt.Sprintf(`"%d-%d"`, time.Now().Unix(), len(newDataStr))
|
||||
|
||||
_, err = b.pool.Exec(ctx, "UPDATE calendar_objects SET data = $1, etag = $2 WHERE calendar_id = $3 AND path = $4",
|
||||
newDataStr, newEtag, calID, p)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update calendar object in DB: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("[email] Successfully updated status to %s for %s in %s", status, attendeeEmail, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// QueryCalendarObjects filters items based on a CalDAV query (e.g. time range).
|
||||
// Currently, it just lists all objects and lets the client filter, but
|
||||
// we use it to enforce privacy rules for the initial report.
|
||||
|
||||
Reference in New Issue
Block a user