summaryrefslogtreecommitdiff
path: root/internal/handlers/widget.go
blob: 6c3b455cacc6124577c71eb927d73ae2174c6f53 (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
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,
		URL:      item.URL,
	}

	switch item.Type {
	case models.TimelineItemTypeEvent:
		wi.Type = "event"
	case models.TimelineItemTypeMeal:
		wi.Type = "event"
	case models.TimelineItemTypeCard, models.TimelineItemTypeGTask:
		wi.Type = "task"
		// not completable via widget API
	default:
		wi.Type = "task"
		wi.Completable = item.Source == "doot"
	}

	// Only populate Start/End for items with a real time (non-all-day, non-zero)
	if !item.IsAllDay && !item.Time.IsZero() {
		t := item.Time
		wi.Start = &t
		if item.EndTime != nil {
			wi.End = item.EndTime
		} else {
			end := item.Time.Add(time.Hour)
			wi.End = &end
		}
	}

	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 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)
}

// 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)
	default:
		http.Error(w, "source not completable", http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusOK)
}