Esempio n. 1
0
async def setup_client():
    if path.exists("./keystore.json"):
        with open("keystore.json") as f:
            keystore = Keystore.load(json.load(f))
    else: 
        with open("./keystore.json", "w") as f:
            keystore = Keystore.create(device_model="Vulcan API")
            json.dump(keystore.as_dict, f)

    if path.exists("./account.json"):
        with open("./account.json") as f:
            account = Account.load(json.load(f))
    else:
        account = await Account.register(keystore, config.credentials[0], config.credentials[1], config.credentials[2])
        with open("./account.json", "w") as f:
            json.dump(account.as_dict, f)

    if path.exists("./homework.txt"):
        with open("./homework.txt") as f:
            homework_cache = json.load(f)
    else:
        homework_cache = []
        with open("./homework.txt", "w") as f:
            json.dump(homework_cache, f)

    client = VulcanHebe(keystore, account)
    await client.select_student()

    return client, homework_cache
Esempio n. 2
0
async def setup():
    try:
        with open("keystore.json", 'r') as file:
            keystore = Keystore.load(file.read())
    except FileNotFoundError:
        print("No keystore found! Creating")
        keystore = Keystore.create()

    try:
        with open("account.json", 'r') as file:
            account = Account.load(file.read())
    except FileNotFoundError:
        print("No account registered!")
        token = input("Please, tell me your token: ")
        symbol = input("Next is your symbol: ")
        pin = input("And lastly, pin: ")

        account = await Account.register(keystore, token, symbol, pin)
        with open("account.json", 'w') as file:
            file.write(account.as_json)

    with open("keystore.json", "w") as file:
        file.write(keystore.as_json)

    client = VulcanHebe(keystore, account)
    await client.select_student()
    return client
Esempio n. 3
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Uonet+ Vulcan integration."""
    hass.data.setdefault(DOMAIN, {})
    try:
        keystore = Keystore.load(entry.data["keystore"])
        account = Account.load(entry.data["account"])
        client = Vulcan(keystore, account, async_get_clientsession(hass))
        await client.select_student()
        students = await client.get_students()
        for student in students:
            if str(student.pupil.id) == str(entry.data["student_id"]):
                client.student = student
                break
    except UnauthorizedCertificateException as err:
        raise ConfigEntryAuthFailed(
            "The certificate is not authorized.") from err
    except ClientConnectorError as err:
        raise ConfigEntryNotReady(
            f"Connection error - please check your internet connection: {err}"
        ) from err
    hass.data[DOMAIN][entry.entry_id] = client

    await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

    return True
Esempio n. 4
0
    async def async_step_select_saved_credentials(self,
                                                  user_input=None,
                                                  errors=None):
        """Allow user to select saved credentials."""
        credentials_list = {}
        for entry in self.hass.config_entries.async_entries(DOMAIN):
            credentials_list[
                entry.entry_id] = entry.data["account"]["UserName"]

        if user_input is not None:
            entry = self.hass.config_entries.async_get_entry(
                user_input["credentials"])
            keystore = Keystore.load(entry.data["keystore"])
            account = Account.load(entry.data["account"])
            client = Vulcan(keystore, account)
            try:
                students = await client.get_students()
            except VulcanAPIException as err:
                if str(err) == "The certificate is not authorized.":
                    return await self.async_step_auth(
                        errors={"base": "expired_credentials"})
                _LOGGER.error(err)
                return await self.async_step_auth(errors={"base": "unknown"})
            except ClientConnectionError as err:
                _LOGGER.error("Connection error: %s", err)
                return await self.async_step_select_saved_credentials(
                    errors={"base": "cannot_connect"})
            except Exception:  # pylint: disable=broad-except
                _LOGGER.exception("Unexpected exception")
                return await self.async_step_auth(errors={"base": "unknown"})
            finally:
                await client.close()
            if len(students) == 1:
                student = students[0]
                await self.async_set_unique_id(str(student.pupil.id))
                self._abort_if_unique_id_configured()
                return self.async_create_entry(
                    title=
                    f"{student.pupil.first_name} {student.pupil.last_name}",
                    data={
                        "student_id": str(student.pupil.id),
                        "keystore": keystore.as_dict,
                        "account": account.as_dict,
                    },
                )
            # pylint:disable=attribute-defined-outside-init
            self.account = account
            self.keystore = keystore
            self.students = students
            return await self.async_step_select_student()

        data_schema = {
            vol.Required("credentials", ): vol.In(credentials_list),
        }
        return self.async_show_form(
            step_id="select_saved_credentials",
            data_schema=vol.Schema(data_schema),
            errors=errors,
        )
Esempio n. 5
0
    async def async_step_add_next_config_entry(self, user_input=None):
        """Flow initialized when user is adding next entry of that integration."""
        existing_entries = []
        for entry in self.hass.config_entries.async_entries(DOMAIN):
            existing_entries.append(entry)

        errors = {}
        if user_input is not None:
            if user_input["use_saved_credentials"]:
                if len(existing_entries) == 1:
                    keystore = Keystore.load(
                        existing_entries[0].data["keystore"])
                    account = Account.load(existing_entries[0].data["account"])
                    client = Vulcan(keystore, account)
                    students = await client.get_students()
                    await client.close()
                    new_students = []
                    existing_entry_ids = []
                    for entry in self.hass.config_entries.async_entries(
                            DOMAIN):
                        existing_entry_ids.append(entry.data["student_id"])
                    for student in students:
                        if str(student.pupil.id) not in existing_entry_ids:
                            new_students.append(student)
                    if not new_students:
                        return self.async_abort(
                            reason="all_student_already_configured")
                    if len(new_students) == 1:
                        await self.async_set_unique_id(
                            str(new_students[0].pupil.id))
                        self._abort_if_unique_id_configured()
                        return self.async_create_entry(
                            title=
                            f"{new_students[0].pupil.first_name} {new_students[0].pupil.last_name}",
                            data={
                                "student_id": str(new_students[0].pupil.id),
                                "keystore": keystore.as_dict,
                                "account": account.as_dict,
                            },
                        )
                    # pylint:disable=attribute-defined-outside-init
                    self.account = account
                    self.keystore = keystore
                    self.students = new_students
                    return await self.async_step_select_student()
                return await self.async_step_select_saved_credentials()
            return await self.async_step_auth()

        data_schema = {
            vol.Required("use_saved_credentials", default=True): bool,
        }
        return self.async_show_form(
            step_id="add_next_config_entry",
            data_schema=vol.Schema(data_schema),
            errors=errors,
        )
Esempio n. 6
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Uonet+ Vulcan integration."""
    hass.data.setdefault(DOMAIN, {})
    try:
        keystore = Keystore.load(entry.data["keystore"])
        account = Account.load(entry.data["account"])
        client = Vulcan(keystore, account)
        await client.select_student()
        students = await client.get_students()
        for student in students:
            if str(student.pupil.id) == str(entry.data["student_id"]):
                client.student = student
                break
    except VulcanAPIException as err:
        if str(err) == "The certificate is not authorized.":
            _LOGGER.error(
                "The certificate is not authorized, please authorize integration again"
            )
            raise ConfigEntryAuthFailed from err
        _LOGGER.error("Vulcan API error: %s", err)
        return False
    except ClientConnectorError as err:
        if "connection_error" not in hass.data[DOMAIN]:
            _LOGGER.error(
                "Connection error - please check your internet connection: %s",
                err)
            hass.data[DOMAIN]["connection_error"] = True
        await client.close()
        raise ConfigEntryNotReady from err
    hass.data[DOMAIN]["students_number"] = len(
        hass.config_entries.async_entries(DOMAIN))
    hass.data[DOMAIN][entry.entry_id] = client

    if not entry.update_listeners:
        entry.add_update_listener(_async_update_options)

    for platform in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, platform))

    return True