Skip to content

Home Information - Your home, your data, organized.

Python

Implement HomeBox Importer; refactor integration framework (#360)

Tony Cea991d691a37
diff --git a/docs/DataImport.md b/docs/DataImport.md
new file mode 100644
index 00000000..9d44eb42
--- /dev/null
+++ b/docs/DataImport.md
@@ -0,0 +1,43 @@
+<img src="../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
+
+# Data Import
+
+Data Import is a one-time copy of items from an upstream system into
+Home Information (HI). Once imported, the items are HI-owned: you
+can edit them freely, and they no longer depend on the upstream
+source.
+
+This is distinct from an
+[Integration](Integrations.md), which mirrors the upstream live —
+the upstream remains the source of truth and changes flow in via
+update. Data Import has no ongoing relationship with the upstream
+after the import completes.
+
+## Importing data
+
+1. Open HI's configuration area and go to the Data Import section.
+2. Choose the integration you want to import from and start its
+ configure flow.
+3. Fill in the credentials and submit the import action.
+4. A preview shows how many new items will be imported and how many
+ existing ones will be skipped. Confirm to proceed.
+5. The result shows what was imported. From there you can place the
+ new items into a location view or collection.
+
+You can re-run the same workflow later to bring in any new upstream
+items; existing imports are skipped by upstream identifier.
+
+## Discarding imported data
+
+To remove imported items along with their custom data and attached
+files, use the discard action on the integration's row in the Data
+Import section. The action is confirmed and cannot be undone — to
+bring the items back you would need to re-import.
+
+## Available imports
+
+- **[HomeBox](integrations/homebox.md#data-import)** — copy your
+ HomeBox inventory into HI as locally-owned items, with custom
+ fields and attached files preserved.
+
+More integrations will offer Data Import as the framework matures.
diff --git a/docs/Integrations.md b/docs/Integrations.md
index 057600bd..0ffa6faf 100644
--- a/docs/Integrations.md
+++ b/docs/Integrations.md
@@ -43,3 +43,12 @@ enter it.
More integrations will be added as demand arises. The per-integration
pages each carry their own troubleshooting section that accretes
real-world fixes over time — start there if something is not working.
+
+## Integrations vs. Data Import
+
+Integrations on this page are live: HI mirrors the upstream system
+continuously and changes flow in via the update action.
+
+A separate feature, [Data Import](DataImport.md), is a one-time
+copy with no ongoing upstream link. Some integrations (HomeBox
+today) offer both options.
diff --git a/docs/dev/integrations/data-import.md b/docs/dev/integrations/data-import.md
new file mode 100644
index 00000000..a06ef0aa
--- /dev/null
+++ b/docs/dev/integrations/data-import.md
@@ -0,0 +1,64 @@
+# Data Import (IMPORT capability)
+
+The IMPORT capability copies upstream items into HI as locally-owned
+entities. Once imported, the integration has no ongoing relationship
+with the upstream; HI is the source of truth.
+
+User-facing setup lives in
+[`docs/DataImport.md`](../../DataImport.md). This page is the
+developer orientation — read the linked modules for the
+authoritative API.
+
+## Where the code lives
+
+- `src/hi/integrations/importer/` — abstract `IntegrationImporter` base,
+ transient models (`CandidateItem`, `IntegrationImportResult`,
+ `IntegrationDiscardResult`), framework-level views (Data Import
+ page, configure, preview, run, discard), templates.
+- `src/hi/integrations/view_mixins.py` — `CapabilityBlockViewMixin`
+ for the cross-capability block-modal detection. Mixed into both
+ `ConnectorConfigureView` and `ImporterConfigureView`.
+- `src/hi/services/homebox/importer/` — `HomeBoxImporter`, the first
+ concrete implementation. Reference example for new IMPORT-capable
+ integrations.
+
+## How a gateway opts in
+
+1. Add `IntegrationCapability.IMPORT` to `IntegrationMetaData.capabilities`.
+2. Override `IntegrationGateway.get_importer()` to return a concrete
+ `IntegrationImporter` subclass.
+
+The `IntegrationImporter` abstract sits parallel to `IntegrationConnector`,
+not inheriting from it. Commonality between Connect and Import is
+composed through shared helpers (`HbEntityFactory`, `HbConverter`,
+`EntityIntegrationOperations`, `PlacementUrlParams`, etc.).
+
+## Key design decisions
+
+- **Per-entity transaction during `run_import`.** A single item's
+ failure does not abort the batch; errors are aggregated into
+ `IntegrationImportResult.error_list`. See HomeBoxImporter for
+ the pattern.
+- **Skip-by-`integration_name`.** Imports are add-only. The framework
+ view computes new-vs-skipped against existing HI entities by
+ matching `integration_name`; `IntegrationImporter.get_candidate_items()`
+ itself returns the full upstream list.
+- **Shared `integrations_sync` exclusion lock.** Connect-side sync
+ and Import-side run serialize against each other to prevent
+ upstream double-fetch races on a single integration.
+- **State is encoded by the integration columns alone.** An entity
+ is `is_external` when `integration_id` is set (live Connect),
+ `has_integration_provenance` when `previous_integration_id` is
+ set (imported or detached), and neither when native. The
+ `EntityModelManager` exposes named helpers (`external_for`,
+ `imported_for`, `detached_for`, `with_integration_provenance`)
+ for query sites; the matching `Entity` properties are
+ `is_external`, `is_imported`, `is_detached`, and
+ `has_integration_provenance`.
+
+## Reference
+
+- HomeBox concrete: `src/hi/services/homebox/importer/`
+- Tests: `src/hi/integrations/tests/test_importer*.py` and
+ `src/hi/services/homebox/tests/test_homebox_importer.py`.
+- User-facing: [`docs/DataImport.md`](../../DataImport.md).
diff --git a/docs/dev/integrations/frigate.md b/docs/dev/integrations/frigate.md
index c0cc3d99..6605c739 100644
--- a/docs/dev/integrations/frigate.md
+++ b/docs/dev/integrations/frigate.md
@@ -27,8 +27,8 @@ User-facing setup lives in
attributes, and change-listener fan-out.
- `src/hi/services/frigate/frigate_client.py` — `FrigateClient`.
Encapsulated HTTP client wrapping the Frigate REST API.
-- `src/hi/services/frigate/frigate_sync.py` —
- `FrigateSynchronizer`. Drives sync; per-camera entity
+- `src/hi/services/frigate/frigate_connector.py` —
+ `FrigateConnector`. Drives sync; per-camera entity
creation in `_create_camera_entity`.
- `src/hi/services/frigate/frigate_converter.py` —
`FrigateConverter`. Wire-format ↔ HI model translation. Owns the
diff --git a/docs/dev/integrations/home-assistant.md b/docs/dev/integrations/home-assistant.md
index 730f7e2c..1094fa43 100644
--- a/docs/dev/integrations/home-assistant.md
+++ b/docs/dev/integrations/home-assistant.md
@@ -26,7 +26,7 @@ User-facing setup and troubleshooting live in
Heuristic mapping of upstream HA states to HI items. The bulk of
integration-specific complexity lives here. Aggregates multi-state
HA devices into a single HI item where it can.
-- `src/hi/services/hass/hass_sync.py` — `HassSynchronizer`. Drives
+- `src/hi/services/hass/hass_connector.py` — `HassConnector`. Drives
the sync flow; delegates to the converter for the
per-item shape.
- `src/hi/services/hass/monitors.py` — `HassMonitor`. Periodic poll
@@ -92,7 +92,7 @@ Tests live in `src/hi/services/hass/tests/`. The converter's mapping
behavior is the largest test surface
(`test_hass_converter_create.py`, `test_hass_converter_mapping.py`,
`test_import_allowlist.py`); sync flow is exercised in
-`test_hass_sync.py`.
+`test_hass_connector.py`.
Manual end-to-end testing uses the simulator; HA simulator support
lives at `src/hi/simulator/services/hass/`. For the operator
diff --git a/docs/dev/integrations/homebox.md b/docs/dev/integrations/homebox.md
index d49144db..a667c11e 100644
--- a/docs/dev/integrations/homebox.md
+++ b/docs/dev/integrations/homebox.md
@@ -15,22 +15,22 @@ User-facing setup and troubleshooting live in
## Key modules
-- `src/hi/services/homebox/integration.py` — `HomeBoxGateway`.
- Framework entry point.
-- `src/hi/services/homebox/hb_manager.py` — `HomeBoxManager`.
- Singleton holding the active `HbClient` and integration attributes.
-- `src/hi/services/homebox/hb_client.py` — `HbClient`. REST wrapper
- around HomeBox's `/api/v1/...` endpoints, plus the
- username/password → session-token login flow.
-- `src/hi/services/homebox/hb_converter.py` — `HbConverter`. Maps
- HomeBox items into HI items, including custom field expansion as
- read-only attributes.
-- `src/hi/services/homebox/hb_sync.py` — `HomeBoxSynchronizer`.
- Drives sync.
-- `src/hi/services/homebox/monitors.py` — `HomeBoxMonitor`. Periodic
- reachability probe only; no state polling.
-- `src/hi/services/homebox/hb_controller.py` — `HomeBoxController`.
- No-op controller; HomeBox items are not controllable.
+HomeBox declares both CONNECT and IMPORT capabilities, so its code
+is split across two peer sub-packages with capability-agnostic
+facilities at the integration top level:
+
+- `services/homebox/integration.py` — `HomeBoxGateway`, framework
+ entry point; returns both a synchronizer and an importer.
+- `services/homebox/hb_*.py` — `HbClient` (REST + login flow),
+ `HbClientFactory`, `HbConverter`, `HomeBoxManager`,
+ `HbEntityFactory`, `HbItem`. Reused by both capabilities.
+- `services/homebox/connector/` — `HomeBoxConnector`,
+ `HomeBoxExternalViewResolver` (live entity-detail view), attachment proxy.
+- `services/homebox/importer/` — `HomeBoxImporter` and attribute-
+ population helpers.
+- `services/homebox/monitors.py`, `hb_controller.py` — periodic
+ reachability probe and no-op controller (no state polling, no
+ controllable items).
## API patterns
@@ -44,6 +44,14 @@ suffix); the client appends the version internally. This is
documented in the user-facing doc and reinforced by an explicit
error message in `HbClient` when responses are not JSON.
+## IntegrationImporter
+
+`HomeBoxImporter` (`services/homebox/importer/`) is the Import-side
+parallel of `HomeBoxConnector`. Both call into shared facilities
+(`HbEntityFactory`, `HbConverter`) so only the orchestration differs.
+See [`data-import.md`](data-import.md) for the framework-level
+IMPORT capability documentation.
+
## Implementation notes
- **No live state.** HomeBox's data model is inventory metadata, not
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index 98338d37..295eca35 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -10,11 +10,22 @@ Each integration is a Django app in `hi/services/` directory. The `hi.integratio
- **detail_attrs**: Opaque data blob - only the integration uses this data
### Capability model
-Each integration declares its `IntegrationCapability` set on `IntegrationMetaData.capabilities` (`hi/integrations/enums.py`). Today only `CONNECT` is used — live mirror of an upstream system. `IMPORT` (one-shot copy of upstream items into HI) is reserved; its abstract protocol and workflow land with the first concrete consumer (issue #358).
+Each integration declares its `IntegrationCapability` set on `IntegrationMetaData.capabilities` (`hi/integrations/enums.py`). Two capabilities exist today:
-Per-attribute `IntegrationAttributeType` declarations may carry an optional `capabilities` set to restrict which capability's UI surfaces the attribute. Default is `ALL_CAPABILITIES`; existing declarations remain unaffected.
+- **`CONNECT`** — live mirror of an upstream system. Realized by an `IntegrationConnector` subclass returned from `IntegrationGateway.get_connector()`. All four production integrations (HA, ZM, Frigate, HomeBox) declare CONNECT.
+- **`IMPORT`** — one-shot copy of upstream items into HI as locally-owned entities. Realized by an `IntegrationImporter` subclass returned from `IntegrationGateway.get_importer()`. HomeBox is the first integration to declare IMPORT alongside CONNECT (see [`docs/dev/integrations/data-import.md`](data-import.md) for the developer surface).
-`Entity.data_source` (an `EntityDataSource` value: `INTERNAL` or `EXTERNAL`, see `hi/apps/entity/enums.py`) records per-entity provenance. Today only HomeBox-Connect entities are `EXTERNAL` (HomeBox refuses HI-side edits); native and HA/ZM/Frigate entities are `INTERNAL`. The field is the hook for the cross-capability transition flows that arrive with `IMPORT`.
+The two abstractions don't share a base class — commonality is composed through shared helpers (`hi/integrations/entity_operations.py`, `hi/integrations/placement_request.py`, etc.). The `connector/` and `importer/` sub-packages live as peers under `hi/integrations/`.
+
+Per-attribute `IntegrationAttributeType` declarations may carry an optional `capabilities` set to restrict which capability's UI surfaces the attribute. Default is `ALL_CAPABILITIES`.
+
+Per-entity capability state is derived from the integration columns on `Entity`, not stored as a separate field:
+
+- **Live Connect** (`is_external`): `integration_id` is set.
+- **Imported or detached** (`is_imported` / `is_detached` — operational synonyms today, with `has_integration_provenance` as the umbrella predicate): `previous_integration_id` is set, `integration_id` is `NULL`.
+- **Native**: both columns `NULL`.
+
+Query sites use the matching `EntityModelManager` helpers (`external_for`, `imported_for`, `detached_for`, `with_integration_provenance`) so the call site reads as semantic intent. The IMPORT-initiation block check in `CapabilityBlockViewMixin` uses `Entity.objects.external_for(...)`; `IntegrationImporter.discard_imported_data` uses `Entity.objects.imported_for(...)`.
### One-to-many state composition
A single upstream state may decompose into multiple HI EntityStates when the upstream protocol packs several independently-controllable values into one entity (e.g., a color light's brightness + hue + saturation + color temperature). The framework supports this via:
@@ -62,10 +73,9 @@ Each integration is a self-contained Django app under `hi/services/<integration_
- `<prefix>_client.py` (and/or `<prefix>_client_factory.py`) — outbound API client + credential validation
- `<prefix>_manager.py` — singleton coordinator (attribute cache, change listeners, health status)
- `<prefix>_converter.py` — wire-format ↔ HI model translation (the bulk of integration logic)
-- `<prefix>_sync.py` — `IntegrationSynchronizer` subclass driving entity sync
+- `<prefix>_sync.py` — `IntegrationConnector` subclass driving entity sync
- `<prefix>_controller.py` — HI control commands → integration service calls
- `<prefix>_mixins.py` — manager-accessor mixin for views/handlers
-- `<prefix>_manage_view_pane.py` — management UI pane
- `monitors.py` — `PeriodicMonitor` subclass(es) for polling and health probes
- `apps.py`, `urls.py`, `views.py` — standard Django wiring
diff --git a/docs/dev/integrations/zoneminder.md b/docs/dev/integrations/zoneminder.md
index 223521a5..fff41e48 100644
--- a/docs/dev/integrations/zoneminder.md
+++ b/docs/dev/integrations/zoneminder.md
@@ -29,7 +29,7 @@ User-facing setup, CORS, and SSL troubleshooting live in
validates the `ZMApi` from the integration attributes.
- `src/hi/services/zoneminder/pyzm_client/` — vendored Python client
for ZM's REST API and `cgi-bin/nph-zms` streaming endpoints.
-- `src/hi/services/zoneminder/zm_sync.py` — `ZoneMinderSynchronizer`.
+- `src/hi/services/zoneminder/zm_connector.py` — `ZmConnector`.
Drives sync; per-monitor entity creation in
`_create_monitor_entity` (this is also the entry point used by the
auto-reconnect path on sync).
@@ -83,7 +83,7 @@ The monitor poll cadence and per-request timeouts are defined in
Tests live in `src/hi/services/zoneminder/tests/`. Sync flow,
controller behavior, and monitor state correlation each have their
-own modules; `test_zm_sync.py` is the largest. Synthetic monitor
+own modules; `test_zm_connector.py` is the largest. Synthetic monitor
data lives in `tests/synthetic_data.py` and `tests/data/`.
Manual end-to-end testing uses the simulator; ZM simulator support
diff --git a/docs/integrations/homebox.md b/docs/integrations/homebox.md
index b0042268..97d977c7 100644
--- a/docs/integrations/homebox.md
+++ b/docs/integrations/homebox.md
@@ -71,6 +71,23 @@ The username or password is wrong, or the HomeBox account is
disabled. Verify by logging into the HomeBox web UI directly with
the same credentials.
+## Data Import
+
+HomeBox also offers a one-time [Data Import](../DataImport.md)
+alongside the live Integration described above. Data Import copies
+your HomeBox items into HI as locally-owned entities — after import,
+edits stay in HI and HomeBox is no longer consulted. Custom fields
+and attached files are preserved, but maintained independently in HI
+from then on.
+
+Use Data Import when you are migrating off HomeBox, or want to
+manage inventory locally without an upstream dependency. Use the
+regular HomeBox Integration when you want HI to track HomeBox as the
+ongoing source of truth.
+
+See the [Data Import](../DataImport.md#importing-data) page for the
+import walkthrough.
+
## Known limitations
- HomeBox items are imported read-only. There are no sensors,
diff --git a/docs/integrations/zoneminder.md b/docs/integrations/zoneminder.md
index 142a0c6d..4fa7ae93 100644
--- a/docs/integrations/zoneminder.md
+++ b/docs/integrations/zoneminder.md
@@ -106,7 +106,7 @@ the ZM portal directly with the same credentials, then check
- ZM monitor renames in the upstream are propagated on Update; ZM
monitor deletes remove the corresponding HI camera unless the user
has added custom data to it (in which case it is preserved as
- detached, with a "Detached from ZoneMinder" indicator).
+ detached, with a "From ZoneMinder" indicator).
- Live stream playback depends on ZM's `cgi-bin/nph-zms` endpoint
being reachable from the user's browser, not just from the HI
server. The CORS and SSL issues above are common consequences.
diff --git a/src/hi/apps/collection/views.py b/src/hi/apps/collection/views.py
index 0523b4b8..741d7647 100644
--- a/src/hi/apps/collection/views.py
+++ b/src/hi/apps/collection/views.py
@@ -13,7 +13,7 @@ from hi.hi_grid_view import HiGridView
from .collection_manager import CollectionManager
from .models import Collection
-from .view_mixins import CollectionViewMixin
+from hi.apps.collection.view_mixins import CollectionViewMixin
logger = logging.getLogger(__name__)
diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.py
index 068f3b36..393edd55 100644
--- a/src/hi/apps/config/enums.py
+++ b/src/hi/apps/config/enums.py
@@ -17,8 +17,9 @@ class ConfigPageType(LabeledEnum):
return
SETTINGS = ('Settings' , '' , 'config_settings' )
- INTEGRATIONS = ('Integrations' , '' , 'integrations_home' )
+ INTEGRATIONS_CONNECT = ('Integrations' , '' , 'integrations_connect_home' )
EVENTS = ('Triggers' , '' , 'event_definitions' )
+ INTEGRATIONS_IMPORT = ('Data Import' , '' , 'integrations_import_home' )
SYSTEM_INFO = ('System Info' , '' , 'system_info' )
@classmethod
diff --git a/src/hi/apps/console/templatetags/video_tags.py b/src/hi/apps/console/templatetags/video_tags.py
index 5d6c09fa..1aa08d17 100644
--- a/src/hi/apps/console/templatetags/video_tags.py
+++ b/src/hi/apps/console/templatetags/video_tags.py
@@ -38,8 +38,12 @@ def sensor_response_video_stream(sensor_response):
logger.warning(f"No integration gateway found for {entity.integration_id}")
return None
+ connector = gateway.get_connector()
+ if connector is None:
+ return None
+
# Get recorded video stream from sensor response
- video_stream = gateway.get_sensor_response_video_stream(sensor_response)
+ video_stream = connector.get_sensor_response_video_stream(sensor_response)
if video_stream:
return video_stream
@@ -72,7 +76,10 @@ def sensor_response_event_snapshot_url(sensor_response):
if not gateway:
logger.warning(f"No integration gateway found for {entity.integration_id}")
return None
- return gateway.get_sensor_response_event_snapshot_url(sensor_response)
+ connector = gateway.get_connector()
+ if connector is None:
+ return None
+ return connector.get_sensor_response_event_snapshot_url(sensor_response)
except Exception as e:
logger.error(f"Error getting event snapshot URL for sensor response: {e}")
return None
@@ -99,7 +106,11 @@ def entity_video_stream(entity):
logger.warning(f"No integration gateway found for {entity.integration_id}")
return None
- video_stream = gateway.get_entity_video_stream(entity)
+ connector = gateway.get_connector()
+ if connector is None:
+ return None
+
+ video_stream = connector.get_entity_video_stream(entity)
if video_stream:
return video_stream
@@ -140,7 +151,10 @@ def entity_video_snapshot(entity):
if not gateway:
logger.warning(f"No integration gateway found for {entity.integration_id}")
return None
- return gateway.get_entity_video_snapshot(entity)
+ connector = gateway.get_connector()
+ if connector is None:
+ return None
+ return connector.get_entity_video_snapshot(entity)
except Exception as e:
logger.error(f"Error getting video snapshot for entity {entity.id}: {e}")
return None
diff --git a/src/hi/apps/control/controller_manager.py b/src/hi/apps/control/controller_manager.py
index 05435dc0..05b94032 100644
--- a/src/hi/apps/control/controller_manager.py
+++ b/src/hi/apps/control/controller_manager.py
@@ -36,7 +36,18 @@ class ControllerManager( Singleton ):
integration_gateway = IntegrationManager().get_integration_gateway(
integration_id = controller.integration_id,
)
- integration_controller = integration_gateway.get_controller()
+ connector = integration_gateway.get_connector()
+ if connector is None:
+ raise RuntimeError(
+ f'No connector for integration {controller.integration_id}; '
+ f'cannot route control action.'
+ )
+ integration_controller = connector.get_controller()
+ if integration_controller is None:
+ raise RuntimeError(
+ f'Integration {controller.integration_id} has no controller; '
+ f'cannot route control action.'
+ )
integration_details = controller.get_integration_details()
if settings.DEBUG and settings.DEBUG_TRACE_STATE:
diff --git a/src/hi/apps/control/tests/test_controller_manager.py b/src/hi/apps/control/tests/test_controller_manager.py
index e747b2f2..378f3fda 100644
--- a/src/hi/apps/control/tests/test_controller_manager.py
+++ b/src/hi/apps/control/tests/test_controller_manager.py
@@ -71,7 +71,7 @@ class TestControllerManager(BaseTestCase):
mock_integration_controller.do_control.return_value = mock_control_result
mock_integration_gateway = Mock()
- mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_gateway.get_connector.return_value.get_controller.return_value = mock_integration_controller
mock_integration_manager = Mock()
mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway
@@ -125,7 +125,7 @@ class TestControllerManager(BaseTestCase):
mock_integration_controller.do_control.return_value = mock_control_result
mock_integration_gateway = Mock()
- mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_gateway.get_connector.return_value.get_controller.return_value = mock_integration_controller
mock_integration_manager = Mock()
mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway
@@ -182,7 +182,7 @@ class TestControllerManager(BaseTestCase):
mock_integration_controller.do_control.return_value = mock_control_result
mock_integration_gateway = Mock()
- mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_gateway.get_connector.return_value.get_controller.return_value = mock_integration_controller
mock_integration_manager = Mock()
mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway
diff --git a/src/hi/apps/control/tests/test_one_click_control_service.py b/src/hi/apps/control/tests/test_one_click_control_service.py
index f77731d0..f4055120 100644
--- a/src/hi/apps/control/tests/test_one_click_control_service.py
+++ b/src/hi/apps/control/tests/test_one_click_control_service.py
@@ -217,7 +217,7 @@ class TestOneClickFindController(BaseTestCase):
mock_integration_controller = Mock()
mock_integration_controller.do_control.return_value = mock_control_result
mock_integration_gateway = Mock()
- mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_gateway.get_connector.return_value.get_controller.return_value = mock_integration_controller
mock_integration_manager = Mock()
mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway
@@ -264,7 +264,7 @@ class TestOneClickFindController(BaseTestCase):
mock_integration_controller = Mock()
mock_integration_controller.do_control.return_value = mock_control_result
mock_integration_gateway = Mock()
- mock_integration_gateway.get_controller.return_value = mock_integration_controller
+ mock_integration_gateway.get_connector.return_value.get_controller.return_value = mock_integration_controller
mock_integration_manager = Mock()
mock_integration_manager.get_integration_gateway.return_value = mock_integration_gateway
diff --git a/src/hi/apps/control/tests/test_views.py b/src/hi/apps/control/tests/test_views.py
index dce33084..3d4a732f 100644
--- a/src/hi/apps/control/tests/test_views.py
+++ b/src/hi/apps/control/tests/test_views.py
@@ -54,7 +54,7 @@ class TestControllerView(SyncViewTestCase):
mock_integration_manager.return_value = mock_manager
mock_gateway = Mock()
mock_manager.get_integration_gateway.return_value = mock_gateway
- mock_gateway.get_controller.return_value.do_control.return_value = IntegrationControlResult(
+ mock_gateway.get_connector.return_value.get_controller.return_value.do_control.return_value = IntegrationControlResult(
new_value='ON',
error_list=[]
)
diff --git a/src/hi/apps/control/views.py b/src/hi/apps/control/views.py
index 0af83a5e..73b3dc11 100644
--- a/src/hi/apps/control/views.py
+++ b/src/hi/apps/control/views.py
@@ -7,7 +7,7 @@ from hi.apps.monitor.status_display_manager import StatusDisplayManager
from .control_mixins import ControllerMixin
from .models import Controller
-from .view_mixins import ControlViewMixin
+from hi.apps.control.view_mixins import ControlViewMixin
logger = logging.getLogger(__name__)
diff --git a/src/hi/apps/entity/entity_placement.py b/src/hi/apps/entity/entity_placement.py
index 1ab16802..656fc4c3 100644
--- a/src/hi/apps/entity/entity_placement.py
+++ b/src/hi/apps/entity/entity_placement.py
@@ -248,13 +248,22 @@ class EntityPlacementService:
"""Entities that have neither an EntityView nor a
CollectionEntity row — fully unplaced in the app. Optionally
filtered to a single integration. Used by the dispatcher
- GET endpoint to seed the modal with what's left to place."""
- queryset = Entity.objects.filter(
+ GET endpoint to seed the modal with what's left to place.
+
+ Integration scoping uses ``with_integration_provenance`` so
+ both active-Connect rows and imported / detached rows for
+ the same integration are eligible — post-import placement
+ and post-sync placement land on the same query."""
+ if integration_id is not None:
+ queryset = Entity.objects.with_integration_provenance(
+ integration_id = integration_id,
+ )
+ else:
+ queryset = Entity.objects.all()
+ queryset = queryset.filter(
entity_views__isnull = True,
collections__isnull = True,
)
- if integration_id is not None:
- queryset = queryset.filter( integration_id = integration_id )
return list( queryset.distinct() )
@classmethod
diff --git a/src/hi/apps/entity/enums.py b/src/hi/apps/entity/enums.py
index 1a915beb..d12f914a 100644
--- a/src/hi/apps/entity/enums.py
+++ b/src/hi/apps/entity/enums.py
@@ -198,12 +198,6 @@ class EntityType(LabeledEnum):
return f'entity/modals/entity_status_{self.name.lower()}.html'
-class EntityDataSource(LabeledEnum):
-
- INTERNAL = ('Internal', 'HI owns the editable representation.')
- EXTERNAL = ('External', 'Upstream constrains HI-side edits.')
-
-
class EntityStateValue(LabeledEnum):
# Alarm-style values (e.g., ACTIVE, OPEN, SMOKE_DETECTED) are
# rendered as the ``status`` attribute on both the SVG icon
diff --git a/src/hi/apps/entity/managers.py b/src/hi/apps/entity/managers.py
index 22cde373..4fefe596 100644
--- a/src/hi/apps/entity/managers.py
+++ b/src/hi/apps/entity/managers.py
@@ -12,3 +12,61 @@ class EntityModelManager( IntegrationDetailsModelManager ):
return self.filter(
Q( has_video_stream = True ) | Q( has_video_snapshot = True )
)
+
+ def external_for( self, integration_id, integration_name = None ):
+ """Entities currently attached to ``integration_id`` (i.e.,
+ data_source=EXTERNAL — live Connect mode). Optional
+ ``integration_name`` narrows to a specific upstream item."""
+ queryset = self.filter( integration_id = integration_id )
+ if integration_name is not None:
+ queryset = queryset.filter( integration_name = integration_name )
+ return queryset
+
+ # Imported and detached entities currently share the same column
+ # shape — both are HI-owned rows that carry upstream provenance
+ # on previous_integration_*. The two predicates below resolve to
+ # the same query today, but each call site asks for what it
+ # *semantically* needs:
+ #
+ # * ``imported_for``: "Import-side wants rows it created or
+ # would skip on re-import."
+ # * ``detached_for``: "the auto-reconnect path wants rows that
+ # used to be Connect-attached."
+ #
+ # Keeping them as distinct methods documents intent at every call
+ # site, and lets a future discriminator (e.g., a provenance flag)
+ # be added in one place without changing readers.
+
+ def imported_for( self, integration_id, integration_name = None ):
+ """Entities created by IMPORT mode for this integration (HI-
+ owned, carrying upstream provenance). Optional
+ ``integration_name`` narrows by the previous-pair name."""
+ return self._with_provenance_to( integration_id, integration_name )
+
+ def detached_for( self, integration_id, integration_name = None ):
+ """Entities detached from this integration via SAFE-disable
+ (HI-owned, carrying upstream provenance — auto-reconnect
+ candidates). Optional ``integration_name`` narrows by the
+ previous-pair name."""
+ return self._with_provenance_to( integration_id, integration_name )
+
+ def _with_provenance_to( self, integration_id, integration_name ):
+ queryset = self.filter(
+ integration_id__isnull = True,
+ previous_integration_id = integration_id,
+ )
+ if integration_name is not None:
+ queryset = queryset.filter(
+ previous_integration_name = integration_name,
+ )
+ return queryset
+
+ def with_integration_provenance( self, integration_id ):
+ """Entities associated with ``integration_id`` in any state
+ (EXTERNAL, imported, or detached). Use when the data-source
+ distinction is irrelevant — e.g., 'does this integration
+ have any entities at all?'"""
+ return self.filter(
+ Q( integration_id = integration_id )
+ | Q( previous_integration_id = integration_id )
+ )
diff --git a/src/hi/apps/entity/migrations/0021_entity_data_source.py b/src/hi/apps/entity/migrations/0021_entity_data_source.py
deleted file mode 100644
index 861d55a0..00000000
--- a/src/hi/apps/entity/migrations/0021_entity_data_source.py
+++ /dev/null
@@ -1,48 +0,0 @@
-import logging
-
-from django.db import migrations, models
-
-
-def backfill_data_source(apps, schema_editor):
- """Mark integration-attached entities that disallow internal
- attributes as EXTERNAL. All others keep the column default
- (INTERNAL). Today this affects only HomeBox-Connect entities."""
- logger = logging.getLogger('hi.apps.entity.migrations.0021')
-
- Entity = apps.get_model('entity', 'Entity')
-
- updated = Entity.objects.filter(
- integration_id__isnull=False,
- allow_internal_attributes=False,
- ).exclude(
- integration_id='',
- ).update(
- data_source_str='external',
- )
-
- logger.info(
- f'EntityDataSource backfill: marked {updated} entity row(s) EXTERNAL.'
- )
-
-
-class Migration(migrations.Migration):
-
- dependencies = [
- ('entity', '0020_entity_allow_internal_attributes'),
- ]
-
- operations = [
- migrations.AddField(
- model_name='entity',
- name='data_source_str',
- field=models.CharField(
- default='internal',
- max_length=16,
- verbose_name='Data Source',
- ),
- ),
- migrations.RunPython(
- code=backfill_data_source,
- reverse_code=migrations.RunPython.noop,
- ),
- ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 9ec1cfc8..5fa3b3eb 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -16,7 +16,6 @@ from hi.integrations.models import IntegrationDetailsModel
from hi.enums import ItemType
from .enums import (
- EntityDataSource,
EntityType,
EntityStateRole,
EntityStateType,
@@ -58,12 +57,6 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):
'Allow Internal Attributes?',
default = True,
)
- data_source_str = models.CharField(
- 'Data Source',
- max_length = 16,
- null = False, blank = False,
- default = str(EntityDataSource.INTERNAL),
- )
has_video_stream = models.BooleanField(
'Has Video Stream',
default = False,
@@ -135,13 +128,31 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):
return
@property
- def data_source(self) -> EntityDataSource:
- return EntityDataSource.from_name_safe( self.data_source_str )
+ def is_external(self) -> bool:
+ """Live-attached to an integration. Upstream constrains
+ HI-side edits while this is True."""
+ return self.integration_id is not None
- @data_source.setter
- def data_source( self, data_source : EntityDataSource ):
- self.data_source_str = str(data_source)
- return
+ @property
+ def has_integration_provenance(self) -> bool:
+ """Carries a record of which integration this entity came
+ from. True for both imported and detached rows; drives the
+ 'From X' UI badge and the auto-reconnect lookup."""
+ return self.previous_integration_id is not None
+
+ # Synonyms today — imported and detached are operationally
+ # indistinguishable (same column shape). Separate names let
+ # each call site read intentionally, parallel to the manager
+ # methods. A future provenance discriminator (if needed) can
+ # split them without changing readers.
+
+ @property
+ def is_imported(self) -> bool:
+ return self.has_integration_provenance
+
+ @property
+ def is_detached(self) -> bool:
+ return self.has_integration_provenance
@property
def has_native_video_stream(self) -> bool:
diff --git a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
index 630e5e9e..1de413fd 100644
--- a/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
+++ b/src/hi/apps/entity/templates/entity/edit/panes/entity_edit_mode_panel.html
@@ -23,7 +23,7 @@
<div class="text-muted font-italic">
{% previous_integration_logo_path entity as prev_logo_path %}
{% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}
- Detached from: <strong>{% previous_integration_display_name entity %}</strong>
+ From: <strong>{% previous_integration_display_name entity %}</strong>
</div>
</div>
{% endif %}
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html b/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html
index 06e9ebe8..8818665b 100644
--- a/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html
+++ b/src/hi/apps/entity/templates/entity/panes/entity_modal_subheader.html
@@ -24,7 +24,7 @@
{% elif entity.previous_integration_id %}
{% previous_integration_logo_path entity as prev_logo_path %}
{% if prev_logo_path %}<img src="{% static prev_logo_path %}" alt="" class="hi-integration-logo--detached mr-1">{% endif %}
- <small class="font-italic">Detached from {% previous_integration_display_name entity %}</small>
+ <small class="font-italic">From {% previous_integration_display_name entity %}</small>
{% endif %}
</div>
<div class="hi-entity-status-subheader__right">
diff --git a/src/hi/apps/entity/tests/test_models.py b/src/hi/apps/entity/tests/test_models.py
index da52da6e..ab913724 100644
--- a/src/hi/apps/entity/tests/test_models.py
+++ b/src/hi/apps/entity/tests/test_models.py
@@ -1,12 +1,10 @@
-import importlib
import json
import logging
-from django.apps import apps as django_apps
from django.db import IntegrityError
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
-from hi.apps.entity.enums import EntityDataSource, EntityStateRole, EntityType, EntityStateType
+from hi.apps.entity.enums import EntityStateRole, EntityType, EntityStateType
from hi.apps.attribute.enums import AttributeValueType
from hi.testing.base_test_case import BaseTestCase
@@ -89,67 +87,38 @@ class TestEntity(BaseTestCase):
self.assertEqual(entity.entity_type, EntityType.CAMERA)
return
- def test_data_source_defaults_to_internal(self):
- entity = Entity.objects.create(
- name='Default Source Entity',
- entity_type_str=str(EntityType.OTHER),
- integration_id='ds_default_001',
- integration_name='test_integration',
- )
- self.assertEqual(entity.data_source, EntityDataSource.INTERNAL)
- self.assertEqual(entity.data_source_str, str(EntityDataSource.INTERNAL))
- return
-
- def test_data_source_property_conversion(self):
- entity = Entity.objects.create(
- name='Source Entity',
- entity_type_str=str(EntityType.OTHER),
- integration_id='ds_conv_001',
- integration_name='test_integration',
- )
- entity.data_source = EntityDataSource.EXTERNAL
- self.assertEqual(entity.data_source_str, str(EntityDataSource.EXTERNAL))
- self.assertEqual(entity.data_source, EntityDataSource.EXTERNAL)
- entity.data_source = EntityDataSource.INTERNAL
- self.assertEqual(entity.data_source, EntityDataSource.INTERNAL)
- return
-
- def test_migration_0021_backfill_marks_external_only_when_integration_disallows_internal_attrs(self):
- # Migration 0021's backfill rule: integration-attached entities
- # whose integration disallows internal attributes get marked
- # EXTERNAL. Everything else stays at the column default (INTERNAL).
- # Today this picks out HomeBox-Connect entities and leaves
- # native + HA/ZM/Frigate alone.
+ def test_data_source_properties_reflect_integration_columns(self):
+ # Native: no integration columns populated.
native = Entity.objects.create(
name='Native',
entity_type_str=str(EntityType.OTHER),
)
- hass_like = Entity.objects.create(
- name='HASS-like',
+ self.assertFalse(native.is_external)
+ self.assertFalse(native.has_integration_provenance)
+ self.assertFalse(native.is_imported)
+ self.assertFalse(native.is_detached)
+
+ # Live Connect: integration_id set.
+ attached = Entity.objects.create(
+ name='Attached',
entity_type_str=str(EntityType.OTHER),
integration_id='hass',
integration_name='hass_thing',
- allow_internal_attributes=True,
- )
- hb_like = Entity.objects.create(
- name='HB-like',
- entity_type_str=str(EntityType.OTHER),
- integration_id='hb',
- integration_name='hb_item_1',
- allow_internal_attributes=False,
)
+ self.assertTrue(attached.is_external)
+ self.assertFalse(attached.has_integration_provenance)
- mig = importlib.import_module(
- 'hi.apps.entity.migrations.0021_entity_data_source',
+ # Imported / detached: previous_integration_* set, integration_id NULL.
+ provenance = Entity.objects.create(
+ name='Provenance',
+ entity_type_str=str(EntityType.OTHER),
+ previous_integration_id='hb',
+ previous_integration_name='item-1',
)
- mig.backfill_data_source(django_apps, schema_editor=None)
-
- native.refresh_from_db()
- hass_like.refresh_from_db()
- hb_like.refresh_from_db()
- self.assertEqual(native.data_source, EntityDataSource.INTERNAL)
- self.assertEqual(hass_like.data_source, EntityDataSource.INTERNAL)
- self.assertEqual(hb_like.data_source, EntityDataSource.EXTERNAL)
+ self.assertFalse(provenance.is_external)
+ self.assertTrue(provenance.has_integration_provenance)
+ self.assertTrue(provenance.is_imported)
+ self.assertTrue(provenance.is_detached)
return
def test_entity_type_property_handles_unknown_types_gracefully(self):
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index 8bb1c285..09f46039 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -433,7 +433,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
)
def _make_structured_view_data(self):
- from hi.integrations.connect.external_view_data import (
+ from hi.integrations.connector.external_view_data import (
NameValuePair, AttachmentRef, StructuredViewData,
)
return StructuredViewData(
@@ -454,7 +454,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
)
def _make_minimal_view_data(self):
- from hi.integrations.connect.external_view_data import MinimalViewData
+ from hi.integrations.connector.external_view_data import MinimalViewData
return MinimalViewData(deep_link_url='https://upstream.example/items/99')
def test_native_entity_omits_section_and_skips_lookup(self):
@@ -479,7 +479,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = None
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = None
with patch(
'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',
@@ -495,7 +495,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
# render (e.g., when the status modal falls back to the edit
# view for an entity with no state data), so we don't pin the
# exact call count.
- mock_gateway.get_external_view_data.assert_called_with(self.integration_entity)
+ mock_gateway.get_connector.return_value.get_external_view_data.assert_called_with(self.integration_entity)
self.assertNotIn('attr-v2-external-view-data', response.content.decode('utf-8'))
def test_integration_entity_structured_view_data_renders_section(self):
@@ -505,7 +505,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
structured = self._make_structured_view_data()
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = structured
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = structured
with patch(
'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',
@@ -530,7 +530,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
minimal = self._make_minimal_view_data()
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = minimal
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = minimal
with patch(
'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',
@@ -549,7 +549,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
"""``MinimalViewData.error_message`` renders in the modal so
the operator sees the failure reason inline rather than only
in server logs."""
- from hi.integrations.connect.external_view_data import MinimalViewData
+ from hi.integrations.connector.external_view_data import MinimalViewData
url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})
@@ -558,7 +558,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
error_message='HomeBox upstream unavailable: Connection refused',
)
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = minimal
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = minimal
with patch(
'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',
@@ -586,7 +586,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
structured = self._make_structured_view_data()
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = structured
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = structured
with patch(
'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',
@@ -619,7 +619,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
structured = self._make_structured_view_data()
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = structured
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = structured
with patch(
'hi.integrations.integration_manager.IntegrationManager.get_integration_gateway',
@@ -659,7 +659,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
verify the include call site honors the instance attribute by
pointing at a template that emits a distinctive marker, then
asserting the marker appears in the rendered output."""
- from hi.integrations.connect.external_view_data import CustomTemplateViewData
+ from hi.integrations.connector.external_view_data import CustomTemplateViewData
custom = CustomTemplateViewData(
template_name='integrations/external_data/entity/minimal.html',
@@ -667,7 +667,7 @@ class TestEntityEditViewExternalViewData(DualModeViewTestCase):
context={'unused': 'unused'},
)
mock_gateway = Mock()
- mock_gateway.get_external_view_data.return_value = custom
+ mock_gateway.get_connector.return_value.get_external_view_data.return_value = custom
url = reverse('entity_edit', kwargs={'entity_id': self.integration_entity.id})
with patch(
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index b1812945..441ad430 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -23,7 +23,7 @@ from .entity_state_history import get_entity_state_history_page
from .entity_state_role_order import ENTITY_STATUS_VIEW_ORDERING
from .models import Entity, EntityAttribute
from .transient_models import EntityHistoryData
-from .view_mixins import EntityStateViewMixin, EntityViewMixin
+from hi.apps.entity.view_mixins import EntityStateViewMixin, EntityViewMixin
from .entity_attribute_edit_context import EntityAttributeItemEditContext
@@ -189,7 +189,10 @@ class EntityEditView( HiModalView, EntityViewMixin, AttributeEditViewMixin ):
f'{entity.id} (integration_id={entity.integration_id!r}).'
)
return None
- return gateway.get_external_view_data( entity )
+ connector = gateway.get_connector()
+ if connector is None:
+ return None
+ return connector.get_external_view_data( entity )
def post( self, request,*args, **kwargs ):
entity = self.get_entity(request, *args, **kwargs)
diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.py
index 95872aa8..a325f179 100644
--- a/src/hi/apps/location/edit/views.py
+++ b/src/hi/apps/location/edit/views.py
@@ -33,7 +33,7 @@ from hi.enums import ItemType, ViewType
from hi.hi_async_view import HiModalView, HiSideView
from . import forms
-from .view_mixins import LocationEditViewMixin
+from hi.apps.location.edit.view_mixins import LocationEditViewMixin
logger = logging.getLogger(__name__)
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index a101548d..133cef1b 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -29,7 +29,7 @@ from .enums import LocationViewType
from .location_attribute_edit_context import LocationAttributeItemEditContext
from .location_manager import LocationManager
from .models import LocationView, LocationAttribute
-from .view_mixins import LocationViewMixin
+from hi.apps.location.view_mixins import LocationViewMixin
logger = logging.getLogger(__name__)
diff --git a/src/hi/apps/sense/views.py b/src/hi/apps/sense/views.py
index 23bb31f4..571a564d 100644
--- a/src/hi/apps/sense/views.py
+++ b/src/hi/apps/sense/views.py
@@ -3,7 +3,7 @@ import logging
from hi.hi_async_view import HiModalView
from .transient_models import SensorResponse
-from .view_mixins import SenseViewMixin
+from hi.apps.sense.view_mixins import SenseViewMixin
logger = logging.getLogger(__name__)
diff --git a/src/hi/apps/system/templates/system/panes/integration_paused_card.html b/src/hi/apps/system/templates/system/panes/integration_paused_card.html
index fd6b52ae..9a19e3b3 100644
--- a/src/hi/apps/system/templates/system/panes/integration_paused_card.html
+++ b/src/hi/apps/system/templates/system/panes/integration_paused_card.html
@@ -10,7 +10,7 @@
Context:
integration_data : IntegrationData (required)
{% endcomment %}
-<a href="{% url 'integrations_manage' integration_id=integration_data.integration_id %}"
+<a href="{% url 'integrations_connect_manage' integration_id=integration_data.integration_id %}"
class="clickable-card">
<div class="card border-warning">
<div class="card-body">
diff --git a/src/hi/integrations/connect/integration_gateway.py b/src/hi/integrations/connect/integration_gateway.py
deleted file mode 100644
index 5459e1fa..00000000
--- a/src/hi/integrations/connect/integration_gateway.py
+++ /dev/null
@@ -1,122 +0,0 @@
-from typing import List, Optional
-
-from hi.apps.entity.models import Entity
-from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
-from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from hi.apps.sense.transient_models import SensorResponse
-from hi.apps.system.health_status_provider import HealthStatusProvider
-
-from .external_view_data import ExternalViewData
-from .integration_controller import IntegrationController
-from .integration_manage_view_pane import IntegrationManageViewPane
-from .integration_synchronizer import IntegrationSynchronizer
-from hi.integrations.models import IntegrationAttribute
-from hi.integrations.transient_models import (
- ConnectionTestResult,
- IntegrationMetaData,
- IntegrationValidationResult,
-)
-
-
-class IntegrationGateway:
- """
- Each integration needs to provide an Integration Manager that implements these methods.
- """
-
- def get_metadata(self) -> IntegrationMetaData:
- raise NotImplementedError('Subclasses must override this method')
-
- def get_manage_view_pane(self) -> IntegrationManageViewPane:
- raise NotImplementedError('Subclasses must override this method')
-
- def get_monitor(self) -> PeriodicMonitor:
- raise NotImplementedError('Subclasses must override this method')
-
- def get_controller(self) -> IntegrationController:
- raise NotImplementedError('Subclasses must override this method')
-
- def notify_settings_changed(self):
- """
- This method is called when Integration or IntegrationAttribute models
- are modified. Each integration should implement this to reload its
- configuration and notify any dependent components.
- """
- raise NotImplementedError('Subclasses must override this method')
-
- def get_health_status_provider(self) -> HealthStatusProvider:
- raise NotImplementedError('Subclasses must override this method')
-
- def get_synchronizer(self) -> Optional[IntegrationSynchronizer]:
- """
- Return the integration's synchronizer when it supports sync;
- None otherwise. Sync is an opt-in capability — not every
- integration requires one. The framework owns the sync workflow
- (pre-sync confirmation, sync execution, post-sync placement);
- the synchronizer participates by providing the integration-
- specific work plus a small amount of peripheral metadata.
-
- The Issue #283 sync-check probe also rides on the synchronizer
- (see ``IntegrationSynchronizer.check_needs_sync``): integrations
- without a synchronizer naturally opt out of both full sync and
- the periodic drift check.
- """
- return None
-
- def validate_configuration(
- self,
- integration_attributes: List[IntegrationAttribute]
- ) -> IntegrationValidationResult:
- """
- Schema-only validation of the proposed configuration. Must NOT
- perform network operations. Returns success if the attribute set
- is structurally usable; returns an error otherwise. For live
- access validation, see validate_access().
- """
- raise NotImplementedError('Subclasses must override this method')
-
- def validate_access(
- self,
- integration_attributes: List[IntegrationAttribute],
- timeout_secs: Optional[float],
- ) -> ConnectionTestResult:
- """
- Live probe to validate access to the upstream system using the
- proposed configuration. Must respect the bounded timeout. Used
- at attribute-save time (Configure / Reconfigure) and before
- relaunching monitors (Resume).
- """
- raise NotImplementedError('Subclasses must override this method')
-
- def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
- return None
-
- def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
- return None
-
- def get_sensor_response_video_stream(
- self,
- sensor_response: SensorResponse) -> Optional[VideoStream]:
- return None
-
- def get_sensor_response_event_snapshot_url(
- self,
- sensor_response: SensorResponse) -> Optional[str]:
- """Return the URL to the per-event captured snapshot frame for
- a SensorResponse, or ``None`` when the integration cannot
- produce one. Generated at render time from the event id so the
- URL always reflects current integration configuration (e.g.,
- an operator who moves the upstream host doesn't get stale
- URLs on historical rows). Pair with
- ``SensorResponse.has_event_video_snapshot`` — only call when
- the flag is True."""
- return None
-
- def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:
- """Return the external-data view payload for the entity-detail
- modal. Return ``None`` if this integration has no external view
- for ``entity`` — the external-data region is then suppressed.
-
- Defaults to ``None``; integrations whose data lives upstream
- override this hook to return a populated ``ExternalViewData``
- subclass (typically ``StructuredViewData``)."""
- return None
diff --git a/src/hi/integrations/connect/integration_manage_view_pane.py b/src/hi/integrations/connect/integration_manage_view_pane.py
deleted file mode 100644
index ce7bac8a..00000000
--- a/src/hi/integrations/connect/integration_manage_view_pane.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from typing import Dict
-
-
-class IntegrationManageViewPane:
- """ For integrations to override to define the management interface. """
-
- def get_template_name( self ) -> str:
- raise NotImplementedError('Subclasses must override this method')
-
- def get_template_context( self, integration_data ) -> Dict[ str, object ]:
- raise NotImplementedError('Subclasses must override this method')
diff --git a/src/hi/integrations/connect/__init__.py b/src/hi/integrations/connector/__init__.py
similarity index 100%
rename from src/hi/integrations/connect/__init__.py
rename to src/hi/integrations/connector/__init__.py
diff --git a/src/hi/integrations/connect/external_view_data.py b/src/hi/integrations/connector/external_view_data.py
similarity index 100%
rename from src/hi/integrations/connect/external_view_data.py
rename to src/hi/integrations/connector/external_view_data.py
diff --git a/src/hi/integrations/connect/integration_synchronizer.py b/src/hi/integrations/connector/integration_connector.py
similarity index 82%
rename from src/hi/integrations/connect/integration_synchronizer.py
rename to src/hi/integrations/connector/integration_connector.py
index de0d0558..d0ff0ab4 100644
--- a/src/hi/integrations/connect/integration_synchronizer.py
+++ b/src/hi/integrations/connector/integration_connector.py
@@ -1,14 +1,14 @@
"""
-Per-integration synchronizer base class.
+Per-integration connector base class.
The general integration framework owns the sync workflow (pre-sync
confirmation modal, sync execution view, post-sync placement modal).
-The synchronizer is the per-integration participant that the framework
+The connector is the per-integration participant that the framework
hands off to for the integration-specific work plus a small amount of
peripheral metadata the framework surfaces alongside.
Each integration that supports sync provides a concrete subclass and
-returns an instance of it from `IntegrationGateway.get_synchronizer()`.
+returns an instance of it from `IntegrationGateway.get_connector()`.
Sync is opt-in: a gateway whose integration does not support sync
returns None.
"""
@@ -23,8 +23,14 @@ from hi.apps.entity.entity_placement import (
EntityPlacementItem,
)
from hi.apps.entity.models import Entity
-
-from .entity_operations import EntityIntegrationOperations
+from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
+from hi.apps.monitor.periodic_monitor import PeriodicMonitor
+from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.system.health_status_provider import HealthStatusProvider
+
+from hi.integrations.entity_operations import EntityIntegrationOperations
+from .external_view_data import ExternalViewData
+from .integration_controller import IntegrationController
from .sync_check import IntegrationSyncCheck, SyncDelta
from .sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey, IntegrationMetaData
@@ -32,9 +38,9 @@ from hi.integrations.transient_models import IntegrationKey, IntegrationMetaData
logger = logging.getLogger(__name__)
-class IntegrationSynchronizer:
+class IntegrationConnector:
"""
- Base class for per-integration synchronizers.
+ Base class for per-integration connectors.
The framework calls `sync()`. The base implementation acquires a
process-wide synchronization lock, delegates to the subclass's
@@ -83,6 +89,70 @@ class IntegrationSynchronizer:
return 'Connect Result'
return 'Update Check Result'
+ def get_monitor(self) -> Optional[PeriodicMonitor]:
+ """Return the integration's periodic monitor when it has one;
+ None otherwise. The monitor polls upstream state for live
+ sensor responses and surfaces health status. Connect-only
+ by nature — Import has no ongoing connection to monitor."""
+ return None
+
+ def get_controller(self) -> Optional[IntegrationController]:
+ """Return the integration's controller when it accepts control
+ actions; None otherwise. The controller routes a control value
+ from HI to the upstream system. Connect-only — Import-mode
+ entities are HI-owned and their controllers are HI-native."""
+ return None
+
+ def get_health_status_provider(self) -> HealthStatusProvider:
+ """Return the integration's health status provider. Every
+ Connect-capable integration must surface one so the framework's
+ health banners and System Info page can report upstream
+ availability."""
+ raise NotImplementedError('Subclasses must override this method')
+
+ def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
+ """Return the live video stream for ``entity``, or ``None`` when
+ the integration cannot produce one. Opt-in capability — most
+ integrations leave this as the default."""
+ return None
+
+ def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
+ """Return a fresh still-image snapshot for ``entity``, or
+ ``None`` when the integration cannot produce one. Opt-in
+ capability — most integrations leave this as the default."""
+ return None
+
+ def get_sensor_response_video_stream(
+ self,
+ sensor_response: SensorResponse) -> Optional[VideoStream]:
+ """Return the recorded video stream for a SensorResponse
+ carrying an event clip, or ``None`` when the integration
+ cannot produce one. Opt-in capability."""
+ return None
+
+ def get_sensor_response_event_snapshot_url(
+ self,
+ sensor_response: SensorResponse) -> Optional[str]:
+ """Return the URL to the per-event captured snapshot frame for
+ a SensorResponse, or ``None`` when the integration cannot
+ produce one. Generated at render time from the event id so the
+ URL always reflects current integration configuration (e.g.,
+ an operator who moves the upstream host doesn't get stale
+ URLs on historical rows). Pair with
+ ``SensorResponse.has_event_video_snapshot`` — only call when
+ the flag is True."""
+ return None
+
+ def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:
+ """Return the external-data view payload for the entity-detail
+ modal. Return ``None`` if this integration has no external view
+ for ``entity`` — the external-data region is then suppressed.
+
+ Defaults to ``None``; integrations whose data lives upstream
+ override this hook to return a populated ``ExternalViewData``
+ subclass (typically ``StructuredViewData``)."""
+ return None
+
def sync(self,
is_initial_connect : bool,
preserve_user_data : bool = True,
@@ -278,7 +348,7 @@ class IntegrationSynchronizer:
match, this method:
* clears the previous-identity columns (which removes the
- "Detached from <integration>" badge in the UI),
+ "From <integration>" badge in the UI),
* dispatches to ``_rebuild_integration_components()`` so the
integration's converter repopulates the integration-owned
components on the existing entity,
diff --git a/src/hi/integrations/connect/integration_controller.py b/src/hi/integrations/connector/integration_controller.py
similarity index 100%
rename from src/hi/integrations/connect/integration_controller.py
rename to src/hi/integrations/connector/integration_controller.py
diff --git a/src/hi/integrations/connect/monitors.py b/src/hi/integrations/connector/monitors.py
similarity index 91%
rename from src/hi/integrations/connect/monitors.py
rename to src/hi/integrations/connector/monitors.py
index 4bfeeb30..558b42ae 100644
--- a/src/hi/integrations/connect/monitors.py
+++ b/src/hi/integrations/connector/monitors.py
@@ -5,9 +5,9 @@ feature.
A single ``IntegrationSyncCheckMonitor`` runs at a long cadence
(``IntegrationSyncCheck.INTERVAL_SECS``, currently 4 hours), iterates
the enabled and unpaused integrations, gets each integration's
-synchronizer via ``gateway.get_synchronizer()``, and dispatches to
+connector via ``gateway.get_connector()``, and dispatches to
its ``check_needs_sync()``. Sync-check rides on the same opt-in
-surface as full sync — an integration without a synchronizer
+surface as full sync — an integration without a connector
naturally opts out of the periodic drift check too. Per-integration
calls are wrapped in try/except so one integration's transient
failure does not abort the cycle for the others. Sequential (not
@@ -31,7 +31,7 @@ from hi.apps.alert.enums import AlarmLevel
from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.system.provider_info import ProviderInfo
-from .integration_data import IntegrationData
+from hi.integrations.integration_data import IntegrationData
from .sync_check import IntegrationSyncCheck, SyncCheckOutcome
logger = logging.getLogger(__name__)
@@ -93,22 +93,22 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):
"""
Run the per-integration probe and write the result to the
cache. Sync-check rides on the same opt-in surface as full
- sync: an integration with no synchronizer
- (``gateway.get_synchronizer() is None``) does not participate.
- Any exception from the synchronizer's check is caught here so
+ sync: an integration with no connector
+ (``gateway.get_connector() is None``) does not participate.
+ Any exception from the connector's check is caught here so
a single integration cannot abort the cycle.
"""
integration_id = integration_data.integration_id
gateway = integration_data.integration_gateway
- synchronizer = gateway.get_synchronizer()
- if synchronizer is None:
- # No synchronizer means no sync support — and therefore
+ connector = gateway.get_connector()
+ if connector is None:
+ # No connector means no sync support — and therefore
# no sync-check. Cache state is not touched.
return SyncCheckOutcome.OPTED_OUT
try:
- delta = await synchronizer.check_needs_sync()
+ delta = await connector.check_needs_sync()
except Exception as e:
logger.warning(
f'Sync check failed for {integration_id}: {e}',
diff --git a/src/hi/integrations/connect/sync_check.py b/src/hi/integrations/connector/sync_check.py
similarity index 99%
rename from src/hi/integrations/connect/sync_check.py
rename to src/hi/integrations/connector/sync_check.py
index 68d31194..7691e8cc 100644
--- a/src/hi/integrations/connect/sync_check.py
+++ b/src/hi/integrations/connector/sync_check.py
@@ -6,7 +6,7 @@ Issue #283: a periodic background probe surfaces a "needs-sync"
signal when an integration's HI representation has drifted from
upstream. The probe never modifies entities — the user always
chooses when to invoke Refresh. Per-integration probe logic lives in
-each ``IntegrationSynchronizer.check_needs_sync()`` override, which
+each ``IntegrationConnector.check_needs_sync()`` override, which
returns a ``SyncDelta``; sync-check rides on the same opt-in surface
as full sync (an integration without a synchronizer naturally opts
out of the periodic drift check too). The framework monitor wraps
diff --git a/src/hi/integrations/connect/sync_result.py b/src/hi/integrations/connector/sync_result.py
similarity index 98%
rename from src/hi/integrations/connect/sync_result.py
rename to src/hi/integrations/connector/sync_result.py
index 43c3e8ba..f9cc9c94 100644
--- a/src/hi/integrations/connect/sync_result.py
+++ b/src/hi/integrations/connector/sync_result.py
@@ -3,7 +3,7 @@ Transient data shapes returned by integration sync operations.
The framework owns the sync workflow (pre-sync modal, sync view,
post-sync placement modal). Each integration's
-``IntegrationSynchronizer.sync()`` returns an
+``IntegrationConnector.sync()`` returns an
``IntegrationSyncResult`` describing what happened during sync —
title, structured change counts, info/error notes — plus an
optional ``EntityPlacementInput`` that drives the placement modal
diff --git a/src/hi/integrations/connect/user_data_detector.py b/src/hi/integrations/connector/user_data_detector.py
similarity index 100%
rename from src/hi/integrations/connect/user_data_detector.py
rename to src/hi/integrations/connector/user_data_detector.py
diff --git a/src/hi/integrations/connect/views.py b/src/hi/integrations/connector/views.py
similarity index 76%
rename from src/hi/integrations/connect/views.py
rename to src/hi/integrations/connector/views.py
index 690042ce..2796dcbe 100644
--- a/src/hi/integrations/connect/views.py
+++ b/src/hi/integrations/connector/views.py
@@ -27,12 +27,16 @@ from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
from hi.integrations.models import IntegrationAttribute
-from .entity_operations import EntityIntegrationOperations
-from .integration_attribute_edit_context import IntegrationAttributeItemEditContext
-from .placement_request import PlacementFormParser, PlacementUrlParams
+from hi.integrations.entity_operations import EntityIntegrationOperations
+from hi.integrations.integration_attribute_edit_context import IntegrationAttributeItemEditContext
+from hi.integrations.placement_request import PlacementFormParser, PlacementUrlParams
from .sync_check import IntegrationSyncCheck
from .sync_result import IntegrationSyncResult
-from .view_mixins import IntegrationPlacementViewMixin, IntegrationViewMixin
+from hi.integrations.view_mixins import (
+ IntegrationPlacementViewMixin,
+ IntegrationViewMixin,
+)
+from hi.integrations.views import CapabilityConfigureView
logger = logging.getLogger(__name__)
@@ -40,10 +44,10 @@ logger = logging.getLogger(__name__)
class IntegrationHomeView( ConfigPageView, IntegrationViewMixin ):
def config_page_type(self) -> ConfigPageType:
- return ConfigPageType.INTEGRATIONS
+ return ConfigPageType.INTEGRATIONS_CONNECT
def get_main_template_name( self ) -> str:
- return 'integrations/pages/no_integrations.html'
+ return 'integrations/connector/pages/no_integrations.html'
def get_main_template_context( self, request, *args, **kwargs ):
@@ -53,7 +57,7 @@ class IntegrationHomeView( ConfigPageView, IntegrationViewMixin ):
if not integration_data:
return dict()
- redirect_url = reverse( 'integrations_manage',
+ redirect_url = reverse( 'integrations_connect_manage',
kwargs = { 'integration_id': integration_data.integration_id })
raise ForceRedirectException( redirect_url )
@@ -61,7 +65,7 @@ class IntegrationHomeView( ConfigPageView, IntegrationViewMixin ):
class IntegrationSelectView( HiModalView, IntegrationViewMixin ):
def get_template_name( self ) -> str:
- return 'integrations/modals/integrations_select.html'
+ return 'integrations/connector/modals/integrations_select.html'
def get( self, request, *args, **kwargs ):
context = {
@@ -78,11 +82,8 @@ class IntegrationHealthStatusView( HiModalView, IntegrationViewMixin ):
return 'system/modals/health_status.html'
def get( self, request, *args, **kwargs ):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
- health_status_provider = integration_data.integration_gateway.get_health_status_provider()
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()
context = {
'health_status_provider': health_status_provider,
}
@@ -102,20 +103,17 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
expresses the policy applied at sync execution if any drops
carry user data.
- 404s when the integration does not provide a synchronizer (sync
+ 404s when the integration does not provide a connector (sync
is opt-in capability — not every integration supports it).
"""
def get_template_name( self ) -> str:
- return 'integrations/modals/pre_sync_confirm.html'
+ return 'integrations/connector/modals/pre_sync_confirm.html'
def get( self, request, *args, **kwargs ):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
- synchronizer = integration_data.integration_gateway.get_synchronizer()
- if synchronizer is None:
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ connector = integration_data.integration_gateway.get_connector()
+ if connector is None:
return page_not_found_response( request )
is_initial_connect = not Entity.objects.filter(
@@ -135,7 +133,7 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
context = {
'integration_data': integration_data,
'is_initial_connect': is_initial_connect,
- 'sync_description': synchronizer.get_description(
+ 'sync_description': connector.get_description(
is_initial_connect = is_initial_connect,
),
'sync_url': sync_url,
@@ -147,7 +145,7 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
"""
Framework sync execution view. Invokes the integration's
- synchronizer and always renders the sync result modal — the
+ connector and always renders the sync result modal — the
operator's single end-of-sync surface. When the sync produced
new entities to place, the result modal exposes a primary
'Place N new items' CTA that navigates (via antinode modal-to-
@@ -163,13 +161,10 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin ):
"""
def get_template_name( self ) -> str:
- return 'integrations/modals/sync_result.html'
+ return 'integrations/connector/modals/sync_result.html'
def post( self, request, *args, **kwargs ):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
+ integration_data = self.get_integration_data( request, *args, **kwargs )
# Operator's per-Refresh policy for items that would be
# dropped. True ("Refresh and Retain") preserves user-data
# entities by detaching them; False ("Refresh and Remove")
@@ -193,7 +188,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
GET queries currently-unplaced entities for the integration
(optionally scoped by ``entity_ids`` URL param), runs them
- through the synchronizer's ``group_entities_for_placement``,
+ through the connector's ``group_entities_for_placement``,
and renders the placement modal. Empty result falls back to
a brief acknowledgement modal so the operator isn't dropped
onto an empty placement.
@@ -211,12 +206,9 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
return 'integrations/modals/placement.html'
def get( self, request, *args, **kwargs ):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
- synchronizer = integration_data.integration_gateway.get_synchronizer()
- if synchronizer is None:
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ connector = integration_data.integration_gateway.get_connector()
+ if connector is None:
return page_not_found_response( request )
url_params = PlacementUrlParams.from_data( request.GET )
@@ -233,14 +225,14 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
if entity_id_filter is not None:
entities = [ e for e in entities if e.id in entity_id_filter ]
- placement_input = synchronizer.group_entities_for_placement(
+ placement_input = connector.group_entities_for_placement(
entities = entities,
)
if placement_input.is_empty():
return self._render_empty(
request = request,
integration_data = integration_data,
- synchronizer = synchronizer,
+ connector = connector,
is_initial_connect = is_initial_connect,
)
return self.render_placement(
@@ -252,10 +244,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
)
def post( self, request, *args, **kwargs ):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
+ integration_data = self.get_integration_data( request, *args, **kwargs )
url_params = PlacementUrlParams.from_data( request.POST )
is_initial_connect = url_params.is_initial_connect
@@ -300,13 +289,13 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
return ids
def _render_empty( self, request, integration_data,
- synchronizer, is_initial_connect : bool ):
+ connector, is_initial_connect : bool ):
"""No-unplaced-items acknowledgement: render the result
modal with the integration's icon + a brief 'no items'
info note rather than an empty placement. Counts stay
zero so the modal lead reads 'Nothing new.'"""
sync_result = IntegrationSyncResult(
- title = synchronizer.get_result_title(
+ title = connector.get_result_title(
is_initial_connect = is_initial_connect,
),
info_list = [ 'No items left to place.' ],
@@ -318,7 +307,7 @@ class IntegrationPlacementView( HiModalView, IntegrationViewMixin,
'integration_data': integration_data,
'is_initial_connect': is_initial_connect,
},
- template_name = 'integrations/modals/sync_result.html',
+ template_name = 'integrations/connector/modals/sync_result.html',
)
@@ -351,86 +340,51 @@ class IntegrationRefineView( View ):
) )
-class IntegrationEnableView( HiModalView, IntegrationViewMixin, AttributeEditViewMixin ):
+class ConnectorConfigureView( CapabilityConfigureView ):
- def get_template_name( self ) -> str:
- return 'integrations/modals/integration_enable.html'
+ capability = IntegrationCapability.CONNECT
+ button_label = 'CONNECT'
+ template_name = 'integrations/connector/modals/integration_enable.html'
+ error_title = 'Cannot configure integration.'
- def get(self, request, *args, **kwargs):
- integration_manager = IntegrationManager()
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
- integration_manager.ensure_all_attributes_exist(
- integration_metadata = integration_data.integration_metadata,
- integration = integration_data.integration,
- )
- attr_item_context = IntegrationAttributeItemEditContext(
+ def handle_post_success(self, request, integration_data):
+ IntegrationManager().enable_integration(
integration_data = integration_data,
- capability = IntegrationCapability.CONNECT,
- update_button_label = 'CONNECT',
- suppress_history = True,
- show_secrets = True,
)
- template_context = self.create_initial_template_context(
- attr_item_context= attr_item_context,
- )
- return self.modal_response( request, template_context )
- def post(self, request, *args, **kwargs):
- integration_manager = IntegrationManager()
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
- attr_item_context = IntegrationAttributeItemEditContext(
- integration_data = integration_data,
- capability = IntegrationCapability.CONNECT,
- update_button_label = 'CONNECT',
- suppress_history = True,
- show_secrets = True,
- )
- response = self.post_attribute_form(
- request = request,
- attr_item_context = attr_item_context,
- )
-
- # Errors just dynamically populate modal content with form errors.
- if response.status_code > 299:
- return response
-
- integration_manager.enable_integration(
- integration_data = integration_data,
- )
+ # Connect-side managers (Frigate/Hass/ZM) gate client (re)build
+ # on integration.is_enabled, so the notify MUST fire after
+ # enable_integration — otherwise the manager reloads with
+ # is_enabled=False, nulls its client, and the immediately-
+ # following sync sees no client. Calling unconditionally also
+ # covers the re-Configure path (already enabled), where
+ # enable_integration early-returns without nudging.
+ try:
+ integration_data.integration_gateway.notify_settings_changed()
+ except Exception as e:
+ logger.warning(
+ f'Synchronous notify_settings_changed failed for '
+ f'{integration_data.integration_id}: {e}'
+ )
# Phase 7 collapse: when the integration supports sync, run it
# right here and render the sync-result modal directly. The
# previous Configure → Pre-Sync → Sync handshake is now one
- # CONNECT click. Synchronizer-less integrations keep the
+ # CONNECT click. Connector-less integrations keep the
# original redirect-to-manage behavior.
- synchronizer = integration_data.integration_gateway.get_synchronizer()
- if synchronizer is not None:
+ connector = integration_data.integration_gateway.get_connector()
+ if connector is not None:
return self.render_sync_result(
request = request,
integration_data = integration_data,
)
- redirect_url = reverse( 'integrations_manage',
- kwargs = { 'integration_id': integration_id } )
+ redirect_url = reverse(
+ 'integrations_connect_manage',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
return AttributeRedirectResponse( url = redirect_url )
- def validate_attributes_extra( self,
- attr_item_context,
- regular_attributes_formset,
- request ):
- """ Override for AttributeEditViewMixin """
- self.validate_attributes_extra_helper(
- attr_item_context,
- regular_attributes_formset,
- error_title = 'Cannot configure integration.' )
- return
-
class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
"""
@@ -441,15 +395,15 @@ class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
"""
def get_template_name( self ) -> str:
- return 'integrations/modals/integration_disable.html'
+ return 'integrations/connector/modals/integration_disable.html'
def get(self, request, *args, **kwargs):
- integration_data = self._get_validated_integration_data( kwargs )
+ integration_data = self._get_validated_integration_data( request, *args, **kwargs )
context = self._build_remove_context( integration_data )
return self.modal_response( request, context )
def post(self, request, *args, **kwargs):
- integration_data = self._get_validated_integration_data( kwargs )
+ integration_data = self._get_validated_integration_data( request, *args, **kwargs )
mode = IntegrationDisableMode.from_name_safe( request.POST.get('mode', '') )
try:
IntegrationManager().disable_integration(
@@ -463,12 +417,11 @@ class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
# rows. Symmetric with the post-sync invalidation.
IntegrationMetadataCache().invalidate()
SensorResponseManager().invalidate_local_sensor_cache()
- redirect_url = reverse( 'integrations_home' )
+ redirect_url = reverse( 'integrations_connect_home' )
return self.redirect_response( request, redirect_url )
- def _get_validated_integration_data(self, kwargs):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data( integration_id = integration_id )
+ def _get_validated_integration_data(self, request, *args, **kwargs):
+ integration_data = self.get_integration_data( request, *args, **kwargs )
if not integration_data.integration.is_enabled:
raise BadRequest( f'{integration_data.label} is not configured' )
return integration_data
@@ -488,27 +441,23 @@ class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
class IntegrationPauseView( View, IntegrationViewMixin ):
def post(self, request, *args, **kwargs):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
+ integration_data = self.get_integration_data( request, *args, **kwargs )
if not integration_data.integration.is_enabled:
raise BadRequest( f'{integration_data.label} integration is not configured' )
IntegrationManager().pause_integration( integration_data = integration_data )
- redirect_url = reverse( 'integrations_manage',
- kwargs = { 'integration_id': integration_id } )
+ redirect_url = reverse(
+ 'integrations_connect_manage',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
return antinode.redirect_response( redirect_url )
class IntegrationResumeView( View, IntegrationViewMixin ):
def post(self, request, *args, **kwargs):
- integration_id = kwargs.get('integration_id')
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
+ integration_data = self.get_integration_data( request, *args, **kwargs )
if not integration_data.integration.is_enabled:
raise BadRequest( f'{integration_data.label} integration is not configured' )
@@ -519,27 +468,27 @@ class IntegrationResumeView( View, IntegrationViewMixin ):
f'{integration_data.label} could not resume: {e}'
)
- redirect_url = reverse( 'integrations_manage',
- kwargs = { 'integration_id': integration_id } )
+ redirect_url = reverse(
+ 'integrations_connect_manage',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
return antinode.redirect_response( redirect_url )
-class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEditViewMixin ):
+class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditViewMixin ):
def config_page_type(self) -> ConfigPageType:
- return ConfigPageType.INTEGRATIONS
+ return ConfigPageType.INTEGRATIONS_CONNECT
def get_main_template_name( self ) -> str:
- return 'integrations/pages/integration_manage.html'
+ return 'integrations/connector/pages/integration_manage.html'
def get_main_template_context( self, request, *args, **kwargs ):
integration_manager = IntegrationManager()
-
+
integration_id = kwargs.get('integration_id')
if integration_id:
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
+ integration_data = self.get_integration_data( request, *args, **kwargs )
else:
integration_data = integration_manager.get_default_integration_data(
capabilities = frozenset({ IntegrationCapability.CONNECT }),
@@ -549,7 +498,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
raise BadRequest( f'{integration_data.label} integration is not configured' )
# Get health status from the integration gateway
- health_status_provider = integration_data.integration_gateway.get_health_status_provider()
+ health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
@@ -561,14 +510,8 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
capabilities = frozenset({ IntegrationCapability.CONNECT }),
)
- manage_view_pane = integration_data.integration_gateway.get_manage_view_pane()
- manage_template_name = manage_view_pane.get_template_name()
- template_context = manage_view_pane.get_template_context( integration_data = integration_data )
-
- template_context.update(
- self.create_initial_template_context(
- attr_item_context= attr_item_context,
- )
+ template_context = self.create_initial_template_context(
+ attr_item_context = attr_item_context,
)
has_entities = Entity.objects.filter(
integration_id = integration_data.integration_id,
@@ -604,7 +547,6 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
'core': {
'integration_data_list': integration_data_list,
'integration_data': integration_data,
- 'manage_view_template_name': manage_template_name,
'health_status': health_status_provider.health_status,
'has_entities': has_entities,
'sync_check_result': sync_check_result,
@@ -615,12 +557,10 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
def post( self, request,*args, **kwargs ):
integration_manager = IntegrationManager()
-
+
integration_id = kwargs.get('integration_id')
if integration_id:
- integration_data = self.get_integration_data(
- integration_id = integration_id,
- )
+ integration_data = self.get_integration_data( request, *args, **kwargs )
else:
integration_data = integration_manager.get_default_integration_data(
capabilities = frozenset({ IntegrationCapability.CONNECT }),
@@ -630,7 +570,7 @@ class IntegrationManageView( ConfigPageView, IntegrationViewMixin, AttributeEdit
raise BadRequest( f'{integration_data.label} integration is not configured' )
# Get health status from the integration gateway
- health_status_provider = integration_data.integration_gateway.get_health_status_provider()
+ health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
@@ -667,7 +607,7 @@ class IntegrationAttributeHistoryInlineView( View,
except IntegrationAttribute.DoesNotExist:
return page_not_found_response(request, "Attribute not found.")
- integration_data = self.get_integration_data(
+ integration_data = IntegrationManager().get_integration_data(
integration_id = attribute.integration.integration_id,
)
attr_item_context = IntegrationAttributeItemEditContext(
@@ -695,10 +635,10 @@ class IntegrationAttributeRestoreInlineView( View,
except IntegrationAttribute.DoesNotExist:
return page_not_found_response(request, "Attribute not found.")
- integration_data = self.get_integration_data(
+ integration_data = IntegrationManager().get_integration_data(
integration_id = attribute.integration.integration_id,
)
-
+
attr_item_context = IntegrationAttributeItemEditContext(
integration_data = integration_data,
capability = IntegrationCapability.CONNECT,
diff --git a/src/hi/integrations/connect/entity_operations.py b/src/hi/integrations/entity_operations.py
similarity index 94%
rename from src/hi/integrations/connect/entity_operations.py
rename to src/hi/integrations/entity_operations.py
index 57cebf6b..f066a2f0 100644
--- a/src/hi/integrations/connect/entity_operations.py
+++ b/src/hi/integrations/entity_operations.py
@@ -27,8 +27,8 @@ from hi.apps.control.models import Controller
from hi.integrations.event_definition_operations import EventDefinitionOperations
from hi.integrations.transient_models import IntegrationKey, IntegrationRemovalSummary
-from .sync_result import IntegrationSyncResult
-from .user_data_detector import EntityUserDataDetector
+from hi.integrations.connector.sync_result import IntegrationSyncResult
+from hi.integrations.connector.user_data_detector import EntityUserDataDetector
logger = logging.getLogger(__name__)
@@ -104,12 +104,16 @@ class EntityIntegrationOperations:
def get_removal_entity_ids( integration_id : str ) -> Set[int]:
"""
Return the full set of entity IDs that a Remove of the given
- integration should target: every entity attached to the integration,
- plus any delegate entities that would be orphaned by their removal.
+ integration should target: every actively-attached
+ (EXTERNAL) entity for the integration, plus any delegate
+ entities that would be orphaned by their removal. Imported /
+ detached rows for the same integration are HI-owned and
+ outside the removal scope.
"""
seed = set(
- Entity.objects.filter( integration_id = integration_id )
- .values_list( 'id', flat = True )
+ Entity.objects.external_for(
+ integration_id = integration_id,
+ ).values_list( 'id', flat = True )
)
return EntityIntegrationOperations.collect_removal_closure( seed )
@@ -254,8 +258,9 @@ class EntityIntegrationOperations:
key.integration_name: key for key in upstream_keys
}
- candidate_entities = Entity.objects.filter(
- previous_integration_id = integration_id,
+ candidate_entities = Entity.objects.detached_for(
+ integration_id = integration_id,
+ ).filter(
previous_integration_name__in = list( upstream_keys_by_name.keys() ),
)
@@ -303,7 +308,7 @@ class EntityIntegrationOperations:
recognize it if the same upstream key reappears later. The
detached state is signaled structurally — ``integration_id``
becomes NULL and ``previous_integration_id`` carries the prior
- identity — and surfaced to the operator via a "Detached from
+ identity — and surfaced to the operator via a "From
<integration>" badge in the entity-detail UI.
Issue #288: integration-owned EventDefinitions are removed
@@ -380,7 +385,7 @@ class EntityIntegrationOperations:
# so the auto-reconnect path can recognize this entity if
# the same upstream key reappears later. The presence of
# previous_integration_id is also what drives the
- # "Detached from <integration>" UI badge.
+ # "From <integration>" UI badge.
entity.previous_integration_key = entity.integration_key
entity.integration_key = None
@@ -392,6 +397,12 @@ class EntityIntegrationOperations:
entity.can_user_delete = True
entity.allow_internal_attributes = True
+ # The data-source state (now DETACHED) is derived from
+ # the integration_id / previous_integration_id columns:
+ # integration_key.setter on line above set integration_id
+ # to NULL and the previous-pair carries the provenance,
+ # so the entity now reads as is_detached.
+
# Suppress integration-backed capabilities. The intrinsic
# video-stream capability is genuinely lost (the backing sensor
# was deleted above). The is_disabled flag is the general
diff --git a/src/hi/integrations/enums.py b/src/hi/integrations/enums.py
index b2327b50..b01103cb 100644
--- a/src/hi/integrations/enums.py
+++ b/src/hi/integrations/enums.py
@@ -21,8 +21,8 @@ class IntegrationDisableMode( LabeledEnum ):
SAFE — delete entities without user-created data; preserve entities with
user-created data by detaching them from the integration (strips
integration association, removes integration-only components, records
- the previous integration identity to drive the "Detached from ..."
- UI badge and the auto-reconnect path). This mirrors the sync-time
+ the previous integration identity to drive the "From ..." UI
+ badge and the auto-reconnect path). This mirrors the sync-time
preservation behavior.
ALL — hard-delete all entities attached to the integration regardless of
diff --git a/src/hi/services/homebox/shared/__init__.py b/src/hi/integrations/importer/__init__.py
similarity index 100%
rename from src/hi/services/homebox/shared/__init__.py
rename to src/hi/integrations/importer/__init__.py
diff --git a/src/hi/integrations/importer/integration_importer.py b/src/hi/integrations/importer/integration_importer.py
new file mode 100644
index 00000000..c92cebf7
--- /dev/null
+++ b/src/hi/integrations/importer/integration_importer.py
@@ -0,0 +1,84 @@
+"""
+Per-integration importer base class.
+
+Parallel to IntegrationConnector (Connect-capability). Each
+IMPORT-capable integration provides a concrete subclass and returns
+an instance from IntegrationGateway.get_importer(). The framework
+owns the import workflow (Data Import page, configure modal,
+preview, confirm, result modal, post-import placement); the
+importer participates by supplying the integration-specific
+candidate-listing, item ingest, and discard operations.
+"""
+from typing import List
+
+from hi.apps.entity.entity_placement import (
+ EntityPlacementInput,
+ EntityPlacementItem,
+)
+from hi.apps.entity.models import Entity
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import (
+ IntegrationMetaData,
+ IntegrationValidationResult,
+)
+
+from .transient_models import (
+ CandidateItem,
+ IntegrationDiscardResult,
+ IntegrationImportResult,
+)
+
+
+class IntegrationImporter:
+
+ def get_metadata(self) -> IntegrationMetaData:
+ raise NotImplementedError('Subclasses must override this method')
+
+ def validate_configuration(
+ self,
+ integration_attributes: List[IntegrationAttribute],
+ ) -> IntegrationValidationResult:
+ """Schema-only validation of the proposed configuration. Must
+ NOT perform network operations. Mirrors IntegrationGateway's
+ contract for the same operation on the Connect side."""
+ raise NotImplementedError('Subclasses must override this method')
+
+ def get_candidate_items(self) -> List[CandidateItem]:
+ """Synchronously fetch the upstream items that would be
+ candidates for import. Used for the preview-step count
+ ("would import N, would skip M"). Implementations filter out
+ items already present in HI (by integration_name match)."""
+ raise NotImplementedError('Subclasses must override this method')
+
+ def run_import(self) -> IntegrationImportResult:
+ """Execute the import. Re-fetches upstream detail per
+ candidate, creates HI entities + attributes, populates
+ attachments. Per-entity transaction so a single-item failure
+ does not abort the batch."""
+ raise NotImplementedError('Subclasses must override this method')
+
+ def discard_imported_data(self, integration_id: str) -> IntegrationDiscardResult:
+ """Remove all entities previously imported under this
+ integration_id. Filters by data_source=INTERNAL so that
+ Connect-mode entities (if somehow coexisting) stay
+ untouched."""
+ raise NotImplementedError('Subclasses must override this method')
+
+ def group_entities_for_placement(
+ self, entities: List[Entity],
+ ) -> EntityPlacementInput:
+ """Partition just-imported entities into the
+ EntityPlacementInput shape consumed by the placement modal.
+
+ Default: every entity is ungrouped. Subclasses override to
+ provide a domain grouping where one exists."""
+ return EntityPlacementInput(
+ ungrouped_items = [
+ EntityPlacementItem(
+ key = f'entity:{entity.id}',
+ label = entity.name,
+ entity = entity,
+ )
+ for entity in entities
+ ],
+ )
diff --git a/src/hi/integrations/importer/transient_models.py b/src/hi/integrations/importer/transient_models.py
new file mode 100644
index 00000000..92eaac2d
--- /dev/null
+++ b/src/hi/integrations/importer/transient_models.py
@@ -0,0 +1,54 @@
+from dataclasses import dataclass, field
+from typing import List, Optional
+
+from hi.apps.entity.entity_placement import EntityPlacementInput
+
+
+@dataclass
+class CandidateItem:
+ """One upstream item surfaced by IntegrationImporter.get_candidate_items().
+
+ ``integration_name`` is the per-integration unique identifier for
+ the upstream item; matched against existing entities'
+ ``integration_name`` to detect already-imported items.
+ """
+ name: str
+ integration_name: str
+
+
+@dataclass
+class IntegrationImportResult:
+ """Outcome of a single IntegrationImporter.run_import() invocation.
+
+ Parallel to IntegrationSyncResult but with import-specific fields.
+ Imports are add-only: items not already in HI are created;
+ pre-existing matches are reported as skipped. There is no
+ update/remove path.
+
+ ``placement_input`` is None when the import produced no new
+ entities to place; populated when the result modal should expose
+ the post-import placement flow.
+ """
+ title: str
+ placement_input: Optional[EntityPlacementInput] = None
+ items_imported_count: int = 0
+ items_skipped_count: int = 0
+ imported_list: List[str] = field(default_factory=list)
+ info_list: List[str] = field(default_factory=list)
+ error_list: List[str] = field(default_factory=list)
+
+ @property
+ def has_imports(self) -> bool:
+ return self.items_imported_count > 0
+
+
+@dataclass
+class IntegrationDiscardResult:
+ """Outcome of an IntegrationImporter.discard_imported_data() invocation.
+
+ ``count`` is the number of imported entities removed. ``errors``
+ carries per-entity failure messages; an empty list means clean
+ removal.
+ """
+ count: int = 0
+ errors: List[str] = field(default_factory=list)
diff --git a/src/hi/integrations/importer/views.py b/src/hi/integrations/importer/views.py
new file mode 100644
index 00000000..6967f845
--- /dev/null
+++ b/src/hi/integrations/importer/views.py
@@ -0,0 +1,224 @@
+"""
+Data Import page + Configure form views.
+
+CONFIGURE on the page row opens the credentials form modal (reuses
+``IntegrationAttributeItemEditContext`` with ``capability=IMPORT``).
+The form's IMPORT submit validates credentials, fetches upstream
+candidates via ``IntegrationImporter.get_candidate_items()``, computes a
+new-vs-skipped split against existing HI entities, and renders the
+preview modal. Phase 5 wires CONFIRM IMPORT → run.
+"""
+import logging
+from typing import Any, Dict
+
+from django.urls import reverse
+
+from hi.apps.config.enums import ConfigPageType
+from hi.apps.config.views import ConfigPageView
+from hi.apps.entity.models import Entity
+from hi.apps.sense.sensor_response_manager import SensorResponseManager
+from hi.hi_async_view import HiModalView
+from hi.views import page_not_found_response
+
+from hi.integrations.enums import IntegrationCapability
+from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
+from hi.integrations.placement_request import PlacementUrlParams
+from hi.integrations.view_mixins import IntegrationViewMixin
+from hi.integrations.views import CapabilityConfigureView
+
+logger = logging.getLogger(__name__)
+
+_IMPORT_CAPABILITY_FILTER = frozenset({ IntegrationCapability.IMPORT })
+
+
+class DataImportPageView( ConfigPageView, IntegrationViewMixin ):
+ """The Data Import tab. Flat list of IMPORT-capable integrations
+ with per-row CONFIGURE / DISCARD affordances."""
+
+ def config_page_type(self) -> ConfigPageType:
+ return ConfigPageType.INTEGRATIONS_IMPORT
+
+ def get_main_template_name(self) -> str:
+ return 'integrations/importer/pages/data_import_page.html'
+
+ def get_main_template_context(self, request, *args, **kwargs) -> Dict[str, Any]:
+ integration_data_list = self.get_integration_data_list(
+ capabilities = _IMPORT_CAPABILITY_FILTER,
+ )
+
+ rows = []
+ for data in integration_data_list:
+ rows.append({
+ 'integration_data': data,
+ 'has_imported': Entity.objects.imported_for(
+ integration_id = data.integration_id,
+ ).exists(),
+ 'is_dual_capability': (
+ IntegrationCapability.CONNECT in data.integration_metadata.capabilities
+ and IntegrationCapability.IMPORT in data.integration_metadata.capabilities
+ ),
+ })
+
+ return {
+ 'rows': rows,
+ }
+
+
+class ImporterConfigureView( CapabilityConfigureView ):
+ """Credentials form for IMPORT. The form's submit (IMPORT) runs
+ validate_configuration + validate_access, fetches candidates, and
+ renders the preview modal with new/skipped counts. No DB writes
+ to entities yet — that happens in the confirm step."""
+
+ capability = IntegrationCapability.IMPORT
+ button_label = 'IMPORT'
+ template_name = 'integrations/importer/modals/importer_configure.html'
+ error_title = 'Cannot configure import.'
+
+ def handle_post_success(self, request, integration_data):
+ # Synchronously refresh the integration's singleton manager so
+ # the freshly-saved credentials are visible before the importer
+ # reads them. The post_save signal eventually delivers this via
+ # DelayedSignalProcessor, but the 0.1s delay races the
+ # immediate get_candidate_items() call.
+ try:
+ integration_data.integration_gateway.notify_settings_changed()
+ except Exception as e:
+ logger.warning(
+ f'Synchronous notify_settings_changed failed for '
+ f'{integration_data.integration_id}: {e}'
+ )
+
+ importer = integration_data.integration_gateway.get_importer()
+ if importer is None:
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'error_message': (
+ f'{integration_data.label} does not support import.'
+ ),
+ },
+ template_name = 'integrations/importer/modals/import_preview.html',
+ )
+
+ candidates = importer.get_candidate_items()
+ existing_names = set(
+ Entity.objects.imported_for(
+ integration_id = integration_data.integration_id,
+ ).values_list( 'previous_integration_name', flat = True )
+ )
+ new_count = sum(
+ 1 for c in candidates if c.integration_name not in existing_names
+ )
+ skipped_count = len(candidates) - new_count
+
+ run_url = reverse(
+ 'integrations_import_run',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ )
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'new_count': new_count,
+ 'skipped_count': skipped_count,
+ 'existing_imported_count': len(existing_names),
+ 'run_url': run_url,
+ },
+ template_name = 'integrations/importer/modals/import_preview.html',
+ )
+
+
+class DataImportInfoView( HiModalView ):
+ """Static info modal explaining Data Import vs. Integration."""
+
+ def get_template_name(self) -> str:
+ return 'integrations/importer/modals/data_import_info.html'
+
+
+class ImporterRunView( HiModalView, IntegrationViewMixin ):
+ """CONFIRM IMPORT handler. Runs the importer, invalidates the
+ metadata + sensor-response caches, renders the result modal with
+ a placement CTA when new entities were created."""
+
+ def post(self, request, *args, **kwargs):
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ importer = integration_data.integration_gateway.get_importer()
+ if importer is None:
+ return page_not_found_response(request)
+
+ try:
+ result = importer.run_import()
+ finally:
+ # Mirror the post-sync invalidations so any cached
+ # metadata or sensor-response state pinned by polls that
+ # raced the import gets dropped.
+ IntegrationMetadataCache().invalidate()
+ SensorResponseManager().invalidate_local_sensor_cache()
+
+ new_entity_ids = (
+ result.placement_input.all_entity_ids()
+ if result.placement_input is not None else []
+ )
+ placement_url = PlacementUrlParams(
+ is_initial_connect = True,
+ entity_ids = new_entity_ids,
+ ).append_to_url( reverse(
+ 'integrations_placement',
+ kwargs = { 'integration_id': integration_data.integration_id },
+ ) )
+
+ return self.modal_response(
+ request,
+ context = {
+ 'result': result,
+ 'integration_data': integration_data,
+ 'placement_url': placement_url,
+ },
+ template_name = 'integrations/importer/modals/import_result.html',
+ )
+
+
+class ImporterDiscardView( HiModalView, IntegrationViewMixin ):
+ """DISCARD handler. GET renders the confirmation modal with the
+ count of imported entities; POST runs discard_imported_data and
+ redirects back to the Data Import page. Single-action confirm —
+ imported items ARE the user data, so the Connect-side SAFE/ALL
+ split doesn't apply."""
+
+ def get_template_name(self) -> str:
+ return 'integrations/importer/modals/import_discard_confirm.html'
+
+ def get(self, request, *args, **kwargs):
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ imported_count = Entity.objects.imported_for(
+ integration_id = integration_data.integration_id,
+ ).count()
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'imported_count': imported_count,
+ },
+ )
+
+ def post(self, request, *args, **kwargs):
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+ importer = integration_data.integration_gateway.get_importer()
+ if importer is None:
+ return page_not_found_response(request)
+
+ try:
+ importer.discard_imported_data(
+ integration_id = integration_data.integration_id,
+ )
+ finally:
+ # Mirror the Connect-side Disable cleanup: any cached
+ # metadata / sensor-response state for the just-deleted
+ # entities must drop too.
+ IntegrationMetadataCache().invalidate()
+ SensorResponseManager().invalidate_local_sensor_cache()
+
+ redirect_url = reverse('integrations_import_home')
+ return self.redirect_response(request, redirect_url)
diff --git a/src/hi/integrations/connect/integration_attribute_edit_context.py b/src/hi/integrations/integration_attribute_edit_context.py
similarity index 100%
rename from src/hi/integrations/connect/integration_attribute_edit_context.py
rename to src/hi/integrations/integration_attribute_edit_context.py
diff --git a/src/hi/integrations/connect/integration_data.py b/src/hi/integrations/integration_data.py
similarity index 100%
rename from src/hi/integrations/connect/integration_data.py
rename to src/hi/integrations/integration_data.py
diff --git a/src/hi/integrations/integration_gateway.py b/src/hi/integrations/integration_gateway.py
new file mode 100644
index 00000000..cdcb70bf
--- /dev/null
+++ b/src/hi/integrations/integration_gateway.py
@@ -0,0 +1,79 @@
+from typing import List, Optional
+
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.importer.integration_importer import IntegrationImporter
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import (
+ ConnectionTestResult,
+ IntegrationMetaData,
+ IntegrationValidationResult,
+)
+
+
+class IntegrationGateway:
+ """
+ Each integration needs to provide an Integration Manager that implements these methods.
+ """
+
+ def get_metadata(self) -> IntegrationMetaData:
+ raise NotImplementedError('Subclasses must override this method')
+
+ def notify_settings_changed(self):
+ """
+ This method is called when Integration or IntegrationAttribute models
+ are modified. Each integration should implement this to reload its
+ configuration and notify any dependent components.
+ """
+ raise NotImplementedError('Subclasses must override this method')
+
+ def get_connector(self) -> Optional[IntegrationConnector]:
+ """
+ Return the integration's connector when it supports sync;
+ None otherwise. Sync is an opt-in capability — not every
+ integration requires one. The framework owns the sync workflow
+ (pre-sync confirmation, sync execution, post-sync placement);
+ the connector participates by providing the integration-
+ specific work plus a small amount of peripheral metadata.
+
+ The Issue #283 sync-check probe also rides on the connector
+ (see ``IntegrationConnector.check_needs_sync``): integrations
+ without a connector naturally opt out of both full sync and
+ the periodic drift check.
+ """
+ return None
+
+ def get_importer(self) -> Optional[IntegrationImporter]:
+ """
+ Return the integration's importer when it supports the IMPORT
+ capability; None otherwise. Parallel to get_connector() for
+ the CONNECT capability. The framework owns the import workflow
+ (Data Import page, preview, confirm, result modal, placement);
+ the importer supplies the integration-specific candidate
+ listing, item ingest, and discard operations.
+ """
+ return None
+
+ def validate_configuration(
+ self,
+ integration_attributes: List[IntegrationAttribute]
+ ) -> IntegrationValidationResult:
+ """
+ Schema-only validation of the proposed configuration. Must NOT
+ perform network operations. Returns success if the attribute set
+ is structurally usable; returns an error otherwise. For live
+ access validation, see validate_access().
+ """
+ raise NotImplementedError('Subclasses must override this method')
+
+ def validate_access(
+ self,
+ integration_attributes: List[IntegrationAttribute],
+ timeout_secs: Optional[float],
+ ) -> ConnectionTestResult:
+ """
+ Live probe to validate access to the upstream system using the
+ proposed configuration. Must respect the bounded timeout. Used
+ at attribute-save time (Configure / Reconfigure) and before
+ relaunching monitors (Resume).
+ """
+ raise NotImplementedError('Subclasses must override this method')
diff --git a/src/hi/integrations/integration_manager.py b/src/hi/integrations/integration_manager.py
index 4442c3c1..58b80880 100644
--- a/src/hi/integrations/integration_manager.py
+++ b/src/hi/integrations/integration_manager.py
@@ -18,11 +18,11 @@ from hi.apps.common.module_utils import import_module_safe
from hi.apps.entity.models import Entity
from hi.apps.system.health_status_provider import HealthStatusProvider
-from .connect.entity_operations import EntityIntegrationOperations
+from .entity_operations import EntityIntegrationOperations
from .enums import IntegrationAttributeType, IntegrationCapability, IntegrationDisableMode
from .exceptions import IntegrationConnectionError
-from .connect.integration_data import IntegrationData
-from .connect.integration_gateway import IntegrationGateway
+from .integration_data import IntegrationData
+from .integration_gateway import IntegrationGateway
from .transient_models import IntegrationKey
from .models import Integration, IntegrationAttribute
from .transient_models import IntegrationMetaData
@@ -121,7 +121,10 @@ class IntegrationManager( Singleton ):
provider_id : str ) -> HealthStatusProvider:
with self._data_lock:
for integration in self._integration_data_map.values():
- provider = integration.integration_gateway.get_health_status_provider()
+ connector = integration.integration_gateway.get_connector()
+ if connector is None:
+ continue
+ provider = connector.get_health_status_provider()
if provider.get_provider_info().provider_id == provider_id:
return provider
continue
@@ -255,10 +258,10 @@ class IntegrationManager( Singleton ):
"""
Start the framework-level sync-check monitor (Issue #283). Singular
across all integrations: iterates enabled+unpaused integrations,
- gets each integration's synchronizer via gateway.get_synchronizer(),
+ gets each integration's connector via gateway.get_connector(),
and dispatches to its check_needs_sync. Sync-check rides on the
same opt-in surface as full sync — integrations without a
- synchronizer naturally opt out. Started after the per-integration
+ connector naturally opt out. Started after the per-integration
health monitors so the integration data map is already populated;
per-integration probe failures inside the cycle are caught
individually so a not-yet-ready integration cannot abort the cycle.
@@ -267,7 +270,7 @@ class IntegrationManager( Singleton ):
# monitor module imports IntegrationManager lazily inside its
# do_work, but the manager only needs the class here for
# construction.
- from .connect.monitors import IntegrationSyncCheckMonitor
+ from .connector.monitors import IntegrationSyncCheckMonitor
if settings.DEBUG and settings.SUPPRESS_MONITORS:
logger.debug( 'Skipping sync-check monitor. See SUPPRESS_MONITORS = True' )
@@ -315,7 +318,11 @@ class IntegrationManager( Singleton ):
logger.warning( f'Tried to start disabled integration monitor: {integration_id}' )
return
- monitor = integration_data.integration_gateway.get_monitor()
+ connector = integration_data.integration_gateway.get_connector()
+ if connector is None:
+ logger.debug( f'No connector for integration: {integration_id}' )
+ return
+ monitor = connector.get_monitor()
if not monitor:
logger.debug( f'No integration monitor defined: {integration_id}' )
return
@@ -485,6 +492,15 @@ class IntegrationManager( Singleton ):
un-pauses) cannot race with another caller. Callers can invoke
this unconditionally without first checking is_enabled, which
avoids a TOCTOU window between caller check and manager write.
+
+ Callers that just saved credentials must invoke
+ ``gateway.notify_settings_changed()`` themselves before calling
+ this method (or before any immediate downstream sync). The
+ post_save signal eventually delivers the same nudge via
+ DelayedSignalProcessor, but that 0.1s delay races synchronous
+ calls — and this method's monitor launch only fires on the
+ disabled→enabled transition, so it cannot be relied on for the
+ re-Configure path.
"""
with self._data_lock:
with transaction.atomic():
@@ -515,7 +531,7 @@ class IntegrationManager( Singleton ):
SAFE (default): delete entities without user-created data; preserve
entities with user-created data by detaching them from the
integration (via EntityIntegrationOperations.preserve_with_user_data).
- Preserved entities surface as "Detached from <integration>" in
+ Preserved entities surface as "From <integration>" in
the entity-detail UI and become candidates for the auto-reconnect
path on a subsequent re-Configure + sync.
@@ -542,15 +558,18 @@ class IntegrationManager( Singleton ):
# calls on every integration for the duration of a wide
# removal.
with transaction.atomic():
- # Seed: every entity attached to this integration. The
- # closure walk inside the helper picks up delegate
- # entities (e.g., Area entities auto-created when a
- # motion sensor was placed in a view) that would be
+ # Seed: every actively-attached (EXTERNAL) entity for
+ # this integration. Detached / imported rows
+ # (integration_id NULL, previous_integration_id set) are
+ # outside the disable scope — they belong to the user
+ # now. The closure walk inside the helper picks up
+ # delegate entities (e.g., Area entities auto-created
+ # when a motion sensor was placed in a view) that would be
# orphaned by the removal.
seed_entity_ids = list(
- Entity.objects
- .filter( integration_id = integration_id )
- .values_list( 'id', flat = True )
+ Entity.objects.external_for(
+ integration_id = integration_id,
+ ).values_list( 'id', flat = True )
)
EntityIntegrationOperations.remove_entities_with_closure(
seed_entity_ids = seed_entity_ids,
diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.py
index 5f2a5210..57d7293c 100644
--- a/src/hi/integrations/models.py
+++ b/src/hi/integrations/models.py
@@ -111,7 +111,7 @@ class IntegrationDetailsModel( models.Model ):
# The previous_integration_* fields record the integration identity
# an instance had at the moment it was disconnected (e.g., via
# sync-time preservation or Disable-SAFE). They drive the
- # auto-reconnect path in IntegrationSynchronizer: when an upstream
+ # auto-reconnect path in IntegrationConnector: when an upstream
# entity reappears whose key matches a disconnected entity's
# previous identity, the entity is reconnected rather than a
# duplicate being created. The previous_integration_id is indexed
@@ -154,7 +154,7 @@ class IntegrationDetailsModel( models.Model ):
# against future call sites that set integration_key
# without going through reconnect_disconnected_items: a
# stale previous_integration_* pair on an active entity
- # would mis-trigger the "Detached from" UI badge and
+ # would mis-trigger the "From X" UI badge and
# confuse any future query that filters disconnected
# entities by previous_integration_id alone.
self.previous_integration_id = None
diff --git a/src/hi/integrations/connect/placement_request.py b/src/hi/integrations/placement_request.py
similarity index 100%
rename from src/hi/integrations/connect/placement_request.py
rename to src/hi/integrations/placement_request.py
diff --git a/src/hi/integrations/templates/integrations/modals/integration_disable.html b/src/hi/integrations/templates/integrations/connector/modals/integration_disable.html
similarity index 100%
rename from src/hi/integrations/templates/integrations/modals/integration_disable.html
rename to src/hi/integrations/templates/integrations/connector/modals/integration_disable.html
diff --git a/src/hi/integrations/templates/integrations/modals/integration_enable.html b/src/hi/integrations/templates/integrations/connector/modals/integration_enable.html
similarity index 93%
rename from src/hi/integrations/templates/integrations/modals/integration_enable.html
rename to src/hi/integrations/templates/integrations/connector/modals/integration_enable.html
index 556d7895..53df3ed9 100644
--- a/src/hi/integrations/templates/integrations/modals/integration_enable.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/integration_enable.html
@@ -11,7 +11,7 @@
<div class="{{ DIVID.ATTR_V2_FORM_CLASS }}">
<form id="{{ attr_page_context.form_html_id }}"
- action="{% url 'integrations_enable' integration_id=integration_data.integration_id %}"
+ action="{% url 'integrations_connect_configure' integration_id=integration_data.integration_id %}"
method="post"
class="{{ DIVID.ATTR_V2_FORM_CLASS }} form"
enctype="multipart/form-data">
diff --git a/src/hi/integrations/templates/integrations/modals/integrations_select.html b/src/hi/integrations/templates/integrations/connector/modals/integrations_select.html
similarity index 94%
rename from src/hi/integrations/templates/integrations/modals/integrations_select.html
rename to src/hi/integrations/templates/integrations/connector/modals/integrations_select.html
index a037c70f..18b60cfa 100644
--- a/src/hi/integrations/templates/integrations/modals/integrations_select.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/integrations_select.html
@@ -40,7 +40,7 @@ All Integrations
{% icon "delete" size="sm" css_class="hi-icon-left" %}DISABLE
</a>
{% else %}
- <a href="{% url 'integrations_enable' integration_id=integration_data.integration.integration_id %}"
+ <a href="{% url 'integrations_connect_configure' integration_id=integration_data.integration.integration_id %}"
class="btn btn-primary btn-control" role="button" data-async="modal">
{% icon "settings" size="sm" css_class="hi-icon-left" %}CONFIGURE
</a>
diff --git a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html b/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html
similarity index 98%
rename from src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html
rename to src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html
index 29c1e8dd..ce301e50 100644
--- a/src/hi/integrations/templates/integrations/modals/pre_sync_confirm.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html
@@ -30,7 +30,7 @@ Context:
(initial CONNECT); False for subsequent
update-check operations.
sync_description : Optional[str] — per-integration text from
- IntegrationSynchronizer.get_description.
+ IntegrationConnector.get_description.
sync_url : str (required) — URL the form posts to.
removal_summary : Optional[IntegrationRemovalSummary] —
integration's user-data classification.
diff --git a/src/hi/integrations/templates/integrations/modals/sync_result.html b/src/hi/integrations/templates/integrations/connector/modals/sync_result.html
similarity index 98%
rename from src/hi/integrations/templates/integrations/modals/sync_result.html
rename to src/hi/integrations/templates/integrations/connector/modals/sync_result.html
index 46e40f2c..4a97b6fd 100644
--- a/src/hi/integrations/templates/integrations/modals/sync_result.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/sync_result.html
@@ -299,6 +299,6 @@
{% block action_right %}
{% if sync_result.created_list and placement_url %}
<a class="btn btn-primary" role="button"
- href="{{ placement_url }}" data-async="modal">Place {{ sync_result.created_list|length }} new item{{ sync_result.created_list|length|pluralize }} {% icon "chevron-right" size="sm" css_class="hi-icon-right" %}</a>
+ href="{{ placement_url }}" data-async="modal">Place new items {% icon "chevron-right" size="sm" css_class="hi-icon-right" %}</a>
{% endif %}
{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/pages/integration_manage.html b/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
similarity index 84%
rename from src/hi/integrations/templates/integrations/pages/integration_manage.html
rename to src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
index 77a84615..345f44cc 100644
--- a/src/hi/integrations/templates/integrations/pages/integration_manage.html
+++ b/src/hi/integrations/templates/integrations/connector/pages/integration_manage.html
@@ -13,7 +13,7 @@
</div>
{% for item in core.sidebar_items %}
<a class="nav-link hi-vertical-nav-link {% if core.integration_data.integration_id == item.integration_data.integration_id %}active{% endif %}"
- href="{% url 'integrations_manage' integration_id=item.integration_data.integration_id %}"
+ href="{% url 'integrations_connect_manage' integration_id=item.integration_data.integration_id %}"
data-async="true">
<div class="d-flex justify-content-between align-items-center">
<span class="d-flex align-items-center" style="white-space: nowrap;">
@@ -23,7 +23,7 @@
{{ item.integration_data.label }}
</span>
{% with health_status=item.integration_data.integration_gateway.get_health_status_provider.health_status %}
- {% include "integrations/panes/integration_status_indicator.html" with health_status=health_status is_paused=item.integration_data.integration.is_paused sync_check_result=item.sync_check_result %}
+ {% include "integrations/connector/panes/integration_status_indicator.html" with health_status=health_status is_paused=item.integration_data.integration.is_paused sync_check_result=item.sync_check_result %}
{% endwith %}
</div>
</a>
@@ -41,10 +41,7 @@
Framework-owned manage page header. Title/logo come from
integration metadata; lifecycle and sync actions are
rendered here unconditionally so individual integrations
- can't accidentally omit them. The per-integration
- template below is a content seam for any
- integration-specific custom UI; for current
- integrations it is empty.
+ can't accidentally omit them.
{% endcomment %}
<div class="d-flex justify-content-between">
<div class="h3 integration-title">
@@ -54,8 +51,8 @@
{{ core.integration_data.integration_metadata.label }}
</div>
<div class="d-flex align-items-center">
- {% include "integrations/panes/lifecycle_actions.html" %}
- {% include "integrations/panes/sync_actions.html" %}
+ {% include "integrations/connector/panes/lifecycle_actions.html" %}
+ {% include "integrations/connector/panes/sync_actions.html" %}
</div>
</div>
{% if core.sync_check_result and core.sync_check_result.needs_sync %}
@@ -67,12 +64,11 @@
data-async="modal">Update</a>.
</div>
{% endif %}
- {% include core.manage_view_template_name %}
</div>
<div class="{{ DIVID.ATTR_V2_FORM_CLASS }}">
<form id="{{ attr_item_context.form_html_id }}"
- action="{% url 'integrations_manage' integration_id=integration.integration_id %}"
+ action="{% url 'integrations_connect_manage' integration_id=integration.integration_id %}"
method="post"
class="{{ DIVID.ATTR_V2_FORM_CLASS }} form"
enctype="multipart/form-data">
diff --git a/src/hi/integrations/templates/integrations/pages/no_integrations.html b/src/hi/integrations/templates/integrations/connector/pages/no_integrations.html
similarity index 100%
rename from src/hi/integrations/templates/integrations/pages/no_integrations.html
rename to src/hi/integrations/templates/integrations/connector/pages/no_integrations.html
diff --git a/src/hi/integrations/templates/integrations/panes/integration_health_banner.html b/src/hi/integrations/templates/integrations/connector/panes/integration_health_banner.html
similarity index 100%
rename from src/hi/integrations/templates/integrations/panes/integration_health_banner.html
rename to src/hi/integrations/templates/integrations/connector/panes/integration_health_banner.html
diff --git a/src/hi/integrations/templates/integrations/panes/integration_status_indicator.html b/src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html
similarity index 100%
rename from src/hi/integrations/templates/integrations/panes/integration_status_indicator.html
rename to src/hi/integrations/templates/integrations/connector/panes/integration_status_indicator.html
diff --git a/src/hi/integrations/templates/integrations/panes/lifecycle_actions.html b/src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html
similarity index 100%
rename from src/hi/integrations/templates/integrations/panes/lifecycle_actions.html
rename to src/hi/integrations/templates/integrations/connector/panes/lifecycle_actions.html
diff --git a/src/hi/integrations/templates/integrations/panes/sync_actions.html b/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html
similarity index 88%
rename from src/hi/integrations/templates/integrations/panes/sync_actions.html
rename to src/hi/integrations/templates/integrations/connector/panes/sync_actions.html
index d385890a..9af77fbd 100644
--- a/src/hi/integrations/templates/integrations/panes/sync_actions.html
+++ b/src/hi/integrations/templates/integrations/connector/panes/sync_actions.html
@@ -3,9 +3,9 @@
Shared CONNECT / UPDATE framework action.
Sync is a framework concern; integrations participate by providing an
- IntegrationSynchronizer from their gateway's get_synchronizer().
+ IntegrationConnector from their gateway's get_connector().
Rendering is conditional on (a) the integration being enabled and
- (b) the gateway returning a synchronizer. Integrations whose gateway
+ (b) the gateway returning a connector. Integrations whose gateway
returns None (sync is opt-in) get no button.
Label flips on `core.has_entities`: CONNECT for the first-time path,
@@ -18,7 +18,7 @@
the eye. The CONNECT variant is always primary since there is
nothing to compare against on a first run.
{% endcomment %}
-{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_synchronizer %}
+{% if core.integration_data.is_enabled and core.integration_data.integration_gateway.get_connector %}
<a href="{% url 'integrations_pre_sync' integration_id=core.integration_data.integration_id %}"
class="btn {% if core.has_entities %}{% if core.sync_check_result.needs_sync %}btn-primary{% else %}btn-outline-secondary{% endif %}{% else %}btn-outline-primary{% endif %}"
role="button"
diff --git a/src/hi/integrations/templates/integrations/importer/modals/data_import_info.html b/src/hi/integrations/templates/integrations/importer/modals/data_import_info.html
new file mode 100644
index 00000000..4e32ef8e
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/importer/modals/data_import_info.html
@@ -0,0 +1,25 @@
+{% extends "modals/action_done.html" %}
+
+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+
+{% block title_text %}
+Data Import vs. Integration
+{% endblock %}
+
+{% block body %}
+<p>
+ <strong>Data Import</strong> is a one-time copy of items from an
+ upstream system into Home Information. Once imported, the items
+ are HI-owned: you can edit them freely, and they no longer depend
+ on the upstream source.
+</p>
+<p>
+ An <a href="{% url 'integrations_connect_home' %}">Integration</a>, in
+ contrast, mirrors the upstream system live — the upstream
+ remains the source of truth, and changes flow in via Update.
+</p>
+<p>
+ An integration may offer both modes (HomeBox today), but only
+ one mode's data should be active at a time for a given upstream.
+</p>
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/importer/modals/import_discard_confirm.html b/src/hi/integrations/templates/integrations/importer/modals/import_discard_confirm.html
new file mode 100644
index 00000000..42464e30
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/importer/modals/import_discard_confirm.html
@@ -0,0 +1,46 @@
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
+
+{% block header_class %}bg-secondary{% endblock %}
+
+{% block preamble %}
+<form action="{% url 'integrations_import_discard' integration_id=integration_data.integration_id %}"
+ method="post"
+ class="form" data-async="modal">
+ {% csrf_token %}
+{% endblock %}
+
+{% block title_text %}
+{{ integration_data.label }}
+{% endblock %}
+
+{% block body %}
+<h4>Discard imported {{ integration_data.label }} items?</h4>
+
+{% if imported_count == 0 %}
+<p>No imported items to discard.</p>
+{% else %}
+<p>
+ This will delete <strong>{{ imported_count }}</strong>
+ {% if imported_count == 1 %}item{% else %}items{% endif %}
+ previously imported from {{ integration_data.label }},
+ along with their custom data and attached files.
+</p>
+<p class="text-muted small">
+ This cannot be undone. To bring these items back, you'd need to
+ re-import from {{ integration_data.label }}.
+</p>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+{% if imported_count > 0 %}
+<button type="submit" class="btn btn-danger">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DISCARD
+</button>
+{% endif %}
+{% endblock %}
+
+{% block postamble %}
+</form>
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/importer/modals/import_preview.html b/src/hi/integrations/templates/integrations/importer/modals/import_preview.html
new file mode 100644
index 00000000..a0d2da6e
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/importer/modals/import_preview.html
@@ -0,0 +1,76 @@
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
+
+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+
+{% block title_text %}
+{% if not error_message and new_count > 0 %}
+Import from {{ integration_data.label }}?
+{% else %}
+{{ integration_data.label }} Import
+{% endif %}
+{% endblock %}
+
+{% block body %}
+{% if error_message %}
+<div class="alert alert-warning">{{ error_message }}</div>
+{% elif new_count == 0 %}
+{% if skipped_count > 0 %}
+<p>
+ No new items to import. All
+ {% if skipped_count == 1 %}
+ <strong>1</strong> upstream item has
+ {% else %}
+ <strong>{{ skipped_count }}</strong> upstream items have
+ {% endif %}
+ already been imported.
+</p>
+{% else %}
+<p>No items found to import.</p>
+{% endif %}
+{% else %}
+<p>
+ Would import <strong>{{ new_count }}</strong>
+ {% if new_count == 1 %}new item{% else %}new items{% endif %}.
+ {% if skipped_count > 0 %}
+ <strong>{{ skipped_count }}</strong>
+ {% if skipped_count == 1 %}existing item{% else %}existing items{% endif %}
+ would be skipped.
+ {% endif %}
+</p>
+<p class="text-muted small">
+ Imported items become HI-owned and editable. The upstream source is
+ no longer consulted after import.
+</p>
+{% endif %}
+
+{% if existing_imported_count > 0 and not error_message %}
+<p class="text-muted small">
+ Currently <strong>{{ existing_imported_count }}</strong>
+ {% if existing_imported_count == 1 %}item{% else %}items{% endif %}
+ imported from {{ integration_data.label }}.
+</p>
+{% endif %}
+{% endblock %}
+
+{% block action_left %}
+{% if error_message or new_count > 0 %}{{ block.super }}{% endif %}
+{% endblock %}
+
+{% block action_center %}
+{% if not error_message and new_count == 0 %}
+<a role="button" autofocus="autofocus" class="btn btn-primary"
+ href="#" data-dismiss="modal">DONE</a>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+{% if not error_message and new_count > 0 %}
+<form action="{{ run_url }}" method="post" class="d-inline" data-async="modal">
+ {% csrf_token %}
+ <button type="submit" class="btn btn-primary">
+ {% icon "upload" size="lg" css_class="hi-icon-left" %}CONFIRM IMPORT
+ </button>
+</form>
+{% endif %}
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/importer/modals/import_result.html b/src/hi/integrations/templates/integrations/importer/modals/import_result.html
new file mode 100644
index 00000000..55408ad3
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/importer/modals/import_result.html
@@ -0,0 +1,119 @@
+{% extends "modals/action_3.html" %}
+{% load icons static %}
+
+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+
+{% block title_text %}
+{{ result.title }}
+{% endblock %}
+
+{% block body %}
+<div class="d-flex align-items-center mb-3 pb-2 border-bottom">
+ <img class="mr-2 hi-integration-logo"
+ src="{% static integration_data.integration_metadata.logo_static_path %}"
+ alt="{{ integration_data.label }} Logo">
+ <div class="text-muted small text-uppercase hi-uppercase-label">
+ {{ integration_data.label }}
+ </div>
+</div>
+
+{% if result.error_list and not result.has_imports %}
+ <div class="text-center mb-4">
+ <div class="text-danger mb-1 hi-sync-result-hero-icon">&#x26A0;</div>
+ <h3 class="text-danger mb-1">Import failed</h3>
+ <div class="text-muted small">
+ {{ result.error_list|length }} error{{ result.error_list|length|pluralize }} — see details below.
+ </div>
+ </div>
+{% elif not result.has_imports %}
+ <div class="text-center mb-4">
+ <div class="text-muted mb-1 hi-sync-result-hero-icon">&#x2014;</div>
+ <h3 class="text-muted mb-1">Nothing imported</h3>
+ <div class="text-muted small">
+ {% if result.items_skipped_count > 0 %}
+ All {{ result.items_skipped_count }} upstream item{{ result.items_skipped_count|pluralize }}
+ already exist in HI.
+ {% else %}
+ The upstream source returned no items to import.
+ {% endif %}
+ </div>
+ </div>
+{% else %}
+ <div class="text-center mb-3">
+ <div class="text-success mb-1 hi-sync-result-hero-icon">&#x2713;</div>
+ <h3 class="text-success mb-1">Import complete</h3>
+ </div>
+
+ <div class="d-flex justify-content-around flex-wrap text-center mb-4 pb-3 border-bottom">
+ <div class="px-3">
+ <div class="text-success font-weight-bold hi-sync-result-stat-number">
+ {{ result.items_imported_count }}
+ </div>
+ <div class="text-muted small text-uppercase hi-uppercase-label">Imported</div>
+ </div>
+ {% if result.items_skipped_count > 0 %}
+ <div class="px-3">
+ <div class="text-muted font-weight-bold hi-sync-result-stat-number">
+ {{ result.items_skipped_count }}
+ </div>
+ <div class="text-muted small text-uppercase hi-uppercase-label">Skipped</div>
+ </div>
+ {% endif %}
+ </div>
+
+ {% if result.imported_list %}
+ <div class="mb-3 pl-3 hi-category-section hi-category-section--success">
+ <div class="small text-success text-uppercase mb-1 hi-uppercase-label">
+ Imported ({{ result.imported_list|length }})
+ </div>
+ <ul class="list-unstyled small mb-0 hi-sync-result-item-list">
+ {% for name in result.imported_list %}
+ <li>{{ name }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+ {% endif %}
+{% endif %}
+
+{% if result.error_list %}
+<div class="mb-2 pl-3 hi-category-section hi-category-section--danger">
+ <a class="small text-danger text-uppercase hi-uppercase-label" data-toggle="collapse"
+ href="#hi-import-result-errors" role="button"
+ aria-expanded="true" aria-controls="hi-import-result-errors">
+ Errors ({{ result.error_list|length }})
+ </a>
+ <div class="collapse show" id="hi-import-result-errors">
+ <ul class="list-unstyled small mt-1 mb-0">
+ {% for error_message in result.error_list %}
+ <li class="text-danger">{{ error_message }}</li>
+ {% endfor %}
+ </ul>
+ </div>
+</div>
+{% endif %}
+{% endblock %}
+
+{% block action_left %}
+{% if result.has_imports and placement_url %}
+<a id="hi-modal-cancel" role="button"
+ class="btn btn-outline-tertiary"
+ href="#"
+ onclick="location.reload(); return false;">{% icon "close" size="sm" css_class="hi-icon-left" %}Place Later</a>
+{% endif %}
+{% endblock %}
+
+{% block action_center %}
+{% if not result.has_imports or not placement_url %}
+<a id="hi-modal-ok" role="button"
+ class="btn btn-primary"
+ href="#"
+ onclick="location.reload(); return false;">OK</a>
+{% endif %}
+{% endblock %}
+
+{% block action_right %}
+{% if result.has_imports and placement_url %}
+<a class="btn btn-primary" role="button"
+ href="{{ placement_url }}" data-async="modal">Place new items {% icon "chevron-right" size="sm" css_class="hi-icon-right" %}</a>
+{% endif %}
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/importer/modals/importer_configure.html b/src/hi/integrations/templates/integrations/importer/modals/importer_configure.html
new file mode 100644
index 00000000..688bdb92
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/importer/modals/importer_configure.html
@@ -0,0 +1,42 @@
+{% extends "modals/base.html" %}
+{% load icons %}
+
+{% block modal_dialog_class %}hi-modal-dialog-600{% endblock %}
+{% block title_text %}Import from {{ integration_data.label }}{% endblock %}
+
+{% block body %}
+<div id="{{ attr_page_context.container_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTAINER_CLASS }}">
+
+ <div class="{{ DIVID.ATTR_V2_FORM_CLASS }}">
+ <form id="{{ attr_page_context.form_html_id }}"
+ action="{% url 'integrations_import_configure' integration_id=integration_data.integration_id %}"
+ method="post"
+ class="{{ DIVID.ATTR_V2_FORM_CLASS }} form"
+ enctype="multipart/form-data">
+ {% csrf_token %}
+
+ <div id="{{ attr_page_context.content_html_id }}"
+ class="{{ DIVID.ATTR_V2_CONTENT_CLASS }}">
+ {% include "integrations/panes/integration_edit_content_body.html" with show_modal_cancel=True %}
+ </div>
+ </form>
+ </div>
+
+ {% if messages %}
+ <div class="{{ DIVID.ATTR_V2_MESSAGES }}" id="{{ DIVID.ATTR_V2_MESSAGES }}">
+ {% for message in messages %}
+ <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
+ {{ message }}
+ <button type="button" class="close" data-dismiss="alert" aria-label="Close">
+ <span aria-hidden="true">&times;</span>
+ </button>
+ </div>
+ {% endfor %}
+ </div>
+ {% endif %}
+</div>
+{% endblock %}
+
+{% block footer %}
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/importer/pages/data_import_page.html b/src/hi/integrations/templates/integrations/importer/pages/data_import_page.html
new file mode 100644
index 00000000..fec9250b
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/importer/pages/data_import_page.html
@@ -0,0 +1,52 @@
+{% extends "config/pages/config_base.html" %}
+{% load icons static %}
+
+{% block config_content %}
+<div class="container py-3">
+
+ <h2 class="mb-3">Data Import</h2>
+
+ <div class="row">
+ {% for row in rows %}
+ <div class="col-12 col-sm-6 col-md-4 col-lg-3 mb-3">
+ <div class="card h-100 text-center">
+ <div class="card-body d-flex flex-column">
+ <img src="{% static row.integration_data.integration_metadata.logo_static_path %}"
+ alt="{{ row.integration_data.integration_metadata.label }}"
+ class="img-fluid hi-integration-logo--card mx-auto mb-3">
+ <h5 class="card-title mb-1">{{ row.integration_data.integration_metadata.label }}</h5>
+ {% if row.is_dual_capability %}
+ <a href="{% url 'integrations_import_info' %}"
+ data-async="modal"
+ title="What's the difference?"
+ class="d-block text-muted small text-decoration-none mb-3">
+ Also available as an Integration.
+ {% icon "info-circle" size="sm" %}
+ </a>
+ {% endif %}
+ <div class="mt-auto pt-2">
+ <a href="{% url 'integrations_import_configure' integration_id=row.integration_data.integration_id %}"
+ class="btn btn-primary btn-block" role="button" data-async="modal">
+ {% icon "settings" size="sm" css_class="hi-icon-left" %}CONFIGURE
+ </a>
+ {% if row.has_imported %}
+ <a href="{% url 'integrations_import_discard' integration_id=row.integration_data.integration_id %}"
+ role="button" class="btn btn-outline-danger btn-block mt-2" data-async="modal">
+ {% icon "delete" size="sm" css_class="hi-icon-left" %}DISCARD
+ </a>
+ {% endif %}
+ </div>
+ </div>
+ </div>
+ </div>
+ {% empty %}
+ <div class="col-12">
+ <div class="alert alert-info">
+ No integrations support Data Import.
+ </div>
+ </div>
+ {% endfor %}
+ </div>
+
+</div>
+{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/capability_blocked.html b/src/hi/integrations/templates/integrations/modals/capability_blocked.html
new file mode 100644
index 00000000..dbb7989d
--- /dev/null
+++ b/src/hi/integrations/templates/integrations/modals/capability_blocked.html
@@ -0,0 +1,25 @@
+{% extends "modals/action_2_with_cancel.html" %}
+{% load icons %}
+
+{% block header_class %}bg-secondary{% endblock %}
+
+{% block title_text %}
+{{ integration_data.label }}
+{% endblock %}
+
+{% block body %}
+<h5 class="mb-3">Cannot configure as {{ my_label }}.</h5>
+<p>
+ {{ integration_data.label }} {{ existing_mode_clause }}
+ <strong>{{ existing_count }}</strong>
+ {% if existing_count == 1 %}item{% else %}items{% endif %}.
+ To {{ desired_action_clause }}, first {{ remediation_clause }}.
+</p>
+{% endblock %}
+
+{% block action_right %}
+<a class="btn btn-primary" role="button"
+ href="{{ link_url }}" data-async="page">
+ {% icon "chevron-right" size="sm" css_class="hi-icon-left" %}{{ link_label }}
+</a>
+{% endblock %}
diff --git a/src/hi/integrations/templatetags/integration_tags.py b/src/hi/integrations/templatetags/integration_tags.py
index 02679df6..8b4b3887 100644
--- a/src/hi/integrations/templatetags/integration_tags.py
+++ b/src/hi/integrations/templatetags/integration_tags.py
@@ -48,9 +48,10 @@ def integration_logo_path( model : IntegrationDetailsModel ) -> str:
@register.simple_tag
def previous_integration_display_name( model : IntegrationDetailsModel ) -> str:
"""The label of the integration this entity was previously
- attached to (i.e., the source of the "Detached from ..." badge).
- Returns None when the entity is not detached, or when the prior
- integration has since been removed from the system."""
+ attached to (i.e., the source of the "From ..." badge).
+ Returns None when the entity carries no integration provenance,
+ or when the prior integration has since been removed from the
+ system."""
metadata = _get_previous_integration_metadata( model )
return metadata.label if metadata else None
@@ -58,13 +59,13 @@ def previous_integration_display_name( model : IntegrationDetailsModel ) -> str:
@register.simple_tag
def previous_integration_logo_path( model : IntegrationDetailsModel ) -> str:
"""Logo for the integration the entity was previously attached
- to. Used in the entity-detail UI to show the "Detached from ..."
- badge alongside the same logo the integration uses when active."""
+ to. Used in the entity-detail UI to show the "From ..." badge
+ alongside the same logo the integration uses when active."""
metadata = _get_previous_integration_metadata( model )
return metadata.logo_static_path if metadata else ''
[email protected]_tag( 'integrations/panes/integration_health_banner.html' )
[email protected]_tag( 'integrations/connector/panes/integration_health_banner.html' )
def integration_health_banner( integration_id : str, context_message : str = None ):
"""Render a banner when the integration is in a non-healthy state.
@@ -81,7 +82,10 @@ def integration_health_banner( integration_id : str, context_message : str = Non
return { 'health_status': None }
try:
gateway = IntegrationManager().get_integration_gateway( integration_id )
- provider = gateway.get_health_status_provider()
+ connector = gateway.get_connector()
+ if connector is None:
+ return { 'health_status': None }
+ provider = connector.get_health_status_provider()
health_status = provider.health_status
metadata = gateway.get_metadata()
except Exception:
diff --git a/src/hi/integrations/tests/test_entity_operations.py b/src/hi/integrations/tests/test_entity_operations.py
index e3f6d168..14069767 100644
--- a/src/hi/integrations/tests/test_entity_operations.py
+++ b/src/hi/integrations/tests/test_entity_operations.py
@@ -3,7 +3,7 @@ Unit tests for EntityIntegrationOperations.
Only covers behavior that encodes real classification / transformation /
graph-traversal logic. The preserve_with_user_data path is already tested
-indirectly via test_integration_synchronizer (which exercises
+indirectly via test_integration_connector (which exercises
_remove_entity_intelligently).
"""
@@ -15,7 +15,7 @@ from hi.apps.attribute.enums import AttributeType, AttributeValueType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState, EntityStateDelegation
from hi.apps.event.models import EventClause, EventDefinition
from hi.apps.sense.models import Sensor
-from hi.integrations.connect.entity_operations import EntityIntegrationOperations
+from hi.integrations.entity_operations import EntityIntegrationOperations
logging.disable(logging.CRITICAL)
@@ -388,7 +388,7 @@ class FindReconnectCandidatesTests(TestCase):
)
upstream_key = self._make_upstream_key('light.kitchen')
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
result = IntegrationSyncResult(title='Test')
candidates = EntityIntegrationOperations.find_reconnect_candidates(
@@ -424,7 +424,7 @@ class FindReconnectCandidatesTests(TestCase):
ambiguous_key = self._make_upstream_key('light.ambiguous')
unmatched_key = self._make_upstream_key('light.never_existed')
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
result = IntegrationSyncResult(title='Mixed')
candidates = EntityIntegrationOperations.find_reconnect_candidates(
diff --git a/src/hi/integrations/tests/test_external_view_data.py b/src/hi/integrations/tests/test_external_view_data.py
index 1e6ce79c..99327624 100644
--- a/src/hi/integrations/tests/test_external_view_data.py
+++ b/src/hi/integrations/tests/test_external_view_data.py
@@ -11,23 +11,23 @@ import logging
from django.test import TestCase
-from hi.integrations.connect.external_view_data import (
+from hi.integrations.connector.external_view_data import (
AttachmentRef,
CustomTemplateViewData,
MinimalViewData,
NameValuePair,
StructuredViewData,
)
-from hi.integrations.connect.integration_gateway import IntegrationGateway
+from hi.integrations.connector.integration_connector import IntegrationConnector
logging.disable(logging.CRITICAL)
-class IntegrationGatewayExternalViewDataDefaultTests(TestCase):
+class IntegrationConnectorExternalViewDataDefaultTests(TestCase):
def test_get_external_view_data_defaults_to_none(self):
- gateway = IntegrationGateway()
- self.assertIsNone(gateway.get_external_view_data(entity=None))
+ connector = IntegrationConnector()
+ self.assertIsNone(connector.get_external_view_data(entity=None))
class ExternalViewDataDefaultTemplateNameTests(TestCase):
diff --git a/src/hi/integrations/tests/test_importer.py b/src/hi/integrations/tests/test_importer.py
new file mode 100644
index 00000000..0bb9e638
--- /dev/null
+++ b/src/hi/integrations/tests/test_importer.py
@@ -0,0 +1,62 @@
+"""
+Unit tests for the IntegrationImporter protocol scaffolding (Phase 2 of #358).
+"""
+
+import logging
+
+from django.test import SimpleTestCase
+
+from hi.integrations.importer.integration_importer import IntegrationImporter
+from hi.integrations.importer.transient_models import (
+ CandidateItem,
+ IntegrationDiscardResult,
+ IntegrationImportResult,
+)
+
+logging.disable(logging.CRITICAL)
+
+
+class ImporterBaseClassTests(SimpleTestCase):
+
+ def test_protocol_methods_raise_not_implemented(self):
+ importer = IntegrationImporter()
+ with self.assertRaises(NotImplementedError):
+ importer.get_metadata()
+ with self.assertRaises(NotImplementedError):
+ importer.validate_configuration([])
+ with self.assertRaises(NotImplementedError):
+ importer.get_candidate_items()
+ with self.assertRaises(NotImplementedError):
+ importer.run_import()
+ with self.assertRaises(NotImplementedError):
+ importer.discard_imported_data('test')
+
+
+class ImportTransientModelsTests(SimpleTestCase):
+
+ def test_candidate_item(self):
+ item = CandidateItem(name='Item One', integration_name='item-1')
+ self.assertEqual(item.name, 'Item One')
+ self.assertEqual(item.integration_name, 'item-1')
+
+ def test_discard_result_defaults(self):
+ result = IntegrationDiscardResult()
+ self.assertEqual(result.count, 0)
+ self.assertEqual(result.errors, [])
+
+ def test_import_result_has_imports_property(self):
+ empty = IntegrationImportResult(title='Empty')
+ self.assertFalse(empty.has_imports)
+ with_imports = IntegrationImportResult(
+ title='With Imports',
+ items_imported_count=3,
+ )
+ self.assertTrue(with_imports.has_imports)
+
+
+class IntegrationGatewayImporterDefaultTests(SimpleTestCase):
+
+ def test_default_returns_none(self):
+ from hi.integrations.integration_gateway import IntegrationGateway
+ gateway = IntegrationGateway()
+ self.assertIsNone(gateway.get_importer())
diff --git a/src/hi/integrations/tests/test_importer_views.py b/src/hi/integrations/tests/test_importer_views.py
new file mode 100644
index 00000000..6f8cd07d
--- /dev/null
+++ b/src/hi/integrations/tests/test_importer_views.py
@@ -0,0 +1,392 @@
+"""View tests for the Data Import page and the Configure form."""
+import logging
+from unittest.mock import patch
+
+from django.test import TestCase
+from django.urls import reverse
+
+from hi.apps.attribute.enums import AttributeValueType
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity
+from hi.integrations.enums import IntegrationAttributeType, IntegrationCapability
+from hi.integrations.importer.integration_importer import IntegrationImporter
+from hi.integrations.importer.transient_models import (
+ CandidateItem,
+ IntegrationDiscardResult,
+ IntegrationImportResult,
+)
+from hi.apps.entity.entity_placement import (
+ EntityPlacementInput,
+ EntityPlacementItem,
+)
+from hi.integrations.integration_data import IntegrationData
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.integration_manager import IntegrationManager
+from hi.integrations.models import Integration
+from hi.integrations.transient_models import (
+ ConnectionTestResult,
+ IntegrationMetaData,
+ IntegrationValidationResult,
+)
+
+logging.disable(logging.CRITICAL)
+
+
+class _ImportTestAttributeType(IntegrationAttributeType):
+ TEST_ATTR = (
+ 'Test Attribute', '',
+ AttributeValueType.TEXT, {}, True, True, 'default',
+ )
+
+
+class _ImportCapableGateway(IntegrationGateway):
+ """Gateway that supports IMPORT (with optional CONNECT too)."""
+
+ def __init__(self, integration_id='hb', capabilities=None, candidates=None):
+ self.integration_id = integration_id
+ self._capabilities = (
+ capabilities if capabilities is not None
+ else frozenset({ IntegrationCapability.IMPORT })
+ )
+ self._candidates = candidates or []
+
+ def get_metadata(self):
+ return IntegrationMetaData(
+ integration_id=self.integration_id,
+ label='Import Test',
+ attribute_type=_ImportTestAttributeType,
+ allow_entity_deletion=True,
+ capabilities=self._capabilities,
+ )
+
+ def validate_configuration(self, integration_attributes):
+ return IntegrationValidationResult.success()
+
+ def validate_access(self, integration_attributes, timeout_secs):
+ return ConnectionTestResult.success()
+
+ def get_importer(self) -> IntegrationImporter:
+ importer = IntegrationImporter()
+ importer.get_candidate_items = lambda: list(self._candidates)
+
+ # Real DISCARD semantics: delete imported (provenance-carrying)
+ # rows for this integration_id. Mirrors HomeBoxImporter for
+ # test purposes.
+ def _stub_discard(integration_id):
+ qs = Entity.objects.imported_for(integration_id=integration_id)
+ count = qs.count()
+ qs.delete()
+ return IntegrationDiscardResult(count=count)
+ importer.discard_imported_data = _stub_discard
+ return importer
+
+
+class _ConnectOnlyGateway(IntegrationGateway):
+ """Gateway that does NOT declare IMPORT (Connect-only). Should not
+ appear on the Data Import page."""
+
+ def __init__(self, integration_id='hass'):
+ self.integration_id = integration_id
+
+ def get_metadata(self):
+ return IntegrationMetaData(
+ integration_id=self.integration_id,
+ label='Connect Only Test',
+ attribute_type=_ImportTestAttributeType,
+ allow_entity_deletion=True,
+ capabilities=frozenset({ IntegrationCapability.CONNECT }),
+ )
+
+
+def _populate_manager(integration_ids_and_gateways):
+ manager = IntegrationManager()
+ manager._integration_data_map = {}
+ for integration_id, gateway in integration_ids_and_gateways:
+ integration, _ = Integration.objects.get_or_create(
+ integration_id=integration_id,
+ defaults={'is_enabled': False},
+ )
+ manager._integration_data_map[integration_id] = IntegrationData(
+ integration_gateway=gateway,
+ integration=integration,
+ )
+
+
+class DataImportPageViewTests(TestCase):
+
+ def setUp(self):
+ IntegrationManager()._instances = {}
+ IntegrationManager._initialized_instance = None
+
+ def test_lists_only_import_capable_integrations(self):
+ _populate_manager([
+ ('hb', _ImportCapableGateway('hb')),
+ ('hass', _ConnectOnlyGateway('hass')),
+ ])
+ response = self.client.get(reverse('integrations_import_home'))
+ self.assertEqual(response.status_code, 200)
+ body = response.content.decode()
+ self.assertIn('Import Test', body)
+ self.assertNotIn('Connect Only Test', body)
+
+ def test_discard_renders_only_when_imported_entities_exist(self):
+ _populate_manager([
+ ('hb', _ImportCapableGateway('hb')),
+ ])
+ response_no_imports = self.client.get(reverse('integrations_import_home'))
+ self.assertNotIn(
+ reverse('integrations_import_discard', kwargs={'integration_id': 'hb'}),
+ response_no_imports.content.decode(),
+ )
+
+ Entity.objects.create(
+ previous_integration_id='hb',
+ previous_integration_name='item-1',
+ name='Imported',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ response_with_imports = self.client.get(reverse('integrations_import_home'))
+ self.assertIn(
+ reverse('integrations_import_discard', kwargs={'integration_id': 'hb'}),
+ response_with_imports.content.decode(),
+ )
+
+ def test_dual_capability_row_shows_integration_note(self):
+ _populate_manager([
+ ('hb', _ImportCapableGateway(
+ 'hb',
+ capabilities=frozenset({
+ IntegrationCapability.CONNECT,
+ IntegrationCapability.IMPORT,
+ }),
+ )),
+ ])
+ response = self.client.get(reverse('integrations_import_home'))
+ self.assertIn('Also available as an', response.content.decode())
+
+
+class ImporterConfigureViewTests(TestCase):
+
+ INTEGRATION_ID = 'hb'
+
+ def setUp(self):
+ IntegrationManager()._instances = {}
+ IntegrationManager._initialized_instance = None
+
+ def _url(self):
+ return reverse(
+ 'integrations_import_configure',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_get_renders_form_with_import_button(self):
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(self.INTEGRATION_ID)),
+ ])
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, 200)
+ body = response.content.decode()
+ self.assertIn('Import Test', body)
+ # The form's submit button label is IMPORT.
+ self.assertIn('>\n IMPORT\n </button>', body)
+
+ def test_post_run_renders_result_modal_with_placement_cta(self):
+ # Stub importer that returns a result with a placement_input
+ # pointing at a freshly-created entity.
+ entity = Entity.objects.create(
+ previous_integration_id=self.INTEGRATION_ID,
+ previous_integration_name='item-fresh',
+ name='Fresh Item',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ gateway = _ImportCapableGateway(self.INTEGRATION_ID)
+ stub_importer = IntegrationImporter()
+ stub_importer.run_import = lambda: IntegrationImportResult(
+ title='Import Result',
+ items_imported_count=1,
+ imported_list=['Fresh Item'],
+ placement_input=EntityPlacementInput(
+ ungrouped_items=[
+ EntityPlacementItem(
+ key=f'entity:{entity.id}',
+ label=entity.name,
+ entity=entity,
+ ),
+ ],
+ ),
+ )
+ gateway.get_importer = lambda: stub_importer
+ _populate_manager([(self.INTEGRATION_ID, gateway)])
+
+ response = self.client.post(reverse(
+ 'integrations_import_run',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ ))
+
+ self.assertEqual(response.status_code, 200)
+ body = response.content.decode()
+ self.assertIn('Import complete', body)
+ self.assertIn('Fresh Item', body)
+ # Placement CTA renders the placement URL.
+ self.assertIn('Place new items', body)
+ self.assertIn('placement', body)
+
+ _DUAL_CAPS = frozenset({
+ IntegrationCapability.CONNECT,
+ IntegrationCapability.IMPORT,
+ })
+
+ def test_get_import_blocked_by_existing_connect_data(self):
+ # Dual-capability integration with existing Connect-mode
+ # (EXTERNAL) entities and no Import-mode entities: opening
+ # Import-side CONFIGURE returns the block modal pointing at
+ # the Integrations tab.
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(
+ self.INTEGRATION_ID,
+ capabilities=self._DUAL_CAPS,
+ )),
+ ])
+ Entity.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ integration_name='connected-1',
+ name='Connected',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ response = self.client.get(self._url())
+ body = response.content.decode()
+ self.assertIn('Cannot configure', body)
+ self.assertIn('GO TO INTEGRATIONS', body)
+ self.assertIn(reverse('integrations_connect_home'), body)
+
+ def test_get_import_not_blocked_for_single_capability_integration(self):
+ # Hypothetical Import-only integration (no CONNECT): block
+ # never fires even with EXTERNAL entities laying around.
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(
+ self.INTEGRATION_ID,
+ capabilities=frozenset({ IntegrationCapability.IMPORT }),
+ )),
+ ])
+ Entity.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ integration_name='stale-external',
+ name='Stale',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ response = self.client.get(self._url())
+ body = response.content.decode()
+ self.assertNotIn('Cannot configure', body)
+
+ def _discard_url(self):
+ return reverse(
+ 'integrations_import_discard',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ )
+
+ def test_get_discard_renders_confirm_with_count(self):
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(self.INTEGRATION_ID)),
+ ])
+ for i in range(3):
+ Entity.objects.create(
+ previous_integration_id=self.INTEGRATION_ID,
+ previous_integration_name=f'item-{i}',
+ name=f'Item {i}',
+ entity_type_str=str(EntityType.OTHER),
+ )
+
+ response = self.client.get(self._discard_url())
+ self.assertEqual(response.status_code, 200)
+ body = response.content.decode()
+ self.assertIn('Discard imported', body)
+ # Count appears in the body.
+ self.assertIn('3', body)
+ self.assertIn('DISCARD', body)
+
+ def test_get_discard_with_zero_imported_hides_action(self):
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(self.INTEGRATION_ID)),
+ ])
+ response = self.client.get(self._discard_url())
+ body = response.content.decode()
+ self.assertIn('No imported items to discard', body)
+
+ def test_post_discard_deletes_imported_and_leaves_connect_alone(self):
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(self.INTEGRATION_ID)),
+ ])
+ Entity.objects.create(
+ previous_integration_id=self.INTEGRATION_ID,
+ previous_integration_name='imported-1',
+ name='Imported',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ Entity.objects.create(
+ integration_id=self.INTEGRATION_ID,
+ integration_name='connected-1',
+ name='Connected',
+ entity_type_str=str(EntityType.OTHER),
+ )
+
+ response = self.client.post(self._discard_url(), {})
+
+ self.assertTrue(200 <= response.status_code < 400)
+ self.assertFalse(
+ Entity.objects.filter(previous_integration_name='imported-1').exists()
+ )
+ self.assertTrue(
+ Entity.objects.filter(integration_name='connected-1').exists()
+ )
+
+ def test_post_run_renders_nothing_imported_when_all_skipped(self):
+ gateway = _ImportCapableGateway(self.INTEGRATION_ID)
+ stub_importer = IntegrationImporter()
+ stub_importer.run_import = lambda: IntegrationImportResult(
+ title='Import Result',
+ items_imported_count=0,
+ items_skipped_count=3,
+ )
+ gateway.get_importer = lambda: stub_importer
+ _populate_manager([(self.INTEGRATION_ID, gateway)])
+
+ response = self.client.post(reverse(
+ 'integrations_import_run',
+ kwargs={'integration_id': self.INTEGRATION_ID},
+ ))
+ body = response.content.decode()
+ self.assertIn('Nothing imported', body)
+ self.assertNotIn('Place ', body)
+
+ def test_post_with_valid_attrs_renders_preview_with_counts(self):
+ candidates = [
+ CandidateItem(name='Item One', integration_name='item-1'),
+ CandidateItem(name='Item Two', integration_name='item-2'),
+ ]
+ _populate_manager([
+ (self.INTEGRATION_ID, _ImportCapableGateway(
+ self.INTEGRATION_ID,
+ candidates=candidates,
+ )),
+ ])
+ # Pre-existing entity for item-2 so the preview counts skip=1, new=1.
+ Entity.objects.create(
+ previous_integration_id=self.INTEGRATION_ID,
+ previous_integration_name='item-2',
+ name='Already',
+ entity_type_str=str(EntityType.OTHER),
+ )
+
+ from hi.integrations.importer.views import ImporterConfigureView
+ from django.http import HttpResponse
+ with patch.object(
+ ImporterConfigureView, 'post_attribute_form',
+ return_value=HttpResponse(status=200),
+ ):
+ response = self.client.post(self._url(), {})
+
+ self.assertEqual(response.status_code, 200)
+ body = response.content.decode()
+ self.assertIn('Would import', body)
+ self.assertIn('1', body) # 1 new
+ self.assertIn('CONFIRM IMPORT', body)
diff --git a/src/hi/integrations/tests/test_initializers.py b/src/hi/integrations/tests/test_initializers.py
index 50156c8d..5bcebc09 100644
--- a/src/hi/integrations/tests/test_initializers.py
+++ b/src/hi/integrations/tests/test_initializers.py
@@ -1,11 +1,9 @@
-from unittest.mock import Mock
-
from django.test import TestCase
from hi.apps.attribute.enums import AttributeValueType
from hi.integrations.enums import IntegrationAttributeType
from hi.integrations.initializers import IntegrationInitializer
-from hi.integrations.connect.integration_gateway import IntegrationGateway
+from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.models import Integration, IntegrationAttribute
from hi.integrations.transient_models import IntegrationMetaData
@@ -28,15 +26,6 @@ class MockIntegrationGateway(IntegrationGateway):
allow_entity_deletion=True,
)
- def get_manage_view_pane(self):
- return Mock()
-
- def get_monitor(self):
- return Mock()
-
- def get_controller(self):
- return Mock()
-
class IntegrationInitializerTestCase(TestCase):
diff --git a/src/hi/integrations/tests/test_integration_attribute_edit_context.py b/src/hi/integrations/tests/test_integration_attribute_edit_context.py
index 61d2e261..c54f7d12 100644
--- a/src/hi/integrations/tests/test_integration_attribute_edit_context.py
+++ b/src/hi/integrations/tests/test_integration_attribute_edit_context.py
@@ -7,11 +7,11 @@ import logging
from django.test import TestCase
from hi.apps.attribute.enums import AttributeValueType
-from hi.integrations.connect.integration_attribute_edit_context import (
+from hi.integrations.integration_attribute_edit_context import (
IntegrationAttributeItemEditContext,
)
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_gateway import IntegrationGateway
+from hi.integrations.integration_data import IntegrationData
+from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.enums import (
ALL_CAPABILITIES,
IntegrationAttributeType,
diff --git a/src/hi/integrations/tests/test_integration_synchronizer.py b/src/hi/integrations/tests/test_integration_connector.py
similarity index 98%
rename from src/hi/integrations/tests/test_integration_synchronizer.py
rename to src/hi/integrations/tests/test_integration_connector.py
index 496b1f90..cdad2d96 100644
--- a/src/hi/integrations/tests/test_integration_synchronizer.py
+++ b/src/hi/integrations/tests/test_integration_connector.py
@@ -1,5 +1,5 @@
"""
-Unit tests for IntegrationSynchronizer framework helpers.
+Unit tests for IntegrationConnector framework helpers.
Covers the framework-owned policies that all per-integration
synchronizers share:
@@ -13,7 +13,7 @@ synchronizers share:
used by reconnect.
End-to-end cycle coverage (sync → detach → reconnect across multiple
-sync passes) lives in ``IntegrationSynchronizerReconnectCycleTests``
+sync passes) lives in ``IntegrationConnectorReconnectCycleTests``
at the bottom of this module; the per-integration converter
contracts live in each ``services/<integration>/tests/`` directory.
"""
@@ -27,8 +27,8 @@ from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.event.models import EventClause, EventDefinition
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.testing.base_test_case import BaseTestCase
logging.disable(logging.CRITICAL)
@@ -42,8 +42,8 @@ def _stub_integration_metadata(integration_id='test_integration', label='TestInt
return SimpleNamespace(integration_id=integration_id, label=label)
-class TestSynchronizer(IntegrationSynchronizer):
- """Concrete IntegrationSynchronizer used to exercise the
+class TestSynchronizer(IntegrationConnector):
+ """Concrete IntegrationConnector used to exercise the
intelligent-removal and reconnect framework helpers. Stubs the
abstract hooks so the class can be instantiated; sync() itself
is not exercised here."""
@@ -60,8 +60,8 @@ class TestSynchronizer(IntegrationSynchronizer):
)
-class IntegrationSynchronizerRemovalTestCase(TestCase):
- """Test cases for IntegrationSynchronizer's _remove_entity_intelligently."""
+class IntegrationConnectorRemovalTestCase(TestCase):
+ """Test cases for IntegrationConnector's _remove_entity_intelligently."""
def setUp(self):
"""Set up test data."""
@@ -697,7 +697,7 @@ class IntegrationSynchronizerRemovalTestCase(TestCase):
self.assertEqual(self.result.removed_list, [])
-class IntegrationSynchronizerPreservationIntegrationTests(BaseTestCase):
+class IntegrationConnectorPreservationIntegrationTests(BaseTestCase):
"""End-to-end ``_remove_entity_intelligently`` exercises with
mixed integration/user components: data consistency under
preservation, foreign-key integrity, user-data detection at
@@ -1076,7 +1076,7 @@ class IntegrationSynchronizerPreservationIntegrationTests(BaseTestCase):
-class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):
+class IntegrationConnectorOrphanDelegateTestCase(TestCase):
"""Refresh-time entity removal must clean up delegate entities
(e.g., the Area auto-created when a camera/motion-detector was
placed in a view) that become orphaned by the removal — the same
@@ -1227,7 +1227,7 @@ class IntegrationSynchronizerOrphanDelegateTestCase(TestCase):
class ReconnectDisconnectedItemsFrameworkTests(TestCase):
"""
Issue #281: framework-level reconnect lives on the
- IntegrationSynchronizer base class, symmetric to disconnect
+ IntegrationConnector base class, symmetric to disconnect
(preserve_with_user_data) which lives on EntityIntegrationOperations.
Each integration only contributes a thin
``_rebuild_integration_components`` override; all the boilerplate
@@ -1253,7 +1253,7 @@ class ReconnectDisconnectedItemsFrameworkTests(TestCase):
integration_label = self.INTEGRATION_LABEL
- class RecordingSynchronizer(IntegrationSynchronizer):
+ class RecordingSynchronizer(IntegrationConnector):
def get_integration_metadata(self):
return _stub_integration_metadata(
integration_id=integration_id,
@@ -1356,7 +1356,7 @@ class ReconnectDisconnectedItemsFrameworkTests(TestCase):
)
upstream_key = self._make_upstream_key('foo')
- class IncompleteSynchronizer(IntegrationSynchronizer):
+ class IncompleteSynchronizer(IntegrationConnector):
# Metadata is provided so the framework reaches the
# _rebuild_integration_components hook (the missing
# override under test) rather than tripping on the
@@ -1379,7 +1379,7 @@ class ReconnectDisconnectedItemsFrameworkTests(TestCase):
self.assertIn('_rebuild_integration_components', str(cm.exception))
-class IntegrationSynchronizerReconnectCycleTests(TestCase):
+class IntegrationConnectorReconnectCycleTests(TestCase):
"""
Issue #281 end-to-end cycle tests. Exercise the full
sync → disconnect → re-add upstream → sync → reconnect cycle
@@ -1410,13 +1410,13 @@ class IntegrationSynchronizerReconnectCycleTests(TestCase):
``_rebuild_integration_components`` override mirrors what a
real integration converter does: set integration_key on the
existing entity and save."""
- from hi.integrations.connect.entity_operations import EntityIntegrationOperations
+ from hi.integrations.entity_operations import EntityIntegrationOperations
from hi.integrations.transient_models import IntegrationKey
integration_id = self.INTEGRATION_ID
integration_label = self.INTEGRATION_LABEL
- class TestE2ESynchronizer(IntegrationSynchronizer):
+ class TestE2ESynchronizer(IntegrationConnector):
def get_integration_metadata(self):
return _stub_integration_metadata(
integration_id=integration_id,
@@ -1531,7 +1531,7 @@ class IntegrationSynchronizerReconnectCycleTests(TestCase):
with user data via the same code path as sync-time
preservation, so reconnect must work for those too. Pinned
in the corrected #281 issue's edge-cases section."""
- from hi.integrations.connect.entity_operations import EntityIntegrationOperations
+ from hi.integrations.entity_operations import EntityIntegrationOperations
synchronizer = self._build_synchronizer()
result = IntegrationSyncResult(title='Disable Cycle')
diff --git a/src/hi/integrations/tests/test_integration_manager.py b/src/hi/integrations/tests/test_integration_manager.py
index c273dd1a..0aef9c20 100644
--- a/src/hi/integrations/tests/test_integration_manager.py
+++ b/src/hi/integrations/tests/test_integration_manager.py
@@ -14,8 +14,8 @@ from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.event.models import EventClause, EventDefinition
from hi.integrations.exceptions import IntegrationConnectionError
from hi.integrations.integration_manager import IntegrationManager
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_gateway import IntegrationGateway
+from hi.integrations.integration_data import IntegrationData
+from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.models import Integration, IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -64,15 +64,6 @@ class MockIntegrationGateway(IntegrationGateway):
capabilities=self.capabilities,
)
- def get_manage_view_pane(self):
- return Mock()
-
- def get_monitor(self):
- return Mock()
-
- def get_controller(self):
- return Mock()
-
def validate_access(self, integration_attributes, timeout_secs):
return self.connection_test_result
diff --git a/src/hi/integrations/tests/test_placement_form.py b/src/hi/integrations/tests/test_placement_form.py
index fb581e77..7db55c88 100644
--- a/src/hi/integrations/tests/test_placement_form.py
+++ b/src/hi/integrations/tests/test_placement_form.py
@@ -13,7 +13,7 @@ from django.test import TestCase
from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity
from hi.apps.location.models import Location, LocationView
-from hi.integrations.connect.placement_request import PlacementFormParser
+from hi.integrations.placement_request import PlacementFormParser
logging.disable(logging.CRITICAL)
@@ -252,7 +252,7 @@ class PlacementFormParserTests(TestCase):
# state. The patched return is the test's existing Location;
# the parser then creates a real LocationView attached to it.
with patch(
- 'hi.integrations.connect.placement_request.LocationManager',
+ 'hi.integrations.placement_request.LocationManager',
) as mock_manager_cls:
instance = mock_manager_cls.return_value
instance.get_default_location.return_value = self.location
diff --git a/src/hi/integrations/tests/test_placement_request.py b/src/hi/integrations/tests/test_placement_request.py
index fba9b92b..c3114ad4 100644
--- a/src/hi/integrations/tests/test_placement_request.py
+++ b/src/hi/integrations/tests/test_placement_request.py
@@ -14,7 +14,7 @@ from django.core.exceptions import BadRequest
from django.http import QueryDict
from django.test import SimpleTestCase
-from hi.integrations.connect.placement_request import PlacementUrlParams
+from hi.integrations.placement_request import PlacementUrlParams
logging.disable(logging.CRITICAL)
diff --git a/src/hi/integrations/tests/test_sync_check.py b/src/hi/integrations/tests/test_sync_check.py
index 1fa761b7..8d7ba3bf 100644
--- a/src/hi/integrations/tests/test_sync_check.py
+++ b/src/hi/integrations/tests/test_sync_check.py
@@ -1,6 +1,6 @@
"""
Unit tests for the Issue #283 sync-check primitives, framework
-monitor, and post-sync cache hook in ``IntegrationSynchronizer``.
+monitor, and post-sync cache hook in ``IntegrationConnector``.
The sync_check module is small and pure (set arithmetic + cache
round-trip + dataclass building); most of the value here is in the
@@ -15,13 +15,13 @@ from unittest.mock import Mock, patch
from django.core.cache import cache
from django.test import TestCase
-from hi.integrations.connect.sync_check import (
+from hi.integrations.connector.sync_check import (
IntegrationSyncCheck,
SyncCheckOutcome,
SyncCheckResult,
SyncDelta,
)
-from hi.integrations.connect.monitors import IntegrationSyncCheckMonitor
+from hi.integrations.connector.monitors import IntegrationSyncCheckMonitor
from hi.integrations.transient_models import IntegrationKey
@@ -470,15 +470,15 @@ class _StubIntegrationData:
def _stub_gateway_returning(delta_or_exception, has_synchronizer=True):
- """Build a Mock gateway whose ``get_synchronizer()`` returns a
+ """Build a Mock gateway whose ``get_connector()`` returns a
Mock synchronizer whose ``check_needs_sync`` coroutine returns
the given SyncDelta (or None) — or raises if an Exception is
supplied. Pass ``has_synchronizer=False`` to simulate an
integration that does not support sync at all (gateway returns
- None from get_synchronizer)."""
+ None from get_connector)."""
gateway = Mock()
if not has_synchronizer:
- gateway.get_synchronizer = Mock(return_value=None)
+ gateway.get_connector = Mock(return_value=None)
return gateway
synchronizer = Mock()
@@ -489,7 +489,7 @@ def _stub_gateway_returning(delta_or_exception, has_synchronizer=True):
return delta_or_exception
synchronizer.check_needs_sync = check_needs_sync
- gateway.get_synchronizer = Mock(return_value=synchronizer)
+ gateway.get_connector = Mock(return_value=synchronizer)
return gateway
@@ -542,7 +542,7 @@ class IntegrationSyncCheckMonitorTests(TestCase):
def test_no_cache_write_when_gateway_has_no_synchronizer(self):
# Integration that does not support sync at all
- # (get_synchronizer returns None) is naturally opted out of
+ # (get_connector returns None) is naturally opted out of
# sync-check too — sync-check rides on the same
# capability.
gateway = _stub_gateway_returning(None, has_synchronizer=False)
@@ -639,7 +639,7 @@ class IntegrationSyncCheckMonitorTests(TestCase):
)
-class IntegrationSynchronizerPostSyncHookTests(TestCase):
+class IntegrationConnectorPostSyncHookTests(TestCase):
"""The post-sync hook clears (writes a zero-delta SyncCheckResult
with current timestamp) on a successful sync, and leaves the
cache alone when the sync errored."""
@@ -654,20 +654,20 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):
cache.clear()
def _make_synchronizer(self, sync_impl_result):
- """Build a concrete IntegrationSynchronizer whose _sync_impl
+ """Build a concrete IntegrationConnector whose _sync_impl
returns the given result. We test sync() (the public entry
point) so the post-hook fires the same way it does in
production."""
- from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
+ from hi.integrations.connector.integration_connector import IntegrationConnector
from hi.integrations.transient_models import IntegrationMetaData
- class _TestSynchronizer(IntegrationSynchronizer):
+ class _TestSynchronizer(IntegrationConnector):
SYNCHRONIZATION_LOCK_NAME = 'sync_check_test_lock'
def get_integration_metadata(self):
return IntegrationMetaData(
- integration_id=IntegrationSynchronizerPostSyncHookTests.INTEGRATION_ID,
- label=IntegrationSynchronizerPostSyncHookTests.INTEGRATION_LABEL,
+ integration_id=IntegrationConnectorPostSyncHookTests.INTEGRATION_ID,
+ label=IntegrationConnectorPostSyncHookTests.INTEGRATION_LABEL,
attribute_type=Mock(),
allow_entity_deletion=True,
)
@@ -678,7 +678,7 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):
return _TestSynchronizer()
def test_successful_sync_records_zero_delta_completion(self):
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
# Pre-populate a stale "needs sync" state.
IntegrationSyncCheck.set_state(
@@ -699,7 +699,7 @@ class IntegrationSynchronizerPostSyncHookTests(TestCase):
self.assertFalse(loaded.needs_sync)
def test_failed_sync_leaves_cache_alone(self):
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
# Pre-populate a stale needs-sync state.
stale = IntegrationSyncCheck.build_result(
diff --git a/src/hi/integrations/tests/test_sync_result.py b/src/hi/integrations/tests/test_sync_result.py
index ef575b0a..5c6d98a7 100644
--- a/src/hi/integrations/tests/test_sync_result.py
+++ b/src/hi/integrations/tests/test_sync_result.py
@@ -20,7 +20,7 @@ from hi.apps.entity.entity_placement import (
EntityPlacementInput,
EntityPlacementItem,
)
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.sync_result import IntegrationSyncResult
logging.disable(logging.CRITICAL)
diff --git a/src/hi/integrations/tests/test_user_data_detector.py b/src/hi/integrations/tests/test_user_data_detector.py
index 1a240bc2..2f033d31 100644
--- a/src/hi/integrations/tests/test_user_data_detector.py
+++ b/src/hi/integrations/tests/test_user_data_detector.py
@@ -11,7 +11,7 @@ from hi.apps.attribute.enums import AttributeType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.sense.models import Sensor
from hi.apps.control.models import Controller
-from hi.integrations.connect.user_data_detector import EntityUserDataDetector
+from hi.integrations.connector.user_data_detector import EntityUserDataDetector
logging.disable(logging.CRITICAL)
diff --git a/src/hi/integrations/tests/test_view_mixins.py b/src/hi/integrations/tests/test_view_mixins.py
index b02fb65a..d5efa674 100644
--- a/src/hi/integrations/tests/test_view_mixins.py
+++ b/src/hi/integrations/tests/test_view_mixins.py
@@ -21,7 +21,7 @@ from hi.integrations.transient_models import (
ConnectionTestResult,
IntegrationValidationResult,
)
-from hi.integrations.connect.view_mixins import IntegrationViewMixin
+from hi.integrations.view_mixins import IntegrationViewMixin
logging.disable(logging.CRITICAL)
diff --git a/src/hi/integrations/tests/test_views.py b/src/hi/integrations/tests/test_views.py
index 4d80d98d..1a75a403 100644
--- a/src/hi/integrations/tests/test_views.py
+++ b/src/hi/integrations/tests/test_views.py
@@ -8,9 +8,13 @@ from unittest.mock import Mock, patch
from django.urls import reverse
from hi.apps.attribute.enums import AttributeValueType
-from hi.integrations.enums import IntegrationAttributeType, IntegrationDisableMode
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_gateway import IntegrationGateway
+from hi.integrations.enums import (
+ IntegrationAttributeType,
+ IntegrationCapability,
+ IntegrationDisableMode,
+)
+from hi.integrations.integration_data import IntegrationData
+from hi.integrations.integration_gateway import IntegrationGateway
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.models import Integration
from hi.integrations.transient_models import IntegrationMetaData
@@ -36,15 +40,6 @@ class _PauseResumeTestGateway(IntegrationGateway):
allow_entity_deletion=True,
)
- def get_manage_view_pane(self):
- return Mock()
-
- def get_monitor(self):
- return Mock()
-
- def get_controller(self):
- return Mock()
-
class PauseResumeViewTests(SyncViewTestCase):
"""
@@ -194,7 +189,7 @@ class RemoveViewTests(SyncViewTestCase):
class _SyncTestSynchronizer:
"""
Stand-in synchronizer for pre-sync / sync view tests. Stays
- intentionally minimal (does NOT extend IntegrationSynchronizer) to
+ intentionally minimal (does NOT extend IntegrationConnector) to
avoid acquiring the real lock or running framework retry logic in
unit tests; the views only need methods the framework actually
calls on it.
@@ -210,8 +205,11 @@ class _SyncTestSynchronizer:
def get_result_title(self, is_initial_connect):
return 'Test Sync Result'
+ def get_health_status_provider(self):
+ return _SyncTestHealthStatusProvider()
+
def sync(self, is_initial_connect=False, preserve_user_data=True):
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
self.sync_called = True
self.last_preserve_user_data = preserve_user_data
return IntegrationSyncResult(
@@ -232,11 +230,16 @@ class _SyncTestHealthStatusProvider:
class _SyncCapableGateway(IntegrationGateway):
"""Gateway that provides a synchronizer + health provider."""
- def __init__(self, integration_id='sync_view_test', synchronizer=None):
+ def __init__(self, integration_id='sync_view_test', synchronizer=None,
+ capabilities=None):
self.integration_id = integration_id
self._synchronizer = (
synchronizer if synchronizer is not None else _SyncTestSynchronizer()
)
+ self._capabilities = (
+ capabilities if capabilities is not None
+ else frozenset({ IntegrationCapability.CONNECT })
+ )
def get_metadata(self):
return IntegrationMetaData(
@@ -244,23 +247,12 @@ class _SyncCapableGateway(IntegrationGateway):
label='Sync View Test Integration',
attribute_type=_PauseResumeTestAttributeType,
allow_entity_deletion=True,
+ capabilities=self._capabilities,
)
- def get_manage_view_pane(self):
- return Mock()
-
- def get_monitor(self):
- return Mock()
-
- def get_controller(self):
- return Mock()
-
- def get_synchronizer(self):
+ def get_connector(self):
return self._synchronizer
- def get_health_status_provider(self):
- return _SyncTestHealthStatusProvider()
-
class _SyncIncapableGateway(IntegrationGateway):
"""Gateway whose integration does NOT support sync."""
@@ -276,15 +268,6 @@ class _SyncIncapableGateway(IntegrationGateway):
allow_entity_deletion=True,
)
- def get_manage_view_pane(self):
- return Mock()
-
- def get_monitor(self):
- return Mock()
-
- def get_controller(self):
- return Mock()
-
class PreSyncViewTests(SyncViewTestCase):
"""
@@ -331,7 +314,7 @@ class PreSyncViewTests(SyncViewTestCase):
def test_get_404s_when_integration_has_no_synchronizer(self):
# Replace the integration_data with one whose gateway returns
- # None from get_synchronizer.
+ # None from get_connector.
IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
integration_gateway=_SyncIncapableGateway(self.INTEGRATION_ID),
integration=self.integration,
@@ -341,7 +324,7 @@ class PreSyncViewTests(SyncViewTestCase):
def test_review_config_action_never_rendered(self):
"""The first-time CONNECT path is collapsed into
- IntegrationEnableView (Phase 7); pre-sync is now only the
+ ConnectorConfigureView (Phase 7); pre-sync is now only the
update-check path. REVIEW CONFIG was an artifact of the
first-time round-trip and must no longer render anywhere
in this template."""
@@ -467,13 +450,13 @@ class SyncViewTests(SyncViewTestCase):
# --------------------------------------------------------------------------
-# IntegrationEnableView tests for the Review Config (post-enable) path
+# ConnectorConfigureView tests for the Review Config (post-enable) path
# --------------------------------------------------------------------------
class EnableViewTests(SyncViewTestCase):
"""
- IntegrationEnableView: Phase 7 collapse. The view renders the
+ ConnectorConfigureView: Phase 7 collapse. The view renders the
config form with a CONNECT action button regardless of the
integration's is_enabled state; the legacy review-mode round
trip (UPDATE label + CONTINUE-to-pre-sync) is gone.
@@ -497,7 +480,7 @@ class EnableViewTests(SyncViewTestCase):
def _url(self):
return reverse(
- 'integrations_enable',
+ 'integrations_connect_configure',
kwargs={'integration_id': self.INTEGRATION_ID},
)
@@ -520,6 +503,20 @@ class EnableViewTests(SyncViewTestCase):
self.assertSuccessResponse(response)
body = response.content.decode()
self.assertIn('CONNECT', body)
+
+ def test_initial_connect_not_blocked_for_single_capability(self):
+ # Default _SyncCapableGateway is Connect-only; no block fires.
+ from hi.apps.entity.enums import EntityType
+ from hi.apps.entity.models import Entity
+ Entity.objects.create(
+ previous_integration_id=self.INTEGRATION_ID,
+ previous_integration_name='stray-internal',
+ name='Stray',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ response = self.client.get(self._url())
+ body = response.content.decode()
+ self.assertNotIn('Cannot configure', body)
self.assertIn('hi-modal-cancel', body)
def test_post_enables_and_runs_sync_when_synchronizer_exists(self):
@@ -530,9 +527,9 @@ class EnableViewTests(SyncViewTestCase):
# under test is the enable → sync chain plus the sync-result
# modal render.
from django.http import HttpResponse
- from hi.integrations.connect.views import IntegrationEnableView
+ from hi.integrations.connector.views import ConnectorConfigureView
with patch.object(
- IntegrationEnableView, 'post_attribute_form',
+ ConnectorConfigureView, 'post_attribute_form',
return_value=HttpResponse(status=200),
):
response = self.client.post(self._url(), {})
@@ -550,9 +547,9 @@ class EnableViewTests(SyncViewTestCase):
integration=self.integration,
)
from django.http import HttpResponse
- from hi.integrations.connect.views import IntegrationEnableView
+ from hi.integrations.connector.views import ConnectorConfigureView
with patch.object(
- IntegrationEnableView, 'post_attribute_form',
+ ConnectorConfigureView, 'post_attribute_form',
return_value=HttpResponse(status=200),
):
response = self.client.post(self._url(), {})
@@ -584,6 +581,9 @@ class _PlacementTestSynchronizer:
def get_result_title(self, is_initial_connect):
return 'Placement Test'
+ def get_health_status_provider(self):
+ return Mock()
+
def sync(self, is_initial_connect=False, preserve_user_data=True):
self.sync_called = True
self.last_preserve_user_data = preserve_user_data
@@ -605,21 +605,9 @@ class _PlacementTestGateway(IntegrationGateway):
allow_entity_deletion=True,
)
- def get_manage_view_pane(self):
- return Mock()
-
- def get_monitor(self):
- return Mock()
-
- def get_controller(self):
- return Mock()
-
- def get_synchronizer(self):
+ def get_connector(self):
return self._synchronizer
- def get_health_status_provider(self):
- return Mock()
-
class PlacementFlowTests(SyncViewTestCase):
"""End-to-end placement flow: sync → placement modal → apply →
@@ -639,7 +627,7 @@ class PlacementFlowTests(SyncViewTestCase):
from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity
from hi.apps.location.models import Location, LocationView
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
self.integration = Integration.objects.create(
integration_id=self.INTEGRATION_ID,
@@ -752,7 +740,7 @@ class PlacementFlowTests(SyncViewTestCase):
# update check, not an Initial Connect.
self.assertIn('Update check complete', body)
self.assertIn('Place Later', body)
- self.assertIn('Place 4 new items', body)
+ self.assertIn('Place new items', body)
self.assertIn(self._placement_url(), body)
# No placement artifacts in the response — operator must
# click the CTA to reach the placement.
@@ -763,7 +751,7 @@ class PlacementFlowTests(SyncViewTestCase):
no 'Place items' CTA. Single centered OK is the only footer
action (matches the project's 'acknowledge info, dismiss'
single-button convention)."""
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
self.synchronizer._sync_result = IntegrationSyncResult(title='Empty')
response = self.client.post(self._sync_url())
self.assertSuccessResponse(response)
@@ -777,7 +765,7 @@ class PlacementFlowTests(SyncViewTestCase):
placement when there are also creates — every change kind
is enumerated in the result modal even though the modal
ultimately routes the operator to placement."""
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
self.synchronizer._sync_result = IntegrationSyncResult(
title='Mixed Result',
created_list=['Brand New Light'],
@@ -793,7 +781,7 @@ class PlacementFlowTests(SyncViewTestCase):
self.assertIn('Old Name → New Name', body)
self.assertIn('Stale Sensor', body)
# And the CTA still routes to the placement.
- self.assertIn('Place 1 new item', body)
+ self.assertIn('Place new items', body)
def test_placement_top_inherits_to_groups_and_entities(self):
"""Top view chosen, groups + entities at default → every
@@ -963,7 +951,7 @@ class PlacementDismissAndShowTests(SyncViewTestCase):
from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity
from hi.apps.location.models import Location, LocationView
- from hi.integrations.connect.sync_result import IntegrationSyncResult
+ from hi.integrations.connector.sync_result import IntegrationSyncResult
self.integration = Integration.objects.create(
integration_id=self.INTEGRATION_ID,
@@ -1233,30 +1221,7 @@ class RefineViewTests(SyncViewTestCase):
self.assertEqual(response.status_code, 404)
-class _RenderableManageViewPane:
- """Minimal stand-in for an IntegrationManageViewPane that points
- at an existing empty per-integration template so the manage view
- can render in tests without a real per-integration pane wired
- in. Reuses ``homebox/panes/hb_manage.html`` (a documented empty
- extension-point template) rather than introducing a test-only
- template file."""
-
- def get_template_name(self):
- return 'homebox/panes/hb_manage.html'
-
- def get_template_context(self, integration_data):
- return {}
-
-
-class _RenderableGateway(_SyncCapableGateway):
- """``_SyncCapableGateway`` plus a real ManageViewPane so the
- full IntegrationManageView render path works."""
-
- def get_manage_view_pane(self):
- return _RenderableManageViewPane()
-
-
-class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):
+class ConnectorManageViewSyncCheckContextTests(SyncViewTestCase):
"""Issue #283 — wire-up tests for the sync-check state on the
integration manage page. Pins:
* banner renders when the active integration's cached
@@ -1278,7 +1243,7 @@ class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):
is_enabled=True,
is_paused=False,
)
- self.gateway = _RenderableGateway(integration_id=self.INTEGRATION_ID)
+ self.gateway = _SyncCapableGateway(integration_id=self.INTEGRATION_ID)
IntegrationManager()._integration_data_map[self.INTEGRATION_ID] = IntegrationData(
integration_gateway=self.gateway,
integration=self.integration,
@@ -1291,12 +1256,12 @@ class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):
def _url(self):
return reverse(
- 'integrations_manage',
+ 'integrations_connect_manage',
kwargs={'integration_id': self.INTEGRATION_ID},
)
def test_banner_renders_when_sync_check_reports_drift(self):
- from hi.integrations.connect.sync_check import (
+ from hi.integrations.connector.sync_check import (
IntegrationSyncCheck,
SyncDelta,
)
@@ -1345,7 +1310,7 @@ class IntegrationManageViewSyncCheckContextTests(SyncViewTestCase):
def test_no_banner_when_in_sync(self):
# Probe has run and confirmed in-sync (zero-delta); the
# banner is gated on needs_sync, so it must not appear.
- from hi.integrations.connect.sync_check import IntegrationSyncCheck
+ from hi.integrations.connector.sync_check import IntegrationSyncCheck
IntegrationSyncCheck.record_sync_complete(
integration_id=self.INTEGRATION_ID,
integration_label='Sync View Test Integration',
diff --git a/src/hi/integrations/urls.py b/src/hi/integrations/urls.py
index 7f9a360c..9d1a6c94 100644
--- a/src/hi/integrations/urls.py
+++ b/src/hi/integrations/urls.py
@@ -4,21 +4,42 @@ from django.urls import re_path, include
from hi.apps.common.module_utils import import_module_safe
-from .connect import views
+from .connector import views
+from .importer import views as importer_views
urlpatterns = [
- path( '',
- views.IntegrationHomeView.as_view(),
- name='integrations_home' ),
+ path( '',
+ views.IntegrationHomeView.as_view(),
+ name='integrations_connect_home' ),
+
+ path( 'import/',
+ importer_views.DataImportPageView.as_view(),
+ name='integrations_import_home' ),
+
+ path( 'import/info',
+ importer_views.DataImportInfoView.as_view(),
+ name='integrations_import_info' ),
+
+ re_path( r'^import/configure/(?P<integration_id>[\w\-]+)$',
+ importer_views.ImporterConfigureView.as_view(),
+ name='integrations_import_configure' ),
+
+ re_path( r'^import/run/(?P<integration_id>[\w\-]+)$',
+ importer_views.ImporterRunView.as_view(),
+ name='integrations_import_run' ),
+
+ re_path( r'^import/discard/(?P<integration_id>[\w\-]+)$',
+ importer_views.ImporterDiscardView.as_view(),
+ name='integrations_import_discard' ),
path( 'select',
views.IntegrationSelectView.as_view(),
name='integrations_select' ),
- re_path( r'^enable/(?P<integration_id>[\w\-]+)$',
- views.IntegrationEnableView.as_view(),
- name='integrations_enable' ),
+ re_path( r'^enable/(?P<integration_id>[\w\-]+)$',
+ views.ConnectorConfigureView.as_view(),
+ name='integrations_connect_configure' ),
re_path( r'^disable/(?P<integration_id>[\w\-]+)$',
views.IntegrationDisableView.as_view(),
@@ -52,9 +73,9 @@ urlpatterns = [
views.IntegrationRefineView.as_view(),
name='integrations_refine' ),
- re_path( r'^manage/(?P<integration_id>[\w\-]*)$',
- views.IntegrationManageView.as_view(),
- name='integrations_manage' ),
+ re_path( r'^manage/(?P<integration_id>[\w\-]*)$',
+ views.ConnectorManageView.as_view(),
+ name='integrations_connect_manage' ),
path( 'attribute/history/<int:integration_id>/<int:attribute_id>/',
views.IntegrationAttributeHistoryInlineView.as_view(),
diff --git a/src/hi/integrations/connect/view_mixins.py b/src/hi/integrations/view_mixins.py
similarity index 84%
rename from src/hi/integrations/connect/view_mixins.py
rename to src/hi/integrations/view_mixins.py
index 8836c4ef..00fe997d 100644
--- a/src/hi/integrations/connect/view_mixins.py
+++ b/src/hi/integrations/view_mixins.py
@@ -1,5 +1,6 @@
from typing import FrozenSet, Optional
+from django.core.exceptions import BadRequest
from django.db.models import Count
from django.http import Http404
from django.urls import reverse
@@ -16,19 +17,89 @@ from hi.integrations.enums import IntegrationCapability
from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.integration_metadata_cache import IntegrationMetadataCache
-from .placement_request import PlacementUrlParams
+from hi.integrations.placement_request import PlacementUrlParams
+
+
+class CapabilityBlockViewMixin:
+ """Block IMPORT initiation when the integration has active
+ Connect entities, directing the user to disable the integration
+ first.
+
+ The asymmetry is principled. CONNECT does not need a symmetric
+ block: sync's reconnect-then-create order will adopt any pre-
+ existing detached/imported rows for the same integration into
+ the live Connect session, so no collision is possible. IMPORT
+ creates new HI-owned rows, which would collide with active-
+ Connect rows unless we block this entry point.
+
+ Mixed into the IMPORT-side Configure view; CONNECT-side views
+ can either omit the mixin or call this method as a no-op for
+ capability=CONNECT.
+ """
+
+ def render_capability_block_if_conflict(
+ self,
+ request,
+ integration_data,
+ capability_being_initiated : IntegrationCapability,
+ ):
+ # CONNECT initiation cannot collide; the reconnect path
+ # adopts any existing provenance entities. Only IMPORT
+ # initiation needs blocking.
+ if capability_being_initiated != IntegrationCapability.IMPORT:
+ return None
+ capabilities = integration_data.integration_metadata.capabilities
+ if IntegrationCapability.CONNECT not in capabilities:
+ return None
+
+ existing_count = Entity.objects.external_for(
+ integration_id = integration_data.integration_id,
+ ).count()
+ if existing_count == 0:
+ return None
+
+ return self.modal_response(
+ request,
+ context = {
+ 'integration_data': integration_data,
+ 'my_label': 'Import',
+ 'existing_count': existing_count,
+ 'existing_mode_clause': (
+ 'has data configured as Integration with'
+ ),
+ 'desired_action_clause': (
+ f'use {integration_data.label} as Import'
+ ),
+ 'remediation_clause': (
+ f'disable the {integration_data.label} '
+ f'Integration'
+ ),
+ 'link_url': reverse( 'integrations_connect_home' ),
+ 'link_label': 'GO TO INTEGRATIONS',
+ },
+ template_name = 'integrations/modals/capability_blocked.html',
+ )
class IntegrationViewMixin:
- def get_integration_data( self, integration_id : str ):
+ def get_integration_data( self, request, *args, **kwargs ):
+ """Resolve the URL-routed integration_id to its IntegrationData.
+
+ Assumes there is a required ``integration_id`` in kwargs;
+ raises BadRequest if missing and Http404 if not registered.
+ Mirrors EntityViewMixin.get_entity's signature so views can
+ chain helpers uniformly.
+ """
+ integration_id = kwargs.get('integration_id')
+ if not integration_id:
+ raise BadRequest('Missing integration id.')
try:
return IntegrationManager().get_integration_data(
integration_id = integration_id,
)
except KeyError:
- raise Http404()
- return
+ raise Http404(request)
def get_integration_data_list(
self,
@@ -44,17 +115,17 @@ class IntegrationViewMixin:
request,
integration_data,
preserve_user_data : bool = True ):
- """Run the integration's synchronizer and render the
+ """Run the integration's connector and render the
sync-result modal. Shared by the initial-connect flow
- (IntegrationEnableView.post after enable) and the update-check
+ (ConnectorConfigureView.post after enable) and the update-check
flow (IntegrationSyncView.post after pre-sync confirm).
Returns the modal response directly, including the placement
URL for the 'Place N new items' CTA when sync produced new
entities. Cache invalidations run in a ``finally`` so a
partial-commit failure during sync also flushes."""
- synchronizer = integration_data.integration_gateway.get_synchronizer()
- if synchronizer is None:
+ connector = integration_data.integration_gateway.get_connector()
+ if connector is None:
return page_not_found_response( request )
is_initial_connect = not Entity.objects.filter(
@@ -62,7 +133,7 @@ class IntegrationViewMixin:
).exists()
try:
- sync_result = synchronizer.sync(
+ sync_result = connector.sync(
is_initial_connect = is_initial_connect,
preserve_user_data = preserve_user_data,
)
@@ -90,7 +161,7 @@ class IntegrationViewMixin:
'is_initial_connect': is_initial_connect,
'placement_url': placement_url,
},
- template_name = 'integrations/modals/sync_result.html',
+ template_name = 'integrations/connector/modals/sync_result.html',
)
def validate_attributes_extra_helper( self,
diff --git a/src/hi/integrations/views.py b/src/hi/integrations/views.py
new file mode 100644
index 00000000..3e235bef
--- /dev/null
+++ b/src/hi/integrations/views.py
@@ -0,0 +1,115 @@
+"""
+Framework-level integration views shared across capabilities.
+"""
+from hi.apps.attribute.view_mixins import AttributeEditViewMixin
+from hi.hi_async_view import HiModalView
+
+from hi.integrations.enums import IntegrationCapability
+from hi.integrations.integration_attribute_edit_context import (
+ IntegrationAttributeItemEditContext,
+)
+from hi.integrations.integration_manager import IntegrationManager
+from hi.integrations.view_mixins import (
+ CapabilityBlockViewMixin,
+ IntegrationViewMixin,
+)
+
+
+class CapabilityConfigureView( HiModalView,
+ IntegrationViewMixin,
+ CapabilityBlockViewMixin,
+ AttributeEditViewMixin ):
+ """Base for the per-capability credentials Configure modal.
+
+ Subclasses set the four class-level constants and override
+ ``handle_post_success`` to define what happens after credentials
+ save. The base owns:
+ * the GET render flow (block check → ensure_all_attributes_exist →
+ build edit context → render modal)
+ * the POST save flow (post_attribute_form → delegate to subclass)
+ * the ``validate_attributes_extra`` hook for AttributeEditViewMixin.
+
+ Subclasses own the timing of ``notify_settings_changed()`` because
+ the right moment is capability-specific: Connect-side managers
+ gate client (re)build on ``integration.is_enabled``, so the notify
+ must fire AFTER ``enable_integration``; Import flows fire it
+ before reading candidates.
+ """
+
+ capability : IntegrationCapability = None
+ button_label : str = None
+ template_name : str = None
+ error_title : str = None
+
+ def get_template_name( self ) -> str:
+ return self.template_name
+
+ def _build_attr_item_context( self, integration_data ):
+ return IntegrationAttributeItemEditContext(
+ integration_data = integration_data,
+ capability = self.capability,
+ update_button_label = self.button_label,
+ suppress_history = True,
+ show_secrets = True,
+ )
+
+ def get(self, request, *args, **kwargs):
+ integration_manager = IntegrationManager()
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+
+ block_response = self.render_capability_block_if_conflict(
+ request = request,
+ integration_data = integration_data,
+ capability_being_initiated = self.capability,
+ )
+ if block_response is not None:
+ return block_response
+
+ integration_manager.ensure_all_attributes_exist(
+ integration_metadata = integration_data.integration_metadata,
+ integration = integration_data.integration,
+ )
+ attr_item_context = self._build_attr_item_context( integration_data )
+ template_context = self.create_initial_template_context(
+ attr_item_context = attr_item_context,
+ )
+ return self.modal_response( request, template_context )
+
+ def post(self, request, *args, **kwargs):
+ integration_data = self.get_integration_data( request, *args, **kwargs )
+
+ # Re-check the mode-switch invariant on POST. The GET path
+ # already runs this, but a direct POST (cached form, replayed
+ # request) would otherwise bypass it.
+ block_response = self.render_capability_block_if_conflict(
+ request = request,
+ integration_data = integration_data,
+ capability_being_initiated = self.capability,
+ )
+ if block_response is not None:
+ return block_response
+
+ attr_item_context = self._build_attr_item_context( integration_data )
+ response = self.post_attribute_form(
+ request = request,
+ attr_item_context = attr_item_context,
+ )
+ # Errors re-render the form with messages.
+ if response.status_code > 299:
+ return response
+ return self.handle_post_success( request, integration_data )
+
+ def handle_post_success( self, request, integration_data ):
+ raise NotImplementedError( 'Subclasses must override.' )
+
+ def validate_attributes_extra( self,
+ attr_item_context,
+ regular_attributes_formset,
+ request ):
+ """ Override for AttributeEditViewMixin """
+ self.validate_attributes_extra_helper(
+ attr_item_context,
+ regular_attributes_formset,
+ error_title = self.error_title,
+ )
+ return
diff --git a/src/hi/services/frigate/frigate_sync.py b/src/hi/services/frigate/frigate_connector.py
similarity index 77%
rename from src/hi/services/frigate/frigate_sync.py
rename to src/hi/services/frigate/frigate_connector.py
index 67a90597..3b9a9fb8 100644
--- a/src/hi/services/frigate/frigate_sync.py
+++ b/src/hi/services/frigate/frigate_connector.py
@@ -4,31 +4,36 @@ from typing import Dict, List, Optional
from asgiref.sync import sync_to_async
from django.db import transaction
-from hi.apps.entity.enums import EntityType
+from hi.apps.entity.enums import EntityType, VideoStreamType
from hi.apps.entity.entity_placement import (
EntityPlacementGroup,
EntityPlacementInput,
EntityPlacementItem,
)
from hi.apps.entity.models import Entity
+from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
from hi.apps.model_helper import HiModelHelper
+from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
-from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.connector.sync_check import IntegrationSyncCheck, SyncDelta
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
+from .frigate_controller import FrigateController
from .frigate_manager import FrigateManager
from .frigate_metadata import FrigateMetaData
from .frigate_mixins import FrigateMixin
+from .monitors import FrigateMonitor
logger = logging.getLogger(__name__)
-class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):
+class FrigateConnector( IntegrationConnector, FrigateMixin ):
"""Drives the Frigate Import / Refresh workflow.
- Mirrors ``ZoneMinderSynchronizer`` in role: pulls the upstream
+ Mirrors ``ZmConnector`` in role: pulls the upstream
camera list from Frigate (via ``/api/config`` since Frigate has
no dedicated cameras endpoint), reconciles it against existing
HI entities by integration_key, creates / updates / removes as
@@ -42,6 +47,82 @@ class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):
def get_integration_metadata(self):
return FrigateMetaData
+ def get_monitor(self) -> FrigateMonitor:
+ return FrigateMonitor()
+
+ def get_controller(self) -> FrigateController:
+ return FrigateController()
+
+ def get_health_status_provider(self) -> HealthStatusProvider:
+ return FrigateManager()
+
+ def get_entity_video_snapshot(self, entity : Entity) -> Optional[ VideoSnapshot ]:
+ """Live still-frame for the Frigate camera backing this entity
+ (``/api/<camera>/latest.jpg``). Returns ``None`` when the
+ entity isn't a Frigate camera, when ``has_video_snapshot`` is
+ off (operator opt-out), or when the integration client isn't
+ ready."""
+ if not entity.has_video_snapshot:
+ return None
+ if entity.integration_id != FrigateMetaData.integration_id:
+ return None
+
+ prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX + '.'
+ integration_name = entity.integration_name or ''
+ if not integration_name.startswith( prefix ):
+ return None
+ camera_name = integration_name[ len( prefix ): ]
+ if not camera_name:
+ return None
+
+ source_url = FrigateManager().get_camera_snapshot_url(
+ camera_name = camera_name,
+ )
+ if source_url is None:
+ return None
+ return VideoSnapshot(
+ source_url = source_url,
+ metadata = { 'camera_name': camera_name },
+ )
+
+ def get_sensor_response_event_snapshot_url(
+ self,
+ sensor_response : SensorResponse,
+ ) -> Optional[ str ]:
+ """Per-event snapshot URL for a Frigate SensorResponse. Pulls
+ the event_id from ``correlation_id`` and builds the URL fresh
+ each call so operator-side base_url changes auto-heal every
+ historical row."""
+ if not sensor_response.has_event_video_snapshot:
+ return None
+ event_id = sensor_response.correlation_id
+ if not event_id:
+ return None
+ return FrigateManager().get_event_snapshot_url( event_id = event_id )
+
+ def get_sensor_response_video_stream(
+ self,
+ sensor_response : SensorResponse,
+ ) -> Optional[ VideoStream ]:
+ """Event-clip MP4 URL for a Frigate SensorResponse.
+ Returns ``None`` when the response carries no clip
+ (``has_event_video_clip`` False), when the
+ ``correlation_id`` — Frigate's event_id — is absent, or when
+ the integration client isn't ready."""
+ if not sensor_response.has_event_video_clip:
+ return None
+ event_id = sensor_response.correlation_id
+ if not event_id:
+ return None
+ source_url = FrigateManager().get_event_clip_url( event_id = event_id )
+ if source_url is None:
+ return None
+ return VideoStream(
+ stream_type = VideoStreamType.MP4,
+ source_url = source_url,
+ metadata = { 'event_id': event_id },
+ )
+
def get_description(self, is_initial_connect : bool) -> Optional[ str ]:
if is_initial_connect:
return (
@@ -236,6 +317,7 @@ class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):
(Issue #281), where integration-owned fields get refilled but
the user-editable ``name`` is preserved across the
intervening disconnect."""
+ is_fresh_create = entity is None
camera_name = camera[ 'name' ]
# Frigate's camera key (snake_case) is the technical identifier;
# the ``friendly_name`` on the per-camera config is the operator's
@@ -289,7 +371,12 @@ class FrigateSynchronizer( IntegrationSynchronizer, FrigateMixin ):
),
)
- result.created_list.append( entity.name )
+ # Only fresh creates contribute to created_list. The
+ # reconnect path (entity supplied by caller) is surfaced via
+ # reconnected_list in reconnect_disconnected_items — appending
+ # here would double-count.
+ if is_fresh_create:
+ result.created_list.append( entity.name )
return entity
def _update_entity( self,
diff --git a/src/hi/services/frigate/frigate_controller.py b/src/hi/services/frigate/frigate_controller.py
index 7454ef35..f646ece8 100644
--- a/src/hi/services/frigate/frigate_controller.py
+++ b/src/hi/services/frigate/frigate_controller.py
@@ -1,6 +1,6 @@
import logging
-from hi.integrations.connect.integration_controller import IntegrationController
+from hi.integrations.connector.integration_controller import IntegrationController
from hi.integrations.transient_models import (
IntegrationControlResult,
IntegrationDetails,
diff --git a/src/hi/services/frigate/frigate_manage_view_pane.py b/src/hi/services/frigate/frigate_manage_view_pane.py
deleted file mode 100644
index 06a89e03..00000000
--- a/src/hi/services/frigate/frigate_manage_view_pane.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from typing import Dict
-
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-
-
-class FrigateManageViewPane( IntegrationManageViewPane ):
- """Management-pane backing for the Settings → Integrations →
- Frigate page. Renders the management template; v1 doesn't add
- any custom context beyond what the framework provides.
- """
-
- def get_template_name( self ) -> str:
- return 'frigate/panes/frigate_manage.html'
-
- def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
- return {}
diff --git a/src/hi/services/frigate/integration.py b/src/hi/services/frigate/integration.py
index 6a471f8e..9743cc0f 100644
--- a/src/hi/services/frigate/integration.py
+++ b/src/hi/services/frigate/integration.py
@@ -1,18 +1,10 @@
import logging
from typing import List, Optional
-from hi.apps.entity.enums import VideoStreamType
-from hi.apps.entity.models import Entity
-from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
-from hi.apps.sense.transient_models import SensorResponse
-from hi.apps.monitor.periodic_monitor import PeriodicMonitor
from hi.apps.system.enums import HealthStatusType
-from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.integration_controller import IntegrationController
-from hi.integrations.connect.integration_gateway import IntegrationGateway
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.connector.integration_connector import IntegrationConnector
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -20,13 +12,10 @@ from hi.integrations.transient_models import (
IntegrationValidationResult,
)
-from .frigate_controller import FrigateController
-from .frigate_manage_view_pane import FrigateManageViewPane
from .frigate_manager import FrigateManager
from .frigate_metadata import FrigateMetaData
from .frigate_mixins import FrigateMixin
-from .frigate_sync import FrigateSynchronizer
-from .monitors import FrigateMonitor
+from .frigate_connector import FrigateConnector
logger = logging.getLogger(__name__)
@@ -45,15 +34,6 @@ class FrigateGateway( IntegrationGateway, FrigateMixin ):
def get_metadata(self) -> IntegrationMetaData:
return FrigateMetaData
- def get_manage_view_pane(self) -> IntegrationManageViewPane:
- return FrigateManageViewPane()
-
- def get_monitor(self) -> PeriodicMonitor:
- return FrigateMonitor()
-
- def get_controller(self) -> IntegrationController:
- return FrigateController()
-
def notify_settings_changed(self):
try:
FrigateManager().notify_settings_changed()
@@ -63,11 +43,8 @@ class FrigateGateway( IntegrationGateway, FrigateMixin ):
f'Error notifying Frigate integration of settings change: {e}'
)
- def get_health_status_provider(self) -> HealthStatusProvider:
- return FrigateManager()
-
- def get_synchronizer(self) -> IntegrationSynchronizer:
- return FrigateSynchronizer()
+ def get_connector(self) -> IntegrationConnector:
+ return FrigateConnector()
def validate_configuration(
self,
@@ -97,70 +74,3 @@ class FrigateGateway( IntegrationGateway, FrigateMixin ):
except Exception as e:
logger.exception( f'Error in Frigate access validation: {e}' )
return ConnectionTestResult.failure( f'Access validation error: {e}' )
-
- def get_entity_video_snapshot(self, entity : Entity) -> Optional[ VideoSnapshot ]:
- """Live still-frame for the Frigate camera backing this entity
- (``/api/<camera>/latest.jpg``). Returns ``None`` when the
- entity isn't a Frigate camera, when ``has_video_snapshot`` is
- off (operator opt-out), or when the integration client isn't
- ready."""
- if not entity.has_video_snapshot:
- return None
- if entity.integration_id != FrigateMetaData.integration_id:
- return None
-
- prefix = FrigateManager.FRIGATE_CAMERA_INTEGRATION_NAME_PREFIX + '.'
- integration_name = entity.integration_name or ''
- if not integration_name.startswith( prefix ):
- return None
- camera_name = integration_name[ len( prefix ): ]
- if not camera_name:
- return None
-
- source_url = FrigateManager().get_camera_snapshot_url(
- camera_name = camera_name,
- )
- if source_url is None:
- return None
- return VideoSnapshot(
- source_url = source_url,
- metadata = { 'camera_name': camera_name },
- )
-
- def get_sensor_response_event_snapshot_url(
- self,
- sensor_response : SensorResponse,
- ) -> Optional[ str ]:
- """Per-event snapshot URL for a Frigate SensorResponse. Pulls
- the event_id from ``correlation_id`` and builds the URL fresh
- each call so operator-side base_url changes auto-heal every
- historical row."""
- if not sensor_response.has_event_video_snapshot:
- return None
- event_id = sensor_response.correlation_id
- if not event_id:
- return None
- return FrigateManager().get_event_snapshot_url( event_id = event_id )
-
- def get_sensor_response_video_stream(
- self,
- sensor_response : SensorResponse,
- ) -> Optional[ VideoStream ]:
- """Event-clip MP4 URL for a Frigate SensorResponse.
- Returns ``None`` when the response carries no clip
- (``has_event_video_clip`` False), when the
- ``correlation_id`` — Frigate's event_id — is absent, or when
- the integration client isn't ready."""
- if not sensor_response.has_event_video_clip:
- return None
- event_id = sensor_response.correlation_id
- if not event_id:
- return None
- source_url = FrigateManager().get_event_clip_url( event_id = event_id )
- if source_url is None:
- return None
- return VideoStream(
- stream_type = VideoStreamType.MP4,
- source_url = source_url,
- metadata = { 'event_id': event_id },
- )
diff --git a/src/hi/services/frigate/templates/frigate/panes/frigate_manage.html b/src/hi/services/frigate/templates/frigate/panes/frigate_manage.html
deleted file mode 100644
index b98346e0..00000000
--- a/src/hi/services/frigate/templates/frigate/panes/frigate_manage.html
+++ /dev/null
@@ -1,7 +0,0 @@
-{% comment %}
- Integration-specific custom content slot for the Frigate manage
- page. The framework owns the page header (title/logo, lifecycle
- actions, sync actions) and the attribute editor; this template
- renders any Frigate-specific UI between them. Currently empty —
- kept as a documented extension point.
-{% endcomment %}
diff --git a/src/hi/services/frigate/tests/test_frigate_sync.py b/src/hi/services/frigate/tests/test_frigate_connector.py
similarity index 99%
rename from src/hi/services/frigate/tests/test_frigate_sync.py
rename to src/hi/services/frigate/tests/test_frigate_connector.py
index 67a3b862..a53cdd70 100644
--- a/src/hi/services/frigate/tests/test_frigate_sync.py
+++ b/src/hi/services/frigate/tests/test_frigate_connector.py
@@ -11,7 +11,7 @@ from hi.apps.sense.models import Sensor
from hi.services.frigate.frigate_manager import FrigateManager
from hi.services.frigate.frigate_metadata import FrigateMetaData
-from hi.services.frigate.frigate_sync import FrigateSynchronizer
+from hi.services.frigate.frigate_connector import FrigateConnector
logging.disable( logging.CRITICAL )
@@ -19,7 +19,7 @@ logging.disable( logging.CRITICAL )
class _FrigateSyncTestBase( TestCase ):
def setUp(self):
- self.synchronizer = FrigateSynchronizer()
+ self.synchronizer = FrigateConnector()
self.mock_manager = Mock( spec = FrigateManager )
# Default: alarm-event auto-creation off so tests that don't
# care about it don't silently exercise the event-creation
diff --git a/src/hi/services/frigate/tests/test_frigate_integration.py b/src/hi/services/frigate/tests/test_frigate_integration.py
index 1c61df7d..dc28332b 100644
--- a/src/hi/services/frigate/tests/test_frigate_integration.py
+++ b/src/hi/services/frigate/tests/test_frigate_integration.py
@@ -26,7 +26,7 @@ from hi.apps.sense.transient_models import SensorResponse
from hi.services.frigate.enums import FrigateAttributeType
from hi.services.frigate.frigate_manager import FrigateManager
from hi.services.frigate.frigate_metadata import FrigateMetaData
-from hi.services.frigate.integration import FrigateGateway
+from hi.services.frigate.frigate_connector import FrigateConnector
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import IntegrationKey
@@ -91,7 +91,7 @@ class TestFrigateGatewayVideoSnapshot( TestCase ):
the live JPEG URL."""
def setUp(self):
- self.gateway = FrigateGateway()
+ self.gateway = FrigateConnector()
def _make_camera_entity( self,
integration_name : str = 'camera.front_yard',
@@ -178,7 +178,7 @@ class TestFrigateGatewayEventSnapshotUrl( TestCase ):
each call so the URL always reflects current manager state."""
def setUp(self):
- self.gateway = FrigateGateway()
+ self.gateway = FrigateConnector()
def _make_response( self, has_snapshot = True, correlation_id = 'evt-1' ):
from datetime import datetime
@@ -229,7 +229,7 @@ class TestFrigateGatewayVideoStream( TestCase ):
otherwise (no clip flag, no event id, or no client)."""
def setUp(self):
- self.gateway = FrigateGateway()
+ self.gateway = FrigateConnector()
def _make_response(
self, has_clip = True, correlation_id = 'evt-1',
diff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_connector.py
similarity index 84%
rename from src/hi/services/hass/hass_sync.py
rename to src/hi/services/hass/hass_connector.py
index 85f4d6ae..c4d05d17 100644
--- a/src/hi/services/hass/hass_sync.py
+++ b/src/hi/services/hass/hass_connector.py
@@ -5,31 +5,80 @@ from asgiref.sync import sync_to_async
from django.db import transaction
from hi.apps.entity.models import Entity
+from hi.apps.entity.transient_models import VideoSnapshot
from hi.apps.entity.entity_placement import (
EntityPlacementInput,
EntityPlacementItem,
EntityPlacementGroup,
)
+from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
-from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.connector.sync_check import IntegrationSyncCheck, SyncDelta
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
+from .hass_controller import HassController
from .hass_converter import HassConverter
+from .hass_manager import HassManager
from .hass_models import HassDevice
from .hass_mixins import HassMixin
from .hass_metadata import HassMetaData
+from .monitors import HassMonitor
logger = logging.getLogger(__name__)
-class HassSynchronizer( IntegrationSynchronizer, HassMixin ):
+class HassConnector( IntegrationConnector, HassMixin ):
def get_integration_metadata(self):
return HassMetaData
+ def get_monitor(self) -> HassMonitor:
+ return HassMonitor()
+
+ def get_controller(self) -> HassController:
+ return HassController()
+
+ def get_health_status_provider(self) -> HealthStatusProvider:
+ return HassManager()
+
+ def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
+ if not entity.has_video_snapshot:
+ return None
+ if entity.integration_id != HassMetaData.integration_id:
+ return None
+
+ hass_manager = HassManager()
+ # ``Entity.integration_name`` is the HassDevice device_id (an HI
+ # grouping construct), not the HA state id the attrs cache is
+ # keyed by. The manager bridges the two via a sync-time-built
+ # map of HI Entity.id -> camera-domain HA state id.
+ ha_state_id = hass_manager.get_ha_state_id_for_entity( entity )
+ if not ha_state_id:
+ return None
+
+ attrs = hass_manager.get_latest_attrs( ha_state_id )
+ if not attrs:
+ return None
+
+ entity_picture = attrs.get( 'entity_picture' )
+ if not entity_picture:
+ return None
+
+ # Some HA integrations emit an absolute URL; pass those
+ # through unchanged. Relative paths get the HA base prefix.
+ if entity_picture.startswith( ('http://', 'https://') ):
+ source_url = entity_picture
+ else:
+ client = hass_manager.hass_client
+ if not client:
+ return None
+ source_url = f'{client.api_base_url}{entity_picture}'
+
+ return VideoSnapshot( source_url = source_url )
+
def get_description(self, is_initial_connect: bool) -> Optional[str]:
if is_initial_connect:
return 'Only items matching your Allowed Item Types setting will be imported.'
diff --git a/src/hi/services/hass/hass_controller.py b/src/hi/services/hass/hass_controller.py
index 991a711d..0a6b05ff 100644
--- a/src/hi/services/hass/hass_controller.py
+++ b/src/hi/services/hass/hass_controller.py
@@ -1,6 +1,6 @@
import logging
-from hi.integrations.connect.integration_controller import IntegrationController
+from hi.integrations.connector.integration_controller import IntegrationController
from hi.integrations.transient_models import IntegrationDetails
from hi.integrations.transient_models import IntegrationControlResult
diff --git a/src/hi/services/hass/hass_manage_view_pane.py b/src/hi/services/hass/hass_manage_view_pane.py
deleted file mode 100644
index 62bb037c..00000000
--- a/src/hi/services/hass/hass_manage_view_pane.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Dict
-
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-
-
-class HassManageViewPane( IntegrationManageViewPane ):
-
- def get_template_name( self ) -> str:
- return 'hass/panes/hass_manage.html'
-
- def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
- return {}
diff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.py
index 47730e1d..6bdec7db 100644
--- a/src/hi/services/hass/integration.py
+++ b/src/hi/services/hass/integration.py
@@ -1,29 +1,20 @@
import logging
from typing import List, Optional
-from hi.apps.entity.models import Entity
-from hi.apps.entity.transient_models import VideoSnapshot
from hi.apps.system.enums import HealthStatusType
-from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.integration_controller import IntegrationController
-from hi.integrations.connect.integration_gateway import IntegrationGateway
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.connector.integration_connector import IntegrationConnector
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
IntegrationMetaData,
IntegrationValidationResult,
)
-from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from .hass_controller import HassController
-from .hass_manage_view_pane import HassManageViewPane
from .hass_manager import HassManager
from .hass_metadata import HassMetaData
-from .hass_sync import HassSynchronizer
-from .monitors import HassMonitor
+from .hass_connector import HassConnector
logger = logging.getLogger(__name__)
@@ -33,18 +24,9 @@ class HassGateway( IntegrationGateway ):
def get_metadata(self) -> IntegrationMetaData:
return HassMetaData
- def get_manage_view_pane(self) -> IntegrationManageViewPane:
- return HassManageViewPane()
-
- def get_monitor(self) -> PeriodicMonitor:
- return HassMonitor()
-
- def get_controller(self) -> IntegrationController:
- return HassController()
-
def notify_settings_changed(self):
"""Notify HASS integration that settings have changed.
-
+
Delegates to HassManager to reload configuration and notify monitors.
"""
try:
@@ -53,12 +35,9 @@ class HassGateway( IntegrationGateway ):
logger.debug('HASS integration notified of settings change')
except Exception as e:
logger.exception(f'Error notifying HASS integration of settings change: {e}')
-
- def get_health_status_provider(self) -> HealthStatusProvider:
- return HassManager()
- def get_synchronizer(self) -> IntegrationSynchronizer:
- return HassSynchronizer()
+ def get_connector(self) -> IntegrationConnector:
+ return HassConnector()
def validate_configuration(
self, integration_attributes: List[IntegrationAttribute]
@@ -89,38 +68,3 @@ class HassGateway( IntegrationGateway ):
except Exception as e:
logger.exception(f'Error in HASS access validation: {e}')
return ConnectionTestResult.failure(f'Access validation error: {e}')
-
- def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
- if not entity.has_video_snapshot:
- return None
- if entity.integration_id != HassMetaData.integration_id:
- return None
-
- hass_manager = HassManager()
- # ``Entity.integration_name`` is the HassDevice device_id (an HI
- # grouping construct), not the HA state id the attrs cache is
- # keyed by. The manager bridges the two via a sync-time-built
- # map of HI Entity.id -> camera-domain HA state id.
- ha_state_id = hass_manager.get_ha_state_id_for_entity( entity )
- if not ha_state_id:
- return None
-
- attrs = hass_manager.get_latest_attrs( ha_state_id )
- if not attrs:
- return None
-
- entity_picture = attrs.get( 'entity_picture' )
- if not entity_picture:
- return None
-
- # Some HA integrations emit an absolute URL; pass those
- # through unchanged. Relative paths get the HA base prefix.
- if entity_picture.startswith( ('http://', 'https://') ):
- source_url = entity_picture
- else:
- client = hass_manager.hass_client
- if not client:
- return None
- source_url = f'{client.api_base_url}{entity_picture}'
-
- return VideoSnapshot( source_url = source_url )
diff --git a/src/hi/services/hass/templates/hass/panes/hass_manage.html b/src/hi/services/hass/templates/hass/panes/hass_manage.html
deleted file mode 100644
index 55b46348..00000000
--- a/src/hi/services/hass/templates/hass/panes/hass_manage.html
+++ /dev/null
@@ -1,7 +0,0 @@
-{% comment %}
- Integration-specific custom content slot for the Home Assistant
- manage page. The framework owns the page header (title/logo,
- lifecycle actions, sync actions) and the attribute editor; this
- template renders any HASS-specific UI between them. Currently empty
- — kept as a documented extension point.
-{% endcomment %}
diff --git a/src/hi/services/hass/tests/test_hass_sync.py b/src/hi/services/hass/tests/test_hass_connector.py
similarity index 89%
rename from src/hi/services/hass/tests/test_hass_sync.py
rename to src/hi/services/hass/tests/test_hass_connector.py
index b6ea441d..696f62b4 100644
--- a/src/hi/services/hass/tests/test_hass_sync.py
+++ b/src/hi/services/hass/tests/test_hass_connector.py
@@ -5,45 +5,45 @@ from unittest.mock import Mock, patch
from django.test import TestCase
from hi.apps.entity.models import Entity
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
-from hi.services.hass.hass_sync import HassSynchronizer
+from hi.services.hass.hass_connector import HassConnector
from hi.services.hass.hass_models import HassState
logging.disable(logging.CRITICAL)
-class TestHassSynchronizerInitialization(TestCase):
- """Test HassSynchronizer initialization and basic setup"""
+class TestHassConnectorInitialization(TestCase):
+ """Test HassConnector initialization and basic setup"""
def test_init_creates_instance_successfully(self):
- """Test HassSynchronizer initialization"""
- synchronizer = HassSynchronizer()
- self.assertIsInstance(synchronizer, HassSynchronizer)
+ """Test HassConnector initialization"""
+ synchronizer = HassConnector()
+ self.assertIsInstance(synchronizer, HassConnector)
def test_synchronization_lock_name_constant(self):
"""All integration synchronizers share a single process-wide
sync lock name; the base class declares it and subclasses do
not override."""
- self.assertEqual(HassSynchronizer.SYNCHRONIZATION_LOCK_NAME, 'integrations_sync')
+ self.assertEqual(HassConnector.SYNCHRONIZATION_LOCK_NAME, 'integrations_sync')
def test_inherits_from_mixins(self):
- """Test that HassSynchronizer inherits from required mixins"""
- synchronizer = HassSynchronizer()
+ """Test that HassConnector inherits from required mixins"""
+ synchronizer = HassConnector()
# Should inherit from HassMixin
self.assertTrue(hasattr(synchronizer, 'hass_manager'))
-class TestHassSynchronizerSyncMethod(TestCase):
+class TestHassConnectorSyncMethod(TestCase):
"""Test main sync() method with database transactions"""
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
- @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')
- @patch.object(HassSynchronizer, '_sync_impl')
+ @patch('hi.integrations.connector.integration_connector.ExclusionLockContext')
+ @patch.object(HassConnector, '_sync_impl')
def test_sync_handles_runtime_error(self, mock_sync_impl, mock_lock_context):
"""Test sync method handles RuntimeError exceptions"""
# Mock RuntimeError in sync helper
@@ -60,8 +60,8 @@ class TestHassSynchronizerSyncMethod(TestCase):
# Verify error handling
self.assertIn('Database connection failed', result.error_list[0])
- @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')
- @patch.object(HassSynchronizer, '_sync_impl')
+ @patch('hi.integrations.connector.integration_connector.ExclusionLockContext')
+ @patch.object(HassConnector, '_sync_impl')
def test_sync_returns_error_result_on_exception(self, mock_sync_impl, mock_lock_context):
"""Test sync method returns proper error result when _sync_impl raises exception"""
# Mock RuntimeError in sync helper
@@ -81,11 +81,11 @@ class TestHassSynchronizerSyncMethod(TestCase):
self.assertEqual(len(result.info_list), 0) # No success messages on error
-class TestHassSynchronizerSyncHelper(TestCase):
+class TestHassConnectorSyncHelper(TestCase):
"""Test _sync_impl method logic"""
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
# Mock hass_manager and dependencies
self.mock_manager = Mock()
@@ -94,8 +94,8 @@ class TestHassSynchronizerSyncHelper(TestCase):
self.mock_manager.import_allowlist = None
-class TestHassSynchronizerStateConversion(TestCase):
- """Test HassSynchronizer with real HASS API data"""
+class TestHassConnectorStateConversion(TestCase):
+ """Test HassConnector with real HASS API data"""
@classmethod
def setUpClass(cls):
@@ -109,7 +109,7 @@ class TestHassSynchronizerStateConversion(TestCase):
cls.real_hass_states_data = []
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
def test_real_data_entity_id_diversity(self):
"""Test that real HASS data contains diverse entity types for comprehensive testing"""
@@ -135,11 +135,11 @@ class TestHassSynchronizerStateConversion(TestCase):
self.assertGreaterEqual(len(entity_ids), 10, "Should have substantial entities for sync testing")
-class TestHassSynchronizerTransactionBehavior(TestCase):
+class TestHassConnectorTransactionBehavior(TestCase):
"""Test transaction handling and atomicity in sync operations"""
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
def test_sync_impl_executes_entity_operations_atomically(self):
"""Test that all entity operations in sync_helper execute within single transaction"""
@@ -163,7 +163,7 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
mock_get_entities.return_value = {old_key: old_entity}
# Track transaction usage
- with patch('hi.services.hass.hass_sync.transaction.atomic') as mock_atomic:
+ with patch('hi.services.hass.hass_connector.transaction.atomic') as mock_atomic:
mock_atomic.return_value.__enter__ = Mock()
mock_atomic.return_value.__exit__ = Mock()
@@ -220,13 +220,13 @@ class TestHassSynchronizerTransactionBehavior(TestCase):
return hass_state
-class TestHassSynchronizerErrorScenarios(TestCase):
+class TestHassConnectorErrorScenarios(TestCase):
"""Test comprehensive error handling scenarios"""
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
- @patch.object(HassSynchronizer, 'hass_manager')
+ @patch.object(HassConnector, 'hass_manager')
def test_sync_impl_handles_api_fetch_failure(self, mock_hass_manager):
"""Test sync helper handles API fetch failures"""
# Mock manager with client that fails API fetch
@@ -241,9 +241,9 @@ class TestHassSynchronizerErrorScenarios(TestCase):
self.assertEqual(str(context.exception), "API connection failed")
- @patch('hi.services.hass.hass_sync.HassConverter.hass_states_to_hass_devices')
- @patch.object(HassSynchronizer, '_get_existing_hass_entities')
- @patch.object(HassSynchronizer, 'hass_manager')
+ @patch('hi.services.hass.hass_connector.HassConverter.hass_states_to_hass_devices')
+ @patch.object(HassConnector, '_get_existing_hass_entities')
+ @patch.object(HassConnector, 'hass_manager')
def test_sync_impl_handles_converter_failure(
self, mock_hass_manager,
mock_get_entities, mock_states_to_devices ):
@@ -265,7 +265,7 @@ class TestHassSynchronizerErrorScenarios(TestCase):
self.assertEqual(str(context.exception), "Invalid state data format")
- @patch('hi.services.hass.hass_sync.Entity.objects')
+ @patch('hi.services.hass.hass_connector.Entity.objects')
def test_get_existing_entities_handles_database_error(self, mock_entity_objects):
"""Test _get_existing_hass_entities handles database errors"""
# Mock database query failure
@@ -279,11 +279,11 @@ class TestHassSynchronizerErrorScenarios(TestCase):
self.assertEqual(str(context.exception), "Database connection lost")
-class TestHassSynchronizerMixinIntegration(TestCase):
+class TestHassConnectorMixinIntegration(TestCase):
"""Test integration with HassMixin"""
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
@patch('hi.services.hass.hass_mixins.HassManager')
def test_hass_mixin_integration(self, mock_manager_class):
@@ -297,14 +297,14 @@ class TestHassSynchronizerMixinIntegration(TestCase):
self.assertEqual(result, mock_manager_instance)
-class TestHassSynchronizerSyncResultGrouping(TestCase):
+class TestHassConnectorSyncResultGrouping(TestCase):
"""Phase 2 grouping behavior: HASS-imported entities are grouped
by Hi-side entity_type_str. The /api/states endpoint exposes no
area metadata, so the synchronizer falls back to entity_type as
the meaningful, available signal."""
def setUp(self):
- self.synchronizer = HassSynchronizer()
+ self.synchronizer = HassConnector()
def _entity(self, name, entity_type_str, integration_name):
entity = Mock()
@@ -367,7 +367,7 @@ class TestHassSynchronizerSyncResultGrouping(TestCase):
from hi.testing.async_task_utils import AsyncTaskTestCase
-class TestHassSynchronizerCheckNeedsSync(AsyncTaskTestCase):
+class TestHassConnectorCheckNeedsSync(AsyncTaskTestCase):
"""Issue #283 — sync-check probe shape for Home Assistant.
Pins the contract that the upstream key set is *post-allowlist*
@@ -399,7 +399,7 @@ class TestHassSynchronizerCheckNeedsSync(AsyncTaskTestCase):
)
def _run_check(self, hass_states_payload, allowlist=''):
- synchronizer = HassSynchronizer()
+ synchronizer = HassConnector()
manager = Mock()
manager.import_allowlist = allowlist
@@ -481,7 +481,7 @@ class TestHassSynchronizerCheckNeedsSync(AsyncTaskTestCase):
self.assertFalse(delta.needs_sync)
def test_returns_none_when_manager_not_ready(self):
- synchronizer = HassSynchronizer()
+ synchronizer = HassConnector()
async def get_manager():
return None
diff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.py
index 333c0ff0..a646fb38 100644
--- a/src/hi/services/hass/tests/test_hass_converter_create.py
+++ b/src/hi/services/hass/tests/test_hass_converter_create.py
@@ -19,7 +19,7 @@ from hi.apps.attribute.enums import AttributeType, AttributeValueType
from hi.apps.entity.enums import EntityStateType
from hi.apps.entity.models import Entity, EntityAttribute, EntityState
from hi.apps.event.models import EventDefinition
-from hi.integrations.connect.entity_operations import EntityIntegrationOperations
+from hi.integrations.entity_operations import EntityIntegrationOperations
from hi.services.hass.hass_converter import HassConverter
from hi.services.hass.hass_metadata import HassMetaData
from hi.services.hass.hass_models import HassDevice
diff --git a/src/hi/services/hass/tests/test_integration.py b/src/hi/services/hass/tests/test_integration.py
index b8089de3..d6e58201 100644
--- a/src/hi/services/hass/tests/test_integration.py
+++ b/src/hi/services/hass/tests/test_integration.py
@@ -10,7 +10,7 @@ from hi.apps.sense.models import Sensor
from hi.services.hass.hass_manager import HassManager
from hi.services.hass.hass_metadata import HassMetaData
-from hi.services.hass.integration import HassGateway
+from hi.services.hass.hass_connector import HassConnector
logging.disable(logging.CRITICAL)
@@ -26,7 +26,7 @@ class GetEntityVideoSnapshotTests(TestCase):
HassManager._instance = None
HassManager._lock = threading.Lock()
self.manager = HassManager()
- self.gateway = HassGateway()
+ self.gateway = HassConnector()
mock_client = Mock()
# HassClient strips the trailing slash on construction, so
diff --git a/src/hi/services/homebox/connector/hb_connector.py b/src/hi/services/homebox/connector/hb_external_view_resolver.py
similarity index 91%
rename from src/hi/services/homebox/connector/hb_connector.py
rename to src/hi/services/homebox/connector/hb_external_view_resolver.py
index 0880ec49..f2855151 100644
--- a/src/hi/services/homebox/connector/hb_connector.py
+++ b/src/hi/services/homebox/connector/hb_external_view_resolver.py
@@ -10,7 +10,7 @@ from urllib.parse import urljoin
from django.urls import reverse
from hi.apps.entity.models import Entity
-from hi.integrations.connect.external_view_data import (
+from hi.integrations.connector.external_view_data import (
AttachmentRef,
ExternalViewData,
MinimalViewData,
@@ -18,17 +18,22 @@ from hi.integrations.connect.external_view_data import (
StructuredViewData,
)
-from hi.services.homebox.shared.hb_converter import HB_ITEM_FIELD_PAIRS
-from hi.services.homebox.shared.hb_manager import HomeBoxManager
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_converter import HB_ITEM_FIELD_PAIRS
+from hi.services.homebox.hb_manager import HomeBoxManager
+from hi.services.homebox.hb_models import HbItem
logger = logging.getLogger(__name__)
-class HomeBoxConnector:
+class HomeBoxExternalViewResolver:
"""Stateless resolver for the entity-detail external-data view hook."""
def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:
+ # Live-attached entities only. Imported / detached HomeBox
+ # rows are HI-owned and have no live upstream view to fetch.
+ if not entity.is_external:
+ return None
+
item_id = entity.integration_name
if not item_id:
return None
diff --git a/src/hi/services/homebox/connector/hb_sync.py b/src/hi/services/homebox/connector/homebox_connector.py
similarity index 83%
rename from src/hi/services/homebox/connector/hb_sync.py
rename to src/hi/services/homebox/connector/homebox_connector.py
index 9b5d8f5a..f4f8d9f9 100644
--- a/src/hi/services/homebox/connector/hb_sync.py
+++ b/src/hi/services/homebox/connector/homebox_connector.py
@@ -5,26 +5,45 @@ from asgiref.sync import sync_to_async
from django.db import transaction
from hi.apps.entity.models import Entity
+from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
-from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.external_view_data import ExternalViewData
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.connector.sync_check import IntegrationSyncCheck, SyncDelta
+from hi.integrations.connector.sync_result import IntegrationSyncResult
+from hi.integrations.enums import IntegrationCapability
from hi.integrations.transient_models import IntegrationKey
-from hi.services.homebox.shared.hb_converter import HbConverter
+from hi.services.homebox.connector.hb_external_view_resolver import HomeBoxExternalViewResolver
+from hi.services.homebox.hb_controller import HomeBoxController
+from hi.services.homebox.monitors import HomeBoxMonitor
+from hi.services.homebox.hb_converter import HbConverter
+from hi.services.homebox.hb_manager import HomeBoxManager
from hi.services.homebox.hb_metadata import HbMetaData
from hi.services.homebox.hb_mixins import HomeBoxMixin
-from hi.services.homebox.shared.hb_models import HbItem
-from .hb_entity_factory import HbEntityFactory
+from hi.services.homebox.hb_models import HbItem
+from hi.services.homebox.hb_entity_factory import HbEntityFactory
logger = logging.getLogger(__name__)
-class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):
+class HomeBoxConnector( IntegrationConnector, HomeBoxMixin ):
def get_integration_metadata(self):
return HbMetaData
+ def get_monitor(self) -> HomeBoxMonitor:
+ return HomeBoxMonitor()
+
+ def get_controller(self) -> HomeBoxController:
+ return HomeBoxController()
+
+ def get_health_status_provider(self) -> HealthStatusProvider:
+ return HomeBoxManager()
+
+ def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:
+ return HomeBoxExternalViewResolver().get_external_view_data(entity)
+
def get_description(self, is_initial_connect: bool) -> Optional[str]:
return (
'HomeBox Labels and Locations are kept as metadata on '
@@ -72,12 +91,16 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):
@staticmethod
def _get_current_integration_keys() -> set:
+ # Scope to actively-attached (EXTERNAL) entities. Detached
+ # entities for the same integration are picked up by the
+ # auto-reconnect path during sync, not by this primary-match
+ # probe.
return {
IntegrationKey(
integration_id = integration_id,
integration_name = integration_name,
)
- for integration_id, integration_name in Entity.objects.filter(
+ for integration_id, integration_name in Entity.objects.external_for(
integration_id = HbMetaData.integration_id,
).values_list( 'integration_id', 'integration_name' )
}
@@ -200,6 +223,7 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):
previously-disconnected entity rather than creating a new one."""
HbEntityFactory.create_models_for_hb_item(
hb_item = upstream,
+ capability = IntegrationCapability.CONNECT,
entity = entity,
)
return
@@ -208,7 +232,12 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):
logger.debug( 'Getting existing HomeBox entities.' )
integration_key_to_entity = dict()
- entity_queryset = Entity.objects.filter( integration_id = HbMetaData.integration_id )
+ # Scope to actively-attached (EXTERNAL) entities. Detached
+ # rows for the same integration are picked up by the
+ # auto-reconnect path, not the primary-match scan.
+ entity_queryset = Entity.objects.external_for(
+ integration_id = HbMetaData.integration_id,
+ )
for entity in entity_queryset:
integration_key = entity.integration_key
if not integration_key:
@@ -227,7 +256,10 @@ class HomeBoxSynchronizer( IntegrationSynchronizer, HomeBoxMixin ):
def _create_entity( self,
item : HbItem,
result : IntegrationSyncResult ) -> Entity:
- entity = HbEntityFactory.create_models_for_hb_item( hb_item = item )
+ entity = HbEntityFactory.create_models_for_hb_item(
+ hb_item = item,
+ capability = IntegrationCapability.CONNECT,
+ )
result.created_list.append( entity.name )
return entity
diff --git a/src/hi/services/homebox/connector/proxy_views.py b/src/hi/services/homebox/connector/proxy_views.py
index 550439eb..821ea56b 100644
--- a/src/hi/services/homebox/connector/proxy_views.py
+++ b/src/hi/services/homebox/connector/proxy_views.py
@@ -10,7 +10,7 @@ from django.views import View
from hi.apps.entity.models import Entity
from hi.services.homebox.hb_metadata import HbMetaData
-from hi.services.homebox.shared.hb_manager import HomeBoxManager
+from hi.services.homebox.hb_manager import HomeBoxManager
logger = logging.getLogger(__name__)
diff --git a/src/hi/services/homebox/shared/hb_client.py b/src/hi/services/homebox/hb_client.py
similarity index 100%
rename from src/hi/services/homebox/shared/hb_client.py
rename to src/hi/services/homebox/hb_client.py
diff --git a/src/hi/services/homebox/shared/hb_client_factory.py b/src/hi/services/homebox/hb_client_factory.py
similarity index 100%
rename from src/hi/services/homebox/shared/hb_client_factory.py
rename to src/hi/services/homebox/hb_client_factory.py
diff --git a/src/hi/services/homebox/hb_controller.py b/src/hi/services/homebox/hb_controller.py
index 8c707a8a..766710aa 100644
--- a/src/hi/services/homebox/hb_controller.py
+++ b/src/hi/services/homebox/hb_controller.py
@@ -1,6 +1,6 @@
import logging
-from hi.integrations.connect.integration_controller import IntegrationController
+from hi.integrations.connector.integration_controller import IntegrationController
from hi.integrations.transient_models import IntegrationDetails
from hi.integrations.transient_models import IntegrationControlResult
diff --git a/src/hi/services/homebox/shared/hb_converter.py b/src/hi/services/homebox/hb_converter.py
similarity index 98%
rename from src/hi/services/homebox/shared/hb_converter.py
rename to src/hi/services/homebox/hb_converter.py
index 2ac414c0..2799f052 100644
--- a/src/hi/services/homebox/shared/hb_converter.py
+++ b/src/hi/services/homebox/hb_converter.py
@@ -270,8 +270,8 @@ class HbConverter:
'name': cls.hb_field_to_attribute_name( hb_field = hb_field ),
'value': hb_field.get('textValue', ''),
'value_type_str': str(AttributeValueType.TEXT),
- 'attribute_type_str': str(AttributeType.PREDEFINED),
- 'is_editable': False,
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'is_editable': True,
'is_required': False,
'order_id': order_id,
'integration_key_str': str( integration_key ),
@@ -319,8 +319,8 @@ class HbConverter:
'name': cls.hb_attachment_to_attribute_name( hb_attachment = hb_attachment ),
'value': hb_attachment.get('textValue', ''),
'value_type_str': str(AttributeValueType.FILE),
- 'attribute_type_str': str(AttributeType.PREDEFINED),
- 'is_editable': False,
+ 'attribute_type_str': str(AttributeType.CUSTOM),
+ 'is_editable': True,
'is_required': False,
'order_id': order_id,
'integration_key_str': str( integration_key ),
diff --git a/src/hi/services/homebox/connector/hb_entity_factory.py b/src/hi/services/homebox/hb_entity_factory.py
similarity index 58%
rename from src/hi/services/homebox/connector/hb_entity_factory.py
rename to src/hi/services/homebox/hb_entity_factory.py
index 424743a4..949bfb86 100644
--- a/src/hi/services/homebox/connector/hb_entity_factory.py
+++ b/src/hi/services/homebox/hb_entity_factory.py
@@ -4,24 +4,31 @@ import logging
from django.db import transaction
from hi.apps.entity.models import Entity
+from hi.integrations.enums import IntegrationCapability
from hi.services.homebox.hb_metadata import HbMetaData
-from hi.services.homebox.shared.hb_converter import HbConverter
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_converter import HbConverter
+from hi.services.homebox.hb_models import HbItem
logger = logging.getLogger(__name__)
class HbEntityFactory:
- """Builds and updates HI Entity rows from HomeBox upstream items."""
+ """Builds and updates HI Entity rows from HomeBox upstream items.
+
+ Shared by HomeBox's CONNECT-mode synchronizer and IMPORT-mode
+ importer. The ``capability`` parameter selects the entity-mode
+ flags: CONNECT produces read-only mirror entities owned by
+ HomeBox; IMPORT produces HI-owned editable entities."""
@classmethod
def create_models_for_hb_item( cls,
- hb_item : HbItem,
- entity : Optional[Entity] = None ) -> Entity:
+ hb_item : HbItem,
+ capability : IntegrationCapability,
+ entity : Optional[Entity] = None ) -> Entity:
"""
Create or repopulate the integration-owned components for an
- HbItem. When ``entity`` is None (the standard import path), a
+ HbItem. When ``entity`` is None (the standard create path), a
fresh Entity is created from the upstream payload. When
``entity`` is provided (the auto-reconnect path from Issue
#281), the integration-owned fields on that entity are
@@ -39,16 +46,28 @@ class HbEntityFactory:
entity_type_str = str( HbConverter.hb_item_to_entity_type( hb_item = hb_item ) ),
)
- # The fields below apply equally to fresh-create and
- # reconnect: integration_key, integration_payload, and the
- # integration-managed access flags are all integration-owned
- # and must reflect the current upstream state. The entity
- # name and entity_type are intentionally left alone on the
- # reconnect path (set above only for fresh-create).
- entity.integration_key = entity_integration_key
entity.integration_payload = entity_payload
- entity.can_user_delete = HbMetaData.allow_entity_deletion
- entity.allow_internal_attributes = HbMetaData.allow_internal_attributes
+ if capability == IntegrationCapability.IMPORT:
+ # Import-mode: HI owns the entity from day one but
+ # carries upstream provenance for re-import skip-
+ # detection and for the auto-reconnect path if the
+ # user later enables CONNECT. The provenance is
+ # recorded on previous_integration_*; integration_id
+ # stays NULL because no live integration owns this
+ # row.
+ entity.integration_key = None
+ entity.previous_integration_key = entity_integration_key
+ entity.can_user_delete = True
+ entity.allow_internal_attributes = True
+ else:
+ # CONNECT-mode (and any other capability): HomeBox
+ # remains the source of truth. Setting integration_key
+ # also clears previous_integration_* via the setter —
+ # safe whether this is a fresh-create or a reconnect
+ # of a previously-detached/imported row.
+ entity.integration_key = entity_integration_key
+ entity.can_user_delete = HbMetaData.allow_entity_deletion
+ entity.allow_internal_attributes = HbMetaData.allow_internal_attributes
entity.save()
return entity
diff --git a/src/hi/services/homebox/hb_manage_view_pane.py b/src/hi/services/homebox/hb_manage_view_pane.py
deleted file mode 100644
index 99eb30f1..00000000
--- a/src/hi/services/homebox/hb_manage_view_pane.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Dict
-
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-
-
-class HbManageViewPane( IntegrationManageViewPane ):
-
- def get_template_name( self ) -> str:
- return 'homebox/panes/hb_manage.html'
-
- def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
- return {}
diff --git a/src/hi/services/homebox/shared/hb_manager.py b/src/hi/services/homebox/hb_manager.py
similarity index 97%
rename from src/hi/services/homebox/shared/hb_manager.py
rename to src/hi/services/homebox/hb_manager.py
index 33d34b2a..aa65ffa4 100644
--- a/src/hi/services/homebox/shared/hb_manager.py
+++ b/src/hi/services/homebox/hb_manager.py
@@ -11,7 +11,6 @@ from hi.apps.system.enums import HealthStatusType
from hi.integrations.exceptions import (
IntegrationAttributeError,
IntegrationError,
- IntegrationDisabledError,
)
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -95,11 +94,6 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatus
self.clear_caches()
self.record_healthy('Reloaded')
- except IntegrationDisabledError:
- msg = 'HomeBox integration disabled'
- logger.info(msg)
- self.record_disabled( msg )
-
except IntegrationError as e:
error_msg = f'HomeBox integration configuration error: {e}'
logger.error(error_msg)
@@ -129,9 +123,6 @@ class HomeBoxManager( SingletonManager, AggregateHealthProvider, ApiHealthStatus
except Integration.DoesNotExist:
raise IntegrationError( 'HomeBox integration is not implemented.' )
- if not hb_integration.is_enabled:
- raise IntegrationDisabledError( 'HomeBox integration is not enabled.' )
-
integration_attributes = list(hb_integration.attributes.all())
return self._build_hb_attr_type_to_attribute_map(
integration_attributes = integration_attributes,
diff --git a/src/hi/services/homebox/hb_metadata.py b/src/hi/services/homebox/hb_metadata.py
index f877c27d..7c023d1c 100644
--- a/src/hi/services/homebox/hb_metadata.py
+++ b/src/hi/services/homebox/hb_metadata.py
@@ -1,3 +1,4 @@
+from hi.integrations.enums import IntegrationCapability
from hi.integrations.transient_models import IntegrationMetaData
from .enums import HbAttributeType
@@ -10,4 +11,8 @@ HbMetaData = IntegrationMetaData(
allow_entity_deletion = False,
allow_internal_attributes = False,
logo_static_path = 'img/integrations/homebox.svg',
+ capabilities = frozenset({
+ IntegrationCapability.CONNECT,
+ IntegrationCapability.IMPORT,
+ }),
)
diff --git a/src/hi/services/homebox/hb_mixins.py b/src/hi/services/homebox/hb_mixins.py
index 0e72d6ed..f6bad42b 100644
--- a/src/hi/services/homebox/hb_mixins.py
+++ b/src/hi/services/homebox/hb_mixins.py
@@ -2,7 +2,7 @@ from asgiref.sync import sync_to_async
import asyncio
import logging
-from .shared.hb_manager import HomeBoxManager
+from hi.services.homebox.hb_manager import HomeBoxManager
logger = logging.getLogger(__name__)
diff --git a/src/hi/services/homebox/shared/hb_models.py b/src/hi/services/homebox/hb_models.py
similarity index 100%
rename from src/hi/services/homebox/shared/hb_models.py
rename to src/hi/services/homebox/hb_models.py
diff --git a/src/hi/services/homebox/importer/hb_attribute_sync.py b/src/hi/services/homebox/importer/hb_attribute_sync.py
deleted file mode 100644
index 65be2a55..00000000
--- a/src/hi/services/homebox/importer/hb_attribute_sync.py
+++ /dev/null
@@ -1,224 +0,0 @@
-"""Preserved attribute-sync code from the pre-#354 copy-on-sync
-architecture. Dormant — no live caller. The HomeBox Importer in #358
-will adapt these into the Importer protocol's run_import method.
-"""
-import logging
-from typing import Dict, List
-
-from django.db import transaction
-
-from hi.apps.entity.models import Entity, EntityAttribute
-
-from hi.integrations.connect.sync_result import IntegrationSyncResult
-from hi.integrations.transient_models import IntegrationKey
-
-from hi.services.homebox.shared.hb_converter import HbConverter
-from hi.services.homebox.shared.hb_models import HbItem
-from .hb_importer import HbImporter
-
-logger = logging.getLogger(__name__)
-
-
-class HbAttributeSync:
-
- @classmethod
- def sync_entity_attributes( cls,
- entity: Entity,
- hb_item: HbItem,
- result: IntegrationSyncResult ):
- attribute_message_list = list()
-
- integration_key_to_regular_field = dict()
- hb_field_list = HbConverter.hb_item_to_attribute_field_list( hb_item = hb_item )
- for order_id, hb_field in enumerate( hb_field_list ):
- if not isinstance( hb_field, dict ):
- continue
-
- integration_key = HbConverter.hb_field_to_integration_key( hb_field = hb_field )
- if integration_key:
- integration_key_to_regular_field[integration_key] = (hb_field, order_id)
-
- integration_key_to_attachment = dict()
- attachment_list = HbConverter.hb_item_to_attachment_field_list( hb_item = hb_item )
- field_count = len( hb_field_list )
- for order_id, hb_attachment in enumerate( attachment_list, start = field_count ):
- if not isinstance( hb_attachment, dict ):
- continue
-
- integration_key = HbConverter.hb_attachment_to_integration_key( hb_attachment = hb_attachment )
- if integration_key:
- integration_key_to_attachment[integration_key] = ( hb_attachment, order_id )
-
- active_integration_keys = set(integration_key_to_regular_field.keys())
- active_integration_keys.update(integration_key_to_attachment.keys())
-
- integration_key_to_attr = cls.get_existing_hb_attributes( entity = entity )
-
- with transaction.atomic():
-
- for integration_key, field_data in integration_key_to_regular_field.items():
- hb_field, order_id = field_data
- attribute = integration_key_to_attr.get( integration_key )
-
- if attribute:
- cls.update_attribute(
- attribute = attribute,
- hb_field = hb_field,
- order_id = order_id,
- message_list = attribute_message_list,
- updated_prefix = 'Field attribute updated',
- )
- else:
- created_attribute = cls.create_attribute(
- entity = entity,
- hb_field = hb_field,
- order_id = order_id,
- )
- if created_attribute:
- integration_key_to_attr[integration_key] = created_attribute
- attribute_message_list.append(
- f'Field attribute added: {created_attribute.name}'
- )
- continue
-
- for integration_key, hb_attachment_tuple in integration_key_to_attachment.items():
- hb_attachment, order_id = hb_attachment_tuple
- attribute = integration_key_to_attr.get( integration_key )
-
- if attribute:
- cls.update_attachment_attribute(
- attribute = attribute,
- hb_attachment = hb_attachment,
- order_id = order_id,
- message_list = attribute_message_list,
- updated_prefix = 'Attachment attribute updated',
- )
- else:
- created_attribute = cls.create_attachment_attribute(
- entity = entity,
- hb_attachment = hb_attachment,
- order_id = order_id,
- )
- if created_attribute:
- integration_key_to_attr[integration_key] = created_attribute
- attribute_message_list.append(
- f'Attachment attribute added: {created_attribute.name}'
- )
- continue
-
- for field_key, attribute in list( integration_key_to_attr.items() ):
- if attribute.entity_id != entity.id:
- continue
-
- if field_key not in active_integration_keys:
- cls.remove_attribute( attribute = attribute, message_list = attribute_message_list )
- del integration_key_to_attr[field_key]
- continue
-
- if (
- attribute_message_list
- and entity.name not in result.created_list
- and entity.name not in result.updated_list
- ):
- result.updated_list.append( entity.name )
- return
-
- @classmethod
- def get_existing_hb_attributes( cls, entity: Entity ) -> Dict[ IntegrationKey, EntityAttribute ]:
- integration_key_to_attribute = dict()
-
- queryset = entity.attributes.filter(
- integration_key_str__isnull = False
- ).exclude( integration_key_str = '' )
-
- for attribute in queryset:
- try:
- integration_key = IntegrationKey.from_string( attribute.integration_key_str )
- except Exception:
- logger.debug(
- 'Ignoring entity attribute with invalid integration key: '
- f'{attribute.integration_key_str}'
- )
- continue
-
- integration_key_to_attribute[integration_key] = attribute
-
- return integration_key_to_attribute
-
- @classmethod
- def create_attribute( cls,
- entity: Entity,
- hb_field: dict,
- order_id: int ) -> EntityAttribute:
- return HbImporter.create_attribute_from_hb_field(
- entity = entity,
- hb_field = hb_field,
- order_id = order_id,
- )
-
- @classmethod
- def update_attribute( cls,
- attribute: EntityAttribute,
- hb_field: dict,
- order_id: int,
- message_list: List[str],
- updated_prefix: str ):
- was_changed = HbImporter.update_attribute_from_hb_field(
- attribute = attribute,
- hb_field = hb_field,
- order_id = order_id,
- )
- if was_changed:
- message = (
- f'{updated_prefix}: '
- f'{HbConverter.hb_field_to_attribute_name( hb_field = hb_field )}'
- )
- message_list.append( message )
- return
-
- @classmethod
- def remove_attribute( cls,
- attribute: EntityAttribute,
- message_list: List[str] ):
- # Hard-delete: these are integration-owned attributes (not
- # editable by the user), so the SoftDeleteAttributeModel's
- # default soft-delete + restore affordance doesn't apply.
- # Soft-deleting would surface the row under "Deleted
- # Attributes" with a restore button, and a restore creates
- # an inconsistency between HI and the integration's source
- # of truth.
- old_name = attribute.name
- attribute.delete( hard_delete = True )
- message_list.append( f'Field attribute removed: {old_name}' )
- return
-
- @classmethod
- def create_attachment_attribute( cls,
- entity: Entity,
- hb_attachment: dict,
- order_id: int ) -> EntityAttribute:
- return HbImporter.create_attribute_from_hb_attachment(
- entity = entity,
- hb_attachment = hb_attachment,
- order_id = order_id,
- )
-
- @classmethod
- def update_attachment_attribute( cls,
- attribute: EntityAttribute,
- hb_attachment: dict,
- order_id: int,
- message_list: List[str],
- updated_prefix: str ):
- was_changed = HbImporter.update_attribute_from_hb_attachment(
- attribute = attribute,
- hb_attachment = hb_attachment,
- order_id = order_id,
- )
- if was_changed:
- message = (
- f'{updated_prefix}: '
- f'{HbConverter.hb_attachment_to_attribute_name( hb_attachment = hb_attachment )}'
- )
- message_list.append( message )
- return
diff --git a/src/hi/services/homebox/importer/hb_importer.py b/src/hi/services/homebox/importer/hb_importer.py
index f2b1d686..dc90f09a 100644
--- a/src/hi/services/homebox/importer/hb_importer.py
+++ b/src/hi/services/homebox/importer/hb_importer.py
@@ -1,17 +1,40 @@
-"""HomeBox attribute-population classmethods. Dormant — these are
-called only from the preserved attribute-sync helpers in
-hb_attribute_sync.py. #358's Importer will exercise them via the
-Importer protocol."""
+"""HomeBox attribute-population for the IMPORT capability.
+
+Exercised by ``HomeBoxImporter.run_import`` via
+``populate_attributes_for_imported_entity``. Creates user-owned
+(CUSTOM) EntityAttribute rows so the operator can freely edit the
+imported data after it lands in HI."""
from typing import Dict, Optional
import logging
from hi.apps.entity.models import Entity, EntityAttribute
-from hi.services.homebox.shared.hb_converter import HbConverter
+from hi.services.homebox.hb_converter import HbConverter
logger = logging.getLogger(__name__)
+def populate_attributes_for_imported_entity( entity : Entity, hb_item ) -> None:
+ """Create user-owned EntityAttribute rows from HomeBox fields and
+ attachments. Called once per item at import time inside the
+ entity's transaction."""
+ hb_field_list = HbConverter.hb_item_to_attribute_field_list( hb_item = hb_item )
+ for order_id, hb_field in enumerate( hb_field_list ):
+ HbImporter.create_attribute_from_hb_field(
+ entity = entity,
+ hb_field = hb_field,
+ order_id = order_id,
+ )
+ attachment_list = HbConverter.hb_item_to_attachment_field_list( hb_item = hb_item )
+ start_order = len( hb_field_list )
+ for order_id, hb_attachment in enumerate( attachment_list, start = start_order ):
+ HbImporter.create_attribute_from_hb_attachment(
+ entity = entity,
+ hb_attachment = hb_attachment,
+ order_id = order_id,
+ )
+
+
class HbImporter:
@classmethod
diff --git a/src/hi/services/homebox/importer/homebox_importer.py b/src/hi/services/homebox/importer/homebox_importer.py
new file mode 100644
index 00000000..1f3a92a5
--- /dev/null
+++ b/src/hi/services/homebox/importer/homebox_importer.py
@@ -0,0 +1,172 @@
+"""HomeBox concrete IntegrationImporter.
+
+Implements the IntegrationImporter protocol for HomeBox. The Connect-mode
+connector lives at ``services/homebox/connector/homebox_connector.py``;
+this is the parallel for the IMPORT capability.
+
+Import is add-only: items not already present in HI (by
+integration_name match) get created as user-owned (INTERNAL)
+entities; existing matches are skipped and surfaced as the
+preview's skip count.
+"""
+import logging
+from typing import List
+
+from django.db import transaction
+
+from hi.apps.common.database_lock import ExclusionLockContext
+from hi.apps.entity.models import Entity
+
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.enums import IntegrationCapability
+from hi.integrations.entity_operations import EntityIntegrationOperations
+from hi.integrations.importer.integration_importer import IntegrationImporter
+from hi.integrations.importer.transient_models import (
+ CandidateItem,
+ IntegrationDiscardResult,
+ IntegrationImportResult,
+)
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import IntegrationMetaData, IntegrationValidationResult
+
+from hi.services.homebox.hb_metadata import HbMetaData
+from hi.services.homebox.hb_mixins import HomeBoxMixin
+from hi.services.homebox.hb_entity_factory import HbEntityFactory
+
+from .hb_importer import populate_attributes_for_imported_entity
+
+logger = logging.getLogger(__name__)
+
+
+class HomeBoxImporter( IntegrationImporter, HomeBoxMixin ):
+
+ def get_metadata(self) -> IntegrationMetaData:
+ return HbMetaData
+
+ def validate_configuration(
+ self,
+ integration_attributes: List[IntegrationAttribute],
+ ) -> IntegrationValidationResult:
+ return self.hb_manager().validate_configuration(
+ integration_attributes = integration_attributes,
+ )
+
+ def get_candidate_items(self) -> List[CandidateItem]:
+ """Lightweight upstream pull for the preview step. Returns the
+ full upstream item list as ``CandidateItem``s; the framework
+ decides which are new vs. already-imported by comparing
+ ``integration_name`` against existing HI entities."""
+ hb_manager = self.hb_manager()
+ if not hb_manager.hb_client:
+ return []
+ summary_list = hb_manager.fetch_hb_items_summary_from_api()
+ candidates: List[CandidateItem] = []
+ for summary in summary_list:
+ item_id = summary.get( 'id' )
+ if item_id is None:
+ continue
+ # ``archived: true`` upstream items are skipped — they
+ # mirror the same filter as the Connect-mode sync check
+ # so imports don't pull HomeBox's tombstones.
+ if summary.get( 'archived' ) is True:
+ continue
+ candidates.append( CandidateItem(
+ name = summary.get( 'name' ) or f'HomeBox Item {item_id}',
+ integration_name = str( item_id ),
+ ) )
+ return candidates
+
+ def run_import(self) -> IntegrationImportResult:
+ """Execute the import. Per-entity transaction so one item's
+ failure does not abort the batch. Shares the
+ ``integrations_sync`` exclusion lock with Connect-side sync
+ so Import and Connect serialize against each other."""
+ result = IntegrationImportResult( title = 'Import Result' )
+ with ExclusionLockContext( name = IntegrationConnector.SYNCHRONIZATION_LOCK_NAME ):
+ self._run_import_locked( result = result )
+ return result
+
+ def _run_import_locked(self, result: IntegrationImportResult) -> None:
+ hb_manager = self.hb_manager()
+ if not hb_manager.hb_client:
+ reason = (
+ hb_manager.health_status.last_message
+ or 'HomeBox integration is disabled or not configured.'
+ )
+ result.error_list.append( f'Cannot import from HomeBox: {reason}' )
+ return
+
+ try:
+ item_list = hb_manager.fetch_hb_items_from_api()
+ except Exception as e:
+ logger.exception( 'HomeBox import failed during fetch.' )
+ result.error_list.append( f'Cannot import from HomeBox: {e}' )
+ return
+
+ # Skip-detection against already-imported rows.
+ existing_integration_names = set(
+ Entity.objects.imported_for(
+ integration_id = HbMetaData.integration_id,
+ ).values_list( 'previous_integration_name', flat = True )
+ )
+
+ created_entities = []
+ for hb_item in item_list:
+ if hb_item.archived is True:
+ continue
+ integration_name = str( hb_item.id )
+ if integration_name in existing_integration_names:
+ result.items_skipped_count += 1
+ continue
+ try:
+ with transaction.atomic():
+ entity = HbEntityFactory.create_models_for_hb_item(
+ hb_item = hb_item,
+ capability = IntegrationCapability.IMPORT,
+ )
+ populate_attributes_for_imported_entity(
+ entity = entity,
+ hb_item = hb_item,
+ )
+ except Exception as e:
+ logger.exception(
+ f'HomeBox import failed for item {integration_name}.'
+ )
+ result.error_list.append(
+ f'Item {integration_name}: {e}'
+ )
+ continue
+ result.items_imported_count += 1
+ result.imported_list.append( entity.name )
+ created_entities.append( entity )
+
+ if created_entities:
+ result.placement_input = self.group_entities_for_placement(
+ entities = created_entities,
+ )
+
+ def discard_imported_data( self, integration_id: str ) -> IntegrationDiscardResult:
+ """Remove all entities previously imported under this
+ integration_id. Any coexisting active-Connect entities for
+ the same integration are untouched."""
+ seed_ids = set(
+ Entity.objects.imported_for(
+ integration_id = integration_id,
+ ).values_list( 'id', flat = True )
+ )
+ if not seed_ids:
+ return IntegrationDiscardResult( count = 0 )
+ try:
+ EntityIntegrationOperations.remove_entities_with_closure(
+ seed_entity_ids = seed_ids,
+ integration_name = HbMetaData.label,
+ preserve_user_data = False,
+ result = None,
+ )
+ except Exception as e:
+ logger.exception( f'HomeBox discard failed for {integration_id}.' )
+ return IntegrationDiscardResult(
+ count = 0,
+ errors = [ str( e ) ],
+ )
+ return IntegrationDiscardResult( count = len( seed_ids ) )
diff --git a/src/hi/services/homebox/integration.py b/src/hi/services/homebox/integration.py
index 01b3a4e8..a8db01c0 100644
--- a/src/hi/services/homebox/integration.py
+++ b/src/hi/services/homebox/integration.py
@@ -1,29 +1,22 @@
import logging
from typing import List, Optional
-from hi.apps.entity.models import Entity
from hi.apps.system.enums import HealthStatusType
-from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.external_view_data import ExternalViewData
-from hi.integrations.connect.integration_controller import IntegrationController
-from hi.integrations.connect.integration_gateway import IntegrationGateway
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.importer.integration_importer import IntegrationImporter
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
IntegrationMetaData,
IntegrationValidationResult,
)
-from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from .hb_controller import HomeBoxController
-from .hb_manage_view_pane import HbManageViewPane
-from .shared.hb_manager import HomeBoxManager
-from .hb_metadata import HbMetaData
-from .connector.hb_sync import HomeBoxSynchronizer
-from .monitors import HomeBoxMonitor
+from hi.services.homebox.hb_manager import HomeBoxManager
+from hi.services.homebox.hb_metadata import HbMetaData
+from hi.services.homebox.connector.homebox_connector import HomeBoxConnector
+from hi.services.homebox.importer.homebox_importer import HomeBoxImporter
logger = logging.getLogger(__name__)
@@ -32,18 +25,9 @@ class HomeBoxGateway(IntegrationGateway):
def get_metadata(self) -> IntegrationMetaData:
return HbMetaData
- def get_manage_view_pane(self) -> IntegrationManageViewPane:
- return HbManageViewPane()
-
- def get_monitor(self) -> PeriodicMonitor:
- return HomeBoxMonitor()
-
- def get_controller(self) -> IntegrationController:
- return HomeBoxController()
-
def notify_settings_changed(self):
"""Notify HomeBox integration that settings have changed.
-
+
Delegates to HomeBoxManager to reload configuration and notify monitors.
"""
try:
@@ -53,11 +37,11 @@ class HomeBoxGateway(IntegrationGateway):
except Exception as e:
logger.exception(f'Error notifying HomeBox integration of settings change: {e}')
- def get_health_status_provider(self) -> HealthStatusProvider:
- return HomeBoxManager()
+ def get_connector(self) -> IntegrationConnector:
+ return HomeBoxConnector()
- def get_synchronizer(self) -> IntegrationSynchronizer:
- return HomeBoxSynchronizer()
+ def get_importer(self) -> IntegrationImporter:
+ return HomeBoxImporter()
def validate_configuration(
self,
@@ -89,7 +73,3 @@ class HomeBoxGateway(IntegrationGateway):
except Exception as e:
logger.exception(f'Error in HomeBox access validation: {e}')
return ConnectionTestResult.failure(f'Access validation error: {e}')
-
- def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:
- from .connector.hb_connector import HomeBoxConnector
- return HomeBoxConnector().get_external_view_data(entity)
diff --git a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html b/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
deleted file mode 100644
index a29825a7..00000000
--- a/src/hi/services/homebox/templates/homebox/panes/hb_manage.html
+++ /dev/null
@@ -1,7 +0,0 @@
-{% comment %}
- Integration-specific custom content slot for the HomeBox manage
- page. The framework owns the page header (title/logo, lifecycle
- actions, sync actions) and the attribute editor; this template
- renders any HomeBox-specific UI between them. Currently empty —
- kept as a documented extension point.
-{% endcomment %}
diff --git a/src/hi/services/homebox/tests/test_hb_client.py b/src/hi/services/homebox/tests/test_hb_client.py
index 1cb32e19..819b3e2f 100644
--- a/src/hi/services/homebox/tests/test_hb_client.py
+++ b/src/hi/services/homebox/tests/test_hb_client.py
@@ -5,7 +5,7 @@ from unittest.mock import Mock, patch
from django.test import SimpleTestCase
from requests import Response
-from hi.services.homebox.shared.hb_client import HbClient
+from hi.services.homebox.hb_client import HbClient
logging.disable(logging.CRITICAL)
diff --git a/src/hi/services/homebox/tests/test_hb_client_factory.py b/src/hi/services/homebox/tests/test_hb_client_factory.py
index 1b792bdf..212aba3f 100644
--- a/src/hi/services/homebox/tests/test_hb_client_factory.py
+++ b/src/hi/services/homebox/tests/test_hb_client_factory.py
@@ -13,7 +13,7 @@ from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import IntegrationKey, IntegrationValidationResult
from hi.services.homebox.enums import HbAttributeType
-from hi.services.homebox.shared.hb_client_factory import HbClientFactory
+from hi.services.homebox.hb_client_factory import HbClientFactory
from hi.services.homebox.hb_metadata import HbMetaData
logging.disable(logging.CRITICAL)
@@ -50,10 +50,10 @@ class TestHbClientFactory(TestCase):
return attributes
- @patch('hi.services.homebox.shared.hb_client_factory.HbClient')
+ @patch('hi.services.homebox.hb_client_factory.HbClient')
def test_create_client_success(self, mock_client_class):
"""Test successful client creation with valid attributes."""
- from hi.services.homebox.shared.hb_client import HbClient as RealHbClient
+ from hi.services.homebox.hb_client import HbClient as RealHbClient
mock_client_class.API_URL = RealHbClient.API_URL
mock_client_class.API_USER = RealHbClient.API_USER
mock_client_class.API_PASSWORD = RealHbClient.API_PASSWORD
@@ -148,10 +148,10 @@ class TestHbClientFactory(TestCase):
mock_client.get_items_summary.assert_called_once()
- @patch('hi.services.homebox.shared.hb_client_factory.HbClient')
+ @patch('hi.services.homebox.hb_client_factory.HbClient')
def test_create_client_threads_timeout_to_client(self, mock_client_class):
"""create_client passes timeout_secs through to the HbClient."""
- from hi.services.homebox.shared.hb_client import HbClient as RealHbClient
+ from hi.services.homebox.hb_client import HbClient as RealHbClient
mock_client_class.API_URL = RealHbClient.API_URL
mock_client_class.API_USER = RealHbClient.API_USER
mock_client_class.API_PASSWORD = RealHbClient.API_PASSWORD
diff --git a/src/hi/services/homebox/tests/test_hb_converter.py b/src/hi/services/homebox/tests/test_hb_converter.py
index 51767129..8f1413d2 100644
--- a/src/hi/services/homebox/tests/test_hb_converter.py
+++ b/src/hi/services/homebox/tests/test_hb_converter.py
@@ -4,8 +4,8 @@ from unittest.mock import Mock
from django.test import TestCase
from hi.apps.attribute.enums import AttributeValueType
-from hi.services.homebox.shared.hb_converter import HbConverter
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_converter import HbConverter
+from hi.services.homebox.hb_models import HbItem
logging.disable(logging.CRITICAL)
diff --git a/src/hi/services/homebox/tests/test_hb_entity_factory.py b/src/hi/services/homebox/tests/test_hb_entity_factory.py
index 63c05da0..a9b51168 100644
--- a/src/hi/services/homebox/tests/test_hb_entity_factory.py
+++ b/src/hi/services/homebox/tests/test_hb_entity_factory.py
@@ -5,9 +5,10 @@ from django.test import TestCase
from hi.apps.entity.enums import EntityType
from hi.apps.entity.models import Entity
-from hi.services.homebox.connector.hb_entity_factory import HbEntityFactory
+from hi.integrations.enums import IntegrationCapability
+from hi.services.homebox.hb_entity_factory import HbEntityFactory
from hi.services.homebox.hb_metadata import HbMetaData
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_models import HbItem
logging.disable(logging.CRITICAL)
@@ -32,10 +33,13 @@ class TestHbEntityFactory(TestCase):
return HbItem(api_dict=api_dict, client=client)
- def test_create_models_for_hb_item_creates_entity(self):
+ def test_create_models_for_hb_item_creates_entity_connect_mode(self):
item = self._mock_item(item_id='item-create', name='Drill')
- entity = HbEntityFactory.create_models_for_hb_item(hb_item=item)
+ entity = HbEntityFactory.create_models_for_hb_item(
+ hb_item=item,
+ capability=IntegrationCapability.CONNECT,
+ )
self.assertIsInstance(entity, Entity)
self.assertEqual(entity.integration_id, HbMetaData.integration_id)
@@ -43,10 +47,23 @@ class TestHbEntityFactory(TestCase):
self.assertEqual(entity.name, 'Drill')
self.assertEqual(entity.entity_type, EntityType.OTHER)
self.assertFalse(entity.allow_internal_attributes)
+ self.assertTrue(entity.is_external)
self.assertNotIn('description', entity.integration_payload)
self.assertEqual(entity.integration_payload.get('location', {}).get('name'), 'Garage')
self.assertEqual(entity.integration_payload.get('tags')[0].get('name'), 'Tools')
+ def test_create_models_for_hb_item_creates_entity_import_mode(self):
+ item = self._mock_item(item_id='item-import', name='Drill')
+
+ entity = HbEntityFactory.create_models_for_hb_item(
+ hb_item=item,
+ capability=IntegrationCapability.IMPORT,
+ )
+
+ self.assertTrue(entity.allow_internal_attributes)
+ self.assertTrue(entity.can_user_delete)
+ self.assertTrue(entity.is_imported)
+
def test_create_models_with_existing_entity_does_not_create_new_and_preserves_name(self):
"""Issue #281 reconnect contract: when an existing Entity is
passed in, repopulate its integration-owned fields without
@@ -61,6 +78,7 @@ class TestHbEntityFactory(TestCase):
returned = HbEntityFactory.create_models_for_hb_item(
hb_item=item,
+ capability=IntegrationCapability.CONNECT,
entity=existing,
)
diff --git a/src/hi/services/homebox/tests/test_hb_connector.py b/src/hi/services/homebox/tests/test_hb_external_view_resolver.py
similarity index 83%
rename from src/hi/services/homebox/tests/test_hb_connector.py
rename to src/hi/services/homebox/tests/test_hb_external_view_resolver.py
index 29b8d643..88e68a86 100644
--- a/src/hi/services/homebox/tests/test_hb_connector.py
+++ b/src/hi/services/homebox/tests/test_hb_external_view_resolver.py
@@ -13,22 +13,25 @@ from unittest.mock import Mock, patch
from django.test import TestCase
from hi.apps.entity.models import Entity
-from hi.integrations.connect.external_view_data import (
+from hi.integrations.connector.external_view_data import (
MinimalViewData,
NameValuePair,
StructuredViewData,
)
-from hi.services.homebox.connector.hb_connector import HomeBoxConnector
+from hi.services.homebox.connector.hb_external_view_resolver import HomeBoxExternalViewResolver
from hi.services.homebox.hb_metadata import HbMetaData
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_models import HbItem
logging.disable(logging.CRITICAL)
-class HomeBoxConnectorTests(TestCase):
+class HomeBoxExternalViewResolverTests(TestCase):
def _make_hb_entity(self, item_id: str = '42') -> Entity:
+ # Connect-mode HomeBox entity: integration_id set marks it
+ # external. The resolver gates on this so Import-mode
+ # entities don't surface live HomeBox view data.
return Entity.objects.create(
name=f'HomeBox Item {item_id}',
entity_type_str='LIGHT',
@@ -44,8 +47,8 @@ class HomeBoxConnectorTests(TestCase):
def test_returns_none_for_native_entity(self):
entity = self._make_native_entity()
- connector = HomeBoxConnector()
- result = connector.get_external_view_data(entity)
+ resolver = HomeBoxExternalViewResolver()
+ result = resolver.get_external_view_data(entity)
self.assertIsNone(result)
def test_returns_minimal_when_upstream_fetch_raises(self):
@@ -58,10 +61,10 @@ class HomeBoxConnectorTests(TestCase):
manager.ensure_initialized = Mock()
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxManager',
+ 'hi.services.homebox.connector.hb_external_view_resolver.HomeBoxManager',
return_value=manager,
):
- result = HomeBoxConnector().get_external_view_data(entity)
+ result = HomeBoxExternalViewResolver().get_external_view_data(entity)
self.assertIsInstance(result, MinimalViewData)
self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/42')
@@ -82,10 +85,10 @@ class HomeBoxConnectorTests(TestCase):
manager.ensure_initialized = Mock()
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxManager',
+ 'hi.services.homebox.connector.hb_external_view_resolver.HomeBoxManager',
return_value=manager,
):
- result = HomeBoxConnector().get_external_view_data(entity)
+ result = HomeBoxExternalViewResolver().get_external_view_data(entity)
self.assertIsInstance(result, MinimalViewData)
self.assertIsNone(result.deep_link_url)
@@ -129,10 +132,10 @@ class HomeBoxConnectorTests(TestCase):
manager.ensure_initialized = Mock()
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxManager',
+ 'hi.services.homebox.connector.hb_external_view_resolver.HomeBoxManager',
return_value=manager,
):
- result = HomeBoxConnector().get_external_view_data(entity)
+ result = HomeBoxExternalViewResolver().get_external_view_data(entity)
self.assertIsInstance(result, StructuredViewData)
self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/123')
@@ -185,10 +188,10 @@ class HomeBoxConnectorTests(TestCase):
manager.ensure_initialized = Mock()
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxManager',
+ 'hi.services.homebox.connector.hb_external_view_resolver.HomeBoxManager',
return_value=manager,
):
- result = HomeBoxConnector().get_external_view_data(entity)
+ result = HomeBoxExternalViewResolver().get_external_view_data(entity)
self.assertIsInstance(result, StructuredViewData)
self.assertEqual(len(result.attachments), 2)
@@ -218,10 +221,10 @@ class HomeBoxConnectorTests(TestCase):
manager.ensure_initialized = Mock()
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxManager',
+ 'hi.services.homebox.connector.hb_external_view_resolver.HomeBoxManager',
return_value=manager,
):
- result = HomeBoxConnector().get_external_view_data(entity)
+ result = HomeBoxExternalViewResolver().get_external_view_data(entity)
self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/500')
@@ -235,9 +238,9 @@ class HomeBoxConnectorTests(TestCase):
manager.ensure_initialized = Mock()
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxManager',
+ 'hi.services.homebox.connector.hb_external_view_resolver.HomeBoxManager',
return_value=manager,
):
- result = HomeBoxConnector().get_external_view_data(entity)
+ result = HomeBoxExternalViewResolver().get_external_view_data(entity)
self.assertEqual(result.deep_link_url, 'http://homebox.example.com/item/600')
diff --git a/src/hi/services/homebox/tests/test_hb_importer.py b/src/hi/services/homebox/tests/test_hb_importer.py
index 082208fe..be5d8666 100644
--- a/src/hi/services/homebox/tests/test_hb_importer.py
+++ b/src/hi/services/homebox/tests/test_hb_importer.py
@@ -4,9 +4,10 @@ from unittest.mock import Mock
from django.test import TestCase
from hi.apps.attribute.enums import AttributeValueType
-from hi.services.homebox.connector.hb_entity_factory import HbEntityFactory
+from hi.integrations.enums import IntegrationCapability
+from hi.services.homebox.hb_entity_factory import HbEntityFactory
from hi.services.homebox.importer.hb_importer import HbImporter
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_models import HbItem
logging.disable(logging.CRITICAL)
@@ -33,7 +34,10 @@ class TestHbImporter(TestCase):
def test_create_and_update_file_attribute_from_attachment(self):
item = self._mock_item(item_id='item-file-sync')
- entity = HbEntityFactory.create_models_for_hb_item(hb_item=item)
+ entity = HbEntityFactory.create_models_for_hb_item(
+ hb_item=item,
+ capability=IntegrationCapability.IMPORT,
+ )
attachment = {
'id': 'att-2',
diff --git a/src/hi/services/homebox/tests/test_hb_manager.py b/src/hi/services/homebox/tests/test_hb_manager.py
index fc664ad1..218e41cf 100644
--- a/src/hi/services/homebox/tests/test_hb_manager.py
+++ b/src/hi/services/homebox/tests/test_hb_manager.py
@@ -7,7 +7,7 @@ from hi.integrations.exceptions import IntegrationAttributeError
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import IntegrationKey
from hi.services.homebox.enums import HbAttributeType
-from hi.services.homebox.shared.hb_manager import HomeBoxManager
+from hi.services.homebox.hb_manager import HomeBoxManager
from hi.services.homebox.hb_metadata import HbMetaData
diff --git a/src/hi/services/homebox/tests/test_hb_models.py b/src/hi/services/homebox/tests/test_hb_models.py
index 39c88a45..b1ed94d0 100644
--- a/src/hi/services/homebox/tests/test_hb_models.py
+++ b/src/hi/services/homebox/tests/test_hb_models.py
@@ -1,7 +1,7 @@
import logging
from django.test import SimpleTestCase
-from hi.services.homebox.shared.hb_models import HbItem
+from hi.services.homebox.hb_models import HbItem
logging.disable(logging.CRITICAL)
diff --git a/src/hi/services/homebox/tests/test_hb_sync.py b/src/hi/services/homebox/tests/test_homebox_connector.py
similarity index 89%
rename from src/hi/services/homebox/tests/test_hb_sync.py
rename to src/hi/services/homebox/tests/test_homebox_connector.py
index 1e19e7d2..9bfc7569 100644
--- a/src/hi/services/homebox/tests/test_hb_sync.py
+++ b/src/hi/services/homebox/tests/test_homebox_connector.py
@@ -5,17 +5,18 @@ from unittest.mock import Mock, patch
from django.test import SimpleTestCase
from hi.apps.entity.models import Entity
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.sync_result import IntegrationSyncResult
+from hi.integrations.enums import IntegrationCapability
from hi.integrations.transient_models import IntegrationKey
from hi.services.homebox.hb_metadata import HbMetaData
-from hi.services.homebox.connector.hb_sync import HomeBoxSynchronizer
+from hi.services.homebox.connector.homebox_connector import HomeBoxConnector
from hi.testing.async_task_utils import AsyncTaskTestCase
logging.disable(logging.CRITICAL)
-class TestHomeBoxSynchronizer(SimpleTestCase):
+class TestHomeBoxConnector(SimpleTestCase):
def _key(self, name: str) -> IntegrationKey:
return IntegrationKey(
@@ -24,7 +25,7 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
)
def test_sync_helper_uses_mocked_api_response_and_delegates_entity_sync(self):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
manager = Mock()
manager.hb_client = object()
manager.fetch_hb_items_from_api.return_value = [Mock(), Mock(), Mock()]
@@ -41,7 +42,7 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
)
def test_sync_helper_entities_create_update_remove_entities(self):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
result = IntegrationSyncResult(title='HomeBox Import Result')
item_new = Mock(name='item_new')
@@ -66,13 +67,13 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
with ExitStack() as stack:
stack.enter_context(
patch(
- 'hi.services.homebox.connector.hb_sync.transaction.atomic',
+ 'hi.services.homebox.connector.homebox_connector.transaction.atomic',
return_value=nullcontext(),
)
)
stack.enter_context(
patch(
- 'hi.services.homebox.connector.hb_sync.HbConverter.hb_item_to_integration_key',
+ 'hi.services.homebox.connector.homebox_connector.HbConverter.hb_item_to_integration_key',
side_effect=key_from_item,
)
)
@@ -100,7 +101,7 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
patch.object(synchronizer, '_remove_entity')
)
# Reconnect pre-pass (Issue #281) is framework-level on
- # IntegrationSynchronizer.reconnect_disconnected_items and
+ # IntegrationConnector.reconnect_disconnected_items and
# does its own DB query; this SimpleTestCase doesn't allow
# DB access, so stub it out. The reconnect logic itself
# is covered by FindReconnectCandidatesTests in
@@ -130,14 +131,14 @@ class TestHomeBoxSynchronizer(SimpleTestCase):
for message in result.error_list))
-class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):
+class TestHomeBoxConnectorSyncResultGrouping(SimpleTestCase):
"""Phase 2 grouping behavior: HomeBox has no domain notion of
grouping, so every imported item lands in `ungrouped_items`.
`groups` stays empty. The framework's placement modal decides
how to surface ungrouped items at render time."""
def test_sync_impl_populates_ungrouped_items_only(self):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
manager = Mock()
manager.hb_client = object()
manager.fetch_hb_items_from_api.return_value = [Mock(), Mock()]
@@ -177,7 +178,7 @@ class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):
)
def test_sync_impl_emits_empty_when_no_items_imported(self):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
manager = Mock()
manager.hb_client = object()
manager.fetch_hb_items_from_api.return_value = []
@@ -190,27 +191,27 @@ class TestHomeBoxSynchronizerSyncResultGrouping(SimpleTestCase):
self.assertIsNone(result.placement_input)
-class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):
+class TestHomeBoxConnectorRebuildIntegrationComponents(SimpleTestCase):
"""
Issue #281: the per-integration ``_rebuild_integration_components``
override is the only piece each synchronizer contributes to the
framework-level reconnect path. This test verifies that
- HomeBoxSynchronizer's override dispatches to ``HbEntityFactory`` with
+ HomeBoxConnector's override dispatches to ``HbEntityFactory`` with
the existing-entity argument set. Framework-level behavior
(find candidates, strip prefix, clear previous identity, update
entity map, info_list note) is covered by tests of
- IntegrationSynchronizer.reconnect_disconnected_items. End-to-end
+ IntegrationConnector.reconnect_disconnected_items. End-to-end
DB cycle is exercised in Phase 6.
"""
def test_dispatches_to_converter_with_existing_entity(self):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
result = IntegrationSyncResult(title='HomeBox Test')
existing_entity = Mock(name='existing_entity')
upstream = Mock(name='hb_item')
with patch(
- 'hi.services.homebox.connector.hb_sync.HbEntityFactory.create_models_for_hb_item'
+ 'hi.services.homebox.connector.homebox_connector.HbEntityFactory.create_models_for_hb_item'
) as mock_converter:
synchronizer._rebuild_integration_components(
entity=existing_entity,
@@ -220,11 +221,12 @@ class TestHomeBoxSynchronizerRebuildIntegrationComponents(SimpleTestCase):
mock_converter.assert_called_once_with(
hb_item=upstream,
+ capability=IntegrationCapability.CONNECT,
entity=existing_entity,
)
-class TestHomeBoxSynchronizerCheckNeedsSync(AsyncTaskTestCase):
+class TestHomeBoxConnectorCheckNeedsSync(AsyncTaskTestCase):
"""Issue #283 — sync-check probe shape for HomeBox.
Uses a real DB so the probe's ``Entity.objects.filter(...)``
@@ -257,7 +259,7 @@ class TestHomeBoxSynchronizerCheckNeedsSync(AsyncTaskTestCase):
)
def _run_check(self, summary_list):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
manager = Mock()
async def fetch_summary():
@@ -299,7 +301,7 @@ class TestHomeBoxSynchronizerCheckNeedsSync(AsyncTaskTestCase):
self.assertFalse(delta.needs_sync)
def test_returns_none_when_manager_not_ready(self):
- synchronizer = HomeBoxSynchronizer()
+ synchronizer = HomeBoxConnector()
async def get_manager():
return None
diff --git a/src/hi/services/homebox/tests/test_homebox_importer.py b/src/hi/services/homebox/tests/test_homebox_importer.py
new file mode 100644
index 00000000..265f3b27
--- /dev/null
+++ b/src/hi/services/homebox/tests/test_homebox_importer.py
@@ -0,0 +1,148 @@
+"""HomeBoxImporter contract + behavior tests."""
+import logging
+from unittest.mock import Mock, patch
+
+from django.test import TestCase
+
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity
+from hi.integrations.importer.transient_models import IntegrationDiscardResult
+from hi.services.homebox.hb_metadata import HbMetaData
+from hi.services.homebox.importer.homebox_importer import HomeBoxImporter
+from hi.services.homebox.hb_models import HbItem
+
+logging.disable(logging.CRITICAL)
+
+
+def _hb_item(item_id, name='Item', archived=False):
+ return HbItem(
+ api_dict={
+ 'id': item_id,
+ 'name': name,
+ 'archived': archived,
+ 'location': {'id': 'loc-1', 'name': 'Garage'},
+ 'tags': [],
+ 'fields': [],
+ 'attachments': [],
+ },
+ client=Mock(),
+ )
+
+
+class TestHomeBoxImporterGetCandidateItems(TestCase):
+
+ def test_returns_unarchived_items(self):
+ importer = HomeBoxImporter()
+ mock_manager = Mock()
+ mock_manager.hb_client = Mock()
+ mock_manager.fetch_hb_items_summary_from_api.return_value = [
+ {'id': 'item-1', 'name': 'Hammer', 'archived': False},
+ {'id': 'item-2', 'name': 'Saw', 'archived': True},
+ {'id': 'item-3', 'name': 'Screwdriver', 'archived': False},
+ ]
+ with patch.object(HomeBoxImporter, 'hb_manager', return_value=mock_manager):
+ candidates = importer.get_candidate_items()
+
+ self.assertEqual(len(candidates), 2)
+ self.assertEqual(
+ sorted(c.integration_name for c in candidates),
+ ['item-1', 'item-3'],
+ )
+
+ def test_returns_empty_when_no_client(self):
+ importer = HomeBoxImporter()
+ mock_manager = Mock()
+ mock_manager.hb_client = None
+ with patch.object(HomeBoxImporter, 'hb_manager', return_value=mock_manager):
+ self.assertEqual(importer.get_candidate_items(), [])
+
+
+class TestHomeBoxImporterRunImport(TestCase):
+
+ def test_skips_already_imported_items(self):
+ # An existing imported entity blocks re-import of the same id.
+ Entity.objects.create(
+ previous_integration_id=HbMetaData.integration_id,
+ previous_integration_name='item-1',
+ name='Already imported',
+ entity_type_str=str(EntityType.OTHER),
+ )
+ importer = HomeBoxImporter()
+ mock_manager = Mock()
+ mock_manager.hb_client = Mock()
+ mock_manager.fetch_hb_items_from_api.return_value = [
+ _hb_item('item-1', 'Should skip'),
+ _hb_item('item-2', 'Should import'),
+ ]
+ with patch.object(HomeBoxImporter, 'hb_manager', return_value=mock_manager):
+ result = importer.run_import()
+
+ self.assertEqual(result.items_imported_count, 1)
+ self.assertEqual(result.items_skipped_count, 1)
+ self.assertEqual(result.error_list, [])
+ new_entity = Entity.objects.get(previous_integration_name='item-2')
+ self.assertTrue(new_entity.is_imported)
+ self.assertTrue(new_entity.allow_internal_attributes)
+ self.assertIsNone(new_entity.integration_id)
+ self.assertEqual(new_entity.previous_integration_id, HbMetaData.integration_id)
+
+ def test_per_item_failure_does_not_abort_batch(self):
+ importer = HomeBoxImporter()
+ mock_manager = Mock()
+ mock_manager.hb_client = Mock()
+ mock_manager.fetch_hb_items_from_api.return_value = [
+ _hb_item('item-a', 'Item A'),
+ _hb_item('item-b', 'Item B'),
+ ]
+ # First item raises during entity creation; second proceeds.
+ with patch.object(HomeBoxImporter, 'hb_manager', return_value=mock_manager):
+ with patch(
+ 'hi.services.homebox.importer.homebox_importer.HbEntityFactory.create_models_for_hb_item',
+ side_effect=[RuntimeError('upstream blew up'), Mock(name='entity-b')],
+ ):
+ result = importer.run_import()
+
+ self.assertEqual(result.items_imported_count, 1)
+ self.assertEqual(len(result.error_list), 1)
+ self.assertIn('item-a', result.error_list[0])
+
+
+class TestHomeBoxImporterDiscard(TestCase):
+
+ def test_discard_targets_only_imported(self):
+ # Imported entity — should be removed.
+ Entity.objects.create(
+ previous_integration_id=HbMetaData.integration_id,
+ previous_integration_name='import-1',
+ name='Imported',
+ entity_type_str=str(EntityType.OTHER),
+ allow_internal_attributes=True,
+ )
+ # Connect-mode entity — must be left alone.
+ Entity.objects.create(
+ integration_id=HbMetaData.integration_id,
+ integration_name='connect-1',
+ name='Connected',
+ entity_type_str=str(EntityType.OTHER),
+ allow_internal_attributes=False,
+ )
+
+ importer = HomeBoxImporter()
+ discard_result = importer.discard_imported_data(
+ integration_id=HbMetaData.integration_id,
+ )
+
+ self.assertIsInstance(discard_result, IntegrationDiscardResult)
+ self.assertEqual(discard_result.count, 1)
+ self.assertFalse(
+ Entity.objects.filter(previous_integration_name='import-1').exists()
+ )
+ self.assertTrue(
+ Entity.objects.filter(integration_name='connect-1').exists()
+ )
+
+ def test_discard_with_no_imported_returns_zero(self):
+ importer = HomeBoxImporter()
+ result = importer.discard_imported_data(integration_id=HbMetaData.integration_id)
+ self.assertEqual(result.count, 0)
+ self.assertEqual(result.errors, [])
diff --git a/src/hi/services/homebox/tests/test_integration_gateway.py b/src/hi/services/homebox/tests/test_integration_gateway.py
index da8ab2f4..8e9a182a 100644
--- a/src/hi/services/homebox/tests/test_integration_gateway.py
+++ b/src/hi/services/homebox/tests/test_integration_gateway.py
@@ -1,36 +1,36 @@
"""
-Smoke tests for HomeBoxGateway hooks the framework calls.
+Smoke tests for HomeBox connector hooks the framework calls.
-The substantive behavior of each gateway method lives in the
-collaborator it delegates to (HomeBoxConnector, HomeBoxManager,
-HomeBoxSynchronizer); these tests pin the delegation contract.
+The substantive behavior of each connector method lives in the
+collaborator it delegates to (HomeBoxExternalViewResolver, HomeBoxManager,
+HomeBoxConnector); these tests pin the delegation contract.
"""
import logging
from unittest.mock import Mock, patch
from django.test import SimpleTestCase
-from hi.services.homebox.integration import HomeBoxGateway
+from hi.services.homebox.connector.homebox_connector import HomeBoxConnector
logging.disable(logging.CRITICAL)
-class HomeBoxGatewayExternalViewDataTests(SimpleTestCase):
+class HomeBoxConnectorExternalViewDataTests(SimpleTestCase):
- def test_delegates_to_homebox_connector(self):
- gateway = HomeBoxGateway()
+ def test_delegates_to_homebox_external_view_resolver(self):
+ connector = HomeBoxConnector()
entity = Mock(name='entity')
expected_result = Mock(name='external_view_data')
with patch(
- 'hi.services.homebox.connector.hb_connector.HomeBoxConnector'
- ) as connector_cls:
- connector_instance = connector_cls.return_value
- connector_instance.get_external_view_data.return_value = expected_result
+ 'hi.services.homebox.connector.homebox_connector.HomeBoxExternalViewResolver'
+ ) as resolver_cls:
+ resolver_instance = resolver_cls.return_value
+ resolver_instance.get_external_view_data.return_value = expected_result
- result = gateway.get_external_view_data(entity)
+ result = connector.get_external_view_data(entity)
self.assertIs(result, expected_result)
- connector_cls.assert_called_once_with()
- connector_instance.get_external_view_data.assert_called_once_with(entity)
+ resolver_cls.assert_called_once_with()
+ resolver_instance.get_external_view_data.assert_called_once_with(entity)
diff --git a/src/hi/services/zoneminder/integration.py b/src/hi/services/zoneminder/integration.py
index 33413319..28fcaf96 100644
--- a/src/hi/services/zoneminder/integration.py
+++ b/src/hi/services/zoneminder/integration.py
@@ -1,33 +1,20 @@
import logging
from typing import List, Optional
-from hi.apps.entity.models import Entity
-from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
-from hi.apps.entity.enums import VideoStreamType, VideoStreamMode
-from hi.apps.entity.constants import VideoStreamMetadataKeys
-from hi.apps.sense.transient_models import SensorResponse
from hi.apps.system.enums import HealthStatusType
-from hi.apps.system.health_status_provider import HealthStatusProvider
-from hi.integrations.connect.integration_controller import IntegrationController
-from hi.integrations.connect.integration_gateway import IntegrationGateway
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.connector.integration_connector import IntegrationConnector
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import (
ConnectionTestResult,
IntegrationMetaData,
IntegrationValidationResult,
)
-from hi.apps.monitor.periodic_monitor import PeriodicMonitor
-from .constants import ZmDetailKeys
-from .zm_controller import ZoneMinderController
-from .zm_manage_view_pane import ZmManageViewPane
from .zm_manager import ZoneMinderManager
from .zm_metadata import ZmMetaData
-from .zm_sync import ZoneMinderSynchronizer
-from .monitors import ZoneMinderMonitor
+from .zm_connector import ZmConnector
from .zm_mixins import ZoneMinderMixin
logger = logging.getLogger(__name__)
@@ -38,18 +25,9 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
def get_metadata(self) -> IntegrationMetaData:
return ZmMetaData
- def get_manage_view_pane(self) -> IntegrationManageViewPane:
- return ZmManageViewPane()
-
- def get_monitor(self) -> PeriodicMonitor:
- return ZoneMinderMonitor()
-
- def get_controller(self) -> IntegrationController:
- return ZoneMinderController()
-
def notify_settings_changed(self):
"""Notify ZoneMinder integration that settings have changed.
-
+
Delegates to ZoneMinderManager to reload configuration and notify monitors.
"""
try:
@@ -58,12 +36,9 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
logger.debug('ZoneMinder integration notified of settings change')
except Exception as e:
logger.exception(f'Error notifying ZoneMinder integration of settings change: {e}')
-
- def get_health_status_provider(self) -> HealthStatusProvider:
- return ZoneMinderManager()
- def get_synchronizer(self) -> IntegrationSynchronizer:
- return ZoneMinderSynchronizer()
+ def get_connector(self) -> IntegrationConnector:
+ return ZmConnector()
def validate_configuration(
self,
@@ -95,130 +70,3 @@ class ZoneMinderGateway( IntegrationGateway, ZoneMinderMixin ):
except Exception as e:
logger.exception(f'Error in ZoneMinder access validation: {e}')
return ConnectionTestResult.failure(f'Access validation error: {e}')
-
- def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
- """Return a fresh still frame for the ZoneMinder monitor backing
- this entity (``nph-zms?mode=single``). Returns None when the
- entity isn't a ZM monitor or the integration_name can't be
- parsed."""
- if not entity.has_video_snapshot:
- return None
-
- if not ( entity.integration_id == ZmMetaData.integration_id
- and entity.integration_name
- and entity.integration_name.startswith(
- self.zm_manager().ZM_MONITOR_INTEGRATION_NAME_PREFIX )):
- return None
-
- try:
- monitor_id = int( entity.integration_name.split('.')[1] )
- except ( IndexError, ValueError ):
- logger.warning(
- f'Could not parse monitor ID from entity integration name: '
- f'{entity.integration_name}'
- )
- return None
-
- return VideoSnapshot(
- source_url = self.zm_manager().get_video_snapshot_url( monitor_id ),
- metadata = { 'monitor_id': monitor_id },
- )
-
- def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
- """Get entity's primary video stream (typically live)"""
- if not entity.has_video_stream:
- return None
-
- # Check if this is a ZoneMinder camera entity
- if (entity.integration_id == ZmMetaData.integration_id
- and entity.integration_name
- and entity.integration_name.startswith(
- self.zm_manager().ZM_MONITOR_INTEGRATION_NAME_PREFIX)):
-
- # Extract monitor ID from integration name (format: "monitor.{id}")
- try:
- monitor_id = int(entity.integration_name.split('.')[1])
- video_url = self.zm_manager().get_video_stream_url(monitor_id)
-
- return VideoStream(
- stream_type=VideoStreamType.MJPEG,
- source_url=video_url,
- metadata={
- 'monitor_id': monitor_id,
- VideoStreamMetadataKeys.STREAM_MODE: str(VideoStreamMode.LIVE)
- }
- )
- except (IndexError, ValueError):
- logger.warning(f"Could not parse monitor ID from entity integration name:"
- f" {entity.integration_name}")
-
- return None
-
- def get_sensor_response_event_snapshot_url(
- self,
- sensor_response: SensorResponse) -> Optional[str]:
- """Per-event snapshot URL for a ZM SensorResponse. Reads the
- event_id from detail_attrs (where the monitor stores it on
- every START / END row), builds the portal URL fresh each
- call so an operator-side portal-URL change auto-heals every
- historical row."""
- if not sensor_response.has_event_video_snapshot:
- return None
- event_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME
- if not sensor_response.detail_attrs:
- return None
- raw_event_id = sensor_response.detail_attrs.get(event_id_fieldname)
- if raw_event_id is None:
- return None
- try:
- event_id = int(raw_event_id)
- except (ValueError, TypeError):
- logger.warning(
- 'Could not parse event ID from ZM sensor response: %s',
- sensor_response.detail_attrs,
- )
- return None
- return self.zm_manager().get_event_snapshot_url(event_id=event_id)
-
- def get_sensor_response_video_stream(
- self,
- sensor_response: SensorResponse) -> Optional[VideoStream]:
- """Get video stream from sensor response (recorded events)"""
- # if not sensor_response.has_event_video_clip:
- # return None
-
- event_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME
-
- # Check if this sensor response has an event ID in its detail_attrs
- if (sensor_response.detail_attrs
- and event_id_fieldname in sensor_response.detail_attrs):
-
- try:
- event_id = int(sensor_response.detail_attrs[event_id_fieldname])
- video_url = self.zm_manager().get_event_video_stream_url(event_id)
-
- # Extract duration from detail_attrs if available
- metadata = {
- event_id_fieldname: event_id,
- VideoStreamMetadataKeys.STREAM_MODE: str(VideoStreamMode.RECORDED)
- }
-
- # Look for duration in detail_attrs using the ZoneMinder constant
- if ZmDetailKeys.DURATION_SECS in sensor_response.detail_attrs:
- try:
- duration_secs = float(sensor_response.detail_attrs[ZmDetailKeys.DURATION_SECS])
- metadata[VideoStreamMetadataKeys.DURATION_SECS] = int(duration_secs)
- except (ValueError, TypeError):
- logger.debug(f"Could not parse duration from sensor response:"
- f" {sensor_response.detail_attrs.get(ZmDetailKeys.DURATION_SECS)}")
-
- return VideoStream(
- stream_type=VideoStreamType.MJPEG,
- source_url=video_url,
- metadata=metadata
- )
- except (ValueError, TypeError):
- logger.warning(f"Could not parse event ID from sensor response:"
- f" {sensor_response.detail_attrs}")
-
- return None
diff --git a/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html b/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
deleted file mode 100644
index 27f14470..00000000
--- a/src/hi/services/zoneminder/templates/zoneminder/panes/zm_manage.html
+++ /dev/null
@@ -1,7 +0,0 @@
-{% comment %}
- Integration-specific custom content slot for the ZoneMinder manage
- page. The framework owns the page header (title/logo, lifecycle
- actions, sync actions) and the attribute editor; this template
- renders any ZM-specific UI between them. Currently empty — kept as
- a documented extension point.
-{% endcomment %}
diff --git a/src/hi/services/zoneminder/tests/test_zm_sync.py b/src/hi/services/zoneminder/tests/test_zm_connector.py
similarity index 93%
rename from src/hi/services/zoneminder/tests/test_zm_sync.py
rename to src/hi/services/zoneminder/tests/test_zm_connector.py
index 51ff7926..4827c3f7 100644
--- a/src/hi/services/zoneminder/tests/test_zm_sync.py
+++ b/src/hi/services/zoneminder/tests/test_zm_connector.py
@@ -9,24 +9,24 @@ from hi.apps.entity.models import Entity, EntityAttribute
from hi.apps.event.models import EventDefinition
from hi.apps.sense.models import Sensor
-from hi.integrations.connect.entity_operations import EntityIntegrationOperations
+from hi.integrations.entity_operations import EntityIntegrationOperations
from hi.integrations.integration_manager import IntegrationManager
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
-from hi.services.zoneminder.zm_sync import ZoneMinderSynchronizer
+from hi.services.zoneminder.zm_connector import ZmConnector
from hi.services.zoneminder.zm_metadata import ZmMetaData
logging.disable(logging.CRITICAL)
-class TestZoneMinderSynchronizerLockBehavior(TestCase):
+class TestZmConnectorLockBehavior(TestCase):
"""Test database lock coordination with exception handling"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
- @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')
+ @patch('hi.integrations.connector.integration_connector.ExclusionLockContext')
def test_sync_uses_exclusion_lock(self, mock_lock_context):
"""Test sync method uses exclusion lock and returns sync results"""
# Mock a successful lock context
@@ -48,7 +48,7 @@ class TestZoneMinderSynchronizerLockBehavior(TestCase):
self.assertGreater(len(result.error_list), 0)
self.assertIn('Sync problem. ZM integration disabled?', result.error_list[0])
- @patch('hi.integrations.connect.integration_synchronizer.ExclusionLockContext')
+ @patch('hi.integrations.connector.integration_connector.ExclusionLockContext')
def test_sync_handles_lock_runtime_error(self, mock_lock_context):
"""Test sync method handles RuntimeError from lock context and returns proper error result"""
lock_error_msg = "Lock acquisition failed"
@@ -69,11 +69,11 @@ class TestZoneMinderSynchronizerLockBehavior(TestCase):
self.assertIsInstance(result.error_list, list)
-class TestZoneMinderSynchronizerSyncHelper(TestCase):
+class TestZmConnectorSyncHelper(TestCase):
"""Test main sync helper logic and flow control"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
# Mock the zm_manager
self.mock_manager = Mock()
@@ -123,11 +123,11 @@ class TestZoneMinderSynchronizerSyncHelper(TestCase):
self.assertEqual(mock_sync_monitors.call_args[1]['result'], result)
-class TestZoneMinderSynchronizerStateSync(TestCase):
+class TestZmConnectorStateSync(TestCase):
"""Test state synchronization and value range updates"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
# Mock the zm_manager
self.mock_manager = Mock()
@@ -141,9 +141,9 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
)
self.synchronizer._zm_manager = self.mock_manager
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')
- @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')
- @patch.object(ZoneMinderSynchronizer, '_create_zm_entity')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Sensor.objects.filter_by_integration_key')
+ @patch.object(ZmConnector, '_create_zm_entity')
def test_sync_states_creates_zm_entity_when_missing(self, mock_create_entity, mock_sensor_filter, mock_entity_filter):
"""Test _sync_states creates ZM entity when it doesn't exist and verifies entity creation parameters"""
# Mock ZM states
@@ -189,8 +189,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
# Test behavior: should not have errors when successful
self.assertEqual(len(result.error_list), 0)
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')
- @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Sensor.objects.filter_by_integration_key')
def test_sync_states_missing_sensor_error(self, mock_sensor_filter, mock_entity_filter):
"""Test _sync_states handles missing run state sensor and stops processing gracefully"""
# Mock states
@@ -217,8 +217,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
# Should not have created any entities since sensor missing
self.assertEqual(len(result.info_list), 0)
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')
- @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Sensor.objects.filter_by_integration_key')
def test_sync_states_updates_value_range_when_changed(self, mock_sensor_filter, mock_entity_filter):
"""Test _sync_states updates value range when states change and persists changes"""
# Mock new states
@@ -264,8 +264,8 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
self.assertIn('start', message)
self.assertIn('pause', message)
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')
- @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Sensor.objects.filter_by_integration_key')
def test_sync_states_no_update_when_unchanged(self, mock_sensor_filter, mock_entity_filter):
"""Test _sync_states doesn't update when state values unchanged and preserves existing state"""
# Mock states - identical to existing
@@ -307,11 +307,11 @@ class TestZoneMinderSynchronizerStateSync(TestCase):
self.assertEqual(len(update_messages), 0)
-class TestZoneMinderSynchronizerMonitorSync(TestCase):
+class TestZmConnectorMonitorSync(TestCase):
"""Test monitor synchronization and entity lifecycle management"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
# Mock the zm_manager
self.mock_manager = Mock()
@@ -362,11 +362,11 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
# Test no errors in successful creation scenario
self.assertEqual(len(result.error_list), 0)
- @patch.object(ZoneMinderSynchronizer, '_fetch_zm_monitors')
- @patch.object(ZoneMinderSynchronizer, '_get_existing_zm_monitor_entities')
- @patch.object(ZoneMinderSynchronizer, '_create_monitor_entity')
- @patch.object(ZoneMinderSynchronizer, '_update_entity')
- @patch.object(ZoneMinderSynchronizer, '_remove_entity')
+ @patch.object(ZmConnector, '_fetch_zm_monitors')
+ @patch.object(ZmConnector, '_get_existing_zm_monitor_entities')
+ @patch.object(ZmConnector, '_create_monitor_entity')
+ @patch.object(ZmConnector, '_update_entity')
+ @patch.object(ZmConnector, '_remove_entity')
def test_sync_monitors_updates_existing_entities(self, mock_remove, mock_update, mock_create, mock_get_existing, mock_fetch):
"""Test _sync_monitors updates existing entities"""
# Mock monitors and entities with same key
@@ -426,11 +426,11 @@ class TestZoneMinderSynchronizerMonitorSync(TestCase):
self.assertEqual(len(result.error_list), 0)
-class TestZoneMinderSynchronizerFetchMonitors(TestCase):
+class TestZmConnectorFetchMonitors(TestCase):
"""Test ZM monitor fetching and integration key generation"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
# Mock the zm_manager
self.mock_manager = Mock()
@@ -477,18 +477,18 @@ class TestZoneMinderSynchronizerFetchMonitors(TestCase):
self.mock_manager.get_zm_monitors.assert_called_once_with(force_load=True)
-class TestZoneMinderSynchronizerExistingEntities(TestCase):
+class TestZmConnectorExistingEntities(TestCase):
"""Test existing entity retrieval and error handling"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
# Mock the zm_manager
self.mock_manager = Mock()
self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
self.synchronizer._zm_manager = self.mock_manager
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter')
def test_get_existing_zm_monitor_entities_filters_by_integration_id(self, mock_filter):
"""Test _get_existing_zm_monitor_entities filters by correct integration ID"""
mock_filter.return_value = []
@@ -498,7 +498,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):
mock_filter.assert_called_once_with(integration_id=ZmMetaData.integration_id)
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter')
def test_get_existing_zm_monitor_entities_handles_missing_integration_key(self, mock_filter):
"""Test entity retrieval handles entities without integration keys"""
# Mock entity without integration key
@@ -516,7 +516,7 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):
# Should NOT include entity in result (mock key doesn't start with 'monitor' prefix)
self.assertEqual(len(result_dict), 0)
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter')
def test_get_existing_zm_monitor_entities_filters_monitor_entities(self, mock_filter):
"""Test entity retrieval only includes monitor entities"""
# Mock entities - one monitor, one non-monitor
@@ -539,11 +539,11 @@ class TestZoneMinderSynchronizerExistingEntities(TestCase):
self.assertNotIn(other_key, result_dict)
-class TestZoneMinderSynchronizerEntityUpdate(TestCase):
+class TestZmConnectorEntityUpdate(TestCase):
"""Test entity update logic"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
def test_update_entity_preserves_user_edited_name(self):
"""Operator-edited names are user-owned after creation; an
@@ -621,13 +621,13 @@ class TestZoneMinderSynchronizerEntityUpdate(TestCase):
self.assertTrue(entity.has_video_snapshot)
-class TestZoneMinderSynchronizerEntityRemoval(TestCase):
+class TestZmConnectorEntityRemoval(TestCase):
"""Test intelligent entity deletion"""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
- @patch.object(ZoneMinderSynchronizer, '_remove_entity_intelligently')
+ @patch.object(ZmConnector, '_remove_entity_intelligently')
def test_remove_entity_calls_intelligent_deletion(self, mock_intelligent_removal):
"""Test _remove_entity calls intelligent deletion with correct parameters"""
mock_entity = Mock()
@@ -638,7 +638,7 @@ class TestZoneMinderSynchronizerEntityRemoval(TestCase):
mock_intelligent_removal.assert_called_once_with(mock_entity, result)
-class TestZoneMinderSynchronizerFunctionConstants(TestCase):
+class TestZmConnectorFunctionConstants(TestCase):
"""Test monitor function name constants"""
def test_monitor_function_name_label_dict_completeness(self):
@@ -646,15 +646,15 @@ class TestZoneMinderSynchronizerFunctionConstants(TestCase):
expected_functions = ['None', 'Monitor', 'Modect', 'Record', 'Mocord', 'Nodect']
for function in expected_functions:
- self.assertIn(function, ZoneMinderSynchronizer.MONITOR_FUNCTION_NAME_LABEL_DICT)
+ self.assertIn(function, ZmConnector.MONITOR_FUNCTION_NAME_LABEL_DICT)
# Labels should match function names
self.assertEqual(
- ZoneMinderSynchronizer.MONITOR_FUNCTION_NAME_LABEL_DICT[function],
+ ZmConnector.MONITOR_FUNCTION_NAME_LABEL_DICT[function],
function
)
-class TestZoneMinderSynchronizerWithRealData(TestCase):
+class TestZmConnectorWithRealData(TestCase):
"""Test synchronizer with real ZoneMinder API response data"""
@classmethod
@@ -670,7 +670,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
cls.real_monitors_data = json.load(f)
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
# Mock the zm_manager
self.mock_manager = Mock()
@@ -703,8 +703,8 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
mock_monitors.append(mock_monitor)
return mock_monitors
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter_by_integration_key')
- @patch('hi.services.zoneminder.zm_sync.Sensor.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter_by_integration_key')
+ @patch('hi.services.zoneminder.zm_connector.Sensor.objects.filter_by_integration_key')
def test_sync_states_with_real_zm_state_names(self, mock_sensor_filter, mock_entity_filter):
"""Test state sync handles real ZM state names: default, Away, HomeDay, Disabled"""
# Use real state data
@@ -738,9 +738,9 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
mock_entity_state.save.assert_called_once()
self.assertIn('Updated ZM state values to:', result.info_list[0])
- @patch.object(ZoneMinderSynchronizer, '_fetch_zm_monitors')
- @patch.object(ZoneMinderSynchronizer, '_get_existing_zm_monitor_entities')
- @patch.object(ZoneMinderSynchronizer, '_create_monitor_entity')
+ @patch.object(ZmConnector, '_fetch_zm_monitors')
+ @patch.object(ZmConnector, '_get_existing_zm_monitor_entities')
+ @patch.object(ZmConnector, '_create_monitor_entity')
def test_sync_monitors_with_real_monitor_configurations(self, mock_create, mock_get_existing, mock_fetch):
"""Test monitor sync with real monitor configurations and diverse setups"""
# Use real monitor data to create integration keys and monitors
@@ -814,7 +814,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
mock_entity.save.assert_not_called()
self.assertEqual(result.updated_list, [])
- @patch('hi.services.zoneminder.zm_sync.Entity.objects.filter')
+ @patch('hi.services.zoneminder.zm_connector.Entity.objects.filter')
def test_get_existing_entities_with_real_monitor_id_patterns(self, mock_filter):
"""Test existing entity retrieval with realistic monitor ID patterns"""
# Create mock entities with integration keys matching real monitor IDs
@@ -875,10 +875,10 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
# Verify IsActive is boolean-like string
self.assertIn(state['IsActive'], ['0', '1'])
- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_sensor')
- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_discrete_controller')
- @patch('hi.services.zoneminder.zm_sync.HiModelHelper.create_movement_event_definition')
- @patch('hi.services.zoneminder.zm_sync.transaction.atomic')
+ @patch('hi.services.zoneminder.zm_connector.HiModelHelper.create_movement_sensor')
+ @patch('hi.services.zoneminder.zm_connector.HiModelHelper.create_discrete_controller')
+ @patch('hi.services.zoneminder.zm_connector.HiModelHelper.create_movement_event_definition')
+ @patch('hi.services.zoneminder.zm_connector.transaction.atomic')
@patch.object(Entity, 'save')
def test_create_monitor_entity_with_real_monitor_variations(self, mock_save, mock_atomic,
mock_create_event, mock_create_controller,
@@ -927,7 +927,7 @@ class TestZoneMinderSynchronizerWithRealData(TestCase):
self.assertEqual(len(result.created_list), 1)
-class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):
+class TestZmConnectorSyncResultGrouping(TestCase):
"""Phase 2 grouping behavior: every imported monitor entity goes
into a single 'Monitors' group on the IntegrationSyncResult.
@@ -936,7 +936,7 @@ class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):
modal's drill-down still allows per-monitor placement when needed."""
def setUp(self):
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
self.mock_manager = Mock()
self.mock_manager.zm_client = Mock()
self.synchronizer._zm_manager = self.mock_manager
@@ -981,7 +981,7 @@ class TestZoneMinderSynchronizerSyncResultGrouping(TestCase):
class CreateMonitorEntityCreateNewContractTests(TestCase):
"""
- Pre-refactor safety net for ``ZoneMinderSynchronizer._create_monitor_entity``.
+ Pre-refactor safety net for ``ZmConnector._create_monitor_entity``.
Phase 3 of Issue #281 will refactor this method to accept an
optional existing Entity (for the auto-reconnect path). These
@@ -997,7 +997,7 @@ class CreateMonitorEntityCreateNewContractTests(TestCase):
# ours (and ours cannot pollute theirs).
IntegrationManager().reset_for_testing()
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
self.mock_manager = Mock()
self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
@@ -1064,7 +1064,7 @@ class CreateMonitorEntityReconnectContractTests(TestCase):
def setUp(self):
IntegrationManager().reset_for_testing()
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
self.mock_manager = Mock()
self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
self.mock_manager.MOVEMENT_SENSOR_PREFIX = 'monitor.motion'
@@ -1153,7 +1153,7 @@ class EventDefinitionLifecycleCycleTests(TestCase):
# ours (and ours cannot pollute theirs).
IntegrationManager().reset_for_testing()
- self.synchronizer = ZoneMinderSynchronizer()
+ self.synchronizer = ZmConnector()
self.mock_manager = Mock()
self.mock_manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
@@ -1260,7 +1260,7 @@ class EventDefinitionLifecycleCycleTests(TestCase):
from hi.testing.async_task_utils import AsyncTaskTestCase
-class TestZoneMinderSynchronizerCheckNeedsSync(AsyncTaskTestCase):
+class TestZmConnectorCheckNeedsSync(AsyncTaskTestCase):
"""Issue #283 — sync-check probe shape for ZoneMinder.
Pins that upstream keys are built using the same prefix scheme
@@ -1299,7 +1299,7 @@ class TestZoneMinderSynchronizerCheckNeedsSync(AsyncTaskTestCase):
)
def _run_check(self, monitor_ids):
- synchronizer = ZoneMinderSynchronizer()
+ synchronizer = ZmConnector()
manager = Mock()
manager.ZM_MONITOR_INTEGRATION_NAME_PREFIX = 'monitor'
@@ -1355,7 +1355,7 @@ class TestZoneMinderSynchronizerCheckNeedsSync(AsyncTaskTestCase):
self.assertFalse(delta.needs_sync)
def test_returns_none_when_manager_not_ready(self):
- synchronizer = ZoneMinderSynchronizer()
+ synchronizer = ZmConnector()
async def get_manager():
return None
diff --git a/src/hi/services/zoneminder/zm_sync.py b/src/hi/services/zoneminder/zm_connector.py
similarity index 68%
rename from src/hi/services/zoneminder/zm_sync.py
rename to src/hi/services/zoneminder/zm_connector.py
index 32d6b395..9823baa7 100644
--- a/src/hi/services/zoneminder/zm_sync.py
+++ b/src/hi/services/zoneminder/zm_connector.py
@@ -5,9 +5,13 @@ from typing import Dict, Optional
from asgiref.sync import sync_to_async
from django.db import transaction
-from hi.apps.entity.enums import EntityType
+from hi.apps.entity.enums import EntityType, VideoStreamType, VideoStreamMode
+from hi.apps.entity.constants import VideoStreamMetadataKeys
from hi.apps.entity.models import Entity
+from hi.apps.entity.transient_models import VideoSnapshot, VideoStream
from hi.apps.sense.models import Sensor
+from hi.apps.sense.transient_models import SensorResponse
+from hi.apps.system.health_status_provider import HealthStatusProvider
from hi.apps.model_helper import HiModelHelper
@@ -17,22 +21,162 @@ from hi.apps.entity.entity_placement import (
EntityPlacementGroup,
)
-from hi.integrations.connect.integration_synchronizer import IntegrationSynchronizer
-from hi.integrations.connect.sync_check import IntegrationSyncCheck, SyncDelta
-from hi.integrations.connect.sync_result import IntegrationSyncResult
+from hi.integrations.connector.integration_connector import IntegrationConnector
+from hi.integrations.connector.sync_check import IntegrationSyncCheck, SyncDelta
+from hi.integrations.connector.sync_result import IntegrationSyncResult
from hi.integrations.transient_models import IntegrationKey
+from .constants import ZmDetailKeys
+from .monitors import ZoneMinderMonitor
+from .zm_controller import ZoneMinderController
+from .zm_manager import ZoneMinderManager
from .zm_metadata import ZmMetaData
from .zm_mixins import ZoneMinderMixin
logger = logging.getLogger(__name__)
-class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
+class ZmConnector( IntegrationConnector, ZoneMinderMixin ):
def get_integration_metadata(self):
return ZmMetaData
+ def get_monitor(self) -> ZoneMinderMonitor:
+ return ZoneMinderMonitor()
+
+ def get_controller(self) -> ZoneMinderController:
+ return ZoneMinderController()
+
+ def get_health_status_provider(self) -> HealthStatusProvider:
+ return ZoneMinderManager()
+
+ def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
+ """Return a fresh still frame for the ZoneMinder monitor backing
+ this entity (``nph-zms?mode=single``). Returns None when the
+ entity isn't a ZM monitor or the integration_name can't be
+ parsed."""
+ if not entity.has_video_snapshot:
+ return None
+
+ if not ( entity.integration_id == ZmMetaData.integration_id
+ and entity.integration_name
+ and entity.integration_name.startswith(
+ self.zm_manager().ZM_MONITOR_INTEGRATION_NAME_PREFIX )):
+ return None
+
+ try:
+ monitor_id = int( entity.integration_name.split('.')[1] )
+ except ( IndexError, ValueError ):
+ logger.warning(
+ f'Could not parse monitor ID from entity integration name: '
+ f'{entity.integration_name}'
+ )
+ return None
+
+ return VideoSnapshot(
+ source_url = self.zm_manager().get_video_snapshot_url( monitor_id ),
+ metadata = { 'monitor_id': monitor_id },
+ )
+
+ def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
+ """Get entity's primary video stream (typically live)"""
+ if not entity.has_video_stream:
+ return None
+
+ # Check if this is a ZoneMinder camera entity
+ if (entity.integration_id == ZmMetaData.integration_id
+ and entity.integration_name
+ and entity.integration_name.startswith(
+ self.zm_manager().ZM_MONITOR_INTEGRATION_NAME_PREFIX)):
+
+ # Extract monitor ID from integration name (format: "monitor.{id}")
+ try:
+ monitor_id = int(entity.integration_name.split('.')[1])
+ video_url = self.zm_manager().get_video_stream_url(monitor_id)
+
+ return VideoStream(
+ stream_type=VideoStreamType.MJPEG,
+ source_url=video_url,
+ metadata={
+ 'monitor_id': monitor_id,
+ VideoStreamMetadataKeys.STREAM_MODE: str(VideoStreamMode.LIVE)
+ }
+ )
+ except (IndexError, ValueError):
+ logger.warning(f"Could not parse monitor ID from entity integration name:"
+ f" {entity.integration_name}")
+
+ return None
+
+ def get_sensor_response_event_snapshot_url(
+ self,
+ sensor_response: SensorResponse) -> Optional[str]:
+ """Per-event snapshot URL for a ZM SensorResponse. Reads the
+ event_id from detail_attrs (where the monitor stores it on
+ every START / END row), builds the portal URL fresh each
+ call so an operator-side portal-URL change auto-heals every
+ historical row."""
+ if not sensor_response.has_event_video_snapshot:
+ return None
+ event_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME
+ if not sensor_response.detail_attrs:
+ return None
+ raw_event_id = sensor_response.detail_attrs.get(event_id_fieldname)
+ if raw_event_id is None:
+ return None
+ try:
+ event_id = int(raw_event_id)
+ except (ValueError, TypeError):
+ logger.warning(
+ 'Could not parse event ID from ZM sensor response: %s',
+ sensor_response.detail_attrs,
+ )
+ return None
+ return self.zm_manager().get_event_snapshot_url(event_id=event_id)
+
+ def get_sensor_response_video_stream(
+ self,
+ sensor_response: SensorResponse) -> Optional[VideoStream]:
+ """Get video stream from sensor response (recorded events)"""
+ # if not sensor_response.has_event_video_clip:
+ # return None
+
+ event_id_fieldname = ZmDetailKeys.EVENT_ID_ATTR_NAME
+
+ # Check if this sensor response has an event ID in its detail_attrs
+ if (sensor_response.detail_attrs
+ and event_id_fieldname in sensor_response.detail_attrs):
+
+ try:
+ event_id = int(sensor_response.detail_attrs[event_id_fieldname])
+ video_url = self.zm_manager().get_event_video_stream_url(event_id)
+
+ # Extract duration from detail_attrs if available
+ metadata = {
+ event_id_fieldname: event_id,
+ VideoStreamMetadataKeys.STREAM_MODE: str(VideoStreamMode.RECORDED)
+ }
+
+ # Look for duration in detail_attrs using the ZoneMinder constant
+ if ZmDetailKeys.DURATION_SECS in sensor_response.detail_attrs:
+ try:
+ duration_secs = float(sensor_response.detail_attrs[ZmDetailKeys.DURATION_SECS])
+ metadata[VideoStreamMetadataKeys.DURATION_SECS] = int(duration_secs)
+ except (ValueError, TypeError):
+ logger.debug(f"Could not parse duration from sensor response:"
+ f" {sensor_response.detail_attrs.get(ZmDetailKeys.DURATION_SECS)}")
+
+ return VideoStream(
+ stream_type=VideoStreamType.MJPEG,
+ source_url=video_url,
+ metadata=metadata
+ )
+ except (ValueError, TypeError):
+ logger.warning(f"Could not parse event ID from sensor response:"
+ f" {sensor_response.detail_attrs}")
+
+ return None
+
MONITOR_FUNCTION_NAME_LABEL_DICT = {
'None': 'None',
'Monitor': 'Monitor',
@@ -293,11 +437,13 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
name_label_dict = run_state_name_label_dict,
)
- # The singleton ZM service entity isn't a placement candidate
- # (already attached to the integration root) — surface as an
- # info note rather than as a created_list entry so it doesn't
- # inflate the count of placeable monitors.
- result.info_list.append( f'Created ZM service item: {zm_entity}' )
+ # Service entity is surfaced in the result-modal Created
+ # list so the user-facing count matches what got persisted.
+ # It is intentionally absent from placement_input — that's
+ # built separately from the monitor-entity list in
+ # _sync_impl, so created_list and placement_input can
+ # disagree where appropriate.
+ result.created_list.append( zm_entity.name )
return zm_entity
def _create_monitor_entity( self,
@@ -313,6 +459,7 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
entity's ``name`` is deliberately preserved because the user
may have edited it before/after the intervening disconnect.
"""
+ is_fresh_create = entity is None
zm_manager = self.zm_manager()
with transaction.atomic():
@@ -362,8 +509,14 @@ class ZoneMinderSynchronizer( IntegrationSynchronizer, ZoneMinderMixin ):
zm_monitor_id = zm_monitor.id(),
),
)
-
- result.created_list.append( entity.name )
+
+ # Only fresh creates contribute to created_list. The
+ # reconnect path (entity supplied by caller) already gets
+ # surfaced via reconnected_list in
+ # reconnect_disconnected_items — appending here too would
+ # double-count the row.
+ if is_fresh_create:
+ result.created_list.append( entity.name )
return entity
def _update_entity( self,
diff --git a/src/hi/services/zoneminder/zm_controller.py b/src/hi/services/zoneminder/zm_controller.py
index f56fe639..ff8ef9ca 100644
--- a/src/hi/services/zoneminder/zm_controller.py
+++ b/src/hi/services/zoneminder/zm_controller.py
@@ -1,7 +1,7 @@
import logging
import re
-from hi.integrations.connect.integration_controller import IntegrationController
+from hi.integrations.connector.integration_controller import IntegrationController
from hi.integrations.transient_models import IntegrationDetails
from hi.integrations.transient_models import IntegrationControlResult
diff --git a/src/hi/services/zoneminder/zm_manage_view_pane.py b/src/hi/services/zoneminder/zm_manage_view_pane.py
deleted file mode 100644
index 69c1d19d..00000000
--- a/src/hi/services/zoneminder/zm_manage_view_pane.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from typing import Dict
-
-from hi.integrations.connect.integration_data import IntegrationData
-from hi.integrations.connect.integration_manage_view_pane import IntegrationManageViewPane
-
-
-class ZmManageViewPane( IntegrationManageViewPane ):
-
- def get_template_name( self ) -> str:
- return 'zoneminder/panes/zm_manage.html'
-
- def get_template_context( self, integration_data : IntegrationData ) -> Dict[ str, object ]:
- return {}
diff --git a/src/hi/simulator/services/homebox/sim_models.py b/src/hi/simulator/services/homebox/sim_models.py
index 36d466d2..05bf927e 100644
--- a/src/hi/simulator/services/homebox/sim_models.py
+++ b/src/hi/simulator/services/homebox/sim_models.py
@@ -7,7 +7,7 @@ HomeBoxInventoryItemFields (persisted via DbSimEntity); the only mutable
runtime state is the ``archived`` flag.
The to_api_dict helper builds the JSON shape the integration's HbItem parser
-(src/hi/services/homebox/shared/hb_models.py) consumes.
+(src/hi/services/homebox/hb_models.py) consumes.
"""
import logging
diff --git a/src/hi/simulator/services/views.py b/src/hi/simulator/services/views.py
index 6dcb9594..58cbb293 100644
--- a/src/hi/simulator/services/views.py
+++ b/src/hi/simulator/services/views.py
@@ -15,7 +15,7 @@ from .exceptions import SimEntityValidationError
from . import forms
from .service_simulator_manager import ServiceSimulatorManager
from .sim_entity import SimEntity
-from .view_mixins import ServiceSimulatorViewMixin
+from hi.simulator.services.view_mixins import ServiceSimulatorViewMixin
def _build_service_tab_specs( active_simulator_id : str ):
diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.css
index 1bfab4cf..d8243a8d 100644
--- a/src/hi/static/css/main.css
+++ b/src/hi/static/css/main.css
@@ -2085,6 +2085,16 @@ g[hover] {
height: auto;
}
+/* Card variant for grid layouts (e.g., Data Import page) where the
+ logo carries primary recognition weight rather than acting as an
+ indicator next to a label. */
+.hi-integration-logo--card {
+ max-height: 72px;
+ max-width: 72px;
+ width: auto;
+ height: auto;
+}
+
/* Smaller variant for inline contexts (entity detail badges,
list-row item indicators) where 24px is too dominant. */
.hi-integration-logo--inline {