-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
370 lines (319 loc) · 8.87 KB
/
main.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
366
367
368
369
370
package main
/* Refactoring needed: */
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
_ "log"
"net/http"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"golang.org/x/net/websocket"
"github.com/frenchdev/caltrain-slack/model"
"github.com/gocraft/web"
"os"
_ "golang.org/x/net/websocket"
)
//Context context
type Context struct {
HelloCount int
}
//StopDir stop dir
type StopDir struct {
StopName string
Direction string
}
type NextTrain struct {
Direction string
StopName string
Next string
}
var _MapStopByID *map[int]model.Stop
var _MapStopIDByName *map[string]int
var _MapTimesByIDWeekDay *map[int][]string
var _MapTimesByIDWeekEnd *map[int][]string
func cleanJSON() {
cmd := exec.Command("python $HOME/go/src/caltrain-slack/python/jsonCleaner.py")
//cmd := exec.Command("cd $GOPATH")
fmt.Println(cmd.Run())
}
// These two structures represent the response of the Slack API rtm.start.
// Only some fields are included. The rest are ignored by json.Unmarshal.
type responseRtmStart struct {
Ok bool `json:"ok"`
Error string `json:"error"`
Url string `json:"url"`
Self responseSelf `json:"self"`
}
type responseSelf struct {
Id string `json:"id"`
}
// slackStart does a rtm.start, and returns a websocket URL and user ID. The
// websocket URL can be used to initiate an RTM session.
func slackStart(token string) (wsurl, id string, err error) {
url := fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", token)
resp, err := http.Get(url)
if err != nil {
return
}
if resp.StatusCode != 200 {
err = fmt.Errorf("API request failed with code %d", resp.StatusCode)
return
}
body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return
}
var respObj responseRtmStart
err = json.Unmarshal(body, &respObj)
if err != nil {
return
}
if !respObj.Ok {
err = fmt.Errorf("Slack error: %s", respObj.Error)
return
}
wsurl = respObj.Url
id = respObj.Self.Id
return
}
// These are the messages read off and written into the websocket. Since this
// struct serves as both read and write, we include the "Id" field which is
// required only for writing.
type Message struct {
Id uint64 `json:"id"`
Type string `json:"type"`
Channel string `json:"channel"`
Text string `json:"text"`
}
func getMessage(ws *websocket.Conn) (m Message, err error) {
err = websocket.JSON.Receive(ws, &m)
return
}
var counter uint64
func postMessage(ws *websocket.Conn, m Message) error {
m.Id = atomic.AddUint64(&counter, 1)
return websocket.JSON.Send(ws, m)
}
// Starts a websocket-based Real Time API session and return the websocket
// and the ID of the (bot-)user whom the token belongs to.
func slackConnect(token string) (*websocket.Conn, string) {
wsurl, id, err := slackStart(token)
if err != nil {
log.Fatal(err)
}
ws, err := websocket.Dial(wsurl, "", "https://api.slack.com/")
if err != nil {
log.Fatal(err)
}
return ws, id
}
func main() {
//port := os.Getenv("PORT")
//
//if port == "" {
// //log.Fatal("$PORT must be set")
// // for testing
// port = "5001"
//}
token := ""
if len(os.Args) > 1 {
token = os.Args[1]
} else {
fmt.Println("Error no token")
os.Exit(4)
}
//cleanJson()
_MapStopByID = getStops("./gtfs/stops.json")
_MapStopIDByName = setMapStopIDByName(_MapStopByID)
_MapTimesByIDWeekDay, _MapTimesByIDWeekEnd = setMapTimesByID(getStoptimes("./gtfs/stoptimes.json"))
// start a websocket-based Real Time API session
ws, id := slackConnect(token)
fmt.Println("caltrainbot ready, ^C exits")
for {
// read each incoming message
m, err := getMessage(ws)
if err != nil {
log.Fatal(err)
}
// see if we're mentioned
if m.Type == "message" && strings.HasPrefix(m.Text, "<@"+id+">") {
// if so try to parse if
parts := strings.Fields(m.Text)
fmt.Println(parts)
if len(parts) >= 4 && parts[1] == "next" {
// looks good, get the quote and reply with the result
go func(m Message) {
m.Text = SearchNext(parts[2], strings.Join(parts[3:], " "))
postMessage(ws, m)
}(m)
// NOTE: the Message object is copied, this is intentional
} else {
// huh?
m.Text = fmt.Sprintf("sorry, that does not compute\n")
postMessage(ws, m)
}
}
}
//router := web.New(Context{}).
// Middleware(web.LoggerMiddleware).
// NotFound((*Context).NotFound).
// Get("/next/:direction/:stop_name", (*Context).FindStop).
// Get("/stop/:id", (*Context).GetStopDetails)
//if os.Getenv("GO_STAGE_NAME") != "prod" {
// router.Middleware(web.ShowErrorsMiddleware)
//}
//http.ListenAndServe(":"+port, router)
}
func (c *Context) notFound(rw web.ResponseWriter, r *web.Request) {
rw.WriteHeader(http.StatusNotFound)
fmt.Fprintf(rw, "Not Found")
}
func (c *Context) findStop(rw web.ResponseWriter, req *web.Request) {
direction := req.PathParams["direction"]
if direction != "NB" && direction != "SB" {
rw.WriteHeader(http.StatusBadRequest)
}
stopName := req.PathParams["stop_name"]
if stopName == "" {
rw.WriteHeader(http.StatusBadRequest)
}
fmt.Fprint(rw, SearchNext(direction, stopName))
}
func SearchNext(dir string, stop string) string {
hr, min, sec := time.Now().Clock()
stringTime := strconv.Itoa(hr) + ":" + strconv.Itoa(min) + ":" + strconv.Itoa(sec)
stopDir := dir + "_" + stop
stopID := (*_MapStopIDByName)[stopDir]
var nextTrains []string
if time.Now().Weekday() == time.Saturday || time.Now().Weekday() == time.Sunday {
nextTrains = (*_MapTimesByIDWeekEnd)[stopID]
} else {
nextTrains = (*_MapTimesByIDWeekDay)[stopID]
}
if nextTrains != nil && len(nextTrains) > 0 {
idx := findTimeIdx(&stringTime, &nextTrains)
if idx == -1 {
idx = len(nextTrains) - 1
}
if len(nextTrains) > idx+3 {
nextTrains = nextTrains[idx : idx+3]
} else if len(nextTrains) > idx { // should be a else only
nextTrains = nextTrains[idx:]
}
var _nextTrains []NextTrain
for _, h := range nextTrains {
next := NextTrain{Direction: dir, StopName: stop, Next: h}
_nextTrains = append(_nextTrains, next)
}
b, _ := json.Marshal(_nextTrains)
return string(b)
} else {
return "{}"
}
}
func getStops(stopsFilePath string) *map[int]model.Stop {
stopsFilePath, _ = filepath.Abs(stopsFilePath)
stopsFile, err := ioutil.ReadFile(stopsFilePath)
if err != nil {
fmt.Println("opening stops file: ", err)
}
var stops []model.Stop
err = json.Unmarshal(stopsFile, &stops)
if err != nil {
fmt.Println("error:", err)
}
stopMap := make(map[int]model.Stop)
for _, stop := range stops {
stopMap[stop.StopID] = stop
}
return &stopMap
}
func getStoptimes(stoptimesFilePath string) *[]model.StopTime {
stoptimesFilePath, _ = filepath.Abs(stoptimesFilePath)
stoptimesFile, err := ioutil.ReadFile(stoptimesFilePath)
if err != nil {
fmt.Println("opening stops file: ", err)
}
var stoptimes []model.StopTime
err = json.Unmarshal(stoptimesFile, &stoptimes)
if err != nil {
fmt.Println("error:", err)
}
return &stoptimes
}
// to translate request from Stop name to Stop ID
func setMapStopIDByName(stops *map[int]model.Stop) *map[string]int {
stopIDByName := make(map[string]int)
for k, v := range *stops {
if v.PlatformCode == "NB" {
_StopDir := "NB_" + v.StopName
stopIDByName[_StopDir] = k
} else {
_StopDir := "SB_" + v.StopName
stopIDByName[_StopDir] = k
}
}
return &stopIDByName
}
func setMapTimesByID(stopTimes *[]model.StopTime) (*map[int][]string, *map[int][]string) {
timesByIDWeekDay := make(map[int][]string)
timesByIDWeekEnd := make(map[int][]string)
var _emptyList []string
// init map
for k, _ := range *_MapStopByID {
timesByIDWeekDay[k] = _emptyList
timesByIDWeekEnd[k] = _emptyList
}
for _, stopTime := range *stopTimes {
if strings.HasPrefix(stopTime.TripID, "8") || strings.HasPrefix(stopTime.TripID, "4") {
if _, ok := timesByIDWeekEnd[stopTime.StopID]; ok {
timesByIDWeekEnd[stopTime.StopID] = append(timesByIDWeekEnd[stopTime.StopID], stopTime.DepartureTime)
}
} else {
if _, ok := timesByIDWeekDay[stopTime.StopID]; ok {
timesByIDWeekDay[stopTime.StopID] = append(timesByIDWeekDay[stopTime.StopID], stopTime.DepartureTime)
}
}
}
for _, v := range timesByIDWeekDay {
sort.Strings(v)
}
for _, v := range timesByIDWeekEnd {
sort.Strings(v)
}
return ×ByIDWeekDay, ×ByIDWeekEnd
}
func findTimeIdx(time *string, times *[]string) int {
return sort.Search(len(*times), func(i int) bool { return (*times)[i] >= *time })
}
func (c *Context) GetStopDetails(rw web.ResponseWriter, req *web.Request) {
_id := req.PathParams["id"]
if _id == "" {
rw.WriteHeader(http.StatusBadRequest)
return
}
id, err := strconv.Atoi(_id)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
fmt.Println("error:", err)
}
if v, ok := (*_MapStopByID)[id]; ok {
b, err := json.Marshal(v)
if err != nil {
rw.WriteHeader(http.StatusMethodNotAllowed)
fmt.Println("error:", err)
return
}
fmt.Fprint(rw, string(b))
} else {
rw.WriteHeader(http.StatusNotFound)
}
}