/
api.go
186 lines (152 loc) · 4.68 KB
/
api.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
package http
import (
"bytes"
"fmt"
"net/http"
"text/template"
"github.com/VagabondDataNinjas/gizlinebot/domain"
logrusmiddleware "github.com/andreiashu/echo-logrusmiddleware"
log "github.com/sirupsen/logrus"
"github.com/line/line-bot-sdk-go/linebot"
"github.com/VagabondDataNinjas/gizlinebot/storage"
"github.com/VagabondDataNinjas/gizlinebot/survey"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
type ApiConf struct {
Port int
// hostname where the API is hosted
GlobalVars *domain.GlobalTplVars
}
type Api struct {
Storage *storage.Sql
LineBot *linebot.Client
Surv *survey.Survey
Conf *ApiConf
}
func NewApi(s *storage.Sql, lb *linebot.Client, surv *survey.Survey, conf *ApiConf) *Api {
return &Api{
Storage: s,
LineBot: lb,
Surv: surv,
Conf: conf,
}
}
// cache-busting middleware
func NoCacheMW(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
return next(c)
}
}
func (a *Api) Serve() error {
e := echo.New()
// Middleware
e.Logger = logrusmiddleware.Logger{log.StandardLogger()}
e.Use(logrusmiddleware.Hook())
e.Use(middleware.Recover())
// CORS default
// Allows requests from any origin wth GET, HEAD, PUT, POST or DELETE method.
e.Use(middleware.CORS())
qs, err := a.Storage.GetQuestions()
if err != nil {
return err
}
e.POST("/linewebhook", LineWebhookHandlerBuilder(a.Surv, a.Storage, a.LineBot, a.Conf.GlobalVars))
e.GET("/api/webform/questions", func(c echo.Context) error {
return c.JSON(http.StatusOK, qs)
})
e.Group("/", NoCacheMW).Static("", "../gizsurvey/build")
e.Group("/admin", NoCacheMW).Static("", "../gizsurvey/build")
e.Group("/admin/login", NoCacheMW).Static("", "../gizsurvey/build")
e.Group("/admin/map", NoCacheMW).Static("", "../gizsurvey/build")
e.Group("/static", NoCacheMW).Static("", "../gizsurvey/build/static")
e.Group("/media", NoCacheMW).Static("", "../media")
// lineimgs/groots.png/700
e.GET("/lineimgs/:filename", LineImgHandler(), NoCacheMW)
e.GET("/lineimgs/:filename/:size", LineImgHandler(), NoCacheMW)
e.GET("/api/islands", IslandsHandler(a.Storage), NoCacheMW)
e.POST("/api/webform/answer", AnswerHandlerBuilder(a.Storage, a.LineBot))
e.POST("/api/webform/answer-gps", AnswerGpsHandlerBuilder(a.Storage))
e.POST("/api/login", loginHandler(a.Storage), NoCacheMW)
r := e.Group("/api/admin")
jwtSecret, err := a.Storage.GetConfigVal("jwtSecret")
if err != nil {
return err
}
jwtConfigCookieAuth := middleware.DefaultJWTConfig
jwtConfigCookieAuth.TokenLookup = "cookie:token"
jwtConfigCookieAuth.SigningKey = []byte(jwtSecret)
r.Use(middleware.JWTWithConfig(jwtConfigCookieAuth))
r.POST("/send-msg", SendLineMsgHandlerBuilder(a.Storage, a.LineBot))
r.POST("/send/custom/question", SendLineCustomQuestionHandlerBuilder(a.Storage, a.LineBot))
r.GET("/location-prices", LocationPricesHandlerBuilder(a.Storage))
r.GET("/download/lineevents.csv", LineEventsDownloadHandlerBuilder(a.Storage), NoCacheMW)
r.GET("/user/wipe/:userid", WipeUserHandlerBuilder(a.Storage, a.LineBot), NoCacheMW)
log.Fatal(e.Start(fmt.Sprintf(":%d", a.Conf.Port)))
return nil
}
func userPriceList(userId string, s *storage.Sql) (priceList string, err error) {
lp, err := s.GetUserNearbyPrices(userId)
if err != nil {
return "", err
}
if len(lp) == 0 {
log.Warnf("No prices found for user %s", userId)
return "", nil
}
tplStr, err := s.GetPriceTplMsg()
if err != nil {
return "", err
}
tmpl, err := template.New("priceMsg").Parse(tplStr)
if err != nil {
return "", err
}
type TplVars struct {
Location string
Price float64
}
var msg string
for _, loc := range lp {
buf := new(bytes.Buffer)
tplVars := TplVars{loc.Name, loc.Price}
err = tmpl.Execute(buf, tplVars)
if err != nil {
return "", err
}
msg += buf.String()
msg += "\n"
}
return msg, nil
}
func sendPriceList(bot *linebot.Client, s *storage.Sql, userId string) error {
priceList, err := userPriceList(userId, s)
if err != nil {
return err
}
if priceList == "" {
return nil
}
if _, err = bot.PushMessage(userId, linebot.NewTextMessage(priceList)).Do(); err != nil {
return err
}
return nil
}
func sendThankYouMsg(bot *linebot.Client, s *storage.Sql, userId string) error {
questions, err := s.GetQuestions()
if err != nil {
log.Errorf("Error getting questions: %s", err)
return err
}
lastQ, err := questions.Last()
if err != nil {
log.Errorf("Error getting last question: %s", err)
return err
}
if _, err = bot.PushMessage(userId, linebot.NewTextMessage(lastQ.Text)).Do(); err != nil {
log.Errorf("Error sending last thankyou / question: %s", err)
return err
}
return nil
}