2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.miio.internal.cloud;
15 import java.io.IOException;
16 import java.net.CookieStore;
17 import java.net.HttpCookie;
18 import java.net.MalformedURLException;
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;
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;
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;
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;
59 * The {@link MiCloudConnector} class is used for connecting to the Xiaomi cloud access
61 * @author Marcel Verpaalen - Initial contribution
64 public class MiCloudConnector {
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();
78 private final String clientId;
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;
88 private final Logger logger = LoggerFactory.getLogger(MiCloudConnector.class);
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");
97 clientId = (new Random().ints(97, 122 + 1).limit(6)
98 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString());
101 void startClient() throws MiCloudException {
102 if (!httpClient.isStarted()) {
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);
117 public void stopClient() {
119 this.httpClient.stop();
120 } catch (Exception e) {
121 logger.debug("Error stopping httpclient :{}", e.getMessage(), e);
125 private boolean checkCredentials() {
126 if (username.trim().isEmpty() || password.trim().isEmpty()) {
127 logger.info("Xiaomi Cloud: username or password missing.");
133 private String getApiUrl(String country) {
134 return "https://" + (country.trim().equalsIgnoreCase("cn") ? "" : country.trim().toLowerCase() + ".")
135 + "api.io.mi.com/app";
138 public String getClientId() {
142 String parseJson(String data) {
143 if (data.contains("&&&START&&&")) {
144 return data.replace("&&&START&&&", "");
146 return UNEXPECTED.concat(data);
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();
163 String mapUrl = jo.get("url").getAsString();
164 return mapUrl != null ? mapUrl : "";
166 errorMsg = "Could not get url";
169 errorMsg = "Could not get result";
172 errorMsg = "Received message is invalid JSON";
174 logger.debug("{}: {}", errorMsg, mapResponse);
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);
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);
188 if (country.length() > 3 || country.length() < 2) {
189 logger.debug("Country ('{}') incorrect or missing. Command not send: {}", device, command);
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);
199 final String response = request("/home/rpc/" + id, country, command);
200 logger.debug("response: {}", response);
204 public List<CloudDeviceDTO> getDevices(String country) {
205 final String response = getDeviceString(country);
206 List<CloudDeviceDTO> devicesList = new ArrayList<>();
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();
214 for (CloudDeviceDTO device : devicesList) {
215 device.setServer(country);
216 logger.debug("Xiaomi cloud info: {}", device);
219 logger.debug("Response missing result: '{}'", response);
222 logger.debug("Response is not a json object: '{}'", response);
224 } catch (JsonSyntaxException | IllegalStateException | ClassCastException e) {
225 logger.info("Error while parsing devices: {}", e.getMessage());
230 public String getDeviceString(String country) {
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);
239 } catch (MiCloudException e) {
240 logger.info("{}", e.getMessage());
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);
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);
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");
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"));
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());
284 String method = "POST";
285 request.method(method);
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);
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));
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 = "";
304 return response.getContentAsString();
305 } catch (HttpResponseException e) {
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);
316 private void addCookie(CookieStore cookieStore, String name, String value, String domain) {
317 HttpCookie cookie = new HttpCookie(name, value);
318 cookie.setDomain("." + domain);
320 cookieStore.add(URI.create("https://" + domain), cookie);
323 public synchronized boolean login() {
324 if (!checkCredentials()) {
327 if (!userId.isEmpty() && !serviceToken.isEmpty()) {
330 logger.debug("Xiaomi cloud login with userid {}", username);
332 if (loginRequest()) {
333 loginFailedCounter = 0;
335 loginFailedCounter++;
336 logger.debug("Xiaomi cloud login attempt {}", loginFailedCounter);
338 } catch (MiCloudException e) {
339 logger.info("Error logging on to Xiaomi cloud ({}): {}", loginFailedCounter, e.getMessage());
340 loginFailedCounter++;
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);
352 protected boolean loginRequest() throws MiCloudException {
355 String sign = loginStep1();
357 if (!sign.startsWith("http")) {
358 location = loginStep2(sign);
360 location = sign; // seems we already have login location
362 final ContentResponse responseStep3 = loginStep3(location);
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:
370 logger.trace("request returned status '{}', reason: {}, content = {}", responseStep3.getStatus(),
371 responseStep3.getReason(), responseStep3.getContentAsString());
372 throw new MiCloudException(responseStep3.getStatus() + responseStep3.getReason());
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);
383 private String loginStep1() throws InterruptedException, TimeoutException, ExecutionException, MiCloudException {
384 final ContentResponse responseStep1;
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));
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);
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);
404 logger.trace("Xiaomi Login _sign missing. Maybe still has login cookie.");
408 } catch (JsonSyntaxException | NullPointerException e) {
409 throw new MiCloudException("Error getting logon sign. Cannot parse response: " + e.getMessage(), e);
413 private String loginStep2(String sign)
414 throws MiIoCryptoException, InterruptedException, TimeoutException, ExecutionException, MiCloudException {
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;
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);
434 fields.put("_json", "true");
436 request.content(new FormContentProvider(fields));
437 responseStep2 = request.send();
439 final String content2 = responseStep2.getContentAsString();
440 logger.trace("Xiaomi login step 2 response = {}", responseStep2);
441 logger.trace("Xiaomi login step 2 content = {}", content2);
443 JsonElement resp2 = new JsonParser().parse(parseJson(content2));
444 CloudLoginDTO jsonResp = GSON.fromJson(resp2, CloudLoginDTO.class);
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();
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);
462 if (!location.isEmpty()) {
465 throw new MiCloudException("Error getting logon location URL. Return code: " + code);
469 private ContentResponse loginStep3(String location)
470 throws MalformedURLException, InterruptedException, TimeoutException, ExecutionException {
471 final ContentResponse responseStep3;
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);
483 URI uri = URI.create("http://sts.api.io.mi.com");
484 String serviceToken = extractServiceToken(uri);
485 if (!serviceToken.isEmpty()) {
486 this.serviceToken = serviceToken;
488 return responseStep3;
491 private void dumpCookies(String url, boolean delete) {
492 if (logger.isTraceEnabled()) {
494 URI uri = URI.create(url);
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);
503 cs.remove(uri, cookie);
507 logger.trace("Could not create URI from {}", url);
509 } catch (IllegalArgumentException | NullPointerException e) {
510 logger.trace("Error dumping cookies from {}: {}", url, e.getMessage(), e);
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);
529 public boolean hasLoginToken() {
530 return !serviceToken.isEmpty();