-
Notifications
You must be signed in to change notification settings - Fork 19
Support Porsche mobile auth flow and Macan EV data #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,12 +4,40 @@ | |
|
|
||
| import logging | ||
|
|
||
| from pyporscheconnectapi.connection import Connection | ||
| from pyporscheconnectapi.vehicle import PorscheVehicle | ||
| from .connection import Connection | ||
| from .vehicle import PorscheVehicle | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _normalize_engine(vehicle: dict) -> str: | ||
| """Best-effort mapping of the portal vehicle payload to drivetrain type.""" | ||
| model_type = vehicle.get("modelType", {}) | ||
| if model_type.get("engine"): | ||
| return model_type["engine"] | ||
| description = str(vehicle.get("modelDescription", "")).lower() | ||
| if description in {"macan", "taycan"}: | ||
| return "BEV" | ||
| return "COMBUSTION" | ||
|
|
||
|
|
||
| def _normalize_vehicle(vehicle: dict) -> dict: | ||
| """Normalize the portal vehicle payload to the legacy library shape.""" | ||
| model_name = vehicle.get("modelDescription") or vehicle.get("modelName") or vehicle.get("vin", "Porsche") | ||
| return { | ||
| "vin": vehicle["vin"], | ||
| "name": model_name, | ||
| "modelName": model_name, | ||
| "modelType": { | ||
| "year": vehicle.get("modelYear") or vehicle.get("modelType", {}).get("year", "not available"), | ||
| "engine": _normalize_engine(vehicle), | ||
| }, | ||
| "systemInfo": vehicle.get("systemInfo", {}), | ||
| "timestamp": vehicle.get("validFrom") or vehicle.get("timestamp"), | ||
| "portalVehicle": vehicle, | ||
| } | ||
|
|
||
|
|
||
| class PorscheConnectAccount: | ||
| """Establishes a connection to a Porsche Connect account.""" | ||
|
|
||
|
|
@@ -39,7 +67,7 @@ async def _init_vehicles(self) -> None: | |
| _LOGGER.debug("Got vehicle %s", vehicle) | ||
| v = PorscheVehicle( | ||
| vin=vehicle["vin"], | ||
| data=vehicle, | ||
| data=_normalize_vehicle(vehicle), | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. See previous comment. |
||
| status={}, | ||
| connection=self.connection, | ||
| ) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,10 +5,11 @@ | |
|
|
||
| import asyncio | ||
| import logging | ||
| import uuid | ||
|
|
||
| import httpx | ||
|
|
||
| from .const import API_BASE_URL, TIMEOUT, USER_AGENT, X_CLIENT_ID | ||
| from .const import API_BASE_URL, DCGW_BASE_URL, TIMEOUT, USER_AGENT, X_CLIENT_ID | ||
| from .exceptions import PorscheExceptionError | ||
| from .oauth2 import Captcha, Credentials, OAuth2Client, OAuth2Token | ||
|
|
||
|
|
@@ -39,6 +40,8 @@ def __init__( | |
| captcha_code: str | None = None, | ||
| state: str | None = None, | ||
| async_client=httpx.AsyncClient(), | ||
| cookies: list[dict] | None = None, | ||
| code_verifier: str | None = None, | ||
| token=None, | ||
| leeway: int = 60, | ||
| ) -> None: | ||
|
|
@@ -47,15 +50,33 @@ def __init__( | |
| token = {} | ||
| self.asyncClient = async_client | ||
| self.token_lock = asyncio.Lock() | ||
| self.country_code = "de" | ||
| self.language_code = "de_DE" | ||
|
|
||
| if cookies: | ||
| for cookie in cookies: | ||
| self.asyncClient.cookies.set( | ||
| cookie["name"], | ||
| cookie["value"], | ||
| domain=cookie.get("domain"), | ||
| path=cookie.get("path", "/"), | ||
| ) | ||
|
|
||
| self.token = OAuth2Token(token) | ||
|
|
||
| self.headers = {"User-Agent": USER_AGENT, "X-Client-ID": X_CLIENT_ID} | ||
| self.headers = { | ||
| "User-Agent": USER_AGENT, | ||
| "X-Client-ID": X_CLIENT_ID, | ||
| "Accept-Language": "de-DE", | ||
| "Origin": "https://security.porsche.com", | ||
| "Referer": "https://security.porsche.com/", | ||
| } | ||
|
|
||
| self.oauth2_client = OAuth2Client( | ||
| self.asyncClient, | ||
| Credentials(email, password), | ||
| Captcha(captcha_code, state), | ||
| code_verifier, | ||
| leeway, | ||
| ) | ||
|
|
||
|
|
@@ -69,6 +90,18 @@ async def get(self, url, params=None): | |
| """Make a GET request to the Porsche Connect API.""" | ||
| return await self.request("GET", url, params=params) | ||
|
|
||
| async def portal_get(self, url, params=None): | ||
| """Make a GET request to the Porsche DCGW portal API.""" | ||
| return await self.absolute_request("GET", f"{DCGW_BASE_URL}{url}", params=params) | ||
|
|
||
| async def get_portal_config(self): | ||
| """Fetch and cache portal localization/config data.""" | ||
| config = await self.portal_get(f"/core/config/v1/{self.country_code}/{self.country_code}/") | ||
| localization = config.get("localization", {}) | ||
| self.country_code = str(localization.get("countryCode", self.country_code)).lower() | ||
| self.language_code = localization.get("languageCode", self.language_code) | ||
| return config | ||
|
|
||
|
Comment on lines
+93
to
+104
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is this used for? |
||
| async def post(self, url, data=None, json=None): | ||
| """Make a POST request to the Porsche Connect API.""" | ||
| return await self.request("POST", url, data=data, json=json) | ||
|
|
@@ -83,20 +116,33 @@ async def delete(self, url, data=None, json=None): | |
|
|
||
| async def request(self, method, url, **kwargs): | ||
| """Create a request to the Porsche Connect API.""" | ||
| return await self.absolute_request(method, f"{API_BASE_URL}{url}", **kwargs) | ||
|
|
||
| async def absolute_request(self, method, url, **kwargs): | ||
| """Create a request to an absolute Porsche API URL.""" | ||
| try: | ||
| async with self.token_lock: | ||
| await self.oauth2_client.ensure_valid_token(self.token) | ||
| headers = self.headers | { | ||
| "Authorization": f"Bearer {self.token.access_token}", | ||
| "X-TRACE-ID": f"PCCK-PORTAL-{uuid.uuid4()}", | ||
| } | ||
| resp = await self.asyncClient.request( | ||
| method, | ||
| f"{API_BASE_URL}{url}", | ||
| headers=self.headers | {"Authorization": f"Bearer {self.token.access_token}"}, | ||
| url, | ||
| headers=headers, | ||
| timeout=TIMEOUT, | ||
| **kwargs, | ||
| ) | ||
| resp.raise_for_status() # A common error seem to be: httpx.HTTPStatusError: Server error '504 Gateway Time-out' | ||
| return resp.json() | ||
| except httpx.HTTPStatusError as exc: | ||
| raise PorscheExceptionError(exc.response.status_code) from exc | ||
| response_text = exc.response.text[:1000] if exc.response.text else None | ||
| raise PorscheExceptionError( | ||
| exc.response.status_code, | ||
| response_body=response_text, | ||
| request_url=str(exc.request.url), | ||
| ) from exc | ||
|
|
||
| async def close(self): | ||
| """Close the asyncClient connection.""" | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see why this is needed, should be removed?