Skip to content

Home Information - Your home, your data, organized.

Python
13.5 KB
Raw Blame
import logging
from asgiref.sync import sync_to_async
from typing import Dict, List, Optional

from hi.apps.common.singleton_manager import SingletonManager
from hi.apps.system.aggregate_health_provider import AggregateHealthProvider
from hi.apps.system.api_health_status_provider import ApiHealthStatusProvider
from hi.apps.system.provider_info import ProviderInfo
from hi.apps.system.enums import HealthStatusType

from hi.integrations.exceptions import (
    IntegrationAttributeError,
    IntegrationError,
)
from hi.integrations.transient_models import (
    ConnectionTestResult,
    IntegrationKey,
    IntegrationValidationResult,
)
from hi.integrations.models import Integration, IntegrationAttribute

from hi.services.homebox.enums import HbAttributeType
from .constants import HbTimeouts
from .hb_client import HbClient
from .hb_client_factory import HbClientFactory
from .hb_models import HbItem
from hi.services.homebox.hb_metadata import HbMetaData

logger = logging.getLogger(__name__)


class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProvider ):

    def __init_singleton__( self ):
        super().__init_singleton__()

        self._hb_attr_type_to_attribute = dict()
        self._hb_client = None
        self._client_factory = HbClientFactory()

        self._hb_items_list = list()
        self._hb_tags_list = list()
        self._hb_locations_list = list()
        self._hb_maintenances_list = list()

        self._change_listeners = set()
        self._polling_interval_secs = HbTimeouts.POLLING_INTERVAL_SECS

        self.add_api_health_status_provider(self)

        return

    @classmethod
    def get_provider_info(cls) -> ProviderInfo:
        return ProviderInfo(
            provider_id = 'hi.services.homebox.manager',
            provider_name = 'HomeBox Integration',
            description = '',
        )

    @classmethod
    def get_api_provider_info(cls) -> ProviderInfo:
        return ProviderInfo(
            provider_id = 'hi.services.homebox.api',
            provider_name = 'HomeBox API',
            description = 'HomeBox REST API',
        )

    def register_change_listener( self, callback ):
        if callback not in self._change_listeners:
            logger.debug( f'Adding HomeBox setting change listener from {callback.__module__}' )
            self._change_listeners.add( callback )
        else:
            logger.debug( f'HomeBox setting change listener from'
                          f' {callback.__module__} already registered, skipping duplicate' )
        return

    def notify_settings_changed(self):
        self.reload()
        for callback in self._change_listeners:
            try:
                callback()
            except Exception:
                logger.exception( 'Problem calling setting change callback.' )
            continue
        return

    @property
    def hb_client(self) -> HbClient:
        return self._hb_client

    @property
    def include_filter( self ) -> str:
        attribute = self._hb_attr_type_to_attribute.get( HbAttributeType.INCLUDE_FILTER )
        if attribute and attribute.value:
            return attribute.value
        return ''

    @property
    def exclude_filter( self ) -> str:
        attribute = self._hb_attr_type_to_attribute.get( HbAttributeType.EXCLUDE_FILTER )
        if attribute and attribute.value:
            return attribute.value
        return ''

    def _reload_implementation( self ):
        try:
            self._hb_attr_type_to_attribute = self._load_attributes()
            self._polling_interval_secs = self._read_polling_interval_secs()
            self._hb_client = self.create_hb_client( self._hb_attr_type_to_attribute )
            self.clear_caches()
            self.record_healthy('Reloaded')

        except IntegrationError as e:
            error_msg = f'HomeBox integration configuration error: {e}'
            logger.error(error_msg)
            self.record_error( f'Configuration error: {error_msg}' )

        except IntegrationAttributeError as e:
            error_msg = f'HomeBox integration attribute error: {e}'
            logger.error(error_msg)
            self.record_error( f'Configuration error: {error_msg}' )

        except Exception as e:
            error_msg = f'Unexpected error loading HomeBox configuration: {e}'
            logger.exception(error_msg)
            self.record_warning( f'Temporary issue: {error_msg}' )
        return

    def clear_caches(self):
        self._hb_items_list = list()
        self._hb_tags_list = list()
        self._hb_locations_list = list()
        self._hb_maintenances_list = list()
        return

    def _load_attributes(self) -> Dict[ HbAttributeType, IntegrationAttribute ]:
        try:
            hb_integration = Integration.objects.get( integration_id = HbMetaData.integration_id )
        except Integration.DoesNotExist:
            raise IntegrationError( 'HomeBox integration is not implemented.' )

        integration_attributes = list(hb_integration.attributes.all())
        return self._build_hb_attr_type_to_attribute_map(
            integration_attributes = integration_attributes,
            enforce_requirements = True,
        )

    def _read_polling_interval_secs(self) -> int:
        """Read the configured polling interval. Form-level validation
        (``AttributeForm._clean_integer_value`` + the schema's
        ``value_range`` declaration) enforces type and range at save
        time, so any persisted value should already be a positive int
        within bounds. The defensive fallbacks here only fire on the
        edge cases form validation can't cover: the attribute row is
        missing (integration enabled but never saved) or the DB was
        manually edited / migrated from legacy data."""
        attribute = self._hb_attr_type_to_attribute.get(
            HbAttributeType.POLLING_INTERVAL_SECS,
        )
        if attribute is None or not attribute.value:
            return HbTimeouts.POLLING_INTERVAL_SECS
        try:
            return int( attribute.value )
        except (ValueError, TypeError):
            logger.warning(
                f'Malformed HomeBox polling interval value "{attribute.value}" '
                f'(form validation should have caught this); falling '
                f'back to default {HbTimeouts.POLLING_INTERVAL_SECS}s'
            )
            return HbTimeouts.POLLING_INTERVAL_SECS

    @property
    def polling_interval_secs(self) -> int:
        return self._polling_interval_secs

    def create_hb_client(
            self,
            hb_attr_type_to_attribute : Dict[ HbAttributeType, IntegrationAttribute ] ) -> HbClient:
        return self._client_factory.create_client(hb_attr_type_to_attribute)

    def fetch_hb_items_from_api( self, verbose : bool = True ) -> list:
        if verbose:
            logger.debug( 'Getting current HomeBox items.' )

        if not self.hb_client:
            raise IntegrationError(
                'HomeBox client is not available. The most recent reload '
                'failed to construct a client (typically a connection or '
                'configuration problem with the upstream HomeBox API).'
            )

        with self.api_call_context( 'hb_items' ):
            return self.hb_client.get_items()

    async def fetch_hb_items_from_api_async( self, verbose : bool = True ) -> list:
        return await sync_to_async(
            self.fetch_hb_items_from_api,
            thread_sensitive = True,
        )(verbose=verbose)

    def fetch_hb_item_from_api( self, item_id : str, verbose : bool = True ) -> HbItem:
        if verbose:
            logger.debug( f'Getting HomeBox item {item_id}.' )

        if not self.hb_client:
            raise IntegrationError(
                'HomeBox client is not available. The most recent reload '
                'failed to construct a client (typically a connection or '
                'configuration problem with the upstream HomeBox API).'
            )

        with self.api_call_context( 'hb_item' ):
            return self.hb_client.get_item( item_id )

    def fetch_hb_items_summary_from_api( self ) -> list:
        """
        Lightweight one-call probe used by the monitor's reachability
        heartbeat. Raises IntegrationError when the client is
        unavailable so the monitor's heartbeat correctly reflects the
        broken state — silently returning [] would let the monitor
        report 'API reachable' against a non-existent client and
        overwrite the manager's true WARNING/ERROR health.
        """
        if not self.hb_client:
            raise IntegrationError(
                'HomeBox client is not available. The most recent reload '
                'failed to construct a client (typically a connection or '
                'configuration problem with the upstream HomeBox API).'
            )

        with self.api_call_context( 'hb_items_summary' ):
            return self.hb_client.get_items_summary()

    async def fetch_hb_items_summary_from_api_async( self ) -> list:
        return await sync_to_async(
            self.fetch_hb_items_summary_from_api,
            thread_sensitive = True,
        )()
    
    def test_client_with_attributes(
            self,
            hb_attr_type_to_attribute: Dict[HbAttributeType, IntegrationAttribute]
    ) -> IntegrationValidationResult:
        try:
            temp_client = self._client_factory.create_client(hb_attr_type_to_attribute)
            return self._client_factory.test_client(temp_client)

        except IntegrationError as e:
            return IntegrationValidationResult.error(
                status=HealthStatusType.ERROR,
                error_message=str(e),
            )
        except IntegrationAttributeError as e:
            return IntegrationValidationResult.error(
                status=HealthStatusType.ERROR,
                error_message=str(e),
            )

    def validate_configuration(
            self,
            integration_attributes: List[IntegrationAttribute]) -> IntegrationValidationResult:
        """
        Schema-only validation. Confirms required attributes are present
        and structurally usable. Does NOT touch the network — for live
        access validation, see validate_access().
        """
        try:
            self._build_hb_attr_type_to_attribute_map(
                integration_attributes = integration_attributes,
                enforce_requirements = True,
            )
            return IntegrationValidationResult.success()

        except IntegrationAttributeError as e:
            return IntegrationValidationResult.error(
                status=HealthStatusType.ERROR,
                error_message=str(e),
            )
        except Exception as e:
            logger.exception(f'Error in HomeBox configuration validation: {e}')
            return IntegrationValidationResult.error(
                status=HealthStatusType.WARNING,
                error_message=f'Configuration validation failed: {e}'
            )

    def validate_access(
            self,
            integration_attributes: List[IntegrationAttribute],
            timeout_secs: Optional[float]) -> ConnectionTestResult:
        """
        Live access validation with bounded timeout. Builds a temporary
        HbClient against the proposed attributes and exercises the
        lightweight items-summary endpoint.
        """
        try:
            hb_attr_type_to_attribute = self._build_hb_attr_type_to_attribute_map(
                integration_attributes = integration_attributes,
                enforce_requirements = True,
            )
            temp_client = self._client_factory.create_client(
                hb_attr_type_to_attribute = hb_attr_type_to_attribute,
                timeout_secs = timeout_secs,
            )
            validation_result = self._client_factory.test_client(temp_client)
            if validation_result.is_valid:
                return ConnectionTestResult.success()
            return ConnectionTestResult.failure(
                validation_result.error_message or 'Access validation failed'
            )

        except IntegrationAttributeError as e:
            return ConnectionTestResult.failure(str(e))
        except IntegrationError as e:
            return ConnectionTestResult.failure(str(e))
        except Exception as e:
            logger.exception(f'Error in HomeBox access validation: {e}')
            return ConnectionTestResult.failure(f'Access validation error: {e}')

    def _build_hb_attr_type_to_attribute_map(
            self,
            integration_attributes: List[IntegrationAttribute],
            enforce_requirements: bool = True) -> Dict[HbAttributeType, IntegrationAttribute]:
        hb_attr_type_to_attribute = {}
        integration_key_to_attribute = {attr.integration_key: attr for attr in integration_attributes}

        for hb_attr_type in HbAttributeType:
            integration_key = IntegrationKey(
                integration_id = HbMetaData.integration_id,
                integration_name = str(hb_attr_type),
            )
            hb_attr = integration_key_to_attribute.get(integration_key)

            if not hb_attr:
                if enforce_requirements and hb_attr_type.is_required:
                    raise IntegrationAttributeError(f'Missing HomeBox attribute {hb_attr_type}')
                continue

            if enforce_requirements and hb_attr.is_required and not hb_attr.value.strip():
                raise IntegrationAttributeError(
                    f'Missing HomeBox attribute value for {hb_attr_type}')

            hb_attr_type_to_attribute[hb_attr_type] = hb_attr

        return hb_attr_type_to_attribute