Skip to content

Commit

Permalink
Better errors management
Browse files Browse the repository at this point in the history
  • Loading branch information
Giga77 committed Mar 11, 2024
1 parent 41c8f1c commit 98f72d6
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 35 deletions.
11 changes: 6 additions & 5 deletions custom_components/ecole_directe/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
{
vol.Required("username"): str,
vol.Required("password"): str,
vol.Required("account_type"): vol.In({'eleve': 'Student', 'famille': 'Family'})
vol.Required("account_type"): vol.In({'famille': 'Famille', 'eleve': 'Elève'})
}
)

Expand All @@ -42,20 +42,21 @@ def __init__(self) -> None:

async def async_step_user(self, user_input: dict | None = None) -> FlowResult:
"""Handle a flow initialized by the user."""
_LOGGER.debug("Setup process initiated by user.")
_LOGGER.debug("ED - Setup process initiated by user.")
errors: dict[str, str] = {}
if user_input is not None:
try:
_LOGGER.debug("User Input: %s", user_input)
_LOGGER.debug("ED - User Input: %s", user_input)
self._user_inputs.update(user_input)
session = await self.hass.async_add_executor_job(get_ecoledirecte_session, self._user_inputs)

if session is None:
raise InvalidAuth

_LOGGER.debug(f"ED - User Inputs UP: {self._user_inputs} - identifiant: [{session.identifiant}]")
return self.async_create_entry(title=session.identifiant, data=self._user_inputs)
except InvalidAuth:
errors["base"] = "invalid_auth"
_LOGGER.debug("_User Inputs UP: %s", self._user_inputs)
return self.async_create_entry(title=session.identifiant, data=self._user_inputs)

return self.async_show_form(step_id="user", data_schema=STEP_USER_DATA_SCHEMA_UP, errors=errors)

Expand Down
54 changes: 28 additions & 26 deletions custom_components/ecole_directe/ecoleDirecte_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,24 @@ def decodeB64(string):
return base64.b64decode(string)

def getResponse(session, url, data):
if not isLogin(session):
return None
if session is not None and isLogin(session):
token = session.token
else:
token = None

response = requests.post(url, data = data, headers = getHeaders(token))

response = requests.post(url, data=data, headers=getHeaders(session.token))
if 'application/json' in response.headers.get('Content-Type', ''):
return response.json()
respJson = response.json()
if respJson['code'] != 200:
raise RequestError('Error with URL:[{}] - Code {}: {}'.format(url, respJson['code'], respJson['message']))
return respJson

raise RequestError('Error with URL:[{}]: {}'.format(url, response.content))

_LOGGER.warning(f"Error with URL:[{url}] - response:[{response.content}]")
return None
class RequestError(Exception):
def __init__(self, message):
super(RequestError, self).__init__(message)

class ED_Session:
def __init__(self, data):
Expand Down Expand Up @@ -73,14 +82,23 @@ def get_fullname(self) -> str | None:

def get_ecoledirecte_session(data) -> ED_Session | None:
try:
session = login(data['username'], data['password'])
_LOGGER.info(f"Connection OK - identifiant: [{session.identifiant}]")
_LOGGER.debug(f"Try connection for username: {data['username']} and password: {data['password']}")

login = getResponse(None, f"{APIURL}/login.awp?v={APIVERSION}", encodeBody({
"data": {
"identifiant": data['username'],
"motdepasse": data['password']
}
}))

_LOGGER.debug(f"login: {login}")
_LOGGER.info(f"Connection OK - identifiant: [{login["data"]["accounts"][0]["identifiant"]}]")
return ED_Session(login);

except Exception as err:
_LOGGER.critical(err)
return None

return session

def getMessages(session, eleve, year):
if(eleve == None):
return getResponse(session,
Expand Down Expand Up @@ -127,22 +145,6 @@ def getHeaders(token):

return headers

def login(username, password) -> ED_Session | None:
_LOGGER.debug(f"Coordinator uses connection for username: {username} and password: {password}")
try:
login = requests.post(f"{APIURL}/login.awp?v={APIVERSION}", data=encodeBody({
"data": {
"identifiant": username,
"motdepasse": password
}
}), headers=getHeaders(None)).json()
except Exception as err:
_LOGGER.critical(err)
return None

_LOGGER.debug(f"login: {login}")
return ED_Session(login);

def isLogin(session):
if session.token != None and session.id != None:
return True
Expand Down
6 changes: 4 additions & 2 deletions custom_components/ecole_directe/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
"description": "Donnez vos informations de connexion à Ecole Directe",
"data": {
"username": "[%key:common::config_flow::data::username%]",
"password": "[%key:common::config_flow::data::password%]"
"password": "[%key:common::config_flow::data::password%]",
"account_type": "[%key:common::config_flow::data::account_type%]"
},
"data_description": {
"username": "user name",
"password": "Password"
"password": "Password",
"account_type": "Account type"
}
}
},
Expand Down
3 changes: 2 additions & 1 deletion custom_components/ecole_directe/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"user": {
"data": {
"password": "Password",
"username": "Username"
"username": "Username",
"account_type": "Account type"
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion custom_components/ecole_directe/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"user": {
"data": {
"password": "Mot de passe",
"username": "Identifiant"
"username": "Identifiant",
"account_type": "Type de compte"
}
}
}
Expand Down

0 comments on commit 98f72d6

Please sign in to comment.