forked from npaton/gogtfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gtfsd.go
311 lines (264 loc) · 6.96 KB
/
gtfsd.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
package main
// import _ "http/pprof"
import (
"code.google.com/p/go.net/websocket"
"encoding/json"
"flag"
"fmt"
"github.com/nicolaspaton/gogtfs"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
var (
pathsString = flag.String("d", "", "Directories containing gtfs txt or zip files or zip file path (directories are traversed, multi coma separated: \"/here,/there\")")
shouldLog = flag.Bool("v", false, "Log to Stdout/err")
needHelp = flag.Bool("h", false, "Displays this help message...")
listenAddr = flag.String("http", ":8080", "HTTP listen address")
prefPath string
homeDir string
feeds map[string]*gtfs.Feed
)
func init() {
homeDir = os.Getenv("HOME")
flag.StringVar(&prefPath, "p", homeDir+"/.gtfs", "Preference file path")
feeds = make(map[string]*gtfs.Feed, 10)
}
type Preferences struct {
Paths []string
}
func (p *Preferences) saveToDisk() {
}
func discoverGtfsPaths(path string) (results []string) {
// log.Println("discoverGtfsPaths")
path = filepath.Clean(path)
fileInfo, err := os.Lstat(path)
if err != nil {
return
}
if fileInfo.IsDir() {
file, err := os.Open(path)
if err != nil {
return
}
defer file.Close()
fileInfos, err := file.Readdir(-1)
if err != nil {
return
}
requiredFiles := gtfs.RequiredFiles
requiredCalendarFiles := gtfs.RequiredEitherCalendarFiles
foundCalendar := false
foundFiles := make([]string, 0, len(requiredFiles))
for _, fi := range fileInfos {
name := fi.Name()
if fi.IsDir() {
subdirectoryResults := discoverGtfsPaths(path + "/" + name)
for _, newpath := range subdirectoryResults {
results = append(results, newpath)
}
} else if filepath.Ext(name) == ".zip" {
results = append(results, path+"/"+name)
} else {
for _, f := range requiredFiles {
if name == f { // This loops a little too much but hey...
foundFiles = append(foundFiles, f)
}
}
if !foundCalendar {
for _, f := range requiredCalendarFiles {
if name == f {
foundCalendar = true
}
}
}
}
}
if len(foundFiles) == len(requiredFiles) && foundCalendar {
results = append(results, path)
}
} else {
if filepath.Ext(path) == ".zip" {
results = append(results, path)
}
}
return
}
func main() {
flag.Parse()
if *needHelp {
flag.Usage()
os.Exit(0)
}
pathsAll := strings.Split(*pathsString, ",")
paths := make([]string, 0, len(pathsAll))
for _, path := range pathsAll {
if path != "" {
// Why do I have to do this
path = strings.Replace(path, "~", homeDir, 1)
newpaths := discoverGtfsPaths(path)
// log.Println("Paths", len(newpaths), newpaths)
if len(newpaths) > 0 {
for _, p := range newpaths {
paths = append(paths, p)
}
}
}
}
log.Println("Paths", paths)
if !*shouldLog {
devNull, _ := os.OpenFile(os.DevNull, os.O_WRONLY, 0) // Shouldn't be an error
defer devNull.Close() // Useless, is it not?
log.SetOutput(devNull)
}
log.SetPrefix("gtfs - ")
channels := make([]chan bool, 0, len(paths))
totalStopTimes := 0
if len(paths) > 0 {
for _, path := range paths[:] {
if path != "" {
channel := make(chan bool)
channels = append(channels, channel)
go func(path string, ch chan bool) {
log.Println("Started loading", path)
feed, err := gtfs.NewFeed(path)
if err != nil {
log.Fatal(err)
} else {
feed.Load()
feeds[path] = feed
currentFeed = path
}
totalStopTimes = totalStopTimes + feed.StopTimesCount
channel <- true
}(path, channel)
}
}
}
if *listenAddr != "-" {
go func() {
// Waiting for jobs to finnish
for _, c := range channels {
<-c
}
log.Println("Total StopTimes count", totalStopTimes)
log.Println("Finished")
}()
http.HandleFunc("/", Index)
http.HandleFunc("/shapes.json", Shapes)
http.HandleFunc("/trips.json", Trips)
http.Handle("/gtfs", websocket.Handler(GTFSSocket))
http.HandleFunc("/load", LoadFeed)
httpInitErr := http.ListenAndServe(*listenAddr, nil)
if httpInitErr != nil {
log.Printf("HTTP init error: %v\n", httpInitErr)
}
} else {
// Waiting for jobs to finnish
for _, c := range channels {
<-c
}
}
}
var currentFeed string
func Index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "web/index.html")
}
func Shapes(w http.ResponseWriter, r *http.Request) {
log.Println("Shapes")
if currentFeed == "" {
fmt.Fprint(w, "{}")
return
}
shapes, err := json.Marshal(feeds[currentFeed].Shapes)
if err != nil {
panic(err)
}
fmt.Fprint(w, string(shapes))
log.Println("Shapes done")
return
}
func Trips(w http.ResponseWriter, r *http.Request) {
log.Println("Trips")
if currentFeed == "" {
fmt.Fprint(w, "{}")
return
}
now := time.Now().Local()
ts := feeds[currentFeed].TripsForDay(&now)
trips, err := json.Marshal(ts)
if err != nil {
panic(err)
}
fmt.Fprint(w, string(trips))
log.Println("Trips done")
return
}
func LoadFeed(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println("Form Parse Error!?", err)
return
}
if feeds[r.Form["feed"][0]] == nil {
fmt.Fprintf(w, "{\"error\":\"Error loading %v (not found)\"}", r.Form["feed"][0])
return
}
feeds[r.Form["feed"][0]].Load()
fmt.Fprintf(w, "{\"success\":\"Loading %v...\"}", r.Form["feed"][0])
return // http.Redirect(w, r, r.Referer, http.StatusTemporaryRedirect) // Come back
}
type WebSocketContext struct {
ws *websocket.Conn
inMessages chan string
outMessages chan string
closeCh chan bool
}
// Echo the data received on the Web Socket.
func GTFSSocket(ws *websocket.Conn) {
ctx := WebSocketContext{ws, make(chan string), make(chan string), make(chan bool)}
ctx.Handle()
}
func (ctx *WebSocketContext) Handle() {
go func() {
for {
select {
case in := <-ctx.inMessages:
log.Println("In Message", in, len(in))
case out := <-ctx.outMessages:
outb := []uint8(out)
// log.Println("Out Message", outb, "ASSTRING:", out)
if _, err := ctx.ws.Write(outb); err != nil {
log.Println("W", err)
ctx.closeCh <- true
}
case <-ctx.closeCh:
log.Println("Closed connection")
ctx.ws.Close()
break
}
}
}()
go func() {
time.Sleep(5 * 1E9)
ctx.outMessages <- "Hello"
// time.Sleep(1*1E9)
// ctx.outMessages <- "How are you"
// time.Sleep(1*1E9)
// ctx.outMessages <- "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}()
for {
buf := make([]byte, 256)
n, err := ctx.ws.Read(buf)
if err != nil {
log.Println(err)
ctx.closeCh <- true
break
} else {
ctx.inMessages <- string(buf[0:n])
}
}
}