summaryrefslogtreecommitdiff
path: root/internal/api/google_calendar.go
blob: a69f734855e144afafd1e757a7e15a8a6cb96cb0 (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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package api

import (
	"context"
	"fmt"
	"log"
	"sort"
	"strings"
	"sync"
	"time"

	"task-dashboard/internal/models"

	"google.golang.org/api/calendar/v3"
	"google.golang.org/api/option"
)

type GoogleCalendarClient struct {
	srv         *calendar.Service
	calendarIDs []string
	displayTZ   *time.Location
}

// parseEventTime extracts start/end times from a Google Calendar event
func (c *GoogleCalendarClient) parseEventTime(item *calendar.Event) (start, end time.Time) {
	displayTZ := c.displayTZ
	if displayTZ == nil {
		displayTZ = time.UTC
	}

	if item.Start.DateTime == "" {
		// All-day event - parse in display timezone
		start, _ = time.ParseInLocation("2006-01-02", item.Start.Date, displayTZ)
		end, _ = time.ParseInLocation("2006-01-02", item.End.Date, displayTZ)
	} else {
		// Try RFC3339 first (includes timezone offset like "2006-01-02T15:04:05-10:00" or "Z")
		var err error
		start, err = time.Parse(time.RFC3339, item.Start.DateTime)
		if err != nil {
			// No timezone in string - use event's timezone or display timezone
			var loc *time.Location
			if item.Start.TimeZone != "" {
				loc, _ = time.LoadLocation(item.Start.TimeZone)
			}
			if loc == nil {
				loc = displayTZ
			}
			start, _ = time.ParseInLocation("2006-01-02T15:04:05", item.Start.DateTime, loc)
		}

		end, err = time.Parse(time.RFC3339, item.End.DateTime)
		if err != nil {
			var loc *time.Location
			if item.End.TimeZone != "" {
				loc, _ = time.LoadLocation(item.End.TimeZone)
			}
			if loc == nil {
				loc = displayTZ
			}
			end, _ = time.ParseInLocation("2006-01-02T15:04:05", item.End.DateTime, loc)
		}

		// Convert to display timezone
		start = start.In(displayTZ)
		end = end.In(displayTZ)
	}
	return
}

// deduplicateEvents removes duplicate events (same summary + start time)
func deduplicateEvents(events []models.CalendarEvent) []models.CalendarEvent {
	seen := make(map[string]bool)
	var unique []models.CalendarEvent
	for _, event := range events {
		key := fmt.Sprintf("%s|%d", event.Summary, event.Start.Unix())
		if !seen[key] {
			seen[key] = true
			unique = append(unique, event)
		}
	}
	sort.Slice(unique, func(i, j int) bool {
		return unique[i].Start.Before(unique[j].Start)
	})
	return unique
}

// NewGoogleCalendarClient creates a client that fetches from multiple calendars.
// calendarIDs can be comma-separated (e.g., "cal1@group.calendar.google.com,cal2@group.calendar.google.com")
// timezone is the IANA timezone name for display (e.g., "Pacific/Honolulu")
func NewGoogleCalendarClient(ctx context.Context, credentialsFile, calendarIDs, timezone string) (*GoogleCalendarClient, error) {
	srv, err := calendar.NewService(ctx, option.WithCredentialsFile(credentialsFile))
	if err != nil {
		return nil, fmt.Errorf("unable to retrieve Calendar client: %v", err)
	}

	// Parse comma-separated calendar IDs
	ids := strings.Split(calendarIDs, ",")
	var trimmedIDs []string
	for _, id := range ids {
		if trimmed := strings.TrimSpace(id); trimmed != "" {
			trimmedIDs = append(trimmedIDs, trimmed)
		}
	}

	// Load display timezone
	displayTZ, err := time.LoadLocation(timezone)
	if err != nil {
		log.Printf("Warning: invalid timezone %q, using UTC: %v", timezone, err)
		displayTZ = time.UTC
	}

	return &GoogleCalendarClient{
		srv:         srv,
		calendarIDs: trimmedIDs,
		displayTZ:   displayTZ,
	}, nil
}

func (c *GoogleCalendarClient) GetUpcomingEvents(ctx context.Context, maxResults int) ([]models.CalendarEvent, error) {
	// TimeMin must be the start of today in the DISPLAY timezone, not raw
	// time.Now() (server/UTC time). Google's API filters TimeMin against
	// each event's END time (exclusive), so this is also what makes an
	// already-ended-today event "past" vs excluded entirely -- using
	// time.Now() here meant, for a UTC-10 display timezone, the cutoff
	// landed mid-afternoon the PREVIOUS Hawaii-local day (server midnight
	// UTC is 2pm HST the day before), not midnight of the actual display
	// day. That's what caused the 2026-08-06 report: past-today events
	// missing entirely (silently never fetched into the cache in the first
	// place, not a client-side bug) and the whole today/tomorrow bucketing
	// downstream skewed by the same ~10h gap.
	tz := c.displayTZ
	if tz == nil {
		tz = time.UTC
	}
	nowInTZ := time.Now().In(tz)
	todayStart := time.Date(nowInTZ.Year(), nowInTZ.Month(), nowInTZ.Day(), 0, 0, 0, 0, tz)
	t := todayStart.Format(time.RFC3339)

	fetchOne := func(calendarID string) []models.CalendarEvent {
		events, err := c.srv.Events.List(calendarID).ShowDeleted(false).
			SingleEvents(true).TimeMin(t).MaxResults(int64(maxResults)).OrderBy("startTime").
			Context(ctx).Do()
		if err != nil {
			log.Printf("Warning: failed to fetch events from calendar %s: %v", calendarID, err)
			return nil
		}
		parsed := make([]models.CalendarEvent, 0, len(events.Items))
		for _, item := range events.Items {
			start, end := c.parseEventTime(item)
			parsed = append(parsed, models.CalendarEvent{
				ID:               item.Id,
				Summary:          item.Summary,
				Description:      item.Description,
				Start:            start,
				End:              end,
				HTMLLink:         item.HtmlLink,
				RecurringEventID: item.RecurringEventId,
			})
		}
		return parsed
	}

	allEvents := c.fetchAllCalendars(fetchOne)

	uniqueEvents := deduplicateEvents(allEvents)
	if len(uniqueEvents) > maxResults {
		uniqueEvents = uniqueEvents[:maxResults]
	}
	return uniqueEvents, nil
}

// fetchAllCalendars runs fetchOne for every configured calendar concurrently
// and merges the results. This must be concurrent, not sequential: every
// caller shares a single deadline-bound ctx (see aggregateData's per-fetch
// context.WithTimeout in internal/handlers/handlers.go), and a sequential
// loop would let an early calendar's slow response starve the deadline
// budget for calendars later in the list -- exactly the failure mode this
// function exists to prevent (see incident notes 2026-08-04). Running them
// concurrently means every calendar gets an equal shot at the same shared
// deadline instead of eating into the next one's share of it.
func (c *GoogleCalendarClient) fetchAllCalendars(fetchOne func(calendarID string) []models.CalendarEvent) []models.CalendarEvent {
	var wg sync.WaitGroup
	var mu sync.Mutex
	var allEvents []models.CalendarEvent

	for _, calendarID := range c.calendarIDs {
		wg.Add(1)
		go func(calendarID string) {
			defer wg.Done()
			events := fetchOne(calendarID)
			if len(events) == 0 {
				return
			}
			mu.Lock()
			allEvents = append(allEvents, events...)
			mu.Unlock()
		}(calendarID)
	}
	wg.Wait()

	return allEvents
}

func (c *GoogleCalendarClient) GetEventsByDateRange(ctx context.Context, start, end time.Time) ([]models.CalendarEvent, error) {
	timeMin := start.Format(time.RFC3339)
	timeMax := end.Format(time.RFC3339)

	fetchOne := func(calendarID string) []models.CalendarEvent {
		events, err := c.srv.Events.List(calendarID).ShowDeleted(false).
			SingleEvents(true).TimeMin(timeMin).TimeMax(timeMax).OrderBy("startTime").
			Context(ctx).Do()
		if err != nil {
			log.Printf("Warning: failed to fetch events from calendar %s: %v", calendarID, err)
			return nil
		}
		parsed := make([]models.CalendarEvent, 0, len(events.Items))
		for _, item := range events.Items {
			evtStart, evtEnd := c.parseEventTime(item)
			parsed = append(parsed, models.CalendarEvent{
				ID:               item.Id,
				Summary:          item.Summary,
				Description:      item.Description,
				Start:            evtStart,
				End:              evtEnd,
				HTMLLink:         item.HtmlLink,
				RecurringEventID: item.RecurringEventId,
			})
		}
		return parsed
	}

	return deduplicateEvents(c.fetchAllCalendars(fetchOne)), nil
}

// SetCalendarIDs updates the calendar IDs used by the client
func (c *GoogleCalendarClient) SetCalendarIDs(ids []string) {
	c.calendarIDs = ids
}

// GetCalendarList returns all calendars accessible to the user
func (c *GoogleCalendarClient) GetCalendarList(ctx context.Context) ([]models.CalendarInfo, error) {
	list, err := c.srv.CalendarList.List().Context(ctx).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to fetch calendar list: %w", err)
	}

	var calendars []models.CalendarInfo
	for _, item := range list.Items {
		name := item.Summary
		if name == "" {
			name = item.Id
		}
		calendars = append(calendars, models.CalendarInfo{
			ID:   item.Id,
			Name: name,
		})
	}
	return calendars, nil
}