-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.js
More file actions
1203 lines (1052 loc) · 41.5 KB
/
Copy pathindex.js
File metadata and controls
1203 lines (1052 loc) · 41.5 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var xmlparse, // xml parser
request, // for running get requests
geohash, // geohashing lib
isTi; // boolean representing whether we're in titanium
isTi = true;
try {
// reference Ti
Ti;
} catch (e) {
// if the above threw a ReferenceError, catch it here, we're clearly
// not in titanium
isTi = false;
}
function log () {
if (isTi) ([].slice.call(arguments)).forEach(function (a) { Ti.API.debug(a); });
else console.log.call(arguments);
}
// work in Titanium hopefully
if (!isTi) {
var jsdom = require('jsdom');
xmlparse = function (data, callback) {
var doc, win;
try {
doc = jsdom.jsdom(data);
callback(null, {document: doc});
} catch (e) {
callback(e, null);
}
};
request = require('request').get;
geohash = require('./geohash');
} else {
geohash = require('/vendor/nextbusjs/geohash');
// wrapper functions around Titanium's library functions to make them
// function the same as the node libraries
xmlparse = function (data, callback) {
if (data === null) {
callback({name: "ParseError", message: "XML Parse Error"}, null);
} else {
callback(null, data);
}
};
request = function (url, callback) {
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function (e) {
var response = {
statusCode : e.source.status
};
callback(null, response, e.source.responseXML);
};
xhr.onerror = function (e) {
var response = {
statusCode : e.source.status
};
var err = new Error("nextbusjs: network error");
err.name = 'NetworkError';
err.status = e.source.status;
callback(err, response, null);
};
xhr.timeout = 6000;
xhr.open("GET", url);
xhr.timeout = 6000;
xhr.send();
};
}
/*
Class: nextbus
Allows easy querying of the Nextbus public xml feed for predictions. The
<cacheAgency> function grabs the route and stop configuration from nextbus
and caches it. This is a very large file, and as such, the process takes a
few seconds. Every time a query is run, the query string is cached
internally.
The agency cache can be retrieved with the <getAgencyCache> function; it can
then be stored or sent to a client. It can be reloaded with the
<setAgencyCache> function.
This is a commonjs module which exports a single function, 'client'. This
function constructs a nextbus client for your use.
Example:
(start code)
var nextbus = require('nextbusjs').client;
rutgers = nextbus();
rutgers.cacheAgency('rutgers', function (err) {
if (err) {
throw err;
} else {
rutgers.routePredict('a', null, function (err, data) {
// data will contain:
[ { title: 'Scott Hall',
predictions: [ '8', '19', '31', '43', '54' ] },
{ title: 'Student Activities Center',
predictions: [ '12', '23', '35', '47', '58' ] },
{ title: 'Visitor Center',
predictions: [ '3', '16', '27', '39', '51' ] },
{ title: 'Stadium',
predictions: [ '4', '17', '28', '40', '52' ] },
{ title: 'Werblin Back Entrance',
predictions: [ '6', '19', '30', '42', '54' ] },
{ title: 'Hill Center',
predictions: [ '7', '20', '31', '43', '55' ] },
{ title: 'Science Building',
predictions: [ '8', '22', '33', '45', '57' ] },
{ title: 'Library of Science',
predictions: [ '10', '23', '34', '46', '58' ] },
{ title: 'Busch Suites',
predictions: [ '1', '12', '25', '36', '48' ] },
{ title: 'Busch Campus Center',
predictions: [ '2', '13', '27', '38', '50' ] },
{ title: 'Buell Apartments',
predictions: [ '4', '15', '28', '39', '51' ] },
{ title: 'Werblin Main Entrance',
predictions: [ '5', '16', '29', '40', '52' ] },
{ title: 'Rutgers Student Center',
predictions: [ '10', '21', '34', '45', '57' ] } ]
}, 'minutes');
rutgers.stopPredict('Hill Center', null, function (err, data) {
// data will contain:
[ { direction: 'To Busch Student Center',
title: 'A',
predictions: [ '7', '20', '31', '43', '55' ] },
{ direction: 'To Busch Student Center',
title: 'B',
predictions: [ '8', '16', '22', '30', '38' ] },
{ direction: 'To Allison Road Classrooms',
title: 'C',
predictions: null },
{ direction: 'To Allison Road Classrooms',
title: 'REX B',
predictions: [ '6', '20', '23', '35', '47' ] },
{ direction: 'To Livingston Student Center',
title: 'All Campuses',
predictions: null },
{ direction: 'To Livingston Student Center',
title: 'Weekend 1',
predictions: null },
{ direction: 'To Stadium West Lot',
title: 'C',
predictions: null },
{ direction: 'To Rutgers Student Center',
title: 'H',
predictions: [ '1', '13', '24', '36', '48' ] },
{ direction: 'To College Hall',
title: 'REX B',
predictions: [ '0', '12', '24', '35', '47' ] },
{ direction: 'To Rutgers Student Center',
title: 'Weekend 2',
predictions: null } ]
}, 'minutes');
var nearest = rutgers.closestStops(40.40264, -74.3840120);
//{ 'Rutgers Student Center': 7,
// 'Student Activities Center': 6,
// 'Scott Hall': 5 }
}
});
(end)
*/
function client () {
"use strict";
var exports = {},
agencyData = {},
agency = null,
baseURL =
"http://webservices.nextbus.com/service/publicXMLFeed?command=",
isAgencyCached = false,
vehicleLastTime = null,
activeExpireTime;
/*
Group: Public Functions
Function: routePredict
Returns an array of predictions for a particular route in a particular
direction. Prediction objects contain a title and a predictions array.
Parameters:
route - *string* route to return predictions for
direction - *string* direction to return predictions for, can be null
cb - *function (err, data)* called with results
units - *string* 'minutes', 'seconds', or 'both'. Defaults to
minutes. If 'both', the return predictions will be an
object with 'minutes' and 'seconds' properties.
Returns:
Object mapping stop names to arrays of strings.
Example:
> nextbus.routePredict('a', null, callback);
(start code)
[ { title: 'Scott Hall',
predictions: [ '8', '19', '31', '43', '54' ] },
{ title: 'Student Activities Center',
predictions: [ '12', '23', '35', '47', '58' ] },
{ title: 'Visitor Center',
predictions: [ '3', '16', '27', '39', '51' ] },
{ title: 'Stadium',
predictions: [ '4', '17', '28', '40', '52' ] },
{ title: 'Werblin Back Entrance',
predictions: [ '6', '19', '30', '42', '54' ] },
{ title: 'Hill Center',
predictions: [ '7', '20', '31', '43', '55' ] },
{ title: 'Science Building',
predictions: [ '8', '22', '33', '45', '57' ] },
{ title: 'Library of Science',
predictions: [ '10', '23', '34', '46', '58' ] },
{ title: 'Busch Suites',
predictions: [ '1', '12', '25', '36', '48' ] },
{ title: 'Busch Campus Center',
predictions: [ '2', '13', '27', '38', '50' ] },
{ title: 'Buell Apartments',
predictions: [ '4', '15', '28', '39', '51' ] },
{ title: 'Werblin Main Entrance',
predictions: [ '5', '16', '29', '40', '52' ] },
{ title: 'Rutgers Student Center',
predictions: [ '10', '21', '34', '45', '57' ] } ]
(end)
*/
function routePredict (route, direction, cb, units) {
var routeData, str = '', stops;
// default to minutes
units = units || 'minutes';
if (direction === null) {
// direction is the string 'null' because its whats actually passed to
// nextbus when we do predictionsForMultiStops
direction = 'null';
}
if (!isAgencyCached) {
cb({name: "nocache", message: "no agency cache"} ,null);
return;
}
routeData = agencyData.routes[route];
if (routeData === undefined) {
cb({name: "noroute", message: "route not found"}, null);
return;
}
if (routeData.queries[direction] === undefined) {
// There's no query string, we'll have to build one.
stops = routeData.stops;
stops.forEach(function (stop) {
str += "&stops=" + route + "|" + direction + "|" + stop;
});
routeData.queries[direction] = str;
}
if (routeData.sorter === undefined) {
// This is a reverse mapping of tags to numbers that can be used
// to sort the data returned from nextbus, since this is now apparently
// necessary.
routeData.sorter = routeData.stops.reduce(function (memo, item, index) {
memo[item] = index; return memo;
}, {});
}
query("predictionsForMultiStops",
routeData.queries[direction],
function (err, response) {
var stop, ret = [], item, j, i, data, currIndex;
try {
if (err) {
throw err;
}
if (isTi) {
data = response.getElementsByTagName("predictions");
} else {
data = response.document.getElementsByTagName("predictions");
}
if (data.length === 0) {
var e = new Error('response is invalid, data.length = 0');
e.name = "ParseError";
e.detail = "zero length data";
e.data = isTi? Ti.XML.serializeToString(response) : response;
throw e;
}
for (i = 0; i < data.length; i++) {
stop = data.item(i).getAttribute(fixStr('stopTitle'));
var stopTag = data.item(i).getAttribute(fixStr('stopTag'));
// push a new object onto the return
ret.push({
title : stop,
predictions : [],
tag: stopTag
});
currIndex = ret.length - 1;
item = data.item(i).getElementsByTagName('prediction');
// in Titanium, getElementsByTagName returns undefined if there
// are no tags by that name. In node (with jsdom), it returns
// an empty nodelist.
if (item === null) {
ret[currIndex].predictions = null;
continue;
}
for (j = 0; j < item.length; j++) {
if (direction !== 'null') {
// if we were given a direction as input, but the
// prediction we're looking at isn't in that direction,
// ignore it
if (direction !== item.item(j).getAttribute(fixStr('dirTag'))) {
continue;
}
}
if (units !== 'both') {
ret[currIndex].predictions.push(
item.item(j).getAttribute(units)
);
} else {
ret[currIndex].predictions.push({
minutes: item.item(j).getAttribute('minutes'),
seconds: item.item(j).getAttribute('seconds')
});
}
}
// if there are no predictions, map the route identifier to null
// this is for jsdom. in titanium
// getElementsByTagName('prediction') will return undefined if
// there are no prediction tags.
if (ret[currIndex].predictions.length === 0) {
ret[currIndex].predictions = null;
}
}
ret = ret.sort(function (a, b) {
return routeData.sorter[a.tag] - routeData.sorter[b.tag];
});
cb(null, ret);
}
catch (e) {
cb(e, null);
return;
}
finally {
if (!isTi) {
// if we're not in titanium, we're in node, and we just used
// jsdom for parsing. If we don't call window.close(), jsdom
// will leak an enormous amount of memory.
if (response) typeof response.close == "function" && response.close();
}
}
}
);
}
/*
Function: stopPredict
Calls a callback function with an object mapping input stops to
arrays of predictions. The predictions will be strings, not Numbers,
as this data is usually intended for display as strings. If a particular
route isn't currently running, null will be returned. If no agency data
is cached, the callback function will be called with an error.
Parameters:
stop - *string* route tag or route title
direction - *string* direction tag, can be null
cb - *function (err, data)* callback function
units - *string* 'minutes', 'seconds', or 'both'. Defaults to
minutes. If 'both', the return predictions will be an
object with 'minutes' and 'seconds' properties.
Example:
> nextbus.stopPredict('Hill Center', null, callback);
Will provide callback with an object resembling
(start code)
[ { direction: 'To Busch Student Center',
title: 'A',
predictions: [ '7', '20', '31', '43', '55' ] },
{ direction: 'To Busch Student Center',
title: 'B',
predictions: [ '8', '16', '22', '30', '38' ] },
{ direction: 'To Allison Road Classrooms',
title: 'C',
predictions: null },
{ direction: 'To Allison Road Classrooms',
title: 'REX B',
predictions: [ '6', '20', '23', '35', '47' ] },
{ direction: 'To Livingston Student Center',
title: 'All Campuses',
predictions: null },
{ direction: 'To Livingston Student Center',
title: 'Weekend 1',
predictions: null },
{ direction: 'To Stadium West Lot',
title: 'C',
predictions: null },
{ direction: 'To Rutgers Student Center',
title: 'H',
predictions: [ '1', '13', '24', '36', '48' ] },
{ direction: 'To College Hall',
title: 'REX B',
predictions: [ '0', '12', '24', '35', '47' ] },
{ direction: 'To Rutgers Student Center',
title: 'Weekend 2',
predictions: null } ]
(end)
*/
function stopPredict (stop, direction, cb, units) {
var tags = [], str = '', queryprops = {}, stopData, inputType = '';
units = units || 'minutes';
if (direction === null) {
direction = 'null';
}
if (!isAgencyCached) {
cb({name: "nocache", message: "no agency cache"}, null);
return;
}
if (agencyData.stops[stop] !== undefined) {
stopData = agencyData.stops[stop];
inputType = 'tag';
// We mark the input type so that we can return using the same
// format.
} else if (agencyData.stopsByTitle &&
agencyData.stopsByTitle[stop] !== undefined) {
stopData = agencyData.stopsByTitle[stop];
inputType = 'title';
} else {
cb(new Error('stop not found'), null);
return;
}
if (stopData.queries[direction] === undefined) {
// Well, there's no query string, so we'll have to make one.
if (inputType === 'title') {
tags = stopData.tags;
} else {
tags = [stop];
}
tags.forEach(function (tag) {
var routes = agencyData.stops[tag].routes;
routes.forEach(function (route) {
// now tag contains a stoptag and route contains a routetag
// combine them and add to query string
str += "&stops=" + route + "|" + direction + "|" + tag;
});
});
stopData.queries[direction] = str;
}
query("predictionsForMultiStops",
stopData.queries[direction], function (err, response) {
var i, j, item, prediction, ret = [], route, data, currIndex,
currDirection, currDirectionNodes;
try {
if (err) {
throw err;
}
if (isTi) {
data = response.getElementsByTagName("predictions");
} else {
data = response.document.getElementsByTagName("predictions");
}
if (data.length === 0) {
var e = new Error('response is invalid');
e.name = "ParseError";
e.detail = "zero length data";
throw e;
}
for (i = 0; i < data.length; i++) {
// getAttribute input type may get the title, if the user gave
// us a title to lookup
route = data.item(i).getAttribute(fixStr('routeTitle'));
currDirectionNodes = data.item(i).getElementsByTagName('direction');
currDirection = null;
// currDirectionNodes will be null in Titanium if there are no
// direction nodes, in jsdom it will have length 0
if (currDirectionNodes === null) {
// correct titanium error in dom implementation
currDirectionNodes = {length: 0};
}
if (currDirectionNodes.length !== 0) {
currDirection = currDirectionNodes.item(0)
.getAttribute('title');
} else {
currDirection = data.item(i)
.getAttribute(fixStr('dirTitleBecauseNoPrediction'));
}
ret.push({
direction : currDirection,
title : route,
predictions : []
});
currIndex = ret.length - 1;
item = data.item(i).getElementsByTagName('prediction');
// see the notes in routePredict about item === null
if (item === null) {
ret[currIndex].predictions = null;
continue;
}
for (j = 0; j < item.length; j++) {
/*
if (direction !== 'null') {
if (direction !== item.item(j).getAttribute('dirtag')) {
continue;
}
}*/
if (units !== 'both') {
ret[currIndex].predictions.push(
item.item(j).getAttribute(units)
);
} else {
ret[currIndex].predictions.push({
minutes: item.item(j).getAttribute('minutes'),
seconds: item.item(j).getAttribute('seconds')
});
}
}
// if there are no predictions, map the route identifier to null
if (ret[currIndex].predictions.length === 0) {
ret[currIndex].predictions = null;
}
}
// we're done now, call the callback
cb(null, ret);
} catch (e) {
cb(e, null);
} finally {
if (!isTi) {
// if we're not in titanium, we're in node, and we just used
// jsdom for parsing. If we don't call window.close(), jsdom
// will leak an enormous amount of memory.
if (response) typeof response.close == "function" && response.close();
}
}
});
}
/*
Function: closestStops
Finds closest stops to a particular lat and lon. Will use only active
stops if that information has been retrieved
Parameters:
lat - *Number* latitude
lon - *Number* longitutde
num - *Number* number of stops to return
accuracy - *Number* # of accuracy characters in the geohash, defaults to 8
*/
function closestStops (lat, lon, num, accuracy) {
num = num || 3; // default to 3
var loc = geohash.encode(lat, lon), nearest, stops, oldData, d;
if (isActiveDataFresh()) {
stops = agencyData.active.stops;
} else {
stops = agencyData.sortedStops;
}
nearest = geohash.nearest(loc, stops, num, accuracy);
return nearest;
}
/*
Function: getAgencies
Get a list of the agencies that nextbus provides data for.
Parameters:
callback - *function (err, data)* called when the process is complete
Example:
> nextbus.getAgencies(callback);
Will provide callback with an object resembling
(start code)
{ agencies:
{ 'actransit':
{ tag: 'actransit',
title: 'AC Transit',
region: 'California-Northern',
shortTitle: null },
'art':
{ tag: 'art',
title: 'Asheville Redefines Transit',
region: 'North Carolina',
shortTitle: null },
'calu-pa':
{ tag: 'calu-pa',
title: 'California University of Pennsylvania',
region: 'Pennsylvania',
shortTitle: null },
'camarillo':
{ tag: 'camarillo',
title: 'Camarillo Area (CAT)',
region: 'California-Southern',
shortTitle: 'Camarillo (CAT)' },
...
}
}
(end)
*/
function getAgencies (callback) {
var out = {};
if (typeof callback !== "function") {
return {name: "TypeError", message: "callback must be a function"};
}
out.agencies = {};
query("agencyList", '', function (err, data) {
var i, agencies;
try {
if (err) {
throw err;
}
if (isTi) {
agencies = data.getElementsByTagName("agency");
} else {
agencies = data.document.getElementsByTagName("agency");
}
for (i = 0; i < agencies.length; i++) {
var tag = agencies.item(i).getAttribute('tag');
out.agencies[tag] = {
tag: tag,
title: agencies.item(i).getAttribute('title'),
region: agencies.item(i).getAttribute('regiontitle'),
shortTitle: agencies.item(i).getAttribute('shorttitle')
}
}
callback(null, out);
} catch (e) {
callback(e, null);
}
})
}
/*
Function: cacheAgency
Load the agency data. Somewhat slow as this is often a huge file.
Also geohashes each lat and lon for easy closest stop calculation.
Also builds an object indexed by stop titles so stops with identical
titles but different tags can be treated as a single stop.
Parameters:
agency - *string* name of the agency to cache]
callback - *function (err)* called when the process is complete
*/
function cacheAgency (name, callback) {
var out = {};
if (typeof name !== "string") {
callback({name: "TypeError", message: "agency must be a string"}, null);
return;
}
if (typeof callback !== "function") {
return {name: "TypeError", message: "callback must be a function"};
}
out.routes = {};
out.stops = {};
agency = name;
// actually run the query
query("routeConfig", '', function (err, data) {
var i, j,
route, routes,
stop, stops,
dirs;
try {
if (err) {
throw err;
}
// the titanium xml parser is a little weird, we don't have to do
// .document. So, if we're in titanium, get the data a little
// differently
if (isTi) {
routes = data.getElementsByTagName("route");
} else {
routes = data.document.getElementsByTagName("route");
}
for (i = 0; i < routes.length; i++) {
route = routes.item(i).getAttribute('tag');
//setup the route object
out.routes[route] = {
queries : {},
stops : [],
directions : [],
title : routes.item(i).getAttribute('title')
};
stops = routes.item(i).getElementsByTagName('stop');
for (j = 0; j < stops.length; j++) {
// if the title is null, this is the stop as listed in the direction
// section. we need the title (and other stuff too) so this node is
// useless
if (stops.item(j).getAttribute('title') === '') {
continue;
}
stop = stops.item(j).getAttribute('tag');
// If we already saw this stop, continue
if (out.routes[route].stops.indexOf(stop) !== -1) continue;
// initialize to defaults values. if this stop in out.stops
// is already set this does nothing, otherwise it sets intial values.
out.stops[stop] = out.stops[stop] || {
routes : [],
queries : {},
title : stops.item(j).getAttribute('title'),
lat : stops.item(j).getAttribute('lat'),
lon : stops.item(j).getAttribute('lon')
};
out.routes[route].stops.push(stop);
out.stops[stop].routes.push(route);
out.stops[stop].stopId =
stops.item(j).getAttribute('stopid') || undefined;
}
dirs = routes.item(i).getElementsByTagName('direction');
for (j = 0; j < dirs.length; j++) {
out.routes[route].directions.push({
title : dirs.item(j).getAttribute('title'),
tag : dirs.item(j).getAttribute('tag')
});
}
}
agencyData = out;
isAgencyCached = true;
// combine like stop names
combineStops();
// created sorted lists of stops
sort();
callback(null, out);
} catch (e) {
callback(e, null);
}
});
}
/*
Function: setAgencyCache
Set the agency cache to a given object. This is useful if you'd like to
generate the agency cache only once or load the agency cache from another
location.
Parameters:
data - *object* agency cache object
agencyname - *string* name of the agency
*/
function setAgencyCache (data, agencyname) {
agencyData = data;
agency = agencyname;
isAgencyCached = true;
}
/*
Function: getAgencyCache
Get the cached agency data. This is useful if you'd like to save this cache
or send it to a client.
Returns:
*object* agency cache
*/
function getAgencyCache () {
return agencyData;
}
function rand (to) {
return Math.floor(Math.random() * (to + 1));
}
/* Function: guessActive
* Guesses which routes are currently active by running a vehicleLocations
* query to discover which routes are active. Then, assumes that
* every stop on each active route is active, yielding a list of active
* routes and active stops for this agency.
*
* Parameters:
* callback - *function (err, data)* called with results; data.routes
* and data.stops will have alphabetically sorted arrays of
* active routes and stops respectively
*/
function guessActive (callback) {
if (!isAgencyCached) {
callback({name: "nocache", message: "no agency cache"}, null);
return;
}
// we temporarily use hashes for activeRoutes/Stops, because then we
// don't have to deal with duplicates. Once we've gone through
// everything one time and we have activeRoutes and activeStops
// completed, we'll loop over these hashes to build the final output
// hash.
var activeRoutes = {},
activeStops = {},
active = {},
route,
i,
stops,
len,
str = '';
// first, we guess which routes are active.
// we do this by simply running a vehiclelocations query. we assume
// any routes that have buses running are active
vehicleLocations(null, function (err, response) {
var i, item, route, data, stop;
// our response will be an object mapping routes to vehicles. we dont
// care about the values, but the keys tell us exactly which routes are
// active.
activeRoutes = response;
// second, we use our route guesses to mark the stops as active
active.routes = [];
// loop over the active routes
for (route in activeRoutes) {
if (activeRoutes.hasOwnProperty(route)) {
// add to the final output
active.routes.push({tag: route, title: agencyData.routes[route].title});
for (i = 0; i < agencyData.routes[route].stops.length; i++) {
// add each stop of current route to active stops list
stop = agencyData.routes[route].stops[i];
activeStops[agencyData.stops[stop].title] = true;
}
}
}
active.stops = [];
// lastly, we build the final return data
for (stop in activeStops) {
if (activeStops.hasOwnProperty(stop)) {
active.stops.push({
title: stop,
geoHash: agencyData.stopsByTitle[stop].geoHash
});
}
}
// sort the active routes & stops
active.routes.sort(function (a, b) {
return a.title.localeCompare(b.title);
});
active.stops.sort(function (a, b) {
return a.title.localeCompare(b.title);
});
agencyData.active = active;
agencyData.active.time = new Date().getTime();
callback(null, active);
});
}
/* Function: setActive
* Sets the active info, if retrieved from another nextbusjs client
*
* Parameters:
* active - *object* active stops and routes
*/
function setActive (active) {
agencyData.active = active;
}
/* Function: vehicleLocations
* Runs a vehicleLocations query against nextbus. Can optionally filter to
* a particular route. By default, this command will return only the
* vehicles which are in a different location since the last call to the
* function (ie, lastTime is handled). This can be overridden by passing
* true as the final argument.
*
* Parameters:
* route - *string* routeTag to use in the query. Will only return
* vehicles in this route. If null is passed, will return
* all vehicles.
* callback - *function (err, data)* to be called with the return data
* resetTime - *boolean* if truthy, will ignore lastTime and run the
* query without the 't' parameter. This will return buses
* which have moved in the last 15 minutes. If falsy, will
* use the last time the function was called for lastTime.
*
* Callback return:
* err - *error* object, if one occurred.
* data - *object* mapping routes to arrays
* data[route] - *array* of vehicles for this route
* data[route][i][id] - *string* vehicle id number
* data[route][i][direction] - *string* direction tag
* data[route][i][lat] - *string* latitude, float as string
* data[route][i][lon] - *string* longitude, float as string
* data[route][i][since] - *string* seconds since the query was run
* data[route][i][predictable] - *boolean* whether the vehicle is
* predictable. not sure what this means,
* but it's returned by the api, so its
* here for consistency
* data[route][i][heading] - *string* heading
* data[route][i][speed] - *string* speed in km/h
*/
function vehicleLocations (route, callback, resetTime) {
var str = '';
if (route) {
str += '&r=' + route;
}
if (!resetTime && vehicleLastTime) {
str += "&t=" + vehicleLastTime;
}
query('vehicleLocations', str, function (err, response) {
var vehicles, vehicle, lastTime, i, result = {}, route, data;
try {
if (err) {
throw err;
}
if (isTi) {
vehicles = response.getElementsByTagName("vehicle");
lastTime = response.getElementsByTagName(fixStr('lastTime'));
} else {
vehicles = response.document.getElementsByTagName("vehicle");
lastTime = response.document.getElementsByTagName(fixStr('lastTime'));
}
vehicleLastTime = lastTime.item(0).getAttribute('time');
for (i = 0; i < vehicles.length; i++) {
vehicle = vehicles.item(i);
route = vehicle.getAttribute(fixStr('routeTag'));
result[route] = result[route] || [];
result[route].push({
id: vehicle.getAttribute('id'),
dirtag: vehicle.getAttribute(fixStr('dirtag')),
lat: vehicle.getAttribute('lat'),
lon: vehicle.getAttribute('lon'),
predictable: vehicle.getAttribute('predictable') === 'true',
heading: vehicle.getAttribute('heading'),
since: vehicle.getAttribute(fixStr('secsSinceReport')),
speed: vehicle.getAttribute(fixStr('speedKmHr'))
});
}
callback(null, result);
} catch (e) {
callback(e, null);
}
});
}
/* Function: setActiveExpireTime
* Sets the amount of time it takes for the active information to expire.
* Default 10 minutes.
*
* Parameters:
* time - *number* time in seconds
*/