]> git.basschouten.com Git - openhab-addons.git/blob
025dc2e86fc29f42fe9040fa27dfda7123bcd658
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.linky.internal.api;
14
15 import java.net.CookieStore;
16 import java.net.HttpCookie;
17 import java.net.URI;
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;
25
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;
46
47 import com.google.gson.Gson;
48 import com.google.gson.JsonSyntaxException;
49
50 /**
51  * {@link EnedisHttpApi} wraps the Enedis Webservice.
52  *
53  * @author GaĆ«l L'hopital - Initial contribution
54  */
55 @NonNullByDefault
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";
63
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;
70
71     public EnedisHttpApi(LinkyConfiguration config, Gson gson, HttpClient httpClient) {
72         this.gson = gson;
73         this.httpClient = httpClient;
74         this.config = config;
75         this.cookieStore = httpClient.getCookieStore();
76         addCookie(LinkyConfiguration.INTERNAL_AUTH_ID, config.internalAuthId);
77     }
78
79     public void initialize() throws LinkyException {
80         logger.debug("Starting login process for user : {}", config.username);
81
82         try {
83             logger.debug("Step 1 : getting authentification");
84             String data = getData(URL_ENEDIS_AUTHENTICATE);
85
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();
90
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");
96             }
97
98             logger.debug("Get the location and the ReqID");
99             Pattern p = Pattern.compile("ReqID%(.*?)%26");
100             Matcher m = p.matcher(getLocation(result));
101             if (!m.find()) {
102                 throw new LinkyException("Unable to locate ReqId in header");
103             }
104
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%"
108                     + 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=";
110
111             logger.debug(
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());
117             }
118
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                 logger.debug("auth1 - invalid template for auth data: {}", result.getContentAsString());
124                 throw new LinkyException("Authentication error, the authentication_cookie is probably wrong");
125             }
126
127             authData.callbacks.get(1).input.get(0).value = config.password;
128             url = URL_MON_COMPTE
129                     + "/auth/json/authenticate?realm=/enedis&spEntityID=SP-ODW-PROD&goto=/auth/SSOPOST/metaAlias/enedis/providerIDP?ReqID%"
130                     + reqId
131                     + "%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
133             logger.debug("Step 3 : auth2 - send the auth data");
134             result = httpClient.POST(url).header(HttpHeader.CONTENT_TYPE, "application/json")
135                     .header("X-NoSession", "true").header("X-Password", "anonymous")
136                     .header("X-Requested-With", "XMLHttpRequest").header("X-Username", "anonymous")
137                     .content(new StringContentProvider(gson.toJson(authData))).send();
138             if (result.getStatus() != 200) {
139                 throw new LinkyException("Connection failed step 3 - auth2 : " + result.getContentAsString());
140             }
141
142             AuthResult authResult = gson.fromJson(result.getContentAsString(), AuthResult.class);
143             if (authResult == null) {
144                 throw new LinkyException("Invalid authentication result data");
145             }
146
147             logger.debug("Add the tokenId cookie");
148             addCookie("enedisExt", authResult.tokenId);
149
150             logger.debug("Step 4 : retrieve the SAMLresponse");
151             data = getData(URL_MON_COMPTE + "/" + authResult.successUrl);
152             htmlDocument = Jsoup.parse(data);
153             el = htmlDocument.select("form").first();
154             samlInput = el.select("input[name=SAMLResponse]").first();
155
156             logger.debug("Step 5 : post the SAMLresponse to finish the authentication");
157             result = httpClient.POST(el.attr("action")).content(getFormContent("SAMLResponse", samlInput.attr("value")))
158                     .send();
159             if (result.getStatus() != 302) {
160                 throw new LinkyException("Connection failed step 5");
161             }
162             connected = true;
163         } catch (InterruptedException | TimeoutException | ExecutionException | JsonSyntaxException e) {
164             throw new LinkyException("Error opening connection with Enedis webservice", e);
165         }
166     }
167
168     private String getLocation(ContentResponse response) {
169         return response.getHeaders().get(HttpHeader.LOCATION);
170     }
171
172     private void disconnect() throws LinkyException {
173         if (connected) {
174             logger.debug("Logout process");
175             try { // Three times in a row to get disconnected
176                 String location = getLocation(httpClient.GET(URL_APPS_LINCS + "/logout"));
177                 location = getLocation(httpClient.GET(location));
178                 location = getLocation(httpClient.GET(location));
179                 cookieStore.removeAll();
180                 connected = false;
181             } catch (InterruptedException | ExecutionException | TimeoutException e) {
182                 throw new LinkyException("Error while disconnecting from Enedis webservice", e);
183             }
184         }
185     }
186
187     public boolean isConnected() {
188         return connected;
189     }
190
191     public void dispose() throws LinkyException {
192         disconnect();
193     }
194
195     private void addCookie(String key, String value) {
196         HttpCookie cookie = new HttpCookie(key, value);
197         cookie.setDomain(".enedis.fr");
198         cookie.setPath("/");
199         cookieStore.add(URI.create(URL_COOKIE), cookie);
200     }
201
202     private FormContentProvider getFormContent(String fieldName, String fieldValue) {
203         Fields fields = new Fields();
204         fields.put(fieldName, fieldValue);
205         return new FormContentProvider(fields);
206     }
207
208     private String getData(String url) throws LinkyException {
209         try {
210             ContentResponse result = httpClient.GET(url);
211             if (result.getStatus() != 200) {
212                 throw new LinkyException(String.format("Error requesting '%s' : %s", url, result.getContentAsString()));
213             }
214             return result.getContentAsString();
215         } catch (InterruptedException | ExecutionException | TimeoutException e) {
216             throw new LinkyException(String.format("Error getting url : '%s'", url), e);
217         }
218     }
219
220     public PrmInfo getPrmInfo() throws LinkyException {
221         if (!connected) {
222             initialize();
223         }
224         final String prm_info_url = URL_APPS_LINCS + "/mes-mesures/api/private/v1/personnes/null/prms";
225         String data = getData(prm_info_url);
226         if (data.isEmpty()) {
227             throw new LinkyException(String.format("Requesting '%s' returned an empty response", prm_info_url));
228         }
229         try {
230             PrmInfo[] prms = gson.fromJson(data, PrmInfo[].class);
231             if (prms == null || prms.length < 1) {
232                 throw new LinkyException("Invalid prms data received");
233             }
234             return prms[0];
235         } catch (JsonSyntaxException e) {
236             logger.debug("invalid JSON response not matching PrmInfo[].class: {}", data);
237             throw new LinkyException(String.format("Requesting '%s' returned an invalid JSON response : %s",
238                     prm_info_url, e.getMessage()), e);
239         }
240     }
241
242     public UserInfo getUserInfo() throws LinkyException {
243         if (!connected) {
244             initialize();
245         }
246         final String user_info_url = URL_APPS_LINCS + "/userinfos";
247         String data = getData(user_info_url);
248         if (data.isEmpty()) {
249             throw new LinkyException(String.format("Requesting '%s' returned an empty response", user_info_url));
250         }
251         try {
252             return Objects.requireNonNull(gson.fromJson(data, UserInfo.class));
253         } catch (JsonSyntaxException e) {
254             logger.debug("invalid JSON response not matching UserInfo.class: {}", data);
255             throw new LinkyException(String.format("Requesting '%s' returned an invalid JSON response : %s",
256                     user_info_url, e.getMessage()), e);
257         }
258     }
259
260     private Consumption getMeasures(String userId, String prmId, LocalDate from, LocalDate to, String request)
261             throws LinkyException {
262         final String measure_url = URL_APPS_LINCS
263                 + "/mes-mesures/api/private/v1/personnes/%s/prms/%s/donnees-%s?dateDebut=%s&dateFin=%s&mesuretypecode=CONS";
264         String url = String.format(measure_url, userId, prmId, request, from.format(API_DATE_FORMAT),
265                 to.format(API_DATE_FORMAT));
266         String data = getData(url);
267         if (data.isEmpty()) {
268             throw new LinkyException(String.format("Requesting '%s' returned an empty response", url));
269         }
270         logger.trace("getData returned {}", data);
271         try {
272             ConsumptionReport report = gson.fromJson(data, ConsumptionReport.class);
273             if (report == null) {
274                 throw new LinkyException("No report data received");
275             }
276             return report.firstLevel.consumptions;
277         } catch (JsonSyntaxException e) {
278             logger.debug("invalid JSON response not matching ConsumptionReport.class: {}", data);
279             throw new LinkyException(
280                     String.format("Requesting '%s' returned an invalid JSON response : %s", url, e.getMessage()), e);
281         }
282     }
283
284     public Consumption getEnergyData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
285         if (!connected) {
286             initialize();
287         }
288         return getMeasures(userId, prmId, from, to, "energie");
289     }
290
291     public Consumption getPowerData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
292         if (!connected) {
293             initialize();
294         }
295         return getMeasures(userId, prmId, from, to, "pmax");
296     }
297 }