forked from rand256/valetudo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SmarthomeAPI.js
462 lines (383 loc) · 13.8 KB
/
SmarthomeAPI.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
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
const request = require('request')
const j = request.jar()
const querystring = require('querystring');
const TreeMap = require("treemap-js");
const fs = require("fs");
const zlib = require("zlib");
var AsyncLock = require('async-lock');
var lock = new AsyncLock();
var stream = require('stream');
var Dummycloud = require('./miio/Dummycloud')
var crypto = require('crypto');
var ssecurity = "";
var servicetoken = "";
var userId = "";
var mapUrlCache = [];
var loginFailedCounter = 0;
const SmarthomeAPI = function(options) {
const self = this;
this.configuration = options.configuration;
this.vacuum = options.vacuum;
this.cloud = options.cloud;
this.smarthomeAPIConfig = this.configuration.get("smarthomeAPI");
}
function encodePassword(password) {
return crypto.createHash('md5').update(password).digest("hex").toUpperCase();
}
function parseJson(data) {
if(data.includes("&&&START&&&"))
return JSON.parse(data.replace("&&&START&&&", ""));
else
return false;
}
function generateSignature(path, params) {
var nonce = crypto.randomBytes(16)
nonce.writeInt32LE(new Date().getTime() / 60000);
nonce = nonce.toString('base64');
var b = Buffer.from(crypto.randomBytes(8));
var millis = Buffer.allocUnsafe(4);
millis.writeUInt32BE(Math.round(new Date().getTime() / 60000));
nonce = Buffer.concat([b,millis]).toString('base64');
var signature = crypto.createHash('sha256').update(Buffer.concat([Buffer.from(ssecurity, "base64"), Buffer.from(nonce, "base64")])).digest("base64");
var paramsTreeMap = new TreeMap();
params.forEach(element => {
paramsTreeMap.set(element.key, element.value);
});
var paramsArray = Array();
if (path != null) {
paramsArray.push(path);
}
paramsArray.push(signature);
paramsArray.push(nonce);
if (paramsTreeMap.getLength() > 0) {
paramsTreeMap.each(function (value, key) {
paramsArray.push(key+"="+value);
});
} else {
paramsArray.push("data=");
}
var postData = "";
paramsArray.forEach(function(value){
if(postData != ""){
postData += "&";
}
postData += value;
});
body = {
"signature": HashHmacSHA256(postData, signature),
"_nonce": nonce
};
paramsTreeMap.each(function (value, key) {
body[key] = value;
});
return body;
}
function HashHmacSHA256(data, secret){
var hmac = crypto.createHmac('sha256',Uint8Array.from(Buffer.from(secret, "base64")));
//passing the data to be hashed
data = hmac.update(data);
//Creating the hmac in the required format
return data.digest('base64');
}
SmarthomeAPI.prototype.login = function (username, password) {
var self = this;
if(username == undefined) {
username = self.smarthomeAPIConfig.username;
servicetoken = null;
loginFailedCounter = 0;
}
if(password == undefined)
password = self.smarthomeAPIConfig.password;
else
servicetoken = null;
return new Promise(function(resolve, reject) {
if(username.trim() == "" || password.trim() == "") {
console.error(new Date(), "Xiaomi Cloud: username or password missing.");
reject("Xiaomi Cloud username or password missing.");
return;
}
lock.acquire("login", function(done) {
if(servicetoken) {
resolve(true);
return;
}
else {
if(loginFailedCounter > 3){
console.error(new Date(),"Xiaomi Cloud: Logging in failed to many times. Please check your credentials and save them again.")
loggingIn = false;
reject("Login failed to many times.")
return;
}
console.info(new Date(),"Xiaomi Cloud: Logging in");
loggingIn = true;
}
// Set the headers for the request
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Android-7.1.1-1.0.0-ONEPLUS A3010-136-9D28921C354D7 APP/xiaomi.smarthome APPV/62830',
'Cookie': "sdkVersion=accountsdk-18.8.15; userId="+username+"; deviceId="+self.smarthomeAPIConfig.clientId
};
// Configure the request
var options = {
url: "https://account.xiaomi.com/pass/serviceLogin?sid=xiaomiio&_json=true",
method: 'GET',
headers: headers,
gzip: true
};
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
// Print out the response body
//console.log({status: 0, statusDsc: "success", data: body});
var jsonData = parseJson(body);
if(jsonData == false) {
loginFailedCounter++;
loggingIn = false;
reject("Failed to get sign variable");
return;
}
headers.Cookie = "sdkVersion=accountsdk-18.8.15; deviceId="+self.smarthomeAPIConfig.clientId;
var options = {
url: "https://account.xiaomi.com/pass/serviceLoginAuth2",
method: 'POST',
headers: headers,
form : {
'sid': "xiaomiio",
'hash': encodePassword(password),
'callback': "https://sts.api.io.mi.com/sts",
'qs': "%3Fsid%3Dxiaomiio%26_json%3Dtrue",
'user': username,
'_sign': jsonData._sign,
'_json': "true"
},
gzip: true
};
//headers.length = postBody.length;
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
// Print out the response body
//console.log({status: 0, statusDsc: "success", data: body});
var jsonData = parseJson(body);
if(jsonData.code != 0) {
console.error(new Date(),"Xiaomi Cloud: Login failed");
loginFailedCounter++;
loggingIn = false;
reject("Login failed");
return;
}
ssecurity = jsonData.ssecurity;
userId = jsonData.userId;
cUserId = jsonData.cUserId;
const j= request.jar()
var options = {
url: jsonData.location,
method: 'GET',
headers: headers,
gzip: true,
jar: j
};
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
const cookies = j.getCookies("https://sts.api.io.mi.com/");
var found = false;
cookies.forEach(cookie => {
if(cookie.key == "serviceToken") {
servicetoken = cookie.value;
found = true;
//console.log(servicetoken);
console.info(new Date(),"Xiaomi Cloud: Login successful");
loggingIn = false;
resolve(true);
done();
return;
}
});
if(!found){
loginFailedCounter++;
loggingIn = false;
reject("Token cookie not found");
done();
return;
}
} else {
loginFailedCounter++;
loggingIn = false;
reject("HTTP error when getting token cookie");
done();
console.error(new Date(), JSON.stringify(error));
}
});
} else {
loginFailedCounter++;
loggingIn = false;
reject("HTTP error when logging in");
done();
console.log(JSON.stringify(error));
}
});
} else {
loginFailedCounter++;
loggingIn = false;
reject("HTTP error when getting _sign");
done();
console.log(JSON.stringify(error));
}
});
}, function(err, ret) {
}, {});
});
}
SmarthomeAPI.prototype.updateMap = function(dontRetry) {
var self = this;
if(dontRetry == true && servicetoken != undefined) {
console.error(new Date(), "Can't get update map because not logged in");
return;
}
self.vacuum.getMapV1(function(error, mapRes){
if(error) {
console.error(new Date(), "Error when getting new map from robot: "+error);
return;
}
if(mapRes != undefined && mapRes[0] != 'retry' && mapRes[0] != 'locating'){
//console.debug(new Date(), "Xiaomi Cloud: got map name: "+mapRes[0]);
var unixtime = Math.floor(new Date() / 1000);
if(mapUrlCache[mapRes[0]] == undefined || mapUrlCache[mapRes[0]].expires < (unixtime - 60)){
//console.debug(new Date(), "Xiaomi Cloud: Updating map url");
getMapURL.call(self, mapRes[0]).then(function(result){
mapUrlCache[mapRes[0]] = {
expires: result.result.expires_time,
url: result.result.url
};
downloadMap.call(self, mapUrlCache[mapRes[0]].url);
}).catch(function(error){
console.error(new Date(), error);
if(!dontRetry) {
self.login().then(function(reponse){
self.updateMap(true);
}).catch(function(){});
}
});
}
else {
//console.debug(new Date(), "Xiaomi Cloud: Downloading map from cached url. Expires: "+mapUrlCache[mapRes[0]].expires+" Current: "+unixtime);
downloadMap.call(this, mapUrlCache[mapRes[0]].url);
}
}
else {
console.error(new Date(), "Xiaomi Cloud: Failed to get map url name:" + mapRes);
}
});
}
SmarthomeAPI.prototype.getDeviceStatus = function (username, password, obj) {
var self = this;
return new Promise(function(resolve, reject) {
self.login(username, password).then(function(resp){
var url = "https://"+self.smarthomeAPIConfig.server+".api.io.mi.com/app/home/device_list";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'x-xiaomi-protocal-flag-cli': 'PROTOCAL-HTTP2',
'User-Agent': 'Android-7.1.1-1.0.0-ONEPLUS A3010-136-9D28921C354D7 APP/xiaomi.smarthome APPV/62830',
'Cookie': "userId="+userId+"; yetAnotherServiceToken="+servicetoken+"; serviceToken="+servicetoken+"; locale=de_DE; timezone=GMT%2B01%3A00; is_daylight=1; dst_offset=3600000; channel=MI_APP_STORE",
}
var params = [{
key: "data",
//value: '{"dids":["117978555"]}'
value: obj
}];
var body = generateSignature("/home/device_list", params);
var options = {
url: url,
method: 'POST',
headers: headers,
form: body,
gzip: true
};
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var json = JSON.parse(response.body);
if(json.message == "ok")
resolve(json.result.list);
else
reject(json.message);
/*if(json.message == "ok") {
resolve(json);
}
else {
servicetoken = undefined;
reject(json.message);
}*/
return;
}
console.log(response);
servicetoken = undefined;
reject("HTTP ERROR");
});
}).catch(function(error){
reject(error);
});
});
}
function getMapURL(mapName) {
var self = this;
return new Promise(function(resolve, reject) {
if(servicetoken == undefined || servicetoken == null || servicetoken == "null"){
reject("Xiaomi Cloud: Can't get map, not logged in");
return;
}
var url = "https://"+self.smarthomeAPIConfig.server+".api.io.mi.com/app/home/getmapfileurl";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'x-xiaomi-protocal-flag-cli': 'PROTOCAL-HTTP2',
'User-Agent': 'Android-7.1.1-1.0.0-ONEPLUS A3010-136-9D28921C354D7 APP/xiaomi.smarthome APPV/62830',
'Cookie': "userId="+userId+"; yetAnotherServiceToken="+servicetoken+"; serviceToken="+servicetoken+"; locale=de_DE; timezone=GMT%2B01%3A00; is_daylight=1; dst_offset=3600000; channel=MI_APP_STORE",
}
var params = [{
key: "data",
value: '{"obj_name":"'+mapName+'"}'
}];
var body = generateSignature("/home/getmapfileurl", params);
var options = {
url: url,
method: 'POST',
headers: headers,
form: body,
gzip: true
};
request(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
var json = JSON.parse(response.body);
if(json.message == "ok") {
resolve(json);
}
else {
console.log("Error when receiving mapurl")
servicetoken = undefined;
reject(json.message);
}
return;
}
var json = JSON.parse(response.body);
servicetoken = undefined;
console.log(response);
reject(json.message);
});
});
}
function downloadMap(url){
var self = this;
var options = {
url: url,
method: 'GET',
gzip: false
};
//console.log(url);
/*request(options, function (error, response, body) {
console.log(response.headers);
}).pipe(request.put("http://127.0.0.1/api/miio/map_upload_handler"));
return;
*/
request(options, function (error, response, body) {
//console.log(response.headers);
}).pipe(request.put("http://127.0.0.1/api/miio/map_upload_handler_0"));
}
module.exports = SmarthomeAPI;