-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_ui.go
365 lines (307 loc) · 8.47 KB
/
web_ui.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
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
package main
import (
"embed"
"encoding/json"
"fmt"
"html/template"
"io/fs"
"net/http"
"os"
"strconv"
"time"
"github.com/adhocore/gronx"
"github.com/charmbracelet/log"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/slack-go/slack"
bolt "go.etcd.io/bbolt"
)
type WebToken struct {
Token string
CreatedAt time.Time
Channel string
Team string
}
type webUI struct {
tokens []WebToken
}
//go:embed static/*
var staticFiles embed.FS
//go:embed templates/*
var templateFiles embed.FS
func ServeUI() {
defer App.wg.Done()
if !App.config.Debug {
gin.SetMode(gin.ReleaseMode)
}
ui := webUI{}
App.webUI = &ui
r := gin.New()
r.Use(gin.Recovery())
r.HTMLRender = ui.newRenderer()
staticFs, err := fs.Sub(staticFiles, "static")
if err != nil {
log.Error("Cannot load static files.", "err", err)
}
r.StaticFS("/static/", http.FS(staticFs))
r.GET("/", ui.handleIndex)
r.GET("/callback/", ui.handleCallback)
g := r.Group("/:team/:channel/:token/", ui.checkToken)
g.GET("/", ui.handleQuestionList)
g.GET("/new/", ui.handleNewQuestion)
g.POST("/new/", ui.handleNewQuestionPost)
g.GET("/edit/:id/", ui.handleEditQuestion)
g.POST("/edit/:id/", ui.handleEditQuestionPost)
g.POST("/invoke/:id/", ui.handleInvokeQuestion)
err = r.Run(App.config.ListenAddress)
if err != nil {
log.Error("Error while running Web UI.", "err", err)
}
}
func (w *webUI) CreateToken(teamID, channel string) string {
token := WebToken{
Token: uuid.NewString(),
CreatedAt: time.Now(),
Team: teamID,
Channel: channel,
}
w.tokens = append(w.tokens, token)
return token.Token
}
func (w *webUI) checkToken(ctx *gin.Context) {
token := ctx.Param("token")
team := ctx.Param("team")
channel := ctx.Param("channel")
var goodTokens []WebToken
ok := false
for _, webToken := range w.tokens {
if webToken.CreatedAt.Add(1 * time.Hour).Before(time.Now()) {
continue
}
goodTokens = append(goodTokens, webToken)
if webToken.Token == token && webToken.Channel == channel && webToken.Team == team {
ok = true
}
}
if !ok {
ctx.String(http.StatusForbidden, "Invalid access token.")
ctx.Abort()
return
}
ctx.Next()
}
func (w *webUI) createTemplate(files ...string) *template.Template {
tmpl, err := template.ParseFS(templateFiles, files...)
if err != nil {
log.Error("Could not parse template.", "err", err)
os.Exit(1)
}
return tmpl
}
func (w *webUI) newRenderer() multitemplate.Renderer {
r := multitemplate.NewRenderer()
r.Add("index", w.createTemplate("templates/index.gohtml"))
r.Add("question_list", w.createTemplate("templates/base.gohtml", "templates/question_list.gohtml"))
r.Add("question_form", w.createTemplate("templates/base.gohtml", "templates/question_form.gohtml"))
return r
}
func (w *webUI) error(ctx *gin.Context, err error) {
log.Error("Error during HTTP request.", "request", ctx.Request.URL.Path, "method", ctx.Request.Method, "err", err)
ctx.String(http.StatusInternalServerError, "Server Error")
ctx.Abort()
}
func (w *webUI) render(ctx *gin.Context, template string, context gin.H) {
context["URLPrefix"] = fmt.Sprintf("/%s/%s/%s", ctx.Param("team"), ctx.Param("channel"), ctx.Param("token"))
ctx.HTML(http.StatusOK, template, context)
}
type userInfo struct {
ID string
Name string
Selected bool
}
func (w *webUI) listChannelMembers(teamID string, channel string) ([]userInfo, error) {
users, err := ListChannelMembers(teamID, channel)
if err != nil {
return nil, err
}
var userInfos []userInfo
for _, user := range users {
name, err := LoadMemberName(teamID, user)
if err != nil {
return nil, err
}
userInfos = append(userInfos, userInfo{
ID: user,
Name: name,
})
}
return userInfos, nil
}
func (w *webUI) handleQuestionList(ctx *gin.Context) {
var questions []Question
err := App.db.View(func(tx *bolt.Tx) error {
return tx.Bucket([]byte("questions")).ForEach(func(k, v []byte) error {
var q Question
err := json.Unmarshal(v, &q)
if err != nil {
return err
}
if q.Channel != ctx.Param("channel") {
return nil
}
questions = append(questions, q)
return nil
})
})
if err != nil {
w.error(ctx, fmt.Errorf("cannot load questions: %w", err))
return
}
w.render(ctx, "question_list", gin.H{"questions": questions})
}
func (w *webUI) handleNewQuestion(ctx *gin.Context) {
users, err := w.listChannelMembers(ctx.Param("team"), ctx.Param("channel"))
if err != nil {
w.error(ctx, fmt.Errorf("could not get channel members: %w", err))
return
}
w.render(ctx, "question_form", gin.H{"users": users})
}
func (w *webUI) handleIndex(ctx *gin.Context) {
w.render(ctx, "index", gin.H{})
}
type questionForm struct {
Users []string `binding:"required" form:"users"`
Message string `binding:"required" form:"message"`
Cron string `binding:"required" form:"cron"`
Active bool `form:"active"`
}
func (w *webUI) handleNewQuestionPost(ctx *gin.Context) {
var data questionForm
err := ctx.Bind(&data)
if err != nil {
ctx.String(400, "Invalid form data.")
return
}
gron := gronx.New()
valid := gron.IsValid(data.Cron)
if !valid {
ctx.String(http.StatusBadRequest, "Invalid cron expression.")
return
}
question := Question{
TeamID: ctx.Param("team"),
Channel: ctx.Param("channel"),
Message: data.Message,
Users: data.Users,
Cron: data.Cron,
CurrentInstance: "",
IsActive: data.Active,
}
err = question.Save()
if err != nil {
ctx.String(http.StatusInternalServerError, "Server Error")
return
}
ctx.Redirect(http.StatusFound, fmt.Sprintf("/%s/%s/%s/edit/%d/", ctx.Param("team"), ctx.Param("channel"), ctx.Param("token"), question.ID))
}
func (w *webUI) handleEditQuestion(ctx *gin.Context) {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
ctx.String(http.StatusNotFound, "Not found")
return
}
question, err := LoadQuestion(id)
if err != nil || question.Channel != ctx.Param("channel") {
ctx.String(http.StatusNotFound, "Not found")
return
}
users, err := w.listChannelMembers(question.TeamID, question.Channel)
if err != nil {
w.error(ctx, fmt.Errorf("could not get channel members: %w", err))
return
}
for i, user := range users {
selected := false
for _, s := range question.Users {
if user.ID == s {
selected = true
break
}
}
users[i].Selected = selected
}
w.render(ctx, "question_form", gin.H{"users": users, "question": question})
}
func (w *webUI) handleEditQuestionPost(ctx *gin.Context) {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
ctx.String(http.StatusNotFound, "Not found")
return
}
question, err := LoadQuestion(id)
if err != nil || question.Channel != ctx.Param("channel") {
ctx.String(http.StatusNotFound, "Not found")
return
}
var data questionForm
err = ctx.Bind(&data)
if err != nil {
ctx.String(400, "Invalid form data.")
return
}
gron := gronx.New()
valid := gron.IsValid(data.Cron)
if !valid {
ctx.String(http.StatusBadRequest, "Invalid cron expression.")
return
}
question.Message = data.Message
question.Users = data.Users
question.Cron = data.Cron
question.IsActive = data.Active
err = question.Save()
if err != nil {
w.error(ctx, fmt.Errorf("could not save question: %w", err))
return
}
ctx.Redirect(http.StatusFound, fmt.Sprintf("/%s/%s/%s/", ctx.Param("team"), ctx.Param("channel"), ctx.Param("token")))
}
func (w *webUI) handleInvokeQuestion(ctx *gin.Context) {
id, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
if err != nil {
ctx.String(http.StatusNotFound, "Not found")
return
}
question, err := LoadQuestion(id)
if err != nil || question.Channel != ctx.Param("channel") {
ctx.String(http.StatusNotFound, "Not found")
return
}
err = question.NewInstance()
if err != nil {
w.error(ctx, fmt.Errorf("could not invoke question: %w", err))
return
}
ctx.Redirect(http.StatusFound, fmt.Sprintf("/%s/%s/%s/", ctx.Param("team"), ctx.Param("channel"), ctx.Param("token")))
}
func (w *webUI) handleCallback(ctx *gin.Context) {
code := ctx.Query("code")
resp, err := slack.GetOAuthV2Response(&http.Client{}, App.config.SlackClientID, App.config.SlackClientSecret, code, App.config.RootURL+"/callback/")
if err != nil {
w.error(ctx, fmt.Errorf("oauth.v2.access: %w", err))
return
}
team := Team{
ID: resp.Team.ID,
Name: resp.Team.Name,
Token: resp.AccessToken,
}
team.Save()
_, ok := App.slack[team.ID]
if !ok {
go team.Connect()
}
ctx.String(200, "Slack úspešne pripojený.")
}