-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
241 lines (197 loc) · 5.79 KB
/
http.go
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
package tiny
import (
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/meyskens/m-planner/pkg/commands/calendar"
"github.com/meyskens/m-planner/pkg/db"
"gorm.io/gorm/clause"
)
// The Tiny API gives small data back, meant to be used in microcontrollers
type HTTPHandler struct {
db *db.Connection
}
func NewHTTPHandler() *HTTPHandler {
return &HTTPHandler{}
}
func (h *HTTPHandler) Register(e *echo.Echo, dbConn *db.Connection) {
h.db = dbConn
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !strings.HasPrefix(c.Path(), "/tiny/") {
return next(c)
}
token := c.Request().Header.Get("Authorization")
if token == "" {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "did not get a valid token"})
}
dbToken := db.ApiToken{}
if err := dbConn.Where("token = ?", token).First(&dbToken).Error; err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "did not get a valid token"})
}
c.Set("user", dbToken.User)
if dbToken.User == "" {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "did not get a valid token"})
}
return next(c)
}
})
e.GET("/tiny/tasks", h.getTasks)
e.GET("/tiny/calendar", h.getCalendar)
e.GET("/tiny/ideas/:channel", h.getIdeas)
e.GET("/tiny/printjobs", h.getPrintjobs)
}
type TinyTask struct {
Name string `json:"name"`
Time string `json:"time"`
IsInAlert bool `json:"isInAlert"`
}
func (h *HTTPHandler) getTasks(c echo.Context) error {
loc, _ := time.LoadLocation("Europe/Brussels")
user := c.Get("user").(string)
plans := []db.Plan{}
if err := h.db.Where(&db.Plan{
User: user,
}).Find(&plans).Error; err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "could not get plans"})
}
dailys := []db.Daily{}
if err := h.db.Preload(clause.Associations).Where(&db.Daily{
User: user,
}).Find(&dailys).Error; err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "could not get dailys"})
}
tasks := []TinyTask{}
for _, plan := range plans {
// if starts today and is in the future add it
if plan.Start.After(time.Now().Truncate(24*time.Hour)) && plan.Start.Before(time.Now().Truncate(24*time.Hour).Add(time.Hour*24)) {
tasks = append(tasks, TinyTask{
Name: plan.Description,
Time: plan.Start.In(loc).Format("15:04"),
IsInAlert: !plan.SnoozedTill.IsZero(),
})
}
}
for _, daily := range dailys {
// if starts today and is in the future add it
for _, reminder := range daily.Reminders {
reminders := []db.DailyReminderEvent{}
h.db.Where(&db.DailyReminderEvent{
DailyID: daily.ID,
}).Find(&reminders)
if reminder.Weekday != getCurrentDay() {
continue
}
if reminder.Hour >= time.Now().In(loc).Hour() || len(reminders) > 0 {
if reminder.Hour == time.Now().In(loc).Hour() && reminder.Minute < time.Now().In(loc).Minute() && len(reminders) == 0 {
continue
}
tasks = append(tasks, TinyTask{
Name: daily.Description,
Time: fmt.Sprintf("%02d:%02d", reminder.Hour, reminder.Minute),
IsInAlert: len(reminders) > 0,
})
}
}
}
sort.Slice(tasks, func(i, j int) bool {
return tasks[i].Time < tasks[j].Time
})
// limit to limit parameter
limit, _ := strconv.Atoi(c.QueryParam("limit"))
if limit > 0 && len(tasks) > limit {
tasks = tasks[:limit]
}
return c.JSON(http.StatusOK, tasks)
}
func getCurrentDay() time.Weekday {
loc, _ := time.LoadLocation("Europe/Brussels")
now := time.Now().In(loc)
currentDay := now.Weekday()
// correct to use monday or saturday
switch currentDay {
case time.Saturday:
fallthrough
case time.Sunday:
currentDay = time.Saturday
default:
currentDay = time.Monday
}
return currentDay
}
type TinyCalendarEvent struct {
Name string `json:"name"`
Start string `json:"start"`
Location string `json:"location"`
}
func (h *HTTPHandler) getCalendar(c echo.Context) error {
cals := []db.Calendar{}
if err := h.db.Preload(clause.Associations).Where(&db.Calendar{
User: c.Get("user").(string),
}).Find(&cals).Error; err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "could not get calendars"})
}
e := []TinyCalendarEvent{}
for _, cal := range cals {
events, err := calendar.ParseSchedule(cal.Link)
if err != nil {
continue
}
for _, event := range events {
e = append(e, TinyCalendarEvent{
Name: event.Name,
Start: event.Start.Format("15:04"),
Location: event.Location,
})
}
}
sort.Slice(e, func(i, j int) bool {
return e[i].Start < e[j].Start
})
// limit to limit parameter
limit, _ := strconv.Atoi(c.QueryParam("limit"))
if limit > 0 && len(e) > limit {
e = e[:limit]
}
return c.JSON(http.StatusOK, e)
}
type TinyIdea struct {
Name string `json:"name"`
}
func (h *HTTPHandler) getIdeas(c echo.Context) error {
ideas := []db.Idea{}
if err := h.db.Preload(clause.Associations).Where(&db.Idea{
User: c.Get("user").(string),
ChannelID: c.Param("channel"),
}).Find(&ideas).Error; err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "could not get ideas"})
}
i := []TinyIdea{}
for _, idea := range ideas {
i = append(i, TinyIdea{
Name: idea.Description,
})
}
// limit to limit parameter
limit, _ := strconv.Atoi(c.QueryParam("limit"))
if limit > 0 && len(i) > limit {
i = i[:limit]
}
return c.JSON(http.StatusOK, i)
}
func (h *HTTPHandler) getPrintjobs(c echo.Context) error {
pj := []db.PrintJob{}
if err := h.db.Preload(clause.Associations).Where(&db.PrintJob{
User: c.Get("user").(string),
}).Find(&pj).Error; err != nil {
return c.JSON(http.StatusBadRequest, echo.Map{"error": "could not get printjobs"})
}
for _, job := range pj {
h.db.Delete(&job) // printed so we delete them
}
return c.JSON(http.StatusOK, echo.Map{"data": pj})
}