-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-trigger-prompt.go
86 lines (72 loc) · 1.89 KB
/
api-trigger-prompt.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
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/reeveci/reeve-lib/schema"
)
type PromptRequest struct {
Name string `json:"name"`
Value string `json:"value"`
}
func HandleTriggerPrompt(p *WebUIPlugin) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
id := vars["id"]
if id == "" {
http.Error(res, "missing prompt ID path parameter", http.StatusBadRequest)
return
}
p.Env.Lock()
prompt, ok := p.Env.Prompts[id]
var message schema.Message
var nameOption string
var valueOption string
if ok {
message = prompt.Message
nameOption = prompt.NameOption
valueOption = prompt.ValueOption
}
p.Env.Unlock()
if !ok {
http.Error(res, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
if nameOption == "" {
nameOption = "name"
}
if valueOption == "" {
valueOption = "value"
}
if req.Header.Get("Content-type") != "application/json" {
http.Error(res, "Content-Type header is not application/json", http.StatusUnsupportedMediaType)
return
}
var request PromptRequest
decoder := json.NewDecoder(req.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&request)
if err != nil {
http.Error(res, fmt.Sprintf("invalid request body - %s", err), http.StatusBadRequest)
return
}
if request.Name == "" {
http.Error(res, "missing name", http.StatusBadRequest)
return
}
options := make(map[string]string, len(message.Options)+2)
for key, value := range message.Options {
options[key] = value
}
options[nameOption] = request.Name
options[valueOption] = request.Value
message.Options = options
err = p.API.NotifyMessages([]schema.Message{message})
if err != nil {
http.Error(res, "sending prompt message failed", http.StatusInternalServerError)
return
}
res.WriteHeader(http.StatusAccepted)
}
}