-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroom.js
100 lines (86 loc) · 2.82 KB
/
room.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
var request = require('request'),
util = require('util'),
m = require('./machine');
require('date-utils');
var roomDynamicStatusUrl = 'http://www.laundryview.com/dynamicRoomData.php?location=%s',
roomApplianceStatusUrl = 'http://www.laundryview.com/appliance_status_ajax.php?lr=%s';
var roomIdPrefix = 'laundry_room.php?lr=',
deadStatus = '1:0:0:0:0:0';
Room = function(campus, $room) {
this.campus = campus;
this.campusName = campus.name;
this.name = $room.text().trim();
this.roomId = $room.attr('href').replace(roomIdPrefix, '');
this.washers = {};
this.dryers = {};
this.lastRefresh = null;
this.nextRefreshDue = new Date();
};
Room.prototype = {
parseRoomOutput: function(roomData) {
var machineId = 1,
dataRows = roomData.split(/^&|:\n&|:\n$/g);
dataRows.shift(); dataRows.pop();
this.washers = {}; this.dryers = {};
for (var i = 0; i < dataRows.length; i++) {
try {
var keyValue = dataRows[i].split('='),
k = keyValue[0], v = keyValue[1];
if (v !== deadStatus && k.substring(0, 13) === 'machineStatus') {
var vs = v.split('\n');
if (vs.length === 1) {
this.washers[machineId] = new m.Machine(machineId++, vs[0]);
} else {
this.dryers[machineId] = new m.Machine(machineId++, vs[0]);
this.dryers[machineId] = new m.Machine(machineId++, vs[1]);
}
}
} catch (err) {
console.log(roomData);
console.log(dataRows);
console.log('Error parsing the room: ' + err);
}
};
},
loadRoom: function(callback) {
var opts = {
url: util.format(roomDynamicStatusUrl, this.roomId),
jar: this.campus.jar
};
self = this;
request(opts, function(error, response, body) {
function handleRoomUpdateData(r,b) {
console.log('Loaded room ' + r.roomId);
r.parseRoomOutput(b);
r.lastRefresh = new Date();
r.nextRefreshDue = r.lastRefresh.clone().addMinutes(1);
callback(null, r);
}
if (!error && response.statusCode == 200) {
if (body.length == 0) { // Cookie expired
self.campus.refreshSession(function(e,r,b) {
console.log('**** Refreshed session cookie');
this.loadRoom(callback);
}.bind(self), true);
} else {
console.log('**** Cookie OK');
handleRoomUpdateData(self,body);
}
} else {
console.log('Could not load room ' + self.roomId);
callback(error, self);
}
}.bind(this));
},
toJSON: function() {
var copy = {},
exclude = {campus: 1}; // Avoid circular references
for (var prop in this) {
if (!exclude[prop] && typeof this[prop] !== 'function') {
copy[prop] = this[prop];
}
}
return copy;
}
};
exports.Room = Room;