forked from dhleong/reverb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·344 lines (304 loc) · 10.5 KB
/
index.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
#!/usr/bin/env node
var util = require('util')
, events = require('events')
, WebSocket = require('ws') // jshint ignore:line
, _ = require('lodash')
, ActivityFetcher = require('./lib/activity')
, NotificationFetcher = require('./lib/notification')
, Echo = require('./lib/echolib')
, Channels = Echo.Channels
/** This is a bit of a hack, but it works */
, Endpoints = {
DEVICE: "urn:tcomm-endpoint:device:deviceType:0:deviceSerialNumber:0"
, WEB_MESSAGING: "urn:tcomm-endpoint:service:serviceName:DeeWebsiteMessagingService"
}
/** It's probably safe to assume a constant device type */
, DEVICE_TYPE = 'ALEGCNGL9K0HM';
/**
* The main entry into the library
*/
function Reverb(opts) {
opts = _.extend({
push_host: 'dp-gw-na-js.amazon.com'
, origin: 'http://echo.amazon.com'
}, opts);
if (!opts.serial) throw new Error("`serial` is required");
if (!opts.cookie) throw new Error("`cookie` is required");
var self = this;
this.log = opts.debug
? function() { console.log.apply(console, arguments); }
: function() {};
this._messageHandlers = [];
this._activityFetcher = new ActivityFetcher(opts);
this._notificationFetcher = new NotificationFetcher(opts, function(notifications){
self.log("Received", notifications.length, "notifications")
for (var i = 0; i < notifications.length; i++) {
if (notifications[i].type == "Timer") {
self.log("Got a timer")
if (notifications[i].status == "ON") {
self.addTimer(notifications[i])
}
} else if (notifications[i].type == "Alarm") {
self.log("Got an alarm")
self.setAlarm(notifications[i])
}
}
});
var url = 'wss://' + opts.push_host + '/'
+ '?x-amz-device-type=' + DEVICE_TYPE
+ '&x-amz-device-serial=' + opts.serial;
var ws = this.ws = new WebSocket(url, {
headers: {
Cookie: opts.cookie
}
, origin: opts.origin
, rejectUnauthorized: false
});
ws.on('open', function open() {
self.log("Opened!");
self.emit('open', self);
// begin the handshake
self.initTuningHandshake();
})
ws.on('error', function error(err) {
self.log("ERROR:", err);
self.emit('error', err);
});
ws.on('close', function close(code, message) {
self.emit('close', code, message);
console.log("Disconnected", code, message);
this._messageHandlers = [];
});
ws.on('message', self.onMessage.bind(self));
}
util.inherits(Reverb, events.EventEmitter);
Reverb.prototype.onMessage = function(data/* , flags */) {
this.log("<<", data);
var handlers = this._messageHandlers;
handlers.forEach(function(fun) {
fun(data);
});
}
Reverb.prototype.addMessageListener = function(proto, handler) {
var fun;
if (handler) {
fun = function(data) {
var decoded;
try {
decoded = proto.decodeMessage(data)
} catch (e) {
console.warn("Failed to decode:", e);
return;
}
// call handlers with themself as "this"
// as you would expect, so they can
// remove themselves
handler.call(handler, decoded);
};
fun.id = handler;
} else {
fun = proto;
fun.id = proto;
}
this._messageHandlers.push(fun);
}
Reverb.prototype.removeMessageListener = function(handler) {
var found = false;
this._messageHandlers = this._messageHandlers.filter(function(fun) {
found |= fun.id == handler;
return fun.id != handler;
});
if (!found) console.warn("UNABLE TO REMOVE HANDLER!");
return found;
};
Reverb.prototype.initTuningHandshake = function() {
var msg = Echo.Protocols.map(function(proto) {
return proto.protocolName;
});
var proto = new Echo.TuningProtocolHandler(Echo.HexCodec);
var self = this;
this.send(proto, msg[0]); // is this correct?
this.addMessageListener(proto, function(data) {
self.removeMessageListener(this);
if (data.protocolName != 'A:H') {
console.error(data);
throw new Error("Unexpected protocol" + data.protocolName);
}
// now ack
self.send(proto, JSON.stringify(data));
self.log("Agreed to A:H protocol");
// prepare the protocol and finish the handshake
var params = {};
Object.keys(data.parameters).forEach(function(param) {
var name = param.substr(param.indexOf('.') + 1);
params[name] = data.parameters[name];
});
self._register(new Echo.AlphaProtocolHandler(params, Echo.HexCodec));
});
}
/** Register the connection to receive events */
Reverb.prototype._register = function(proto) {
var message = Echo.jsonToAb({
command: "REGISTER_CONNECTION"
});
var gwChannel = Channels.DEE_WEBSITE_MESSAGING;
var origin = Echo.IdentityFactory.getFromUrn(Endpoints.DEVICE);
var dest = Echo.IdentityFactory.getFromUrn(Endpoints.WEB_MESSAGING);
var gateway = new Echo.GatewayProtocolHandler(Echo.HexCodec);
var encoded = gateway.encodeMessage(message, gwChannel, origin, dest);
// now wrap it in our outer protocol
var wrapped = proto.encodeMessage(encoded, Channels.GW_CHANNEL);
this.send(wrapped);
this.emit('ready', self);
this.log("Ready");
var self = this;
this.addMessageListener(proto, function(gwPacket) {
self.log("<< GW PAYLOAD:", gwPacket.getPayloadAsString());
var decoded = gateway.decodeMessage(gwPacket.getPayloadAsBuffer());
var payload = JSON.parse(decoded.getPayloadAsString());
self.onGatewayCommand(payload);
});
}
Reverb.prototype.onGatewayCommand = function(command) {
this.log("<< GW CMD:", command);
this.emit('command', command);
if (command.command == 'PUSH_ACTIVITY') {
var body = JSON.parse(command.payload);
this.onActivity({
id: body.key.entryId
, user: body.key.registeredUserId
});
} else if (command.command == 'PUSH_NOTIFICATION_CHANGE') {
var body = JSON.parse(command.payload);
if (body.notificationId == "t1") {
this.onTimer({
id: body.notificationId
});
} else if (body.notificationId == "a1") {
this.onAlarm({
id: body.notificationId
});
}
}
}
Reverb.prototype.onActivity = function(activity) {
this.log("<< Activity", activity);
if (!this.listeners('activity').length) {
// no listeners; don't bother fetching
return;
}
this.log("Resolving activity...");
var self = this;
this._activityFetcher.fetch(activity)
.then(function(resolved) {
self.log("<< RESOLVED activity", resolved);
self.emit('activity', resolved);
}, function(err) {
console.warn("Failed to resolve activity", err);
});
}
Reverb.prototype.onTimer = function(notification) {
this.log("<< Timer", notification);
/* if (!this.listeners('timer').length) {
// no listeners; don't bother fetching
return;
} */
this.log("Resolving timer...");
var self = this;
this._notificationFetcher.fetch(notification)
.then(function(resolved) {
self.log("<< RESOLVED notification", resolved);
if (resolved.status == "ON") {
self.addTimer(resolved)
self.emit('timerStart', resolved);
} else if (resolved.status == "OFF") {
self.removeTimer(resolved)
self.emit('timerRemove', resolved);
} else if (resolved.status == "PAUSED") {
self.pauseTimer(resolved)
self.emit('timerPause', resolved);
}
}, function(err) {
console.warn("Failed to resolve timer", err);
});
}
Reverb.prototype.onAlarm = function(notification) {
this.log("<< Alarm", notification);
this.log("Resolving alarm...");
var self = this;
this._notificationFetcher.fetch(notification)
.then(function(resolved) {
self.log("<< RESOLVED notification", resolved);
if (resolved.status == "ON") {
if (self.alarm.status == "ON") {
self.emit('alarmUpdate', resolved);
} else {
self.emit('alarmSet', resolved);
}
self.setAlarm(resolved)
} else if (resolved.status == "OFF") {
if (self.alarm.status == "OFF") {
self.emit('alarmUpdate', resolved);
self.setAlarm(resolved)
} else {
self.emit('alarmRemove', resolved);
self.removeAlarm(resolved)
}
}
}, function(err) {
console.warn("Failed to resolve timer", err);
});
}
Reverb.prototype.send = function(protocol, message) {
if (message) {
var encoded = protocol.encodeMessage(message);
this.ws.send(encoded);
this.log(">>", Echo.abToStr(encoded));
} else {
this.ws.send(protocol); // send directly
}
}
Reverb.prototype.addTimer = function(timer) {
var self = this;
this.log("Adding a timer")
this.timer = {
status: timer.status
, remainingTime: timer.remainingTime
}
this.timer.timeoutId = setTimeout(function() {
self.log("Timer has completed")
self.emit('timerComplete', timer);
}, this.timer.remainingTime)
}
Reverb.prototype.pauseTimer = function(timer) {
this.log("Clearing internal timer.")
clearTimeout(this.timer.timeoutId)
}
Reverb.prototype.removeTimer = function(timer) {
this.log("Clearing internal timer.")
clearTimeout(this.timer.timeoutId)
}
Reverb.prototype.setAlarm = function(alarm) {
var self = this;
var now = new Date().getTime()
var delta = alarm.alarmTime - now
this.log("Setting an alarm")
// alarmTime / 1000 is the next time the alarm should fire
this.alarm = {
status: alarm.status
, alarmTime: alarm.alarmTime
}
this.log("Alarm in", delta / 1000, "seconds")
if (delta > 0 && alarm.status == "ON") {
this.log("Alarm active")
this.alarm.timeoutId = setTimeout(function() {
self.log("Alarm has completed")
self.emit('alarmComplete', alarm)
}, delta)
}
}
Reverb.prototype.removeAlarm = function(alarm) {
this.log("Clearing internal alarm")
clearTimeout(this.alarm.timeoutId)
}
module.exports = Reverb;