Skip to content
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

feat: rework auth flow - part 2 #221

Merged
merged 6 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions library_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import aiohttp
from colorlog import ColoredFormatter

from midealocal.cloud import clouds, get_midea_cloud
from midealocal.cloud import SUPPORTED_CLOUDS, get_midea_cloud
from midealocal.devices import device_selector
from midealocal.discover import discover

Expand All @@ -31,7 +31,7 @@ def get_arguments() -> tuple[ArgumentParser, Namespace]:
"--cloud_name",
"-cn",
type=str,
help="Set Cloud name, options are: " + ", ".join(clouds.keys()),
help="Set Cloud name, options are: " + ", ".join(SUPPORTED_CLOUDS.keys()),
)
parser.add_argument(
"--configfile",
Expand Down
4 changes: 2 additions & 2 deletions midealocal/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import platformdirs
from colorlog import ColoredFormatter

from midealocal.cloud import clouds, get_midea_cloud
from midealocal.cloud import SUPPORTED_CLOUDS, get_midea_cloud
from midealocal.device import ProtocolVersion
from midealocal.devices import device_selector
from midealocal.discover import discover
Expand Down Expand Up @@ -162,7 +162,7 @@ def main() -> NoReturn:
"-cn",
type=str,
help="Set Cloud name",
choices=clouds.keys(),
choices=SUPPORTED_CLOUDS.keys(),
)

# Setup discover parser
Expand Down
79 changes: 58 additions & 21 deletions midealocal/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

_LOGGER = logging.getLogger(__name__)

clouds = {
SUPPORTED_CLOUDS = {
"美的美居": {
"class_name": "MeijuCloud",
"app_id": "900",
Expand All @@ -41,6 +41,7 @@
"api_url": "https://mp-prod.smartmidea.net/mas/v5/app/proxy?alias=",
},
"MSmartHome": {
"default": True,
"class_name": "MSmartHomeCloud",
"app_id": "1010",
"app_key": "ac21b9f9cbfe4ca5a88562ef25e2b768",
Expand Down Expand Up @@ -78,6 +79,36 @@
},
}

PRESET_ACCOUNT_DATA = [
39182118275972017797890111985649342047468653967530949796945843010512,
29406100301096535908214728322278519471982973450672552249652548883645,
39182118275972017797890111985649342050088014265865102175083010656997,
]


def get_default_cloud() -> str:
"""Return default cloud."""
for key, value in SUPPORTED_CLOUDS.items():
if cast(dict, value).get("default"):
return key
raise ElementMissing


def get_preset_account_cloud() -> dict[str, str]:
"""Return preset account data for cloud login."""
username: str = bytes.fromhex(
format((PRESET_ACCOUNT_DATA[0] ^ PRESET_ACCOUNT_DATA[1]), "X"),
).decode("ASCII")
password: str = bytes.fromhex(
format((PRESET_ACCOUNT_DATA[0] ^ PRESET_ACCOUNT_DATA[2]), "X"),
).decode("ASCII")

return {
"username": username,
"password": password,
"cloud_name": get_default_cloud(),
}


class MideaCloud:
"""Midea Cloud."""
Expand Down Expand Up @@ -215,7 +246,7 @@ async def get_cloud_keys(self, appliance_id: int) -> dict[int, dict[str, Any]]:
@staticmethod
async def get_cloud_servers() -> dict[int, str]:
"""Get available cloud servers."""
return {i: cloud for i, cloud in enumerate(clouds, start=1)}
return {i: cloud for i, cloud in enumerate(SUPPORTED_CLOUDS, start=1)}

async def list_home(self) -> dict[int, Any] | None:
"""List homes."""
Expand Down Expand Up @@ -259,18 +290,19 @@ def __init__(
password: str,
) -> None:
"""Initialize Meiju Cloud."""
cloud_data = cast(dict[str, Any], SUPPORTED_CLOUDS[cloud_name])
super().__init__(
session=session,
security=MeijuCloudSecurity(
login_key=clouds[cloud_name]["login_key"],
iot_key=clouds[cloud_name]["iot_key"],
hmac_key=clouds[cloud_name]["hmac_key"],
login_key=cloud_data["login_key"],
iot_key=cloud_data["iot_key"],
hmac_key=cloud_data["hmac_key"],
),
app_id=clouds[cloud_name]["app_id"],
app_key=clouds[cloud_name]["app_key"],
app_id=cloud_data["app_id"],
app_key=cloud_data["app_key"],
account=account,
password=password,
api_url=clouds[cloud_name]["api_url"],
api_url=cloud_data["api_url"],
)

async def login(self) -> bool:
Expand Down Expand Up @@ -452,21 +484,24 @@ def __init__(
password: str,
) -> None:
"""Initialize MSmart Cloud."""
cloud_data = cast(dict[str, Any], SUPPORTED_CLOUDS[cloud_name])
super().__init__(
session=session,
security=MSmartCloudSecurity(
login_key=clouds[cloud_name]["app_key"],
iot_key=clouds[cloud_name]["iot_key"],
hmac_key=clouds[cloud_name]["hmac_key"],
login_key=cloud_data["app_key"],
iot_key=cloud_data["iot_key"],
hmac_key=cloud_data["hmac_key"],
),
app_id=clouds[cloud_name]["app_id"],
app_key=clouds[cloud_name]["app_key"],
app_id=cloud_data["app_id"],
app_key=cloud_data["app_key"],
account=account,
password=password,
api_url=clouds[cloud_name]["api_url"],
api_url=cloud_data["api_url"],
)
self._auth_base = base64.b64encode(
f"{self._app_key}:{clouds['MSmartHome']['iot_key']}".encode("ascii"),
f"{self._app_key}:{cloud_data['iot_key']}".encode(
"ascii",
),
).decode("ascii")

def _make_general_data(self) -> dict[str, Any]:
Expand Down Expand Up @@ -643,14 +678,15 @@ def __init__(
password: str,
) -> None:
"""Initialize Midea Air Cloud."""
cloud_data = cast(dict[str, Any], SUPPORTED_CLOUDS[cloud_name])
super().__init__(
session=session,
security=MideaAirSecurity(login_key=clouds[cloud_name]["app_key"]),
app_id=clouds[cloud_name]["app_id"],
app_key=clouds[cloud_name]["app_key"],
security=MideaAirSecurity(login_key=cloud_data["app_key"]),
app_id=cloud_data["app_id"],
app_key=cloud_data["app_key"],
account=account,
password=password,
api_url=clouds[cloud_name]["api_url"],
api_url=cloud_data["api_url"],
)
self._session_id: str | None = None

Expand Down Expand Up @@ -783,14 +819,15 @@ def get_midea_cloud(
password: str,
) -> MideaCloud:
"""Get Midea Cloud implementation."""
if cloud_name not in clouds:
if cloud_name not in SUPPORTED_CLOUDS:
raise ElementMissing(
f"Unsupported Cloud specified: {cloud_name}",
)

cloud_data = cast(dict[str, Any], SUPPORTED_CLOUDS[cloud_name])
return cast(
MideaCloud,
globals()[clouds[cloud_name]["class_name"]](
globals()[cloud_data["class_name"]](
cloud_name=cloud_name,
session=session,
account=account,
Expand Down