From 565e12a9a1adb0d473c15fd7f213035e89cc5c6c Mon Sep 17 00:00:00 2001 From: Tan Suwandecha Date: Fri, 27 Nov 2026 12:46:04 +0700 Subject: [PATCH] feat: add support for MG Thailand configuration and login authorization --- .gitignore | 1 + README.md | 33 +++++ examples/.env.example | 9 +- examples/example_env.py | 18 +++ examples/main.py | 46 ++++++- examples/maxus_login.py | 14 +- src/saic_ismart_client_ng/api/base.py | 36 ++++- src/saic_ismart_client_ng/model.py | 17 +++ src/saic_ismart_client_ng/net/crypto.py | 4 +- src/saic_ismart_client_ng/thai_capture.py | 153 ++++++++++++++++++++++ tests/test_model.py | 8 ++ 11 files changed, 318 insertions(+), 21 deletions(-) create mode 100644 examples/example_env.py create mode 100644 src/saic_ismart_client_ng/thai_capture.py diff --git a/.gitignore b/.gitignore index b32c4f0..161f2a2 100644 --- a/.gitignore +++ b/.gitignore @@ -80,6 +80,7 @@ celerybeat-schedule # dotenv .env +*.pgen/ # virtualenv venv/ ENV/ diff --git a/README.md b/README.md index 3dcb8eb..7473851 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,44 @@ Presets are classmethods on `SaicApiConfiguration`. Each takes `(username, passw | `mg_eu()` | `https://gateway-mg-eu.soimt.com/api.app/v1/` | `eu` | `459771` | `com.saicmotor.europecar` | | `mg_au()` | `https://gateway-mg-au.soimt.com/api.app/v1/` | `au` | `459771` | `com.saicmotor.europecar` | | `mg_tr()` | `https://gateway-mg-tr.soimt.com/api.app/v1/` | `tr` | `459771` | `com.saicmotor.europecar` | +| `mg_th()` | `https://gateway-mg-th.soimt.com/api.app/v1/` | `th` | `459771` | `com.saicmotor.ismartthai` | | `mg_br()` | `https://gateway-mg-br.soimt.com/api.app/v1/` | `br` | `459771` | `com.saicmotor.europecar` | | `maxus_eu()` | `https://gateway-maxus-eu.soimt.com/api.app/v1/` | `eu` | `590224` | `com.saicmaxus.ismarteu` | MAXUS Europe vehicles use the same API. The `maxus_eu()` values were confirmed by a live traffic capture of the MAXUS app. +For Thailand, supply `login_authorization` as the complete `Authorization` header +(`Basic ...`) from the app's login request. Keep it secret; do not commit it or the +traffic capture. For phone login, also set `username_is_email=False` and +`phone_country_code="66"`. For example: + +```python +import os + +from saic_ismart_client_ng.model import SaicApiConfiguration + +config = SaicApiConfiguration.mg_th( + os.environ["SAIC_USERNAME"], + os.environ["SAIC_PASSWORD"], + username_is_email=False, + phone_country_code="66", + login_authorization=os.environ["SAIC_LOGIN_AUTHORIZATION"], +) +``` + +For the Thailand example, copy `examples/.env.example` to `examples/.env` and +set the complete authorization header there: + +```dotenv +SAIC_LOGIN_AUTHORIZATION="Basic ..." +``` + +Existing environment variables take precedence over `.env`. The example's +username and password are configured separately in `examples/main.py`. +The example requests both vehicle status and charging management data for each +vehicle. If SAIC reports that vehicle access has been revoked, restore the +account's authorization to that vehicle in the app before retrying. + Supported functionality (partial list, check the code for more) * login diff --git a/examples/.env.example b/examples/.env.example index cc8d9f1..5b82269 100644 --- a/examples/.env.example +++ b/examples/.env.example @@ -1,6 +1,13 @@ SAIC_USER= SAIC_PASS= -# SAIC_REGION=eu +# Full Basic authorization header for Thailand +SAIC_LOGIN_AUTHORIZATION= +# Optional overrides for examples/main.py (defaults are for Thailand) +# SAIC_USERNAME_IS_EMAIL=false +# SAIC_BASE_URI=https://gateway-mg-th.soimt.com/api.app/v1/ +# SAIC_REGION=th +# SAIC_PHONE_COUNTRY_CODE=66 +# SAIC_DEVICE_APP_ID=com.saicmotor.ismartthai # SAIC_VIN= # Only for examples/maxus_login.py (MAXUS Europe account) # MAXUS_USER= diff --git a/examples/example_env.py b/examples/example_env.py new file mode 100644 index 0000000..e208d7e --- /dev/null +++ b/examples/example_env.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pathlib import Path + + +def load_env(path: Path) -> None: + if not path.exists(): + raise SystemExit(f"Missing {path}; copy .env.example to .env and fill it in") + for line in path.read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + os.environ.setdefault(key.strip(), value.strip().strip("\"'")) diff --git a/examples/main.py b/examples/main.py index 26a0d5a..5510877 100644 --- a/examples/main.py +++ b/examples/main.py @@ -1,17 +1,35 @@ from __future__ import annotations import asyncio +from dataclasses import asdict import logging +import os +from pathlib import Path import sys from saic_ismart_client_ng import SaicApi from saic_ismart_client_ng.model import SaicApiConfiguration +if __package__: + from .example_env import load_env +else: + from example_env import load_env + async def main() -> None: + load_env(Path(__file__).parent / ".env") config = SaicApiConfiguration( - username="XXXXX@xxxx.com", - password="XXXXX", + username=os.environ.get("SAIC_USER"), + username_is_email=os.environ.get("SAIC_USERNAME_IS_EMAIL", "false").lower() + in ("1", "true", "yes"), + password=os.environ.get("SAIC_PASS"), + base_uri=os.environ.get( + "SAIC_BASE_URI", "https://gateway-mg-th.soimt.com/api.app/v1/" + ), + region=os.environ.get("SAIC_REGION", "th"), + phone_country_code=os.environ.get("SAIC_PHONE_COUNTRY_CODE", "66"), + device_app_id=os.environ.get("SAIC_DEVICE_APP_ID", "com.saicmotor.ismartthai"), + login_authorization=os.environ.get("SAIC_LOGIN_AUTHORIZATION"), ) saic_api = SaicApi(config) await saic_api.login() @@ -21,11 +39,27 @@ async def main() -> None: cars = vehicle_list_rest.vinList for car in cars: vin_num = car.vin - # vehicle_status = await saic_api.get_vehicle_status(vin_num) - # logging.info("Battery voltage is %d", vehicle_status.basicVehicleStatus.batteryVoltage) - # charging_status = await saic_api.get_vehicle_charging_management_data(vin_num) - # logging.info("Current power is %d", charging_status.rvsChargeStatus.realtimePower) + if not vin_num: + logging.warning("Vehicle list entry has no VIN; skipping status requests") + continue logging.info("My VIN is %s", vin_num) + vehicle_status = await saic_api.get_vehicle_status(vin_num) + if vehicle_status.basicVehicleStatus is None: + logging.info("No basicVehicleStatus") + else: + for name, value in asdict(vehicle_status.basicVehicleStatus).items(): + logging.info("basicVehicleStatus.%s = %s", name, value) + charging_status = await saic_api.get_vehicle_charging_management_data(vin_num) + + chrg_mgmt_data = charging_status.chrgMgmtData + if chrg_mgmt_data is None: + logging.info("No chrgMgmtData") + continue + for name, value in asdict(chrg_mgmt_data).items(): + logging.info("chrgMgmtData.%s = %s", name, value) + logging.info("decoded_current = %s A", chrg_mgmt_data.decoded_current) + logging.info("decoded_voltage = %s V", chrg_mgmt_data.decoded_voltage) + logging.info("decoded_power = %s kW", chrg_mgmt_data.decoded_power) await asyncio.sleep(10) diff --git a/examples/maxus_login.py b/examples/maxus_login.py index e9307fe..8a93ea4 100644 --- a/examples/maxus_login.py +++ b/examples/maxus_login.py @@ -7,16 +7,10 @@ from saic_ismart_client_ng import SaicApi from saic_ismart_client_ng.model import SaicApiConfiguration - -def load_env(path: Path) -> None: - if not path.exists(): - raise SystemExit(f"Missing {path}; copy .env.example to .env and fill it in") - for line in path.read_text().splitlines(): - line = line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, _, value = line.partition("=") - os.environ.setdefault(key.strip(), value.strip().strip("\"'")) +if __package__: + from .example_env import load_env +else: + from example_env import load_env async def main() -> None: diff --git a/src/saic_ismart_client_ng/api/base.py b/src/saic_ismart_client_ng/api/base.py index daa3c04..0381cd7 100644 --- a/src/saic_ismart_client_ng/api/base.py +++ b/src/saic_ismart_client_ng/api/base.py @@ -1,5 +1,7 @@ from __future__ import annotations +import base64 +import binascii from dataclasses import asdict import datetime import logging @@ -55,10 +57,32 @@ async def close(self) -> None: await self.__api_client.close() async def login(self) -> LoginResp: + is_thai = self.__configuration.region.lower() == "th" + authorization = "Basic c3dvcmQ6c3dvcmRfc2VjcmV0" + if is_thai: + thai_authorization = self.__configuration.login_authorization + if not thai_authorization: + raise SaicApiException( + "Thai login requires login_authorization with the app's Basic authorization header." + ) + scheme, separator, credentials = thai_authorization.partition(" ") + try: + decoded_credentials = base64.b64decode(credentials, validate=True) + except (binascii.Error, ValueError): + decoded_credentials = b"" + if ( + scheme.lower() != "basic" + or not separator + or b":" not in decoded_credentials + ): + raise SaicApiException( + "login_authorization must be a valid Basic authorization header." + ) + authorization = thai_authorization headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", - "Authorization": "Basic c3dvcmQ6c3dvcmRfc2VjcmV0", + "Authorization": authorization, } firebase_device_id = ( "simulator*********************************************" @@ -67,11 +91,17 @@ async def login(self) -> LoginResp: form_body = { "grant_type": "password", "username": self.__configuration.username, - "password": sha1_hex_digest(self.__configuration.password), + "password": ( + base64.b64encode(self.__configuration.password.encode("utf-8")).decode( + "ascii" + ) + if is_thai + else sha1_hex_digest(self.__configuration.password) + ), "scope": "all", "deviceId": f"{firebase_device_id}###{self.__configuration.device_app_id}", "deviceType": "0", # 2 for huawei - "language": "EN", + "language": "TH" if is_thai else "EN", } if self.__configuration.username_is_email: diff --git a/src/saic_ismart_client_ng/model.py b/src/saic_ismart_client_ng/model.py index 7cc8c4f..26a2221 100644 --- a/src/saic_ismart_client_ng/model.py +++ b/src/saic_ismart_client_ng/model.py @@ -5,10 +5,12 @@ MG_EU_BASE_URI = "https://gateway-mg-eu.soimt.com/api.app/v1/" MG_AU_BASE_URI = "https://gateway-mg-au.soimt.com/api.app/v1/" MG_TR_BASE_URI = "https://gateway-mg-tr.soimt.com/api.app/v1/" +MG_TH_BASE_URI = "https://gateway-mg-th.soimt.com/api.app/v1/" MG_BR_BASE_URI = "https://gateway-mg-br.soimt.com/api.app/v1/" MAXUS_EU_BASE_URI = "https://gateway-maxus-eu.soimt.com/api.app/v1/" MAXUS_EU_TENANT_ID = "590224" MAXUS_EU_DEVICE_APP_ID = "com.saicmaxus.ismarteu" +MAXUS_TH_DEVICE_APP_ID = "com.saicmotor.ismartthai" class SaicApiConfiguration: @@ -25,6 +27,8 @@ def __init__( sms_delivery_delay: float = 3.0, read_timeout: float = 5.0, device_app_id: str = "com.saicmotor.europecar", + *, + login_authorization: str | None = None, ) -> None: self.__username = username self.__password = password @@ -36,6 +40,7 @@ def __init__( self.__sms_delivery_delay = sms_delivery_delay self.__read_timeout = read_timeout self.__device_app_id = device_app_id + self.__login_authorization = login_authorization @classmethod def mg_eu(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfiguration: @@ -58,6 +63,14 @@ def mg_tr(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfigurat kwargs.setdefault("region", "tr") return cls(username, password, **kwargs) + @classmethod + def mg_th(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfiguration: + """Build the configuration for MG iSMART in Thailand.""" + kwargs.setdefault("base_uri", MG_TH_BASE_URI) + kwargs.setdefault("region", "th") + kwargs.setdefault("device_app_id", MAXUS_TH_DEVICE_APP_ID) + return cls(username, password, **kwargs) + @classmethod def mg_br(cls, username: str, password: str, **kwargs: Any) -> SaicApiConfiguration: """Build the configuration for MG iSMART in Brazil (the "MG i-SMART LATAM" app).""" @@ -122,3 +135,7 @@ def read_timeout(self) -> float: @property def device_app_id(self) -> str: return self.__device_app_id + + @property + def login_authorization(self) -> str | None: + return self.__login_authorization diff --git a/src/saic_ismart_client_ng/net/crypto.py b/src/saic_ismart_client_ng/net/crypto.py index 1370026..9ca72df 100644 --- a/src/saic_ismart_client_ng/net/crypto.py +++ b/src/saic_ismart_client_ng/net/crypto.py @@ -122,7 +122,9 @@ def encrypt_request( original_request_headers["APP-CONTENT-ENCRYPTED"] = "1" original_request_headers["tenant-id"] = tenant_id original_request_headers["User-Type"] = "app" - original_request_headers["APP-LANGUAGE-TYPE"] = "en" + original_request_headers["APP-LANGUAGE-TYPE"] = ( + "th" if region.lower() == "th" else "en" + ) if user_token: original_request_headers["blade-auth"] = user_token app_verification_string = get_app_verification_string( diff --git a/src/saic_ismart_client_ng/thai_capture.py b/src/saic_ismart_client_ng/thai_capture.py new file mode 100644 index 0000000..2cdec3a --- /dev/null +++ b/src/saic_ismart_client_ng/thai_capture.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import argparse +import base64 +import json +import plistlib +import sys +from collections.abc import Sequence +from pathlib import Path +from urllib.parse import urlsplit + +def dump_capture_to_text(path: Path) -> Path: + """Write a readable text report containing every item in a Proxygen capture.""" + with path.open("rb") as capture_file: + capture = plistlib.load(capture_file) + + if not isinstance(capture, dict) or not isinstance(capture.get("history"), dict): + raise ValueError("Invalid Proxygen capture: missing request history.") + history = capture["history"] + entries = history.get("entries") + if not isinstance(entries, list): + raise ValueError("Invalid Proxygen capture: missing request entries.") + + lines = ["Capture metadata:"] + metadata = {key: value for key, value in capture.items() if key != "history"} + lines.extend(_format_value(metadata, 2)) + history_metadata = {key: value for key, value in history.items() if key != "entries"} + if history_metadata: + lines.extend(["", "History metadata:"]) + lines.extend(_format_value(history_metadata, 2)) + + for index, entry in enumerate(entries, start=1): + lines.extend(["", f"Entry {index}:"]) + lines.extend(_format_value(entry, 2)) + + output_path = path.with_suffix(".txt") + output_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return output_path + + +def main(argv: Sequence[str] | None = None) -> None: + """Dump a Proxygen plist capture to a companion text file.""" + parser = argparse.ArgumentParser(description=main.__doc__) + parser.add_argument("capture", type=Path, help="path to the Proxygen plist") + args = parser.parse_args(argv) + output_path = dump_capture_to_text(args.capture) + sys.stdout.write(f"Wrote text dump to {output_path}\n") + + +def _format_value(value: object, indent: int = 0, key: str | None = None) -> list[str]: + prefix = " " * indent + if isinstance(value, dict): + if not value: + return [f"{prefix}{{}}"] + lines: list[str] = [] + for item_key, item_value in value.items(): + item_lines = _format_value( + item_value, indent + 2, str(item_key).lower() + ) + if not isinstance(item_value, (dict, list)) and len(item_lines) == 1: + lines.append(f"{prefix}{item_key}: {item_lines[0].strip()}") + continue + lines.append(f"{prefix}{item_key}:") + lines.extend(item_lines) + return lines + if isinstance(value, list): + if not value: + return [f"{prefix}[]"] + lines = [] + for item in value: + formatted = _format_value(item, indent + 2, key) + lines.append(f"{prefix}- {formatted[0].lstrip()}") + lines.extend(formatted[1:]) + return lines + if isinstance(value, bytes): + try: + value = value.decode("utf-8") + except UnicodeDecodeError: + value = f"[binary data, base64] {base64.b64encode(value).decode('ascii')}" + else: + if key == "body": + try: + value = json.dumps( + json.loads(value), ensure_ascii=False, indent=2 + ) + except json.JSONDecodeError: + pass + elif isinstance(value, str) and key == "body": + try: + value = json.dumps(json.loads(value), ensure_ascii=False, indent=2) + except json.JSONDecodeError: + pass + + rendered = str(value) + if "\n" in rendered: + return [f"{prefix}{line}" for line in rendered.splitlines()] + return [f"{prefix}{rendered}"] + + +def login_authorization_from_capture(path: Path) -> str: + """Read the unique Thai login authorization from a Proxygen plist capture.""" + with path.open("rb") as capture_file: + capture = plistlib.load(capture_file) + + if not isinstance(capture, dict) or not isinstance(capture.get("history"), dict): + raise ValueError("Invalid Proxygen capture: missing request history.") + entries = capture["history"].get("entries") + if not isinstance(entries, list): + raise ValueError("Invalid Proxygen capture: missing request entries.") + + authorizations: set[str] = set() + for entry in entries: + if not isinstance(entry, dict) or not isinstance( + entry.get("transaction"), dict + ): + continue + transaction = entry["transaction"] + request = transaction.get("request") + target = transaction.get("target") + if not isinstance(request, dict) or not isinstance(target, dict): + continue + uri = request.get("uri") + if not isinstance(uri, str): + continue + url = urlsplit(uri) + if ( + target.get("host") != "gateway-mg-th.soimt.com" + or url.hostname not in (None, "gateway-mg-th.soimt.com") + or url.path != "/api.app/v1/oauth/token" + or request.get("method") != "POST" + ): + continue + headers = request.get("headers") + if not isinstance(headers, list): + continue + for header in headers: + if ( + isinstance(header, dict) + and isinstance(header.get("name"), str) + and header["name"].lower() == "authorization" + and isinstance(header.get("value"), str) + ): + authorizations.add(header["value"]) + + if not authorizations: + raise ValueError("No Thai login authorization found in the capture.") + if len(authorizations) != 1: + raise ValueError("Multiple Thai login authorizations found in the capture.") + return authorizations.pop() + + +if __name__ == "__main__": + main() diff --git a/tests/test_model.py b/tests/test_model.py index 1715c9e..0746a81 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -79,6 +79,14 @@ def test_mg_preset_overrides(self) -> None: assert config.tenant_id == "1" assert config.region == "x" + def test_mg_th_preset(self) -> None: + config = SaicApiConfiguration.mg_th("u", "p", login_authorization="example") + assert config.base_uri == "https://gateway-mg-th.soimt.com/api.app/v1/" + assert config.region == "th" + assert config.tenant_id == "459771" + assert config.device_app_id == "com.saicmotor.ismartthai" + assert config.login_authorization == "example" + if __name__ == "__main__": unittest.main()