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.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;
50 * {@link EnedisHttpApi} wraps the Enedis Webservice.
52 * @author Gaƫl L'hopital - Initial contribution
55 public class EnedisHttpApi {
56 private static final DateTimeFormatter API_DATE_FORMAT = DateTimeFormatter.ofPattern("dd-MM-yyyy");
57 private static final String URL_APPS_LINCS = "https://apps.lincs.enedis.fr";
58 private static final String URL_MON_COMPTE = "https://mon-compte.enedis.fr";
59 private static final String URL_ENEDIS_AUTHENTICATE = URL_APPS_LINCS
60 + "/authenticate?target=https://mon-compte-particulier.enedis.fr/suivi-de-mesure/";
61 private static final String URL_COOKIE = "https://mon-compte-particulier.enedis.fr";
63 private final Logger logger = LoggerFactory.getLogger(EnedisHttpApi.class);
64 private final Gson gson;
65 private final HttpClient httpClient;
66 private final LinkyConfiguration config;
67 private boolean connected = false;
69 public EnedisHttpApi(LinkyConfiguration config, Gson gson, HttpClient httpClient) {
71 this.httpClient = httpClient;
75 public void initialize() throws LinkyException {
76 addCookie(LinkyConfiguration.INTERNAL_AUTH_ID, config.internalAuthId);
78 logger.debug("Starting login process for user : {}", config.username);
81 logger.debug("Step 1 : getting authentification");
82 String data = getData(URL_ENEDIS_AUTHENTICATE);
84 logger.debug("Reception request SAML");
85 Document htmlDocument = Jsoup.parse(data);
86 Element el = htmlDocument.select("form").first();
87 Element samlInput = el.select("input[name=SAMLRequest]").first();
89 logger.debug("Step 2 : send SSO SAMLRequest");
90 ContentResponse result = httpClient.POST(el.attr("action"))
91 .content(getFormContent("SAMLRequest", samlInput.attr("value"))).send();
92 if (result.getStatus() != 302) {
93 throw new LinkyException("Connection failed step 2");
96 logger.debug("Get the location and the ReqID");
97 Pattern p = Pattern.compile("ReqID%(.*?)%26");
98 Matcher m = p.matcher(getLocation(result));
100 throw new LinkyException("Unable to locate ReqId in header");
103 String reqId = m.group(1);
104 String url = URL_MON_COMPTE
105 + "/auth/json/authenticate?realm=/enedis&forward=true&spEntityID=SP-ODW-PROD&goto=/auth/SSOPOST/metaAlias/enedis/providerIDP?ReqID%"
107 + "%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=";
110 "Step 3 : auth1 - retrieve the template, thanks to cookie internalAuthId, user is already set");
111 result = httpClient.POST(url).send();
112 if (result.getStatus() != 200) {
113 throw new LinkyException("Connection failed step 3 - auth1 : " + result.getContentAsString());
116 AuthData authData = gson.fromJson(result.getContentAsString(), AuthData.class);
117 if (authData.callbacks.size() < 2 || authData.callbacks.get(0).input.size() == 0
118 || authData.callbacks.get(1).input.size() == 0 || !config.username
119 .equals(Objects.requireNonNull(authData.callbacks.get(0).input.get(0)).valueAsString())) {
120 throw new LinkyException("Authentication error, the authentication_cookie is probably wrong");
123 authData.callbacks.get(1).input.get(0).value = config.password;
124 url = "https://mon-compte.enedis.fr/auth/json/authenticate?realm=/enedis&spEntityID=SP-ODW-PROD&goto=/auth/SSOPOST/metaAlias/enedis/providerIDP?ReqID%"
126 + "%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=";
128 logger.debug("Step 3 : auth2 - send the auth data");
129 result = httpClient.POST(url).header(HttpHeader.CONTENT_TYPE, "application/json")
130 .content(new StringContentProvider(gson.toJson(authData))).send();
131 if (result.getStatus() != 200) {
132 throw new LinkyException("Connection failed step 3 - auth2 : " + result.getContentAsString());
135 AuthResult authResult = gson.fromJson(result.getContentAsString(), AuthResult.class);
136 logger.debug("Add the tokenId cookie");
137 addCookie("enedisExt", authResult.tokenId);
139 logger.debug("Step 4 : retrieve the SAMLresponse");
140 data = getData(URL_MON_COMPTE + "/" + authResult.successUrl);
141 htmlDocument = Jsoup.parse(data);
142 el = htmlDocument.select("form").first();
143 samlInput = el.select("input[name=SAMLResponse]").first();
145 logger.debug("Step 5 : post the SAMLresponse to finish the authentication");
146 result = httpClient.POST(el.attr("action")).content(getFormContent("SAMLResponse", samlInput.attr("value")))
148 if (result.getStatus() != 302) {
149 throw new LinkyException("Connection failed step 5");
152 } catch (InterruptedException | TimeoutException | ExecutionException e) {
153 throw new LinkyException("Error opening connection with Enedis webservice", e);
157 public String getLocation(ContentResponse response) {
158 return response.getHeaders().get(HttpHeader.LOCATION);
161 public void disconnect() throws LinkyException {
163 try { // Three times in a row to get disconnected
164 String location = getLocation(httpClient.GET(URL_APPS_LINCS + "/logout"));
165 location = getLocation(httpClient.GET(location));
166 location = getLocation(httpClient.GET(location));
167 CookieStore cookieStore = httpClient.getCookieStore();
168 cookieStore.removeAll();
170 } catch (InterruptedException | ExecutionException | TimeoutException e) {
171 throw new LinkyException("Error while disconnecting from Enedis webservice", e);
176 public void dispose() throws LinkyException {
180 private void addCookie(String key, String value) {
181 CookieStore cookieStore = httpClient.getCookieStore();
182 HttpCookie cookie = new HttpCookie(key, value);
183 cookie.setDomain(".enedis.fr");
185 cookieStore.add(URI.create(URL_COOKIE), cookie);
188 private FormContentProvider getFormContent(String fieldName, String fieldValue) {
189 Fields fields = new Fields();
190 fields.put(fieldName, fieldValue);
191 return new FormContentProvider(fields);
194 private String getData(String url) throws LinkyException {
196 ContentResponse result = httpClient.GET(url);
197 if (result.getStatus() != 200) {
198 throw new LinkyException(String.format("Error requesting '%s' : %s", url, result.getContentAsString()));
200 return result.getContentAsString();
201 } catch (InterruptedException | ExecutionException | TimeoutException e) {
202 throw new LinkyException(String.format("Error getting url : '%s'", url), e);
206 public PrmInfo getPrmInfo() throws LinkyException {
207 final String prm_info_url = URL_APPS_LINCS + "/mes-mesures/api/private/v1/personnes/null/prms";
208 String data = getData(prm_info_url);
209 PrmInfo[] prms = gson.fromJson(data, PrmInfo[].class);
213 public UserInfo getUserInfo() throws LinkyException {
214 final String user_info_url = URL_APPS_LINCS + "/userinfos";
215 String data = getData(user_info_url);
216 return gson.fromJson(data, UserInfo.class);
219 private Consumption getMeasures(String userId, String prmId, LocalDate from, LocalDate to, String request)
220 throws LinkyException {
221 final String measure_url = URL_APPS_LINCS
222 + "/mes-mesures/api/private/v1/personnes/%s/prms/%s/donnees-%s?dateDebut=%s&dateFin=%s&mesuretypecode=CONS";
223 String url = String.format(measure_url, userId, prmId, request, from.format(API_DATE_FORMAT),
224 to.format(API_DATE_FORMAT));
225 String data = getData(url);
226 ConsumptionReport report = gson.fromJson(data, ConsumptionReport.class);
227 return report.firstLevel.consumptions;
230 public Consumption getEnergyData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
231 return getMeasures(userId, prmId, from, to, "energie");
234 public Consumption getPowerData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
235 return getMeasures(userId, prmId, from, to, "pmax");