summaryrefslogtreecommitdiff
path: root/lib/calendar/calendar.go
blob: dbce6bce25306e5aa1543ca7f1c446b6c8e91699 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package calendar

import (
	"bytes"
	"fmt"
	"io"
	"net/mail"
	"regexp"
	"strings"
	"time"

	ics "github.com/arran4/golang-ical"
)

type Reply struct {
	MimeType     string
	Params       map[string]string
	CalendarText io.ReadWriter
	PlainText    io.ReadWriter
	Organizers   []string
}

func (cr *Reply) AddOrganizer(o string) {
	cr.Organizers = append(cr.Organizers, o)
}

// CreateReply parses a ics request and return a ics reply (RFC 2446, Section 3.2.3)
func CreateReply(reader io.Reader, from *mail.Address, partstat string) (*Reply, error) {

	cr := Reply{
		MimeType: "text/calendar",
		Params: map[string]string{
			"charset": "UTF-8",
			"method":  "REPLY",
		},
		CalendarText: &bytes.Buffer{},
		PlainText:    &bytes.Buffer{},
	}

	var (
		status ics.ParticipationStatus
		action string
	)

	switch partstat {
	case "accept":
		status = ics.ParticipationStatusAccepted
		action = "accepted"
	case "accept-tentative":
		status = ics.ParticipationStatusTentative
		action = "tentatively accepted"
	case "decline":
		status = ics.ParticipationStatusDeclined
		action = "declined"
	default:
		return nil, fmt.Errorf("participation status %s is not implemented", partstat)
	}

	name := from.Name
	if name == "" {
		name = from.Address
	}
	fmt.Fprintf(cr.PlainText, "%s has %s this invitation.", name, action)

	invite, err := parse(reader)
	if err != nil {
		return nil, err
	}

	if ok := invite.request(); !ok {
		return nil, fmt.Errorf("no reply is requested")
	}

	// update invite as a reply
	reply := invite
	reply.SetMethod(ics.MethodReply)
	reply.SetProductId("aerc")

	// check all events
	for _, vevent := range reply.Events() {
		e := event{vevent}

		// check if we should answer
		if err := e.isReplyRequested(from.Address); err != nil {
			return nil, err
		}

		// make sure we send our reply to the meeting organizer
		if organizer := e.GetProperty(ics.ComponentPropertyOrganizer); organizer != nil {
			cr.AddOrganizer(organizer.Value)
		}

		// update attendee participation status
		e.updateAttendees(status, from.Address)

		// update timestamp
		e.SetDtStampTime(time.Now())

		// remove any subcomponents of event
		e.Components = nil
	}

	// keep only timezone and event components
	reply.clean()

	if len(reply.Events()) == 0 {
		return nil, fmt.Errorf("no events to respond to")
	}

	if err := reply.SerializeTo(cr.CalendarText); err != nil {
		return nil, err
	}
	return &cr, nil
}

type calendar struct {
	*ics.Calendar
}

func parse(reader io.Reader) (*calendar, error) {
	// fix capitalized mailto for parsing of ics file
	var sb strings.Builder
	io.Copy(&sb, reader)
	re := regexp.MustCompile("MAILTO:(.+@)")
	str := re.ReplaceAllString(sb.String(), "mailto:${1}")

	// parse calendar
	invite, err := ics.ParseCalendar(strings.NewReader(str))
	if err != nil {
		return nil, err
	}
	return &calendar{invite}, nil
}

func (cal *calendar) request() (ok bool) {
	ok = false
	for i := range cal.CalendarProperties {
		if cal.CalendarProperties[i].IANAToken == string(ics.PropertyMethod) {
			if cal.CalendarProperties[i].Value == string(ics.MethodRequest) {
				ok = true
				return
			}
		}
	}
	return
}

func (cal *calendar) clean() {
	var clean []ics.Component
	for _, comp := range cal.Components {
		switch comp.(type) {
		case *ics.VTimezone, *ics.VEvent:
			clean = append(clean, comp)
		default:
			continue
		}
	}
	cal.Components = clean
}

type event struct {
	*ics.VEvent
}

func (e *event) isReplyRequested(from string) error {
	var present bool = false
	var rsvp bool = false
	for _, a := range e.Attendees() {
		if a.Email() == from {
			present = true
			if r, ok := a.ICalParameters[string(ics.ParameterRsvp)]; ok {
				if len(r) > 0 && strings.ToLower(r[0]) == "true" {
					rsvp = true
				}
			}
		}
	}
	if !present {
		return fmt.Errorf("we are not invited")
	}
	if !rsvp {
		return fmt.Errorf("we don't have to rsvp")
	}
	return nil
}

func (e *event) updateAttendees(status ics.ParticipationStatus, from string) {
	var clean []ics.IANAProperty
	for _, prop := range e.Properties {
		if prop.IANAToken == string(ics.ComponentPropertyAttendee) {
			att := ics.Attendee{IANAProperty: prop}
			if att.Email() != from {
				continue
			}
			prop.ICalParameters[string(ics.ParameterParticipationStatus)] = []string{string(status)}
			delete(prop.ICalParameters, string(ics.ParameterRsvp))
		}
		clean = append(clean, prop)
	}
	e.Properties = clean
}