-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathpoll.js
353 lines (312 loc) · 9.82 KB
/
poll.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
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
'use strict';
var Q = require('q');
var querystring = require('querystring');
var sprintf = require('sprintf-js').sprintf;
var text = require('mtextbelt');
var gm = require('googlemaps');
var https = require('https');
var cheerio = require('cheerio');
var geolib = require('geolib');
var jsdom = require('jsdom');
var fs = require('fs');
var settings = require('./config.json');
var dmvInfo = require('./DMV_Info.json');
var HEADERS = {
'User-Agent':
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
'Content-Type': 'application/x-www-form-urlencoded',
'Referer': 'https://www.dmv.ca.gov' + getPath(settings)
};
var found = {};
console.log(
'Checking every ' + settings.checkEveryMinutes +
' minutes, at DMV offices ' + settings.maxDistanceMiles + ' miles from ' +
settings.home);
if (settings.textOnFind) {
console.log('Will text ' + settings.textNumber + ' when a match is found.');
}
// Main programming flow
Q.fcall(getHomeLocation(settings.home))
.then(getNearbyDMV(dmvInfo, settings.maxDistanceMiles))
.then(checkLoop(settings))
.catch(function(e) {
console.log(e);
});
/**
* @param {Object} settings User Settings object.
* @return {string} The request url path.
*/
function getPath(settings) {
if (settings.behindTheWheelTest) {
return '/wasapp/foa/findDriveTest.do';
} else {
return '/wasapp/foa/findOfficeVisit.do';
}
}
/**
* Check Loop
* @param {settings} settings User Settings
*/
function checkLoop(settings) {
return function(dmvInfo) {
var promise = Q.resolve();
for (var i in dmvInfo) {
promise = promise.then(makeDMVRequest(dmvInfo[i], settings))
.then(handleDMVRedirect())
.then(checkAppointmentResult(
dmvInfo[i].name, settings.dayOfWeeks))
.delay(1000 * settings.secondsBetweenRequests);
}
return promise
.then(function() {
return Q.resolve(dmvInfo);
})
.delay(settings.checkEveryMinutes * 1000 * 60)
.fail(function(e) {
console.log('Error: ' + JSON.stringify(e));
})
.then(checkLoop(settings));
};
}
/**
* Make DMV Request
*
* Makes a https request to the DMV website and returns the data as a promise
* @param {Object} dmvInfo DMV's information
* @param {Object} settings User Settings
* @return {Promise} Promise to return the data
*/
function makeDMVRequest(dmvInfo, settings) {
return function() {
var deferred = Q.defer();
try {
var host = 'www.dmv.ca.gov';
var path = getPath(settings);
var post_data = settings.appointmentInfo;
post_data.officeId = dmvInfo.id;
post_data.numberItems = 1;
if (settings.behindTheWheelTest) {
post_data.requestedTask = 'DT';
} else {
post_data.taskRWT = true;
}
var postString = querystring.stringify(post_data);
var headers = HEADERS;
headers['Content-Length'] = postString.length;
var options =
{host: host, port: 443, path: path, method: 'POST', headers: headers};
// Setup the request. The options parameter is
// the object we defined above.
var req = https.request(options, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
deferred.resolve(responseString);
});
req.on('error', function(e) {
deferred.reject(e);
});
});
req.write(postString);
req.end();
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
};
}
/**
* Get Home Location
*
* Returns promise for the gps coordinates of the home address
* @param {String} home Home Address
* @return {Object} Promise for GPS Coordinates
*/
function getHomeLocation(home) {
return function() {
var deferred = Q.defer();
gm.geocode(home, function(err, data) {
if (!err && data.hasOwnProperty('results') &&
data.results.hasOwnProperty(0) &&
data.results[0].hasOwnProperty('geometry')) {
var coords = data.results[0].geometry.location;
deferred.resolve(coords);
} else {
deferred.reject('Could not find your home location.');
}
});
return deferred.promise;
};
}
/**
* Get Nearby DMVs
* Get all DMVs within a radius
* @param {Object} dmvInfo All DMV information
* @param {Integer} maxDistanceMiles Max distance to travel from Home
* @return {Function} Function to pass to Q
*/
function getNearbyDMV(dmvInfo, maxDistanceMiles) {
/**
* @param {[type]} homeLocation GPS Coordinates of home
* @return {[type]} An array of DMVs
*/
return function(homeLocation) {
var validDMVLocations = [];
for (var dmvName in dmvInfo) {
var distance = geolib.getDistance(
{latitude: homeLocation.lat, longitude: homeLocation.lng},
{latitude: dmvInfo[dmvName].lat, longitude: dmvInfo[dmvName].lng});
var distanceMiles = 0.000621371 * distance;
if (distanceMiles <= maxDistanceMiles) {
var obj = dmvInfo[dmvName];
obj.name = dmvName;
obj.distanceMiles = distanceMiles;
validDMVLocations.push(obj);
}
}
return validDMVLocations;
};
}
/**
* Handles the DMV js redirect page.
* @return {function} returns a function for Q to call
*/
function handleDMVRedirect() {
/**
* @param {String} str HTML results of the page request
*/
return function(str) {
var deferred = Q.defer();
try {
jsdom.env({
html: str,
script: 'challenge();',
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: ['script']
},
done: function(err, window) {
var elements = window.document.forms[0].elements;
var secondRequest = {};
for (var i = 0; i < elements.length; i++) {
var key = elements[i].name;
var value = elements[i].value;
secondRequest[key] = value;
}
var host = 'www.dmv.ca.gov';
var path = getPath(settings);
var postString = querystring.stringify(secondRequest);
var headers = HEADERS;
headers['Content-Length'] = postString.length;
var options = {
host: host,
port: 443,
path: path,
method: 'POST',
headers: headers
};
// Setup the request. The options parameter is
// the object we defined above.
var req = https.request(options, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
deferred.resolve(responseString);
});
req.on('error', function(e) {
deferred.reject(e);
});
});
req.write(postString);
req.end();
}
});
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
};
}
/**
* Check appointment results
* @param {String} name DMV Name
* @param {Object} schedule Schedule of classes
* @return {function} returns a function for Q to call
*/
function checkAppointmentResult(name, schedule) {
/**
* @param {String} str HTML results of the page request
*/
return function(str) {
var $ = cheerio.load(str);
var dateString = $('#ApptForm')
.parent()
.parent()
.parent()
.find('tr:nth-child(3) .alert')
.text()
.replace(' at ', ' ');
console.log(name + ':\t' + dateString);
if (!dateString) {
displayErrors($);
return;
}
var date = new Date(Date.parse(dateString));
var timeDiff = (date - (new Date()));
// verify saturday
// only on a saturday
var daysUntil = timeDiff / 1000 / 60 / 60 / 24;
for (var day in schedule) {
// why is triple equals not working?
var isDayOfWeek = parseInt(day) === parseInt(date.getDay());
// console.log(schedule[day].allowed)
var withinTime = date.getHours() >= schedule[day].startHour &&
date.getHours() < schedule[day].endHour;
var withinDays = daysUntil < settings.findAppointmentWithinDays;
// console.log("within "+settings.findAppointmentWithinDays+" days:
// "+withinDays);
if (withinDays && isDayOfWeek && withinTime && schedule[day].allowed) {
if (!found[dateString + name]) {
found[dateString + name] = true;
console.log('FOUND NEW MATCH! \x07 \n');
if (settings.textOnFind) {
text.send(
settings.textNumber,
sprintf('%20s', name) + ': ' + formatDate(date), function() {});
}
} else {
console.log('found duplicate match!');
}
}
}
};
}
function displayErrors($) {
console.log('Match failed - check your config.json. Possible reasons: ');
$('.validation_error').each(function(i, element) {
console.log(element.firstChild.data);
})
}
/**
* Format Date
* @param {Date} date
* @return {String} Human readable date
*/
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var strTime =
sprintf('%02d', hours) + ':' + sprintf('%02d', minutes) + ' ' + ampm;
return sprintf('%02d', date.getMonth() + 1) + '/' +
sprintf('%02d', date.getDate()) + '/' + date.getFullYear() + ' ' +
strTime;
}