pyeauidf 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyeauidf-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyeauidf
3
+ Version: 0.1.0
4
+ Summary: Python client for L'eau d'Ile-de-France (SEDIF) water consumption data
5
+ Author-email: Timothy <6560631+TimoPtr@users.noreply.github.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TimoPtr/pyeauidf
8
+ Project-URL: Repository, https://github.com/TimoPtr/pyeauidf
9
+ Project-URL: Issues, https://github.com/TimoPtr/pyeauidf/issues
10
+ Keywords: water,consumption,sedif,ile-de-france,home-assistant
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Home Automation
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: requests>=2.28
23
+ Requires-Dist: certifi
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest; extra == "dev"
26
+ Requires-Dist: responses; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # pyeauidf
30
+
31
+ Python client for [L'eau d'Île-de-France](https://connexion.leaudiledefrance.fr) (SEDIF) water consumption data.
32
+
33
+ Fetches daily, weekly, or monthly water consumption history directly via the Salesforce Aura API — no browser or Selenium required.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install .
39
+ ```
40
+
41
+ Requires Python 3.10+ and `requests`.
42
+
43
+ ## Usage
44
+
45
+ ### CLI
46
+
47
+ ```bash
48
+ # Last 7 days (default)
49
+ pyeauidf -u email@example.com -p password
50
+
51
+ # Custom number of days
52
+ pyeauidf -u email@example.com -p password --days 30
53
+
54
+ # Weekly aggregation
55
+ pyeauidf -u email@example.com -p password --days 90 --step weekly
56
+
57
+ # Credentials via environment variables
58
+ export EAUIDF_USERNAME=email@example.com
59
+ export EAUIDF_PASSWORD=password
60
+ pyeauidf
61
+ ```
62
+
63
+ ### Python
64
+
65
+ ```python
66
+ from pyeauidf import EauIDFClient
67
+ from pyeauidf.client import TimeStep
68
+ from datetime import date, timedelta
69
+
70
+ with EauIDFClient("email@example.com", "password") as client:
71
+ client.login()
72
+
73
+ # Daily consumption (last 90 days by default)
74
+ records = client.get_daily_consumption()
75
+ for r in records:
76
+ print(f"{r.date:%Y-%m-%d}: {r.consumption_liters:.0f}L")
77
+
78
+ # Weekly or monthly
79
+ records = client.get_daily_consumption(time_step=TimeStep.WEEKLY)
80
+
81
+ # Custom date range
82
+ records = client.get_daily_consumption(
83
+ start_date=date(2026, 1, 1),
84
+ end_date=date(2026, 3, 1),
85
+ )
86
+ ```
87
+
88
+ ### Data model
89
+
90
+ Each `ConsumptionRecord` contains:
91
+
92
+ | Field | Type | Description |
93
+ |---|---|---|
94
+ | `date` | `datetime` | Timestamp of the reading |
95
+ | `consumption_liters` | `float` | Water consumed (liters) |
96
+ | `meter_reading` | `float` | Cumulative meter reading (m³) |
97
+ | `is_estimated` | `bool` | Whether the value is estimated |
98
+
99
+ ## How it works
100
+
101
+ The library authenticates against the Salesforce Experience Cloud portal that powers L'eau d'Île-de-France, then calls the same Aura API endpoints that the website uses:
102
+
103
+ 1. Login via `LightningLoginFormController`
104
+ 2. Follow `frontdoor.jsp` to establish session cookies
105
+ 3. Call Apex actions (`LTN015_ICL_ContratConsoHisto.getData`) for consumption data
@@ -0,0 +1,77 @@
1
+ # pyeauidf
2
+
3
+ Python client for [L'eau d'Île-de-France](https://connexion.leaudiledefrance.fr) (SEDIF) water consumption data.
4
+
5
+ Fetches daily, weekly, or monthly water consumption history directly via the Salesforce Aura API — no browser or Selenium required.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install .
11
+ ```
12
+
13
+ Requires Python 3.10+ and `requests`.
14
+
15
+ ## Usage
16
+
17
+ ### CLI
18
+
19
+ ```bash
20
+ # Last 7 days (default)
21
+ pyeauidf -u email@example.com -p password
22
+
23
+ # Custom number of days
24
+ pyeauidf -u email@example.com -p password --days 30
25
+
26
+ # Weekly aggregation
27
+ pyeauidf -u email@example.com -p password --days 90 --step weekly
28
+
29
+ # Credentials via environment variables
30
+ export EAUIDF_USERNAME=email@example.com
31
+ export EAUIDF_PASSWORD=password
32
+ pyeauidf
33
+ ```
34
+
35
+ ### Python
36
+
37
+ ```python
38
+ from pyeauidf import EauIDFClient
39
+ from pyeauidf.client import TimeStep
40
+ from datetime import date, timedelta
41
+
42
+ with EauIDFClient("email@example.com", "password") as client:
43
+ client.login()
44
+
45
+ # Daily consumption (last 90 days by default)
46
+ records = client.get_daily_consumption()
47
+ for r in records:
48
+ print(f"{r.date:%Y-%m-%d}: {r.consumption_liters:.0f}L")
49
+
50
+ # Weekly or monthly
51
+ records = client.get_daily_consumption(time_step=TimeStep.WEEKLY)
52
+
53
+ # Custom date range
54
+ records = client.get_daily_consumption(
55
+ start_date=date(2026, 1, 1),
56
+ end_date=date(2026, 3, 1),
57
+ )
58
+ ```
59
+
60
+ ### Data model
61
+
62
+ Each `ConsumptionRecord` contains:
63
+
64
+ | Field | Type | Description |
65
+ |---|---|---|
66
+ | `date` | `datetime` | Timestamp of the reading |
67
+ | `consumption_liters` | `float` | Water consumed (liters) |
68
+ | `meter_reading` | `float` | Cumulative meter reading (m³) |
69
+ | `is_estimated` | `bool` | Whether the value is estimated |
70
+
71
+ ## How it works
72
+
73
+ The library authenticates against the Salesforce Experience Cloud portal that powers L'eau d'Île-de-France, then calls the same Aura API endpoints that the website uses:
74
+
75
+ 1. Login via `LightningLoginFormController`
76
+ 2. Follow `frontdoor.jsp` to establish session cookies
77
+ 3. Call Apex actions (`LTN015_ICL_ContratConsoHisto.getData`) for consumption data
@@ -0,0 +1,4 @@
1
+ from .client import EauIDFClient
2
+
3
+ __all__ = ["EauIDFClient"]
4
+ __version__ = "0.1.0"
@@ -0,0 +1,89 @@
1
+ """CLI entry point for pyeauidf."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from datetime import date, timedelta
9
+
10
+ from .client import EauIDFClient, EauIDFError, TimeStep
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(
15
+ prog="pyeauidf",
16
+ description="Fetch water consumption from L'eau d'Île-de-France",
17
+ )
18
+ parser.add_argument(
19
+ "-u", "--username",
20
+ default=os.environ.get("EAUIDF_USERNAME"),
21
+ help="Account email (or set EAUIDF_USERNAME)",
22
+ )
23
+ parser.add_argument(
24
+ "-p", "--password",
25
+ default=os.environ.get("EAUIDF_PASSWORD"),
26
+ help="Account password (or set EAUIDF_PASSWORD)",
27
+ )
28
+ parser.add_argument(
29
+ "--days",
30
+ type=int,
31
+ default=7,
32
+ help="Number of days to fetch (default: 7)",
33
+ )
34
+ parser.add_argument(
35
+ "--step",
36
+ choices=["daily", "weekly", "monthly"],
37
+ default="daily",
38
+ help="Time step (default: daily)",
39
+ )
40
+ args = parser.parse_args()
41
+
42
+ if not args.username or not args.password:
43
+ parser.error(
44
+ "Credentials required. Use -u/-p flags or set "
45
+ "EAUIDF_USERNAME and EAUIDF_PASSWORD environment variables."
46
+ )
47
+
48
+ step_map = {
49
+ "daily": TimeStep.DAILY,
50
+ "weekly": TimeStep.WEEKLY,
51
+ "monthly": TimeStep.MONTHLY,
52
+ }
53
+
54
+ try:
55
+ with EauIDFClient(args.username, args.password) as client:
56
+ client.login()
57
+
58
+ end = date.today()
59
+ start = end - timedelta(days=args.days)
60
+
61
+ records = client.get_daily_consumption(
62
+ start_date=start,
63
+ end_date=end,
64
+ time_step=step_map[args.step],
65
+ )
66
+
67
+ if not records:
68
+ print("No consumption data found for the given period.")
69
+ return
70
+
71
+ total_liters = sum(r.consumption_liters for r in records)
72
+
73
+ print(f"Water consumption ({start} to {end}, {args.step}):\n")
74
+ print(f" {'Date':<12} {'Liters':>8} {'Meter (m³)':>12} {'Est.':>5}")
75
+ print(f" {'─' * 12} {'─' * 8} {'─' * 12} {'─' * 5}")
76
+ for r in records:
77
+ est = "yes" if r.is_estimated else ""
78
+ print(f" {r.date:%Y-%m-%d} {r.consumption_liters:7.0f} {r.meter_reading:11.3f} {est:>4}")
79
+
80
+ print(f" {'─' * 12} {'─' * 8} {'─' * 12}")
81
+ print(f" {'Total':<12} {total_liters:7.0f}L")
82
+
83
+ except EauIDFError as e:
84
+ print(f"Error: {e}", file=sys.stderr)
85
+ sys.exit(1)
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,409 @@
1
+ """Client for L'eau d'Ile-de-France (SEDIF) water consumption API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import tempfile
8
+ from dataclasses import dataclass
9
+ from datetime import date, datetime, timedelta
10
+ from enum import Enum
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import certifi
15
+ import requests
16
+
17
+
18
+ BASE_URL = "https://connexion.leaudiledefrance.fr/espace-particuliers"
19
+ _INTERMEDIATE_CERT = Path(__file__).parent / "gandi_intermediate.pem"
20
+ AURA_URL = f"{BASE_URL}/s/sfsites/aura"
21
+ LOGIN_URL = f"{BASE_URL}/s/login/"
22
+
23
+ LOGIN_APP = "siteforce:loginApp2"
24
+ COMMUNITY_APP = "siteforce:communityApp"
25
+
26
+
27
+ class TimeStep(str, Enum):
28
+ DAILY = "JOURNEE"
29
+ WEEKLY = "SEMAINE"
30
+ MONTHLY = "MOIS"
31
+
32
+
33
+ @dataclass
34
+ class ConsumptionRecord:
35
+ date: datetime
36
+ consumption_liters: float
37
+ meter_reading: float
38
+ is_estimated: bool
39
+
40
+ @classmethod
41
+ def from_api(cls, raw: dict) -> ConsumptionRecord:
42
+ return cls(
43
+ date=datetime.strptime(raw["DATE_INDEX"], "%Y-%m-%d %H:%M:%S"),
44
+ consumption_liters=float(raw["CONSOMMATION"]) * 1000,
45
+ meter_reading=float(raw["VALEUR_INDEX"]),
46
+ is_estimated=raw.get("FLAG_ESTIMATION", False),
47
+ )
48
+
49
+
50
+ class EauIDFError(Exception):
51
+ pass
52
+
53
+
54
+ class AuthenticationError(EauIDFError):
55
+ pass
56
+
57
+
58
+ class EauIDFClient:
59
+ """Client to fetch water consumption data from L'eau d'Ile-de-France."""
60
+
61
+ def __init__(self, username: str, password: str) -> None:
62
+ self._username = username
63
+ self._password = password
64
+ self._session = requests.Session()
65
+ self._session.headers.update({
66
+ "User-Agent": (
67
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
68
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
69
+ "Chrome/145.0.0.0 Safari/537.36"
70
+ ),
71
+ "Origin": "https://connexion.leaudiledefrance.fr",
72
+ })
73
+ # The server doesn't send the intermediate CA cert, so we build
74
+ # a custom CA bundle: certifi roots + the bundled Gandi intermediate.
75
+ self._ca_bundle = self._build_ca_bundle()
76
+ self._session.verify = self._ca_bundle
77
+ self._fwuid: str | None = None
78
+ self._aura_token: str | None = None
79
+ self._app_loaded: dict | None = None
80
+ self._authenticated = False
81
+
82
+ @staticmethod
83
+ def _build_ca_bundle() -> str:
84
+ """Create a temp CA bundle with the missing Gandi intermediate cert."""
85
+ intermediate = _INTERMEDIATE_CERT.read_text()
86
+ roots = Path(certifi.where()).read_text()
87
+ bundle = tempfile.NamedTemporaryFile(
88
+ suffix=".pem", prefix="pyeauidf_ca_", delete=False
89
+ )
90
+ bundle.write((intermediate + "\n" + roots).encode())
91
+ bundle.close()
92
+ return bundle.name
93
+
94
+ def _get_login_context(self) -> None:
95
+ """Fetch the login page to extract fwuid and app context."""
96
+ resp = self._session.get(LOGIN_URL)
97
+ resp.raise_for_status()
98
+ html = resp.text
99
+
100
+ # Extract fwuid from the page scripts
101
+ match = re.search(r'"fwuid"\s*:\s*"([^"]+)"', html)
102
+ if match:
103
+ self._fwuid = match.group(1)
104
+
105
+ # Extract the loginApp2 loaded hash
106
+ match = re.search(
107
+ r'"APPLICATION@markup://siteforce:loginApp2"\s*:\s*"([^"]+)"', html
108
+ )
109
+ if match:
110
+ self._app_loaded = {
111
+ "APPLICATION@markup://siteforce:loginApp2": match.group(1)
112
+ }
113
+
114
+ if not self._fwuid:
115
+ raise AuthenticationError("Could not extract fwuid from login page")
116
+
117
+ def _extract_aura_token(self) -> str | None:
118
+ """Extract the CSRF token from the __Host-ERIC cookie set by Salesforce."""
119
+ for cookie in self._session.cookies:
120
+ if "ERIC" in cookie.name:
121
+ return cookie.value
122
+ return None
123
+
124
+ def _build_aura_context(self, app: str = COMMUNITY_APP) -> dict:
125
+ loaded_key = f"APPLICATION@markup://{app}"
126
+ loaded = {}
127
+ if self._app_loaded:
128
+ # Reuse whatever loaded hash we have
129
+ for k, v in self._app_loaded.items():
130
+ loaded[k] = v
131
+ return {
132
+ "mode": "PROD",
133
+ "fwuid": self._fwuid,
134
+ "app": app,
135
+ "loaded": loaded,
136
+ "dn": [],
137
+ "globals": {},
138
+ "uad": True,
139
+ }
140
+
141
+ def _aura_call_raw(
142
+ self,
143
+ actions: list[dict],
144
+ app: str = COMMUNITY_APP,
145
+ page_uri: str = "/espace-particuliers/s/",
146
+ ) -> dict:
147
+ """Make an Aura API call and return the full JSON response."""
148
+ # Build query string descriptor hints
149
+ descriptors = []
150
+ for a in actions:
151
+ desc = a.get("descriptor", "")
152
+ if "ApexActionController" in desc:
153
+ descriptors.append("aura.ApexAction.execute=1")
154
+ else:
155
+ short = desc.split("/")[-1].replace("ACTION$", ".")
156
+ descriptors.append(f"other.{short}=1")
157
+
158
+ query_parts = ["r=0"]
159
+ seen = set()
160
+ for d in descriptors:
161
+ if d not in seen:
162
+ query_parts.append(d)
163
+ seen.add(d)
164
+
165
+ url = f"{AURA_URL}?{'&'.join(query_parts)}"
166
+
167
+ resp = self._session.post(
168
+ url,
169
+ data={
170
+ "message": json.dumps({"actions": actions}),
171
+ "aura.context": json.dumps(self._build_aura_context(app)),
172
+ "aura.pageURI": page_uri,
173
+ "aura.token": self._aura_token or "undefined",
174
+ },
175
+ headers={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
176
+ )
177
+ resp.raise_for_status()
178
+
179
+ result = resp.json()
180
+
181
+ # Update context if returned
182
+ ctx = result.get("context", {})
183
+ if ctx.get("fwuid"):
184
+ self._fwuid = ctx["fwuid"]
185
+ loaded = ctx.get("loaded")
186
+ if loaded:
187
+ self._app_loaded = loaded
188
+
189
+ return result
190
+
191
+ def _aura_call(
192
+ self,
193
+ actions: list[dict],
194
+ **kwargs: Any,
195
+ ) -> list[dict]:
196
+ """Make an Aura API call and return just the action results."""
197
+ return self._aura_call_raw(actions, **kwargs).get("actions", [])
198
+
199
+ def _apex_action(
200
+ self,
201
+ classname: str,
202
+ method: str,
203
+ params: dict | None = None,
204
+ **kwargs: Any,
205
+ ) -> Any:
206
+ """Call a single Apex action and return its returnValue."""
207
+ action_params: dict[str, Any] = {
208
+ "namespace": "",
209
+ "classname": classname,
210
+ "method": method,
211
+ "cacheable": False,
212
+ "isContinuation": False,
213
+ }
214
+ if params:
215
+ action_params["params"] = params
216
+
217
+ action = {
218
+ "id": "1;a",
219
+ "descriptor": "aura://ApexActionController/ACTION$execute",
220
+ "callingDescriptor": "UNKNOWN",
221
+ "params": action_params,
222
+ }
223
+
224
+ results = self._aura_call([action], **kwargs)
225
+ if not results:
226
+ raise EauIDFError(f"No response for {classname}.{method}")
227
+
228
+ result = results[0]
229
+ if result.get("state") != "SUCCESS":
230
+ error = result.get("error", [])
231
+ raise EauIDFError(
232
+ f"{classname}.{method} failed: {error}"
233
+ )
234
+
235
+ rv = result.get("returnValue", {})
236
+ # Apex actions wrap in an extra returnValue
237
+ if isinstance(rv, dict) and "returnValue" in rv:
238
+ return rv["returnValue"]
239
+ return rv
240
+
241
+ def login(self) -> None:
242
+ """Authenticate with the L'eau d'Ile-de-France portal."""
243
+ self._get_login_context()
244
+
245
+ # Call the Aura login action
246
+ action = {
247
+ "id": "1;a",
248
+ "descriptor": "apex://LightningLoginFormController/ACTION$login",
249
+ "callingDescriptor": "UNKNOWN",
250
+ "params": {
251
+ "username": self._username,
252
+ "password": self._password,
253
+ "startUrl": "/espace-particuliers/s/",
254
+ },
255
+ }
256
+
257
+ response = self._aura_call_raw(
258
+ [action],
259
+ app=LOGIN_APP,
260
+ page_uri="/espace-particuliers/s/login",
261
+ )
262
+
263
+ actions = response.get("actions", [])
264
+ if actions:
265
+ result = actions[0]
266
+ if result.get("state") != "SUCCESS":
267
+ raise AuthenticationError(f"Login failed: {result.get('error', [])}")
268
+ # returnValue is an error message on failure, None on success
269
+ return_value = result.get("returnValue")
270
+ if isinstance(return_value, str) and return_value:
271
+ raise AuthenticationError(f"Login failed: {return_value}")
272
+
273
+ self._complete_login(response)
274
+
275
+ def _complete_login(self, login_response: dict) -> None:
276
+ """Follow the frontdoor redirect and extract session tokens."""
277
+ # Extract the redirect URL from aura:clientRedirect event
278
+ events = login_response.get("events", [])
279
+ redirect_url = None
280
+ for event in events:
281
+ if event.get("descriptor") == "markup://aura:clientRedirect":
282
+ redirect_url = event["attributes"]["values"]["url"]
283
+ break
284
+
285
+ if not redirect_url:
286
+ raise AuthenticationError("No redirect URL in login response")
287
+
288
+ # Follow frontdoor.jsp to establish session cookies (sid, etc.)
289
+ self._session.get(redirect_url)
290
+
291
+ # Load the authenticated community page to get the app context
292
+ resp = self._session.get(f"{BASE_URL}/s/")
293
+ resp.raise_for_status()
294
+ html = resp.text
295
+
296
+ # Extract the CSRF token from the __Host-ERIC cookie
297
+ self._aura_token = self._extract_aura_token()
298
+ if not self._aura_token:
299
+ raise AuthenticationError("Could not extract CSRF token after login")
300
+
301
+ # Extract communityApp loaded hash
302
+ match = re.search(
303
+ r'"APPLICATION@markup://siteforce:communityApp"\s*:\s*"([^"]+)"', html
304
+ )
305
+ if match:
306
+ self._app_loaded = {
307
+ "APPLICATION@markup://siteforce:communityApp": match.group(1)
308
+ }
309
+
310
+ # Update fwuid if available
311
+ match = re.search(r'"fwuid"\s*:\s*"([^"]+)"', html)
312
+ if match:
313
+ self._fwuid = match.group(1)
314
+
315
+ self._authenticated = True
316
+
317
+ def _ensure_authenticated(self) -> None:
318
+ if not self._authenticated:
319
+ self.login()
320
+
321
+ def get_contracts(self) -> list[str]:
322
+ """Get list of active contract IDs."""
323
+ self._ensure_authenticated()
324
+ result = self._apex_action(
325
+ "LTN009_ICL_ContratsGroupements",
326
+ "listCurrentUserActiveContrats",
327
+ )
328
+ if isinstance(result, list):
329
+ return result
330
+ return []
331
+
332
+ def get_contract_details(self, contract_id: str) -> dict:
333
+ """Get details for a contract including meter number and PDS ID."""
334
+ self._ensure_authenticated()
335
+ return self._apex_action(
336
+ "LTN008_ICL_ContratDetails",
337
+ "getContratDetails",
338
+ params={"contratId": contract_id},
339
+ )
340
+
341
+ def get_daily_consumption(
342
+ self,
343
+ contract_id: str | None = None,
344
+ start_date: date | None = None,
345
+ end_date: date | None = None,
346
+ time_step: TimeStep = TimeStep.DAILY,
347
+ ) -> list[ConsumptionRecord]:
348
+ """
349
+ Fetch water consumption history.
350
+
351
+ If contract_id is not provided, uses the first active contract.
352
+ Defaults to last 90 days if dates are not specified.
353
+ """
354
+ self._ensure_authenticated()
355
+
356
+ if end_date is None:
357
+ end_date = date.today()
358
+ if start_date is None:
359
+ start_date = end_date - timedelta(days=90)
360
+
361
+ # Get contract ID if not provided
362
+ if contract_id is None:
363
+ contracts = self.get_contracts()
364
+ if not contracts:
365
+ raise EauIDFError("No active contracts found")
366
+ contract_id = contracts[0]
367
+
368
+ # Get contract details for meter number and PDS ID
369
+ details = self.get_contract_details(contract_id)
370
+ compte_info = details.get("compteInfo", [])
371
+ if not compte_info:
372
+ raise EauIDFError("No meter information found for contract")
373
+
374
+ meter = compte_info[0]
375
+ numero_compteur = meter["ELEMB"]
376
+ id_pds = meter["ELEMA"]
377
+
378
+ # Fetch consumption data
379
+ result = self._apex_action(
380
+ "LTN015_ICL_ContratConsoHisto",
381
+ "getData",
382
+ params={
383
+ "contractId": contract_id,
384
+ "TYPE_PAS": time_step.value,
385
+ "DATE_DEBUT": start_date.isoformat(),
386
+ "DATE_FIN": end_date.isoformat(),
387
+ "NUMERO_COMPTEUR": numero_compteur,
388
+ "ID_PDS": id_pds,
389
+ },
390
+ page_uri="/espace-particuliers/s/historique",
391
+ )
392
+
393
+ records = []
394
+ data = result.get("data", {})
395
+ for raw in data.get("CONSOMMATION", []):
396
+ records.append(ConsumptionRecord.from_api(raw))
397
+
398
+ return records
399
+
400
+ def close(self) -> None:
401
+ self._session.close()
402
+ if self._ca_bundle:
403
+ Path(self._ca_bundle).unlink(missing_ok=True)
404
+
405
+ def __enter__(self) -> EauIDFClient:
406
+ return self
407
+
408
+ def __exit__(self, *args: Any) -> None:
409
+ self.close()
@@ -0,0 +1,36 @@
1
+ -----BEGIN CERTIFICATE-----
2
+ MIIGXDCCBESgAwIBAgIRAOkH5f+AdSJBCZB9ZyjKABAwDQYJKoZIhvcNAQEMBQAw
3
+ gYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5MRQwEgYDVQQHEwtK
4
+ ZXJzZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMS4wLAYD
5
+ VQQDEyVVU0VSVHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTIz
6
+ MDgwMjAwMDAwMFoXDTMzMDgwMTIzNTk1OVowVjELMAkGA1UEBhMCRlIxDjAMBgNV
7
+ BAoTBUdhbmRpMTcwNQYDVQQDEy5HYW5kaSBSU0EgRG9tYWluIFZhbGlkYXRpb24g
8
+ U2VjdXJlIFNlcnZlciBDQSAzMIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKC
9
+ AYEAwrwuXKdKIiD9eu4fsNjLN0mS8HsTdDFyPPB5F5uUd6SJGutc7sqDd3T/p+gn
10
+ VoAZERvzAz8+OEux1GN1UJ+Gd8s5btXJCbDV5DpvzJOhfztk5JmFKz2XBka+MvDA
11
+ giyiZKs3G6yoMk8lEOu6NOsK3X8D1w0E6/C/ROa6Ml0ROnKm7vHGNVTfXTP5IqiN
12
+ h2JXmp4vD23gemf8nfuI2FngayMNsjm6SwpVYWfT3S8jn5el52FKzwo+uKVZAjNH
13
+ 1ulgWoyO8p+PCsP+CvaEGDId3leSUVhPBBPRsxL42jjqo9aOKREgmrGco39JGf4O
14
+ ImxM8vKxQ9AjDrRTRETB9V9jbRf3v3Tojt3vBBwa3xQelVp9xUWQxo/5dV73g/c7
15
+ WWAvZ628XUw6k6vn6bY7qWuhehUO02plRLd5zP8nBORCbPmFCI97lZAnDYLprB4e
16
+ 9IgCPJp+0zQDLr9o+eNKtR0a2Txb6nzGahIPi3a7QCH6+Yq4iwYVEQm+e6KBJZOm
17
+ +YiLAgMBAAGjggFwMIIBbDAfBgNVHSMEGDAWgBRTeb9aqitKz1SA4dibwJ3ysgNm
18
+ yzAdBgNVHQ4EFgQUgRGS3mYypbBbMz1lQ4X81AQt8a4wDgYDVR0PAQH/BAQDAgGG
19
+ MBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUF
20
+ BwMCMCIGA1UdIAQbMBkwDQYLKwYBBAGyMQECAhowCAYGZ4EMAQIBMFAGA1UdHwRJ
21
+ MEcwRaBDoEGGP2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FD
22
+ ZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDBxBggrBgEFBQcBAQRlMGMwOgYIKwYB
23
+ BQUHMAKGLmh0dHA6Ly9jcnQudXNlcnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FBQUFD
24
+ QS5jcnQwJQYIKwYBBQUHMAGGGWh0dHA6Ly9vY3NwLnVzZXJ0cnVzdC5jb20wDQYJ
25
+ KoZIhvcNAQEMBQADggIBADvVncOMStREyA00ZSRUmrkmR3KzAlHVz06X1ydG9EpZ
26
+ z+JTQMWO809buLbDnr6t9z9jVnsDTQnWcMG4qiIkwhJVLxOVXUO+LFSBMskOe1SP
27
+ BtHwHS42DeZ8QTgbRlW9p/Ey9wIo+MS2tryQ9eaDTkc2FBed/82VjrdsQoeoTyuD
28
+ dp4tqarixjM/iJMgyEAMCpTkx4EqXJ/z7qgXusacsxMzt6NLv7FYcaKGbwjKqzrR
29
+ vEk/+ZYnZc5mxnautf0uwRCcOe0kCOh1fd+g6Tyd+cSj6oGcJY/f/Db0sxELpzGq
30
+ jRkbXan+eMojQfsgIe1n7SVyI5Yxz2RnQQL5ZT5K1mBcucqsTqkk3C7L3hF4hkwC
31
+ /Otm+badymHQcnbE1Pmz6ymqj2vtwT0mEQzetQdbvv3jc3ey4YcxirAM1ihxtXeI
32
+ NsEP1ndUV/0v+qqmk9iCoIjZQce8vAdziZqBYxO3NiZwTRAtqseiZWLJqQ077fy3
33
+ ebdjmw6y5U+DhDW2kxF/e+FJnu53DuY5/bE+oUneY770A7BfCuH+6uhEOaMNsn21
34
+ AHymLr1xlRPQYR0DMgHmsGTqdINcQfot1mlIXr05HQUK0b84CPgEU0zvVQL+j9dc
35
+ /4rh2sR6rl//tjG01Q+zQKStnR2NlNNrElDUC9IDmvL9JcF20cvOlE4R0lfTXa1k
36
+ -----END CERTIFICATE-----
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyeauidf
3
+ Version: 0.1.0
4
+ Summary: Python client for L'eau d'Ile-de-France (SEDIF) water consumption data
5
+ Author-email: Timothy <6560631+TimoPtr@users.noreply.github.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/TimoPtr/pyeauidf
8
+ Project-URL: Repository, https://github.com/TimoPtr/pyeauidf
9
+ Project-URL: Issues, https://github.com/TimoPtr/pyeauidf/issues
10
+ Keywords: water,consumption,sedif,ile-de-france,home-assistant
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Home Automation
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: requests>=2.28
23
+ Requires-Dist: certifi
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest; extra == "dev"
26
+ Requires-Dist: responses; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # pyeauidf
30
+
31
+ Python client for [L'eau d'Île-de-France](https://connexion.leaudiledefrance.fr) (SEDIF) water consumption data.
32
+
33
+ Fetches daily, weekly, or monthly water consumption history directly via the Salesforce Aura API — no browser or Selenium required.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install .
39
+ ```
40
+
41
+ Requires Python 3.10+ and `requests`.
42
+
43
+ ## Usage
44
+
45
+ ### CLI
46
+
47
+ ```bash
48
+ # Last 7 days (default)
49
+ pyeauidf -u email@example.com -p password
50
+
51
+ # Custom number of days
52
+ pyeauidf -u email@example.com -p password --days 30
53
+
54
+ # Weekly aggregation
55
+ pyeauidf -u email@example.com -p password --days 90 --step weekly
56
+
57
+ # Credentials via environment variables
58
+ export EAUIDF_USERNAME=email@example.com
59
+ export EAUIDF_PASSWORD=password
60
+ pyeauidf
61
+ ```
62
+
63
+ ### Python
64
+
65
+ ```python
66
+ from pyeauidf import EauIDFClient
67
+ from pyeauidf.client import TimeStep
68
+ from datetime import date, timedelta
69
+
70
+ with EauIDFClient("email@example.com", "password") as client:
71
+ client.login()
72
+
73
+ # Daily consumption (last 90 days by default)
74
+ records = client.get_daily_consumption()
75
+ for r in records:
76
+ print(f"{r.date:%Y-%m-%d}: {r.consumption_liters:.0f}L")
77
+
78
+ # Weekly or monthly
79
+ records = client.get_daily_consumption(time_step=TimeStep.WEEKLY)
80
+
81
+ # Custom date range
82
+ records = client.get_daily_consumption(
83
+ start_date=date(2026, 1, 1),
84
+ end_date=date(2026, 3, 1),
85
+ )
86
+ ```
87
+
88
+ ### Data model
89
+
90
+ Each `ConsumptionRecord` contains:
91
+
92
+ | Field | Type | Description |
93
+ |---|---|---|
94
+ | `date` | `datetime` | Timestamp of the reading |
95
+ | `consumption_liters` | `float` | Water consumed (liters) |
96
+ | `meter_reading` | `float` | Cumulative meter reading (m³) |
97
+ | `is_estimated` | `bool` | Whether the value is estimated |
98
+
99
+ ## How it works
100
+
101
+ The library authenticates against the Salesforce Experience Cloud portal that powers L'eau d'Île-de-France, then calls the same Aura API endpoints that the website uses:
102
+
103
+ 1. Login via `LightningLoginFormController`
104
+ 2. Follow `frontdoor.jsp` to establish session cookies
105
+ 3. Call Apex actions (`LTN015_ICL_ContratConsoHisto.getData`) for consumption data
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ pyeauidf/__init__.py
5
+ pyeauidf/__main__.py
6
+ pyeauidf/client.py
7
+ pyeauidf/gandi_intermediate.pem
8
+ pyeauidf.egg-info/PKG-INFO
9
+ pyeauidf.egg-info/SOURCES.txt
10
+ pyeauidf.egg-info/dependency_links.txt
11
+ pyeauidf.egg-info/entry_points.txt
12
+ pyeauidf.egg-info/requires.txt
13
+ pyeauidf.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyeauidf = pyeauidf.__main__:main
@@ -0,0 +1,6 @@
1
+ requests>=2.28
2
+ certifi
3
+
4
+ [dev]
5
+ pytest
6
+ responses
@@ -0,0 +1 @@
1
+ pyeauidf
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pyeauidf"
7
+ version = "0.1.0"
8
+ description = "Python client for L'eau d'Ile-de-France (SEDIF) water consumption data"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Timothy", email = "6560631+TimoPtr@users.noreply.github.com" }]
13
+ keywords = ["water", "consumption", "sedif", "ile-de-france", "home-assistant"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Topic :: Home Automation",
23
+ ]
24
+ dependencies = ["requests>=2.28", "certifi"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/TimoPtr/pyeauidf"
28
+ Repository = "https://github.com/TimoPtr/pyeauidf"
29
+ Issues = "https://github.com/TimoPtr/pyeauidf/issues"
30
+
31
+ [project.scripts]
32
+ pyeauidf = "pyeauidf.__main__:main"
33
+
34
+ [project.optional-dependencies]
35
+ dev = ["pytest", "responses"]
36
+
37
+ [tool.setuptools.package-data]
38
+ pyeauidf = ["gandi_intermediate.pem"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+