Skip to content

Commit

Permalink
Merge pull request #6 from hacf-fr/main
Browse files Browse the repository at this point in the history
main to dev
  • Loading branch information
Giga77 authored Apr 26, 2024
2 parents ed9422b + e1f3b96 commit f3d8f1a
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 19 deletions.
24 changes: 19 additions & 5 deletions custom_components/ecole_directe/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

from __future__ import annotations

import json
import os.path
import logging
from typing import Any

import voluptuous as vol

from homeassistant import config_entries
Expand All @@ -13,7 +14,7 @@
from homeassistant.core import callback

from .ecole_directe_helper import (
get_ecoledirecte_session,
check_ecoledirecte_session,
)

from .const import (
Expand Down Expand Up @@ -45,18 +46,31 @@ async def async_step_user(self, user_input: dict | None = None) -> FlowResult:
"""Handle a flow initialized by the user."""
_LOGGER.debug("ED - Setup process initiated by user.")
errors: dict[str, str] = {}

path = self.hass.config.config_dir + "/custom_components/ecole_directe/qcm.json"
if not os.path.isfile(path):
with open(
path,
"w",
encoding="utf-8",
) as f:
json.dump({}, f, ensure_ascii=False, indent=4)

if user_input is not None:
try:
self._user_inputs.update(user_input)
session = await self.hass.async_add_executor_job(
get_ecoledirecte_session, self._user_inputs
check_ecoledirecte_session,
self._user_inputs,
self.hass.config.config_dir,
self.hass,
)

if session is None:
if not session:
raise InvalidAuth

return self.async_create_entry(
title=session.identifiant, data=self._user_inputs
title=self._user_inputs["username"], data=self._user_inputs
)
except InvalidAuth:
errors["base"] = "invalid_auth"
Expand Down
4 changes: 3 additions & 1 deletion custom_components/ecole_directe/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]:

data = self.config_entry.data

session = await self.hass.async_add_executor_job(get_ecoledirecte_session, data)
session = await self.hass.async_add_executor_job(
get_ecoledirecte_session, data, self.hass.config.config_dir, self.hass
)

if session is None:
_LOGGER.error("Unable to init ecole directe client")
Expand Down
35 changes: 24 additions & 11 deletions custom_components/ecole_directe/ecole_directe_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import base64
import requests

from .const import EVENT_TYPE

_LOGGER = logging.getLogger(__name__)

APIURL = "https://api.ecoledirecte.com/v3"
Expand Down Expand Up @@ -284,7 +286,17 @@ def __init__(self, data):
self.elements_programme = ""


def get_ecoledirecte_session(data) -> EDSession | None:
def check_ecoledirecte_session(data, config_path, hass) -> bool:
"""check if credentials to Ecole Directe are ok"""
try:
session = get_ecoledirecte_session(data, config_path, hass)
except QCMError:
return True

return session is not None


def get_ecoledirecte_session(data, config_path, hass) -> EDSession | None:
"""Function connecting to Ecole Directe"""
try:
payload = (
Expand All @@ -299,7 +311,7 @@ def get_ecoledirecte_session(data) -> EDSession | None:
# Si connexion initiale
if login["code"] == 250:
with open(
"config/custom_components/ecole_directe/qcm.json",
config_path + "/custom_components/ecole_directe/qcm.json",
encoding="utf-8",
) as f:
qcm_json = json.load(f)
Expand All @@ -312,6 +324,9 @@ def get_ecoledirecte_session(data) -> EDSession | None:
question = base64.b64decode(qcm["question"]).decode("utf-8")

if qcm_json is not None and question in qcm_json:
if len(qcm_json[question]) > 1:
try_login -= 1
continue
reponse = base64.b64encode(
bytes(qcm_json[question][0], "utf-8")
).decode("ascii")
Expand All @@ -336,17 +351,19 @@ def get_ecoledirecte_session(data) -> EDSession | None:
qcm_json[question] = rep

with open(
"config/custom_components/ecole_directe/qcm.json",
config_path + "/custom_components/ecole_directe/qcm.json",
"w",
encoding="utf-8",
) as f:
json.dump(qcm_json, f, ensure_ascii=False, indent=4)
event_data = {"type": "new_qcm", "question": question}
hass.bus.async_fire(EVENT_TYPE, event_data)

try_login -= 1

if try_login == 0:
raise QCMError(
"Vérifiez le fichier qcm.json, et recharchez l'intégration Ecole Directe."
"Vérifiez le fichier qcm.json, et rechargez l'intégration Ecole Directe."
)

_LOGGER.debug("cn: [%s] - cv: [%s]", cn, cv)
Expand All @@ -371,6 +388,9 @@ def get_ecoledirecte_session(data) -> EDSession | None:
login["data"]["accounts"][0]["identifiant"],
)
return EDSession(login)
except QCMError as err:
_LOGGER.warning(err)
raise
except Exception as err:
_LOGGER.critical(err)
return None
Expand Down Expand Up @@ -501,10 +521,3 @@ def get_headers(token):
headers["X-Token"] = token

return headers


def is_login(session):
"""Ckeck valid login"""
if session.token is not None and session.id is not None:
return True
return False
2 changes: 0 additions & 2 deletions custom_components/ecole_directe/qcm.json

This file was deleted.

1 change: 1 addition & 0 deletions custom_components/ecole_directe/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"double_auth": "[%key:common::config_flow::error::double_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
Expand Down
1 change: 1 addition & 0 deletions custom_components/ecole_directe/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"error": {
"cannot_connect": "Failed to connect",
"invalid_auth": "Invalid authentication",
"double_auth": "Check the file qcm.json",
"unknown": "Unexpected error"
},
"step": {
Expand Down
1 change: 1 addition & 0 deletions custom_components/ecole_directe/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"error": {
"cannot_connect": "Impossible de se connecter",
"invalid_auth": "Erreur d'authentification",
"double_auth": "Vérifier le fichier qcm.json",
"unknown": "Une erreur est survenue"
},
"step": {
Expand Down

0 comments on commit f3d8f1a

Please sign in to comment.