2 * Copyright (c) 2010-2021 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.linky.internal.api;
15 import java.net.CookieStore;
16 import java.net.HttpCookie;
18 import java.time.LocalDate;
19 import java.time.format.DateTimeFormatter;
20 import java.util.Objects;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeoutException;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jetty.client.HttpClient;
28 import org.eclipse.jetty.client.api.ContentResponse;
29 import org.eclipse.jetty.client.util.FormContentProvider;
30 import org.eclipse.jetty.client.util.StringContentProvider;
31 import org.eclipse.jetty.http.HttpHeader;
32 import org.eclipse.jetty.util.Fields;
33 import org.jsoup.Jsoup;
34 import org.jsoup.nodes.Document;
35 import org.jsoup.nodes.Element;
36 import org.openhab.binding.linky.internal.LinkyConfiguration;
37 import org.openhab.binding.linky.internal.LinkyException;
38 import org.openhab.binding.linky.internal.dto.AuthData;
39 import org.openhab.binding.linky.internal.dto.AuthResult;
40 import org.openhab.binding.linky.internal.dto.ConsumptionReport;
41 import org.openhab.binding.linky.internal.dto.ConsumptionReport.Consumption;
42 import org.openhab.binding.linky.internal.dto.PrmInfo;
43 import org.openhab.binding.linky.internal.dto.UserInfo;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 import com.google.gson.Gson;
48 import com.google.gson.JsonSyntaxException;
51 * {@link EnedisHttpApi} wraps the Enedis Webservice.
53 * @author Gaƫl L'hopital - Initial contribution
56 public class EnedisHttpApi {
57 private static final DateTimeFormatter API_DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy");
58 private static final String URL_APPS_LINCS = "https://apps.lincs.enedis.fr";
59 private static final String URL_MON_COMPTE = "https://mon-compte.enedis.fr";
60 private static final String URL_ENEDIS_AUTHENTICATE = URL_APPS_LINCS
61 + "/authenticate?target=https://mon-compte-particulier.enedis.fr/suivi-de-mesure/";
62 private static final String URL_COOKIE = "https://mon-compte-particulier.enedis.fr";
64 private final Logger logger = LoggerFactory.getLogger(EnedisHttpApi.class);
65 private final Gson gson;
66 private final HttpClient httpClient;
67 private boolean connected = false;
68 private final CookieStore cookieStore;
69 private final LinkyConfiguration config;
71 public EnedisHttpApi(LinkyConfiguration config, Gson gson, HttpClient httpClient) {
73 this.httpClient = httpClient;
75 this.cookieStore = httpClient.getCookieStore();
76 addCookie(LinkyConfiguration.INTERNAL_AUTH_ID, config.internalAuthId);
79 public void initialize() throws LinkyException {
80 logger.debug("Starting login process for user : {}", config.username);
83 logger.debug("Step 1 : getting authentification");
84 String data = getData(URL_ENEDIS_AUTHENTICATE);
86 logger.debug("Reception request SAML");
87 Document htmlDocument = Jsoup.parse(data);
88 Element el = htmlDocument.select("form").first();
89 Element samlInput = el.select("input[name=SAMLRequest]").first();
91 logger.debug("Step 2 : send SSO SAMLRequest");
92 ContentResponse result = httpClient.POST(el.attr("action"))
93 .content(getFormContent("SAMLRequest", samlInput.attr("value"))).send();
94 if (result.getStatus() != 302) {
95 throw new LinkyException("Connection failed step 2");
98 logger.debug("Get the location and the ReqID");
99 Pattern p = Pattern.compile("ReqID%(.*?)%26");
100 Matcher m = p.matcher(getLocation(result));
102 throw new LinkyException("Unable to locate ReqId in header");
105 String reqId = m.group(1);
106 String url = URL_MON_COMPTE
107 + "/auth/json/authenticate?realm=/enedis&forward=true&spEntityID=SP-ODW-PROD&goto=/auth/SSOPOST/metaAlias/enedis/providerIDP?ReqID%"
109 + "%26index%3Dnull%26acsURL%3Dhttps://apps.lincs.enedis.fr/saml/SSO%26spEntityID%3DSP-ODW-PROD%26binding%3Durn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST&AMAuthCookie=";
112 "Step 3 : auth1 - retrieve the template, thanks to cookie internalAuthId, user is already set");
113 result = httpClient.POST(url).header("X-NoSession", "true").header("X-Password", "anonymous")
114 .header("X-Requested-With", "XMLHttpRequest").header("X-Username", "anonymous").send();
115 if (result.getStatus() != 200) {
116 throw new LinkyException("Connection failed step 3 - auth1 : " + result.getContentAsString());
119 AuthData authData = gson.fromJson(result.getContentAsString(), AuthData.class);
120 if (authData == null || authData.callbacks.size() < 2 || authData.callbacks.get(0).input.isEmpty()
121 || authData.callbacks.get(1).input.isEmpty() || !config.username
122 .equals(Objects.requireNonNull(authData.callbacks.get(0).input.get(0)).valueAsString())) {
123 throw new LinkyException("Authentication error, the authentication_cookie is probably wrong");
126 authData.callbacks.get(1).input.get(0).value = config.password;
128 + "/auth/json/authenticate?realm=/enedis&spEntityID=SP-ODW-PROD&goto=/auth/SSOPOST/metaAlias/enedis/providerIDP?ReqID%"
130 + "%26index%3Dnull%26acsURL%3Dhttps://apps.lincs.enedis.fr/saml/SSO%26spEntityID%3DSP-ODW-PROD%26binding%3Durn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST&AMAuthCookie=";
132 logger.debug("Step 3 : auth2 - send the auth data");
133 result = httpClient.POST(url).header(HttpHeader.CONTENT_TYPE, "application/json")
134 .header("X-NoSession", "true").header("X-Password", "anonymous")
135 .header("X-Requested-With", "XMLHttpRequest").header("X-Username", "anonymous")
136 .content(new StringContentProvider(gson.toJson(authData))).send();
137 if (result.getStatus() != 200) {
138 throw new LinkyException("Connection failed step 3 - auth2 : " + result.getContentAsString());
141 AuthResult authResult = gson.fromJson(result.getContentAsString(), AuthResult.class);
142 if (authResult == null) {
143 throw new LinkyException("Invalid authentication result data");
146 logger.debug("Add the tokenId cookie");
147 addCookie("enedisExt", authResult.tokenId);
149 logger.debug("Step 4 : retrieve the SAMLresponse");
150 data = getData(URL_MON_COMPTE + "/" + authResult.successUrl);
151 htmlDocument = Jsoup.parse(data);
152 el = htmlDocument.select("form").first();
153 samlInput = el.select("input[name=SAMLResponse]").first();
155 logger.debug("Step 5 : post the SAMLresponse to finish the authentication");
156 result = httpClient.POST(el.attr("action")).content(getFormContent("SAMLResponse", samlInput.attr("value")))
158 if (result.getStatus() != 302) {
159 throw new LinkyException("Connection failed step 5");
162 } catch (InterruptedException | TimeoutException | ExecutionException | JsonSyntaxException e) {
163 throw new LinkyException("Error opening connection with Enedis webservice", e);
167 private String getLocation(ContentResponse response) {
168 return response.getHeaders().get(HttpHeader.LOCATION);
171 private void disconnect() throws LinkyException {
173 logger.debug("Logout process");
174 try { // Three times in a row to get disconnected
175 String location = getLocation(httpClient.GET(URL_APPS_LINCS + "/logout"));
176 location = getLocation(httpClient.GET(location));
177 location = getLocation(httpClient.GET(location));
178 cookieStore.removeAll();
180 } catch (InterruptedException | ExecutionException | TimeoutException e) {
181 throw new LinkyException("Error while disconnecting from Enedis webservice", e);
186 public boolean isConnected() {
190 public void dispose() throws LinkyException {
194 private void addCookie(String key, String value) {
195 HttpCookie cookie = new HttpCookie(key, value);
196 cookie.setDomain(".enedis.fr");
198 cookieStore.add(URI.create(URL_COOKIE), cookie);
201 private FormContentProvider getFormContent(String fieldName, String fieldValue) {
202 Fields fields = new Fields();
203 fields.put(fieldName, fieldValue);
204 return new FormContentProvider(fields);
207 private String getData(String url) throws LinkyException {
209 ContentResponse result = httpClient.GET(url);
210 if (result.getStatus() != 200) {
211 throw new LinkyException(String.format("Error requesting '%s' : %s", url, result.getContentAsString()));
213 return result.getContentAsString();
214 } catch (InterruptedException | ExecutionException | TimeoutException e) {
215 throw new LinkyException(String.format("Error getting url : '%s'", url), e);
219 public PrmInfo getPrmInfo() throws LinkyException {
223 final String prm_info_url = URL_APPS_LINCS + "/mes-mesures/api/private/v1/personnes/null/prms";
224 String data = getData(prm_info_url);
225 if (data.isEmpty()) {
226 throw new LinkyException(String.format("Requesting '%s' returned an empty response", prm_info_url));
229 PrmInfo[] prms = gson.fromJson(data, PrmInfo[].class);
230 if (prms == null || prms.length < 1) {
231 throw new LinkyException("Invalid prms data received");
234 } catch (JsonSyntaxException e) {
235 logger.debug("invalid JSON response not matching PrmInfo[].class: {}", data);
236 throw new LinkyException(String.format("Requesting '%s' returned an invalid JSON response : %s",
237 prm_info_url, e.getMessage()), e);
241 public UserInfo getUserInfo() throws LinkyException {
245 final String user_info_url = URL_APPS_LINCS + "/userinfos";
246 String data = getData(user_info_url);
247 if (data.isEmpty()) {
248 throw new LinkyException(String.format("Requesting '%s' returned an empty response", user_info_url));
251 return Objects.requireNonNull(gson.fromJson(data, UserInfo.class));
252 } catch (JsonSyntaxException e) {
253 logger.debug("invalid JSON response not matching UserInfo.class: {}", data);
254 throw new LinkyException(String.format("Requesting '%s' returned an invalid JSON response : %s",
255 user_info_url, e.getMessage()), e);
259 private Consumption getMeasures(String userId, String prmId, LocalDate from, LocalDate to, String request)
260 throws LinkyException {
261 final String measure_url = URL_APPS_LINCS
262 + "/mes-mesures/api/private/v1/personnes/%s/prms/%s/donnees-%s?dateDebut=%s&dateFin=%s&mesuretypecode=CONS";
263 String url = String.format(measure_url, userId, prmId, request, from.format(API_DATE_FORMAT),
264 to.format(API_DATE_FORMAT));
265 String data = getData(url);
266 if (data.isEmpty()) {
267 throw new LinkyException(String.format("Requesting '%s' returned an empty response", url));
269 logger.trace("getData returned {}", data);
271 ConsumptionReport report = gson.fromJson(data, ConsumptionReport.class);
272 if (report == null) {
273 throw new LinkyException("No report data received");
275 return report.firstLevel.consumptions;
276 } catch (JsonSyntaxException e) {
277 logger.debug("invalid JSON response not matching ConsumptionReport.class: {}", data);
278 throw new LinkyException(
279 String.format("Requesting '%s' returned an invalid JSON response : %s", url, e.getMessage()), e);
283 public Consumption getEnergyData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
287 return getMeasures(userId, prmId, from, to, "energie");
290 public Consumption getPowerData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
294 return getMeasures(userId, prmId, from, to, "pmax");