-
Notifications
You must be signed in to change notification settings - Fork 12
/
app.js
203 lines (167 loc) · 5.45 KB
/
app.js
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
var express = require('express'),
bodyParser = require('body-parser'),
fs = require('fs'),
Trips = require('./api/trips'),
mongo = require('mongodb'),
gtfs = require('./gtfs'),
request = require('request'),
moment = require('moment');
var mongoUri = process.env.MONGOLAB_URI || 'mongodb://localhost/mtamdbustrack';
fs.readFile(__dirname + '/data/routes.txt', {
encoding: 'UTF-8'
}, function read(err, data) {
if (err) {
console.log('Could not load route file', err);
return;
}
// low brow CSV parsing
var routes = [],
dataRows = data.split('\n');
dataRows.forEach(function(row) {
var rowData = row.split(',');
if (parseInt(rowData[0],10) !== NaN) {
routes.push({
lineDirId: rowData[0] + '0',
number: rowData[2],
name: rowData[3]
});
routes.push({
lineDirId: rowData[0] + '1',
number: rowData[2],
name: rowData[3]
});
}
});
mongo.Db.connect(mongoUri, {
auto_reconnect: true
}, function(err, db) {
if (err) throw err;
console.log("Connected to database");
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(process.env.PORT || 5000, function() {
var port = server.address().port;
console.log("Node app listening on port " + port + "...");
});
app.get('/vehicles', function(req, res) {
var trips = new Trips({
allRoutes: routes,
db: db,
cacheLatency: 30
});
trips.getCurrent(req, res);
});
app.get('/save', function(req, res) {
var trips = new Trips({
allRoutes: routes,
db: db,
cacheLatency: 30
});
trips.logData(req, res);
});
app.get('/history', function(req, res) {
var trips = new Trips({
allRoutes: routes,
db: db,
cacheLatency: 30
});
trips.getGlobalHistory(req,res);
});
app.get('/history/:route_id', function(req, res) {
var trips = new Trips({
allRoutes: routes,
db: db,
cacheLatency: 30
});
trips.getHistory(req,res);
});
//export from realtime logs for a given route
app.get('/export/:route_id', function(req, res) {
var trips = new Trips({
allRoutes: routes,
db: db,
cacheLatency: 30
});
trips.export(req,res);
});
//proxy API for getBusTimes
app.get('/stoptimes/:stop_id', function(req, res) {
getStopTimes(req,res);
});
function getStopTimes(req,res) {
console.log(req.params);
//build a payload to POST
var payload = {
"version":"1.1",
"method":"GetBusTimes",
"params":{
"stopId":req.params.stop_id,
"Radius":-1,
"NumTimesPerLine":5,
"NumStopTimes":20
}
}
//POST it
request.post({
headers: {
'content-type': 'application/json'
},
url: 'http://realtimemap.mta.maryland.gov/InfoWeb',
body: JSON.stringify(payload)
}, function(error, response, body) {
console.log(body);
body = JSON.parse(body);
if(body.result[0].StopTimeResult[0].StopTimes) { //TODO figure out how to validate the response, this keeps crashing
var stops = body.result[0].StopTimeResult[0].StopTimes;
var cleanStops = [];
//clean up the stops data
stops.forEach(function(stop){
var newStop = {
'route_number': stop.LineAbbr,
'route_name': stop.LineName,
'direction_name': stop.DirectionName,
'route_id': parseInt(stop.LineDirId.toString().slice(0,-1)),
'stop_time': moment().zone(300).startOf('day').add(stop.ETime,'seconds').format(), //if between midnight and 4:59 am, need to roll back to previous day's start?
'realtime' : realTimeStatus(stop)
}
cleanStops.push(newStop);
});
//build a new object to response, stops data from above is a child object
var stopInfo = {
'stop_id': req.params.stop_id,
'stop_name': body.result[0].StopTimeResult[0].Lines[0].StopName,
'stop_times': cleanStops,
'timestamp': moment().format()
}
res.json(stopInfo);
//This is some trickery to figure out whether there is real-time data available
//it compares the stops from stopTimes[] with those in RealTimeResults[]
//Basically mimicking the technique used by the vendor in
//http://realtimemap.mta.maryland.gov/file/apps/fixedroute/customerinfo/javascript/info_realtime.js line 623
function realTimeStatus(stop) {
var realTimeStops = body.result[0].RealTimeResults;
for (var i=0; i<realTimeStops.length; i++) {
var s = stop;
var r = realTimeStops[i];
if((s.TripId == r.TripId) && (s.BlockId == r.BlockId) && (r.Lat != 0 && r.Lon != 0) && !r.IgnoreAdherence) {
return true
}
}
return false;
}
} else {
res.send('no buses for this stop ');
}
});
}
});
});