summaryrefslogtreecommitdiff
path: root/internal/handlers/widget.go
blob: f0fd1013623710c9ed6b1020326a92018634b5e4 (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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package handlers

import (
	"encoding/json"
	"errors"
	"net/http"
	"strings"
	"time"

	"task-dashboard/internal/config"
	"task-dashboard/internal/models"
	"task-dashboard/internal/store"
)

// WidgetAuthMiddleware validates the static bearer token for widget API endpoints.
func WidgetAuthMiddleware(token string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if token == "" {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		auth := r.Header.Get("Authorization")
		if !strings.HasPrefix(auth, "Bearer ") || strings.TrimPrefix(auth, "Bearer ") != token {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// TimelineItemToWidgetItem converts a TimelineItem to a WidgetItem for the widget API.
// Exported for testability.
func TimelineItemToWidgetItem(item models.TimelineItem) models.WidgetItem {
	wi := models.WidgetItem{
		ID:               item.ID,
		Title:            item.Title,
		Source:           item.Source,
		IsAllDay:         item.IsAllDay,
		IsOverdue:        item.IsOverdue,
		URL:              item.URL,
		RecurringEventID: item.RecurringEventID,
	}

	switch item.Type {
	case models.TimelineItemTypeEvent:
		wi.Type = "event"
	case models.TimelineItemTypeMeal:
		wi.Type = "event"
	case models.TimelineItemTypeCard:
		wi.Type = "task"
		wi.Completable = true
	case models.TimelineItemTypeGTask:
		wi.Type = "task"
		wi.Completable = true
	default:
		wi.Type = "task"
		wi.Completable = item.Source == "doot"
	}

	// Only populate Start/End for items with a real time. All-day CALENDAR
	// EVENTS (not undated doot/gtask tasks, which are also flagged IsAllDay
	// as a "no specific time" fallback -- see TimelineItem.ComputeDaySection)
	// get Start populated too, using their real event date, so the widget
	// client can pin them to the top of the correct day's section instead of
	// losing them in the floating-task hourly-slot packer, which has no
	// concept of "all day" and can push a slot past the visible grid range
	// entirely. Tasks keep the existing nil-Start "floating" treatment
	// regardless of IsAllDay -- only Start is set for them (never End), and
	// only when they have a real time.
	if !item.Time.IsZero() && (!item.IsAllDay || item.Type == models.TimelineItemTypeEvent) {
		t := item.Time
		wi.Start = &t
		if item.Type == models.TimelineItemTypeEvent {
			// Events always forward End when known, even when IsAllDay --
			// a multi-day all-day event (e.g. a 3-day conference) needs its
			// End date reaching the client so it can detect the span and
			// render "starts"/"ends"/spans-through labels per rendered day.
			if item.EndTime != nil {
				wi.End = item.EndTime
			}
		} else if !item.IsAllDay {
			if item.EndTime != nil {
				wi.End = item.EndTime
			} else {
				end := item.Time.Add(time.Hour)
				wi.End = &end
			}
		}
	}

	// DueDate is independent of Start/IsAllDay -- doot tasks deliberately
	// keep Start nil (see the "floating task" doc comment above) so the
	// client's SlotPacker positions them, but the Android detail popup
	// still needs to know the real due date to display and reschedule it.
	if item.Type == models.TimelineItemTypeTask && item.Source == "doot" && !item.Time.IsZero() {
		due := item.Time
		wi.DueDate = &due
	}

	return wi
}

// HandleWidgetGet returns today's timeline items as JSON for the Android widget.
func (h *Handler) HandleWidgetGet(w http.ResponseWriter, r *http.Request) {
	now := config.Now()
	tz := config.GetDisplayTimezone()
	start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, tz)
	end := start.Add(48 * time.Hour)

	items, err := BuildTimeline(r.Context(), h.store, start, end)
	if err != nil {
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}

	widgetItems := make([]models.WidgetItem, 0, len(items))
	for _, item := range items {
		if item.DaySection == models.DaySectionToday ||
			item.DaySection == models.DaySectionTomorrow ||
			item.IsOverdue {
			widgetItems = append(widgetItems, TimelineItemToWidgetItem(item))
		}
	}

	resp := models.WidgetResponse{
		Now:   now,
		Items: widgetItems,
	}

	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(resp)
}

type widgetCompleteRequest struct {
	ID     string `json:"id"`
	Source string `json:"source"`
}

type widgetAddRequest struct {
	Title string `json:"title"`
}

type widgetRescheduleRequest struct {
	ID     string `json:"id"`
	Source string `json:"source"`
	Date   string `json:"date"` // YYYY-MM-DD
}

// HandleWidgetReschedule updates the due date of a native task.
func (h *Handler) HandleWidgetReschedule(w http.ResponseWriter, r *http.Request) {
	var req widgetRescheduleRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	if req.Source != "doot" {
		http.Error(w, "only doot tasks can be rescheduled via widget", http.StatusBadRequest)
		return
	}
	parsed, err := time.Parse("2006-01-02", req.Date)
	if err != nil {
		http.Error(w, "invalid date", http.StatusBadRequest)
		return
	}
	tz := config.GetDisplayTimezone()
	dueDate := time.Date(parsed.Year(), parsed.Month(), parsed.Day(), 0, 0, 0, 0, tz)
	if err := h.store.RescheduleNativeTask(req.ID, dueDate); err != nil {
		if errors.Is(err, store.ErrNativeTaskNotFound) {
			http.Error(w, "task not found", http.StatusNotFound)
			return
		}
		http.Error(w, "failed to reschedule", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
}

// findGoogleTask looks up a cached Google Task by ID.
func (h *Handler) findGoogleTask(id string) (models.GoogleTask, bool) {
	gTasks, err := h.store.GetGoogleTasks()
	if err != nil {
		return models.GoogleTask{}, false
	}
	for _, t := range gTasks {
		if t.ID == id {
			return t, true
		}
	}
	return models.GoogleTask{}, false
}

// findCard looks up a cached Trello card by ID.
func (h *Handler) findCard(id string) (models.Card, bool) {
	boards, err := h.store.GetBoards()
	if err != nil {
		return models.Card{}, false
	}
	for _, b := range boards {
		for _, c := range b.Cards {
			if c.ID == id {
				return c, true
			}
		}
	}
	return models.Card{}, false
}

type widgetDetailResponse struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Editable    bool   `json:"editable"`
}

// HandleWidgetDetail returns a task's title/description for the widget's edit popup.
func (h *Handler) HandleWidgetDetail(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	source := r.URL.Query().Get("source")
	if id == "" || source == "" {
		http.Error(w, "missing id or source", http.StatusBadRequest)
		return
	}

	var resp widgetDetailResponse
	switch source {
	case "doot":
		tasks, err := h.store.GetNativeTasks()
		if err != nil {
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		for _, t := range tasks {
			if t.ID == id {
				resp = widgetDetailResponse{Title: t.Content, Description: t.Description, Editable: true}
				break
			}
		}
	case "gtasks":
		if t, ok := h.findGoogleTask(id); ok {
			resp = widgetDetailResponse{Title: t.Title, Description: t.Notes, Editable: h.googleTasksClient != nil}
		}
	case "trello":
		if c, ok := h.findCard(id); ok {
			resp = widgetDetailResponse{Title: c.Name, Description: c.Description, Editable: h.trelloClient != nil}
		}
	default:
		http.Error(w, "unsupported source", http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(resp)
}

type widgetUpdateRequest struct {
	ID          string `json:"id"`
	Source      string `json:"source"`
	Description string `json:"description"`
}

// HandleWidgetUpdate saves an edited description from the widget's edit popup.
func (h *Handler) HandleWidgetUpdate(w http.ResponseWriter, r *http.Request) {
	var req widgetUpdateRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	switch req.Source {
	case "doot":
		if err := h.store.UpdateNativeTaskDescription(req.ID, req.Description); err != nil {
			http.Error(w, "failed to update task", http.StatusInternalServerError)
			return
		}
	case "gtasks":
		if h.googleTasksClient == nil {
			http.Error(w, "google tasks not configured", http.StatusServiceUnavailable)
			return
		}
		t, ok := h.findGoogleTask(req.ID)
		if !ok {
			http.Error(w, "task not found", http.StatusNotFound)
			return
		}
		if err := h.googleTasksClient.UpdateTaskNotes(r.Context(), t.ListID, req.ID, req.Description); err != nil {
			http.Error(w, "failed to update task", http.StatusInternalServerError)
			return
		}
		_ = h.store.InvalidateCache(store.CacheKeyGoogleTasks)
	case "trello":
		if h.trelloClient == nil {
			http.Error(w, "trello not configured", http.StatusServiceUnavailable)
			return
		}
		if err := h.trelloClient.UpdateCard(r.Context(), req.ID, map[string]interface{}{"desc": req.Description}); err != nil {
			http.Error(w, "failed to update task", http.StatusInternalServerError)
			return
		}
		_ = h.store.InvalidateCache(store.CacheKeyTrelloBoards)
	default:
		http.Error(w, "source not editable", http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusOK)
}

// HandleWidgetComplete proxies a task completion to the source API or native store.
func (h *Handler) HandleWidgetComplete(w http.ResponseWriter, r *http.Request) {
	var req widgetCompleteRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	switch req.Source {
	case "doot":
		if err := h.store.CompleteNativeTask(req.ID); err != nil {
			if errors.Is(err, store.ErrNativeTaskNotFound) {
				// Surfaced as 404 (not a silent 200) so the caller -- the
				// Android widget -- can tell "nothing changed" apart from
				// "it worked", instead of the previous behavior where a
				// stale/wrong id looked identical to a real completion.
				http.Error(w, "task not found", http.StatusNotFound)
				return
			}
			http.Error(w, "failed to complete task", http.StatusInternalServerError)
			return
		}
		_ = h.store.SaveCompletedTask("doot", req.ID, "", nil)
	case "gtasks":
		if h.googleTasksClient == nil {
			http.Error(w, "google tasks not configured", http.StatusServiceUnavailable)
			return
		}
		t, ok := h.findGoogleTask(req.ID)
		if !ok {
			http.Error(w, "task not found", http.StatusNotFound)
			return
		}
		if err := h.googleTasksClient.CompleteTask(r.Context(), t.ListID, req.ID); err != nil {
			http.Error(w, "failed to complete task", http.StatusInternalServerError)
			return
		}
		_ = h.store.SaveCompletedTask("gtasks", req.ID, t.Title, t.DueDate)
		_ = h.store.InvalidateCache(store.CacheKeyGoogleTasks)
	case "trello":
		if h.trelloClient == nil {
			http.Error(w, "trello not configured", http.StatusServiceUnavailable)
			return
		}
		c, ok := h.findCard(req.ID)
		if !ok {
			http.Error(w, "task not found", http.StatusNotFound)
			return
		}
		if err := h.trelloClient.UpdateCard(r.Context(), req.ID, map[string]interface{}{"closed": true}); err != nil {
			http.Error(w, "failed to complete task", http.StatusInternalServerError)
			return
		}
		_ = h.store.SaveCompletedTask("trello", req.ID, c.Name, c.DueDate)
		_ = h.store.DeleteCard(req.ID)
	default:
		http.Error(w, "source not completable", http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusOK)
}

// HandleWidgetAdd creates a new undated native task from the widget's quick-add sheet.
func (h *Handler) HandleWidgetAdd(w http.ResponseWriter, r *http.Request) {
	var req widgetAddRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	title := strings.TrimSpace(req.Title)
	if title == "" {
		http.Error(w, "title is required", http.StatusBadRequest)
		return
	}

	task := models.Task{
		ID:       newID(),
		Content:  title,
		Priority: 1,
	}
	if err := h.store.CreateNativeTask(task); err != nil {
		http.Error(w, "failed to create task", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}