]> git.basschouten.com Git - openhab-addons.git/blob
5077294b097f7e7ba1fa33b8bb2b440f6c0f5e3a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.miio.internal.cloud;
14
15 import java.io.IOException;
16 import java.net.CookieStore;
17 import java.net.HttpCookie;
18 import java.net.MalformedURLException;
19 import java.net.URI;
20 import java.net.URL;
21 import java.time.ZonedDateTime;
22 import java.time.format.DateTimeFormatter;
23 import java.util.ArrayList;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Locale;
28 import java.util.Map;
29 import java.util.Random;
30 import java.util.TimeZone;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.TimeoutException;
34
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jetty.client.HttpClient;
37 import org.eclipse.jetty.client.HttpResponseException;
38 import org.eclipse.jetty.client.api.ContentResponse;
39 import org.eclipse.jetty.client.api.Request;
40 import org.eclipse.jetty.client.util.FormContentProvider;
41 import org.eclipse.jetty.http.HttpHeader;
42 import org.eclipse.jetty.http.HttpMethod;
43 import org.eclipse.jetty.http.HttpStatus;
44 import org.eclipse.jetty.util.Fields;
45 import org.openhab.binding.miio.internal.MiIoCrypto;
46 import org.openhab.binding.miio.internal.MiIoCryptoException;
47 import org.openhab.binding.miio.internal.Utils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 import com.google.gson.Gson;
52 import com.google.gson.GsonBuilder;
53 import com.google.gson.JsonElement;
54 import com.google.gson.JsonObject;
55 import com.google.gson.JsonParser;
56 import com.google.gson.JsonSyntaxException;
57
58 /**
59  * The {@link MiCloudConnector} class is used for connecting to the Xiaomi cloud access
60  *
61  * @author Marcel Verpaalen - Initial contribution
62  */
63 @NonNullByDefault
64 public class MiCloudConnector {
65
66     private static final int REQUEST_TIMEOUT_SECONDS = 10;
67     private static final String UNEXPECTED = "Unexpected :";
68     private static final String AGENT_ID = (new Random().ints(65, 70).limit(13)
69             .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString());
70     private static final String USERAGENT = "Android-7.1.1-1.0.0-ONEPLUS A3010-136-" + AGENT_ID
71             + " APP/xiaomi.smarthome APPV/62830";
72     private static Locale locale = Locale.getDefault();
73     private static final TimeZone TZ = TimeZone.getDefault();
74     private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("OOOO");
75     private static final Gson GSON = new GsonBuilder().serializeNulls().create();
76     private static final JsonParser PARSER = new JsonParser();
77
78     private final String clientId;
79
80     private String username;
81     private String password;
82     private String userId = "";
83     private String serviceToken = "";
84     private String ssecurity = "";
85     private int loginFailedCounter = 0;
86     private HttpClient httpClient;
87
88     private final Logger logger = LoggerFactory.getLogger(MiCloudConnector.class);
89
90     public MiCloudConnector(String username, String password, HttpClient httpClient) throws MiCloudException {
91         this.username = username;
92         this.password = password;
93         this.httpClient = httpClient;
94         if (!checkCredentials()) {
95             throw new MiCloudException("username or password can't be empty");
96         }
97         clientId = (new Random().ints(97, 122 + 1).limit(6)
98                 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString());
99     }
100
101     void startClient() throws MiCloudException {
102         if (!httpClient.isStarted()) {
103             try {
104                 httpClient.start();
105                 CookieStore cookieStore = httpClient.getCookieStore();
106                 // set default cookies
107                 addCookie(cookieStore, "sdkVersion", "accountsdk-18.8.15", "mi.com");
108                 addCookie(cookieStore, "sdkVersion", "accountsdk-18.8.15", "xiaomi.com");
109                 addCookie(cookieStore, "deviceId", this.clientId, "mi.com");
110                 addCookie(cookieStore, "deviceId", this.clientId, "xiaomi.com");
111             } catch (Exception e) {
112                 throw new MiCloudException("No http client cannot be started: " + e.getMessage(), e);
113             }
114         }
115     }
116
117     public void stopClient() {
118         try {
119             this.httpClient.stop();
120         } catch (Exception e) {
121             logger.debug("Error stopping httpclient :{}", e.getMessage(), e);
122         }
123     }
124
125     private boolean checkCredentials() {
126         if (username.trim().isEmpty() || password.trim().isEmpty()) {
127             logger.info("Xiaomi Cloud: username or password missing.");
128             return false;
129         }
130         return true;
131     }
132
133     private String getApiUrl(String country) {
134         return "https://" + (country.trim().equalsIgnoreCase("cn") ? "" : country.trim().toLowerCase() + ".")
135                 + "api.io.mi.com/app";
136     }
137
138     public String getClientId() {
139         return clientId;
140     }
141
142     String parseJson(String data) {
143         if (data.contains("&&&START&&&")) {
144             return data.replace("&&&START&&&", "");
145         } else {
146             return UNEXPECTED.concat(data);
147         }
148     }
149
150     public String getMapUrl(String vacuumMap, String country) throws MiCloudException {
151         String url = getApiUrl(country) + "/home/getmapfileurl";
152         Map<String, String> map = new HashMap<String, String>();
153         map.put("data", "{\"obj_name\":\"" + vacuumMap + "\"}");
154         String mapResponse = request(url, map);
155         logger.trace("response: {}", mapResponse);
156         String errorMsg = "";
157         JsonElement response = PARSER.parse(mapResponse);
158         if (response.isJsonObject()) {
159             logger.debug("Received  JSON message {}", response.toString());
160             if (response.getAsJsonObject().has("result") && response.getAsJsonObject().get("result").isJsonObject()) {
161                 JsonObject jo = response.getAsJsonObject().get("result").getAsJsonObject();
162                 if (jo.has("url")) {
163                     String mapUrl = jo.get("url").getAsString();
164                     return mapUrl != null ? mapUrl : "";
165                 } else {
166                     errorMsg = "Could not get url";
167                 }
168             } else {
169                 errorMsg = "Could not get result";
170             }
171         } else {
172             errorMsg = "Received message is invalid JSON";
173         }
174         logger.debug("{}: {}", errorMsg, mapResponse);
175         return "";
176     }
177
178     public String getDeviceStatus(String device, String country) throws MiCloudException {
179         final String response = request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}");
180         logger.debug("response: {}", response);
181         return response;
182     }
183
184     public String sendRPCCommand(String device, String country, String command) throws MiCloudException {
185         if (device.length() != 8) {
186             logger.debug("Device ID ('{}') incorrect or missing. Command not send: {}", device, command);
187         }
188         if (country.length() > 3 || country.length() < 2) {
189             logger.debug("Country ('{}') incorrect or missing. Command not send: {}", device, command);
190         }
191         String id = "";
192         try {
193             id = String.valueOf(Long.parseUnsignedLong(device, 16));
194         } catch (NumberFormatException e) {
195             String err = "Could not parse device ID ('" + device.toString() + "')";
196             logger.debug("{}", err);
197             throw new MiCloudException(err, e);
198         }
199         final String response = request("/home/rpc/" + id, country, command);
200         logger.debug("response: {}", response);
201         return response;
202     }
203
204     public List<CloudDeviceDTO> getDevices(String country) {
205         final String response = getDeviceString(country);
206         List<CloudDeviceDTO> devicesList = new ArrayList<>();
207         try {
208             final JsonElement resp = PARSER.parse(response);
209             if (resp.isJsonObject()) {
210                 final JsonObject jor = resp.getAsJsonObject();
211                 if (jor.has("result")) {
212                     devicesList = GSON.fromJson(jor.get("result"), CloudDeviceListDTO.class).getCloudDevices();
213
214                     for (CloudDeviceDTO device : devicesList) {
215                         device.setServer(country);
216                         logger.debug("Xiaomi cloud info: {}", device);
217                     }
218                 } else {
219                     logger.debug("Response missing result: '{}'", response);
220                 }
221             } else {
222                 logger.debug("Response is not a json object: '{}'", response);
223             }
224         } catch (JsonSyntaxException | IllegalStateException | ClassCastException e) {
225             logger.info("Error while parsing devices: {}", e.getMessage());
226         }
227         return devicesList;
228     }
229
230     public String getDeviceString(String country) {
231         String resp;
232         try {
233             resp = request("/home/device_list", country, "{\"getVirtualModel\":false,\"getHuamiDevices\":0}");
234             logger.trace("Get devices response: {}", resp);
235             if (resp.length() > 2) {
236                 CloudUtil.saveDeviceInfoFile(resp, country, logger);
237                 return resp;
238             }
239         } catch (MiCloudException e) {
240             logger.info("{}", e.getMessage());
241         }
242         return "";
243     }
244
245     public String request(String urlPart, String country, String params) throws MiCloudException {
246         Map<String, String> map = new HashMap<String, String>();
247         map.put("data", params);
248         return request(urlPart, country, map);
249     }
250
251     public String request(String urlPart, String country, Map<String, String> params) throws MiCloudException {
252         String url = urlPart.trim();
253         url = getApiUrl(country) + (url.startsWith("/app") ? url.substring(4) : url);
254         String response = request(url, params);
255         logger.debug("Request to {} server {}. Response: {}", country, urlPart, response);
256         return response;
257     }
258
259     public String request(String url, Map<String, String> params) throws MiCloudException {
260         if (this.serviceToken.isEmpty() || this.userId.isEmpty()) {
261             throw new MiCloudException("Cannot execute request. service token or userId missing");
262         }
263         startClient();
264         logger.debug("Send request: {} to {}", params.get("data"), url);
265         Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
266         request.agent(USERAGENT);
267         request.header("x-xiaomi-protocal-flag-cli", "PROTOCAL-HTTP2");
268         request.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded");
269         request.cookie(new HttpCookie("userId", this.userId));
270         request.cookie(new HttpCookie("yetAnotherServiceToken", this.serviceToken));
271         request.cookie(new HttpCookie("serviceToken", this.serviceToken));
272         request.cookie(new HttpCookie("locale", locale.toString()));
273         request.cookie(new HttpCookie("timezone", ZonedDateTime.now().format(FORMATTER)));
274         request.cookie(new HttpCookie("is_daylight", TZ.inDaylightTime(new Date()) ? "1" : "0"));
275         request.cookie(new HttpCookie("dst_offset", Integer.toString(TZ.getDSTSavings())));
276         request.cookie(new HttpCookie("channel", "MI_APP_STORE"));
277
278         if (logger.isTraceEnabled()) {
279             for (HttpCookie cookie : request.getCookies()) {
280                 logger.trace("Cookie set for request ({}) : {} --> {}     (path: {})", cookie.getDomain(),
281                         cookie.getName(), cookie.getValue(), cookie.getPath());
282             }
283         }
284         String method = "POST";
285         request.method(method);
286
287         try {
288             String nonce = CloudUtil.generateNonce(System.currentTimeMillis());
289             String signedNonce = CloudUtil.signedNonce(ssecurity, nonce);
290             String signature = CloudUtil.generateSignature(url.replace("/app", ""), signedNonce, nonce, params);
291
292             Fields fields = new Fields();
293             fields.put("signature", signature);
294             fields.put("_nonce", nonce);
295             fields.put("data", params.get("data"));
296             request.content(new FormContentProvider(fields));
297
298             logger.trace("fieldcontent: {}", fields.toString());
299             final ContentResponse response = request.send();
300             if (response.getStatus() >= HttpStatus.BAD_REQUEST_400
301                     && response.getStatus() < HttpStatus.INTERNAL_SERVER_ERROR_500) {
302                 this.serviceToken = "";
303             }
304             return response.getContentAsString();
305         } catch (HttpResponseException e) {
306             serviceToken = "";
307             logger.debug("Error while executing request to {} :{}", url, e.getMessage());
308         } catch (InterruptedException | TimeoutException | ExecutionException | IOException e) {
309             logger.debug("Error while executing request to {} :{}", url, e.getMessage());
310         } catch (MiIoCryptoException e) {
311             logger.debug("Error while decrypting response of request to {} :{}", url, e.getMessage(), e);
312         }
313         return "";
314     }
315
316     private void addCookie(CookieStore cookieStore, String name, String value, String domain) {
317         HttpCookie cookie = new HttpCookie(name, value);
318         cookie.setDomain("." + domain);
319         cookie.setPath("/");
320         cookieStore.add(URI.create("https://" + domain), cookie);
321     }
322
323     public synchronized boolean login() {
324         if (!checkCredentials()) {
325             return false;
326         }
327         if (!userId.isEmpty() && !serviceToken.isEmpty()) {
328             return true;
329         }
330         logger.debug("Xiaomi cloud login with userid {}", username);
331         try {
332             if (loginRequest()) {
333                 loginFailedCounter = 0;
334             } else {
335                 loginFailedCounter++;
336                 logger.debug("Xiaomi cloud login attempt {}", loginFailedCounter);
337             }
338         } catch (MiCloudException e) {
339             logger.info("Error logging on to Xiaomi cloud ({}): {}", loginFailedCounter, e.getMessage());
340             loginFailedCounter++;
341             serviceToken = "";
342             if (loginFailedCounter > 10) {
343                 logger.info("Repeated errors logging on to Xiaomi cloud. Cleaning stored cookies");
344                 dumpCookies(".xiaomi.com", true);
345                 dumpCookies(".mi.com", true);
346             }
347             return false;
348         }
349         return true;
350     }
351
352     protected boolean loginRequest() throws MiCloudException {
353         try {
354             startClient();
355             String sign = loginStep1();
356             String location;
357             if (!sign.startsWith("http")) {
358                 location = loginStep2(sign);
359             } else {
360                 location = sign; // seems we already have login location
361             }
362             final ContentResponse responseStep3 = loginStep3(location);
363
364             switch (responseStep3.getStatus()) {
365                 case HttpStatus.FORBIDDEN_403:
366                     throw new MiCloudException("Access denied. Did you set the correct api-key and/or username?");
367                 case HttpStatus.OK_200:
368                     return true;
369                 default:
370                     logger.trace("request returned status '{}', reason: {}, content = {}", responseStep3.getStatus(),
371                             responseStep3.getReason(), responseStep3.getContentAsString());
372                     throw new MiCloudException(responseStep3.getStatus() + responseStep3.getReason());
373             }
374         } catch (InterruptedException | TimeoutException | ExecutionException e) {
375             throw new MiCloudException("Cannot logon to Xiaomi cloud: " + e.getMessage(), e);
376         } catch (MiIoCryptoException e) {
377             throw new MiCloudException("Error decrypting. Cannot logon to Xiaomi cloud: " + e.getMessage(), e);
378         } catch (MalformedURLException e) {
379             throw new MiCloudException("Error getting logon URL. Cannot logon to Xiaomi cloud: " + e.getMessage(), e);
380         }
381     }
382
383     private String loginStep1() throws InterruptedException, TimeoutException, ExecutionException, MiCloudException {
384         final ContentResponse responseStep1;
385
386         logger.trace("Xiaomi Login step 1");
387         String url = "https://account.xiaomi.com/pass/serviceLogin?sid=xiaomiio&_json=true";
388         Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
389         request.agent(USERAGENT);
390         request.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded");
391         request.cookie(new HttpCookie("userId", this.userId.length() > 0 ? this.userId : this.username));
392
393         responseStep1 = request.send();
394         final String content = responseStep1.getContentAsString();
395         logger.trace("Xiaomi Login step 1 content response= {}", content);
396         logger.trace("Xiaomi Login step 1 response = {}", responseStep1);
397         try {
398             JsonElement resp = new JsonParser().parse(parseJson(content));
399             if (resp.getAsJsonObject().has("_sign")) {
400                 String sign = resp.getAsJsonObject().get("_sign").getAsString();
401                 logger.trace("Xiaomi Login step 1 sign = {}", sign);
402                 return sign;
403             } else {
404                 logger.trace("Xiaomi Login _sign missing. Maybe still has login cookie.");
405                 return "";
406             }
407
408         } catch (JsonSyntaxException | NullPointerException e) {
409             throw new MiCloudException("Error getting logon sign. Cannot parse response: " + e.getMessage(), e);
410         }
411     }
412
413     private String loginStep2(String sign)
414             throws MiIoCryptoException, InterruptedException, TimeoutException, ExecutionException, MiCloudException {
415         String passToken;
416         String cUserId;
417
418         logger.trace("Xiaomi Login step 2");
419         String url = "https://account.xiaomi.com/pass/serviceLoginAuth2";
420         Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
421         request.agent(USERAGENT);
422         request.method(HttpMethod.POST);
423         final ContentResponse responseStep2;
424
425         Fields fields = new Fields();
426         fields.put("sid", "xiaomiio");
427         fields.put("hash", Utils.getHex(MiIoCrypto.md5(password.getBytes())));
428         fields.put("callback", "https://sts.api.io.mi.com/sts");
429         fields.put("qs", "%3Fsid%3Dxiaomiio%26_json%3Dtrue");
430         fields.put("user", username);
431         if (!sign.isEmpty()) {
432             fields.put("_sign", sign);
433         }
434         fields.put("_json", "true");
435
436         request.content(new FormContentProvider(fields));
437         responseStep2 = request.send();
438
439         final String content2 = responseStep2.getContentAsString();
440         logger.trace("Xiaomi login step 2 response = {}", responseStep2);
441         logger.trace("Xiaomi login step 2 content = {}", content2);
442
443         JsonElement resp2 = new JsonParser().parse(parseJson(content2));
444         CloudLoginDTO jsonResp = GSON.fromJson(resp2, CloudLoginDTO.class);
445
446         ssecurity = jsonResp.getSsecurity();
447         userId = jsonResp.getUserId();
448         cUserId = jsonResp.getcUserId();
449         passToken = jsonResp.getPassToken();
450         String location = jsonResp.getLocation();
451         String code = jsonResp.getCode();
452
453         logger.trace("Xiaomi login ssecurity = {}", ssecurity);
454         logger.trace("Xiaomi login userId = {}", userId);
455         logger.trace("Xiaomi login cUserId = {}", cUserId);
456         logger.trace("Xiaomi login passToken = {}", passToken);
457         logger.trace("Xiaomi login location = {}", location);
458         logger.trace("Xiaomi login code = {}", code);
459         if (logger.isTraceEnabled()) {
460             dumpCookies(url, false);
461         }
462         if (!location.isEmpty()) {
463             return location;
464         } else {
465             throw new MiCloudException("Error getting logon location URL. Return code: " + code);
466         }
467     }
468
469     private ContentResponse loginStep3(String location)
470             throws MalformedURLException, InterruptedException, TimeoutException, ExecutionException {
471         final ContentResponse responseStep3;
472         Request request;
473         logger.trace("Xiaomi Login step 3 @ {}", (new URL(location)).getHost());
474         request = httpClient.newRequest(location).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
475         request.agent(USERAGENT);
476         request.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded");
477         responseStep3 = request.send();
478         logger.trace("Xiaomi login step 3 content = {}", responseStep3.getContentAsString());
479         logger.trace("Xiaomi login step 3 response = {}", responseStep3);
480         if (logger.isTraceEnabled()) {
481             dumpCookies(location, false);
482         }
483         URI uri = URI.create("http://sts.api.io.mi.com");
484         String serviceToken = extractServiceToken(uri);
485         if (!serviceToken.isEmpty()) {
486             this.serviceToken = serviceToken;
487         }
488         return responseStep3;
489     }
490
491     private void dumpCookies(String url, boolean delete) {
492         if (logger.isTraceEnabled()) {
493             try {
494                 URI uri = URI.create(url);
495                 if (uri != null) {
496                     logger.trace("Cookie dump for {}", uri);
497                     CookieStore cs = httpClient.getCookieStore();
498                     List<HttpCookie> cookies = cs.get(uri);
499                     for (HttpCookie cookie : cookies) {
500                         logger.trace("Cookie ({}) : {} --> {}     (path: {}. Removed: {})", cookie.getDomain(),
501                                 cookie.getName(), cookie.getValue(), cookie.getPath(), delete);
502                         if (delete) {
503                             cs.remove(uri, cookie);
504                         }
505                     }
506                 } else {
507                     logger.trace("Could not create URI from {}", url);
508                 }
509             } catch (IllegalArgumentException | NullPointerException e) {
510                 logger.trace("Error dumping cookies from {}: {}", url, e.getMessage(), e);
511             }
512         }
513     }
514
515     private String extractServiceToken(URI uri) {
516         String serviceToken = "";
517         List<HttpCookie> cookies = httpClient.getCookieStore().get(uri);
518         for (HttpCookie cookie : cookies) {
519             logger.trace("Cookie :{} --> {}", cookie.getName(), cookie.getValue());
520             if (cookie.getName().contentEquals("serviceToken")) {
521                 serviceToken = cookie.getValue();
522                 logger.debug("Xiaomi cloud logon succesfull.");
523                 logger.trace("Xiaomi cloud servicetoken: {}", serviceToken);
524             }
525         }
526         return serviceToken;
527     }
528
529     public boolean hasLoginToken() {
530         return !serviceToken.isEmpty();
531     }
532 }