]> git.basschouten.com Git - openhab-addons.git/blob
47f964df666aad1c4354b70e2e8c904bcd000e76
[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                 throw new LinkyException("Authentication error, the authentication_cookie is probably wrong");
124             }
125
126             authData.callbacks.get(1).input.get(0).value = config.password;
127             url = URL_MON_COMPTE
128                     + "/auth/json/authenticate?realm=/enedis&spEntityID=SP-ODW-PROD&goto=/auth/SSOPOST/metaAlias/enedis/providerIDP?ReqID%"
129                     + 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=";
131
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());
139             }
140
141             AuthResult authResult = gson.fromJson(result.getContentAsString(), AuthResult.class);
142             if (authResult == null) {
143                 throw new LinkyException("Invalid authentication result data");
144             }
145
146             logger.debug("Add the tokenId cookie");
147             addCookie("enedisExt", authResult.tokenId);
148
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();
154
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")))
157                     .send();
158             if (result.getStatus() != 302) {
159                 throw new LinkyException("Connection failed step 5");
160             }
161             connected = true;
162         } catch (InterruptedException | TimeoutException | ExecutionException | JsonSyntaxException e) {
163             throw new LinkyException("Error opening connection with Enedis webservice", e);
164         }
165     }
166
167     private String getLocation(ContentResponse response) {
168         return response.getHeaders().get(HttpHeader.LOCATION);
169     }
170
171     private void disconnect() throws LinkyException {
172         if (connected) {
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();
179                 connected = false;
180             } catch (InterruptedException | ExecutionException | TimeoutException e) {
181                 throw new LinkyException("Error while disconnecting from Enedis webservice", e);
182             }
183         }
184     }
185
186     public boolean isConnected() {
187         return connected;
188     }
189
190     public void dispose() throws LinkyException {
191         disconnect();
192     }
193
194     private void addCookie(String key, String value) {
195         HttpCookie cookie = new HttpCookie(key, value);
196         cookie.setDomain(".enedis.fr");
197         cookie.setPath("/");
198         cookieStore.add(URI.create(URL_COOKIE), cookie);
199     }
200
201     private FormContentProvider getFormContent(String fieldName, String fieldValue) {
202         Fields fields = new Fields();
203         fields.put(fieldName, fieldValue);
204         return new FormContentProvider(fields);
205     }
206
207     private String getData(String url) throws LinkyException {
208         try {
209             ContentResponse result = httpClient.GET(url);
210             if (result.getStatus() != 200) {
211                 throw new LinkyException(String.format("Error requesting '%s' : %s", url, result.getContentAsString()));
212             }
213             return result.getContentAsString();
214         } catch (InterruptedException | ExecutionException | TimeoutException e) {
215             throw new LinkyException(String.format("Error getting url : '%s'", url), e);
216         }
217     }
218
219     public PrmInfo getPrmInfo() throws LinkyException {
220         if (!connected) {
221             initialize();
222         }
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));
227         }
228         try {
229             PrmInfo[] prms = gson.fromJson(data, PrmInfo[].class);
230             if (prms == null || prms.length < 1) {
231                 throw new LinkyException("Invalid prms data received");
232             }
233             return prms[0];
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);
238         }
239     }
240
241     public UserInfo getUserInfo() throws LinkyException {
242         if (!connected) {
243             initialize();
244         }
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));
249         }
250         try {
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);
256         }
257     }
258
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));
268         }
269         logger.trace("getData returned {}", data);
270         try {
271             ConsumptionReport report = gson.fromJson(data, ConsumptionReport.class);
272             if (report == null) {
273                 throw new LinkyException("No report data received");
274             }
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);
280         }
281     }
282
283     public Consumption getEnergyData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
284         if (!connected) {
285             initialize();
286         }
287         return getMeasures(userId, prmId, from, to, "energie");
288     }
289
290     public Consumption getPowerData(String userId, String prmId, LocalDate from, LocalDate to) throws LinkyException {
291         if (!connected) {
292             initialize();
293         }
294         return getMeasures(userId, prmId, from, to, "pmax");
295     }
296 }