Debian Codegraph @

src/anova_wifi/parser.py

raw
1 import asyncio
2 import logging
3
4 import aiohttp
5 from aiohttp import ClientConnectorError
6
7 from .exceptions import InvalidLogin, LoginUnreachable, NoDevicesFound, WebsocketFailure
8 from .websocket_handler import AnovaWebsocketHandler
9
10 _LOGGER = logging.getLogger(__name__)
11
12 # Found here - https://github.com/ammarzuberi/pyanova-api/blob/master/anova/AnovaCooker.py and personally confirmed.
13 ANOVA_FIREBASE_KEY = "AIzaSyDQiOP2fTR9zvFcag2kSbcmG9zPh6gZhHw"
14
15
16 class AnovaApi:
17 """A class to handle communicating with the anova api to get devices"""
18
19 def __init__(
20 self,
21 session: aiohttp.ClientSession,
22 username: str,
23 password: str,
24 ) -> None:
25 """Creates an anova api class"""
26 self.session = session
27 self.username = username
28 self.password = password
29 self.jwt: str | None = None
30 self._firebase_jwt: str | None = None
31 self.websocket_handler: AnovaWebsocketHandler | None = None
32
33 async def authenticate(self) -> bool:
34 """Auth with Firebase server"""
35 # Code loving yoinked from https://github.com/ammarzuberi/pyanova-api/blob/master/anova/AnovaCooker.py
36 firebase_req_data = {
37 "email": self.username,
38 "password": self.password,
39 "returnSecureToken": True,
40 }
41 try:
42 firebase_req = await self.session.post(
43 f"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={ANOVA_FIREBASE_KEY}",
44 json=firebase_req_data,
45 )
46 except ClientConnectorError as err:
47 raise LoginUnreachable(
48 "Failed to connect to Anova's firebase instance"
49 ) from err
50 firebase_id_token_json = await firebase_req.json()
51 self._firebase_jwt = firebase_id_token_json.get("idToken")
52
53 if not self._firebase_jwt:
54 raise InvalidLogin("Could not log in with Google Firebase")
55
56 # Now authenticate with Anova using the Firebase ID token to get the JWT
57 anova_auth_req = await self.session.post(
58 "https://anovaculinary.io/authenticate",
59 json={},
60 headers={"firebase-token": self._firebase_jwt},
61 )
62 jwt_json = await anova_auth_req.json()
63 jwt = jwt_json.get("jwt") # Looks like this JWT is valid for an entire year...
64
65 if not jwt:
66 raise InvalidLogin("Could not authenticate with Anova")
67
68 # Set JWT local variable
69 self.jwt = jwt
70
71 return True
72
73 async def create_websocket(self) -> None:
74 if self._firebase_jwt is None:
75 raise WebsocketFailure("Firebase jwt was none.")
76 if self.jwt is None:
77 raise WebsocketFailure("jwt was none.")
78 self.websocket_handler = AnovaWebsocketHandler(
79 firebase_jwt=self._firebase_jwt, jwt=self.jwt, session=self.session
80 )
81 await self.websocket_handler.connect()
82 await asyncio.sleep(5)
83 if not self.websocket_handler.devices:
84 raise NoDevicesFound("No devices were found on the websocket.")
85
86 async def disconnect_websocket(self) -> None:
87 if self.websocket_handler is not None:
88 await self.websocket_handler.disconnect()