]> git.basschouten.com Git - openhab-addons.git/blob
0e446b6a73c48207a46fff19a46092a6e5644ac0
[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                     return jo.get("url").getAsString();
164                 } else {
165                     errorMsg = "Could not get url";
166                 }
167             } else {
168                 errorMsg = "Could not get result";
169             }
170         } else {
171             errorMsg = "Received message is invalid JSON";
172         }
173         logger.debug("{}: {}", errorMsg, mapResponse);
174         return "";
175     }
176
177     public String getDeviceStatus(String device, String country) throws MiCloudException {
178         String url = getApiUrl(country) + "/home/device_list";
179         Map<String, String> map = new HashMap<String, String>();
180         map.put("data", "{\"dids\":[\"" + device + "\"]}");
181         final String response = request(url, map);
182         logger.debug("response: {}", response);
183         return response;
184     }
185
186     public List<CloudDeviceDTO> getDevices(String country) {
187         final String response = getDeviceString(country);
188         List<CloudDeviceDTO> devicesList = new ArrayList<>();
189         try {
190             final JsonElement resp = PARSER.parse(response);
191             if (resp.isJsonObject()) {
192                 final JsonObject jor = resp.getAsJsonObject();
193                 if (jor.has("result")) {
194                     devicesList = GSON.fromJson(jor.get("result"), CloudDeviceListDTO.class).getCloudDevices();
195
196                     for (CloudDeviceDTO device : devicesList) {
197                         device.setServer(country);
198                         logger.debug("Xiaomi cloud info: {}", device);
199                     }
200                 } else {
201                     logger.debug("Response missing result: '{}'", response);
202                 }
203             } else {
204                 logger.debug("Response is not a json object: '{}'", response);
205             }
206         } catch (JsonSyntaxException | IllegalStateException | ClassCastException e) {
207             logger.info("Error while parsing devices: {}", e.getMessage());
208         }
209         return devicesList;
210     }
211
212     public String getDeviceString(String country) {
213         String url = getApiUrl(country) + "/home/device_list";
214         Map<String, String> map = new HashMap<String, String>();
215         map.put("data", "{\"getVirtualModel\":false,\"getHuamiDevices\":0}");
216         String resp;
217         try {
218             resp = request(url, map);
219             logger.trace("Get devices response: {}", resp);
220             if (resp.length() > 2) {
221                 CloudUtil.saveDeviceInfoFile(resp, country, logger);
222                 return resp;
223             }
224         } catch (MiCloudException e) {
225             logger.info("{}", e.getMessage());
226         }
227         return "";
228     }
229
230     public String request(String urlPart, String country, Map<String, String> params) throws MiCloudException {
231         String url = getApiUrl(country) + urlPart;
232         String response = request(url, params);
233         logger.debug("Request to {} server {}. Response: {}", country, urlPart, response);
234         return response;
235     }
236
237     public String request(String url, Map<String, String> params) throws MiCloudException {
238         if (this.serviceToken.isEmpty() || this.userId.isEmpty()) {
239             throw new MiCloudException("Cannot execute request. service token or userId missing");
240         }
241         startClient();
242         logger.debug("Send request: {} to {}", params.get("data"), url);
243         Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
244         request.agent(USERAGENT);
245         request.header("x-xiaomi-protocal-flag-cli", "PROTOCAL-HTTP2");
246         request.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded");
247         request.cookie(new HttpCookie("userId", this.userId));
248         request.cookie(new HttpCookie("yetAnotherServiceToken", this.serviceToken));
249         request.cookie(new HttpCookie("serviceToken", this.serviceToken));
250         request.cookie(new HttpCookie("locale", locale.toString()));
251         request.cookie(new HttpCookie("timezone", ZonedDateTime.now().format(FORMATTER)));
252         request.cookie(new HttpCookie("is_daylight", TZ.inDaylightTime(new Date()) ? "1" : "0"));
253         request.cookie(new HttpCookie("dst_offset", Integer.toString(TZ.getDSTSavings())));
254         request.cookie(new HttpCookie("channel", "MI_APP_STORE"));
255
256         if (logger.isTraceEnabled()) {
257             for (HttpCookie cookie : request.getCookies()) {
258                 logger.trace("Cookie set for request ({}) : {} --> {}     (path: {})", cookie.getDomain(),
259                         cookie.getName(), cookie.getValue(), cookie.getPath());
260             }
261         }
262         String method = "POST";
263         request.method(method);
264
265         try {
266             String nonce = CloudUtil.generateNonce(System.currentTimeMillis());
267             String signedNonce = CloudUtil.signedNonce(ssecurity, nonce);
268             String signature = CloudUtil.generateSignature(url.replace("/app", ""), signedNonce, nonce, params);
269
270             Fields fields = new Fields();
271             fields.put("signature", signature);
272             fields.put("_nonce", nonce);
273             fields.put("data", params.get("data"));
274             request.content(new FormContentProvider(fields));
275
276             logger.trace("fieldcontent: {}", fields.toString());
277             final ContentResponse response = request.send();
278             if (response.getStatus() == HttpStatus.FORBIDDEN_403) {
279                 this.serviceToken = "";
280             }
281             return response.getContentAsString();
282         } catch (HttpResponseException e) {
283             serviceToken = "";
284             logger.debug("Error while executing request to {} :{}", url, e.getMessage());
285         } catch (InterruptedException | TimeoutException | ExecutionException | IOException e) {
286             logger.debug("Error while executing request to {} :{}", url, e.getMessage());
287         } catch (MiIoCryptoException e) {
288             logger.debug("Error while decrypting response of request to {} :{}", url, e.getMessage(), e);
289         }
290         return "";
291     }
292
293     private void addCookie(CookieStore cookieStore, String name, String value, String domain) {
294         HttpCookie cookie = new HttpCookie(name, value);
295         cookie.setDomain("." + domain);
296         cookie.setPath("/");
297         cookieStore.add(URI.create("https://" + domain), cookie);
298     }
299
300     public synchronized boolean login() {
301         if (!checkCredentials()) {
302             return false;
303         }
304         if (!userId.isEmpty() && !serviceToken.isEmpty()) {
305             return true;
306         }
307         logger.debug("Xiaomi cloud login with userid {}", username);
308         try {
309             if (loginRequest()) {
310                 loginFailedCounter = 0;
311             } else {
312                 loginFailedCounter++;
313                 logger.debug("Xiaomi cloud login attempt {}", loginFailedCounter);
314             }
315         } catch (MiCloudException e) {
316             logger.info("Error logging on to Xiaomi cloud ({}): {}", loginFailedCounter, e.getMessage());
317             loginFailedCounter++;
318             serviceToken = "";
319             if (loginFailedCounter > 10) {
320                 logger.info("Repeated errors logging on to Xiaomi cloud. Cleaning stored cookies");
321                 dumpCookies(".xiaomi.com", true);
322                 dumpCookies(".mi.com", true);
323             }
324             return false;
325         }
326         return true;
327     }
328
329     protected boolean loginRequest() throws MiCloudException {
330         try {
331             startClient();
332             String sign = loginStep1();
333             String location;
334             if (!sign.startsWith("http")) {
335                 location = loginStep2(sign);
336             } else {
337                 location = sign; // seems we already have login location
338             }
339             final ContentResponse responseStep3 = loginStep3(location);
340
341             switch (responseStep3.getStatus()) {
342                 case HttpStatus.FORBIDDEN_403:
343                     throw new MiCloudException("Access denied. Did you set the correct api-key and/or username?");
344                 case HttpStatus.OK_200:
345                     return true;
346                 default:
347                     logger.trace("request returned status '{}', reason: {}, content = {}", responseStep3.getStatus(),
348                             responseStep3.getReason(), responseStep3.getContentAsString());
349                     throw new MiCloudException(responseStep3.getStatus() + responseStep3.getReason());
350             }
351         } catch (InterruptedException | TimeoutException | ExecutionException e) {
352             throw new MiCloudException("Cannot logon to Xiaomi cloud: " + e.getMessage(), e);
353         } catch (MiIoCryptoException e) {
354             throw new MiCloudException("Error decrypting. Cannot logon to Xiaomi cloud: " + e.getMessage(), e);
355         } catch (MalformedURLException e) {
356             throw new MiCloudException("Error getting logon URL. Cannot logon to Xiaomi cloud: " + e.getMessage(), e);
357         }
358     }
359
360     private String loginStep1() throws InterruptedException, TimeoutException, ExecutionException, MiCloudException {
361         final ContentResponse responseStep1;
362
363         logger.trace("Xiaomi Login step 1");
364         String url = "https://account.xiaomi.com/pass/serviceLogin?sid=xiaomiio&_json=true";
365         Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
366         request.agent(USERAGENT);
367         request.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded");
368         request.cookie(new HttpCookie("userId", this.userId.length() > 0 ? this.userId : this.username));
369
370         responseStep1 = request.send();
371         final String content = responseStep1.getContentAsString();
372         logger.trace("Xiaomi Login step 1 content response= {}", content);
373         logger.trace("Xiaomi Login step 1 response = {}", responseStep1);
374         try {
375             JsonElement resp = new JsonParser().parse(parseJson(content));
376             if (resp.getAsJsonObject().has("_sign")) {
377                 String sign = resp.getAsJsonObject().get("_sign").getAsString();
378                 logger.trace("Xiaomi Login step 1 sign = {}", sign);
379                 return sign;
380             } else {
381                 logger.trace("Xiaomi Login _sign missing. Maybe still has login cookie.");
382                 return "";
383             }
384
385         } catch (JsonSyntaxException | NullPointerException e) {
386             throw new MiCloudException("Error getting logon sign. Cannot parse response: " + e.getMessage(), e);
387         }
388     }
389
390     private String loginStep2(String sign)
391             throws MiIoCryptoException, InterruptedException, TimeoutException, ExecutionException, MiCloudException {
392         String passToken;
393         String cUserId;
394
395         logger.trace("Xiaomi Login step 2");
396         String url = "https://account.xiaomi.com/pass/serviceLoginAuth2";
397         Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
398         request.agent(USERAGENT);
399         request.method(HttpMethod.POST);
400         final ContentResponse responseStep2;
401
402         Fields fields = new Fields();
403         fields.put("sid", "xiaomiio");
404         fields.put("hash", Utils.getHex(MiIoCrypto.md5(password.getBytes())));
405         fields.put("callback", "https://sts.api.io.mi.com/sts");
406         fields.put("qs", "%3Fsid%3Dxiaomiio%26_json%3Dtrue");
407         fields.put("user", username);
408         if (!sign.isEmpty()) {
409             fields.put("_sign", sign);
410         }
411         fields.put("_json", "true");
412
413         request.content(new FormContentProvider(fields));
414         responseStep2 = request.send();
415
416         final String content2 = responseStep2.getContentAsString();
417         logger.trace("Xiaomi login step 2 response = {}", responseStep2);
418         logger.trace("Xiaomi login step 2 content = {}", content2);
419
420         JsonElement resp2 = new JsonParser().parse(parseJson(content2));
421         CloudLoginDTO jsonResp = GSON.fromJson(resp2, CloudLoginDTO.class);
422
423         ssecurity = jsonResp.getSsecurity();
424         userId = jsonResp.getUserId();
425         cUserId = jsonResp.getcUserId();
426         passToken = jsonResp.getPassToken();
427         String location = jsonResp.getLocation();
428         String code = jsonResp.getCode();
429
430         logger.trace("Xiaomi login ssecurity = {}", ssecurity);
431         logger.trace("Xiaomi login userId = {}", userId);
432         logger.trace("Xiaomi login cUserId = {}", cUserId);
433         logger.trace("Xiaomi login passToken = {}", passToken);
434         logger.trace("Xiaomi login location = {}", location);
435         logger.trace("Xiaomi login code = {}", code);
436         if (logger.isTraceEnabled()) {
437             dumpCookies(url, false);
438         }
439         if (!location.isEmpty()) {
440             return location;
441         } else {
442             throw new MiCloudException("Error getting logon location URL. Return code: " + code);
443         }
444     }
445
446     private ContentResponse loginStep3(String location)
447             throws MalformedURLException, InterruptedException, TimeoutException, ExecutionException {
448         final ContentResponse responseStep3;
449         Request request;
450         logger.trace("Xiaomi Login step 3 @ {}", (new URL(location)).getHost());
451         request = httpClient.newRequest(location).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
452         request.agent(USERAGENT);
453         request.header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded");
454         responseStep3 = request.send();
455         logger.trace("Xiaomi login step 3 content = {}", responseStep3.getContentAsString());
456         logger.trace("Xiaomi login step 3 response = {}", responseStep3);
457         if (logger.isTraceEnabled()) {
458             dumpCookies(location, false);
459         }
460         URI uri = URI.create("http://sts.api.io.mi.com");
461         String serviceToken = extractServiceToken(uri);
462         if (!serviceToken.isEmpty()) {
463             this.serviceToken = serviceToken;
464         }
465         return responseStep3;
466     }
467
468     private void dumpCookies(String url, boolean delete) {
469         if (logger.isTraceEnabled()) {
470             try {
471                 URI uri = URI.create(url);
472                 if (uri != null) {
473                     logger.trace("Cookie dump for {}", uri);
474                     CookieStore cs = httpClient.getCookieStore();
475                     List<HttpCookie> cookies = cs.get(uri);
476                     for (HttpCookie cookie : cookies) {
477                         logger.trace("Cookie ({}) : {} --> {}     (path: {}. Removed: {})", cookie.getDomain(),
478                                 cookie.getName(), cookie.getValue(), cookie.getPath(), delete);
479                         if (delete) {
480                             cs.remove(uri, cookie);
481                         }
482                     }
483                 } else {
484                     logger.trace("Could not create URI from {}", url);
485                 }
486             } catch (IllegalArgumentException | NullPointerException e) {
487                 logger.trace("Error dumping cookies from {}: {}", url, e.getMessage(), e);
488             }
489         }
490     }
491
492     private String extractServiceToken(URI uri) {
493         String serviceToken = "";
494         List<HttpCookie> cookies = httpClient.getCookieStore().get(uri);
495         for (HttpCookie cookie : cookies) {
496             logger.trace("Cookie :{} --> {}", cookie.getName(), cookie.getValue());
497             if (cookie.getName().contentEquals("serviceToken")) {
498                 serviceToken = cookie.getValue();
499                 logger.debug("Xiaomi cloud logon succesfull.");
500                 logger.trace("Xiaomi cloud servicetoken: {}", serviceToken);
501             }
502         }
503         return serviceToken;
504     }
505
506     public boolean hasLoginToken() {
507         return !serviceToken.isEmpty();
508     }
509 }