Home Information - Your home, your data, organized.
Python
Generalize camera live feed and decouple from video timeline (#336) (#337)
Tony C7984604f486d
diff --git a/src/hi/apps/alert/tests/test_alert_manager_delegation.py b/src/hi/apps/alert/tests/test_alert_manager_delegation.pyindex 6199471c..496c3c2d 100644--- a/src/hi/apps/alert/tests/test_alert_manager_delegation.py+++ b/src/hi/apps/alert/tests/test_alert_manager_delegation.py@@ -124,7 +124,7 @@ class TestAlertManagerDelegation(BaseTestCase):# Verify suggestion was created with correct contentsuggestion = self.transient_manager.get_current_suggestion()self.assertIsNotNone(suggestion)- self.assertIn('/console/entity/video-stream/', suggestion.url)+ self.assertIn('/console/entity/video/', suggestion.url)self.assertIn(str(entity.id), suggestion.url)self.assertEqual(suggestion.duration_seconds, 30)self.assertEqual(suggestion.priority, motion_alarm.alarm_level.priority)diff --git a/src/hi/apps/attribute/managers.py b/src/hi/apps/attribute/managers.pyindex ebd48817..a5e7b2ff 100644--- a/src/hi/apps/attribute/managers.py+++ b/src/hi/apps/attribute/managers.py@@ -1,14 +1,14 @@from django.db import models-class ActiveAttributeManager( models.Manager ):+class ActiveAttributeModelManager( models.Manager ):"""Default manager that hides soft-deleted attributes."""def get_queryset( self ):return super().get_queryset().filter( is_deleted = False )-class DeletedAttributeManager( models.Manager ):+class DeletedAttributeModelManager( models.Manager ):"""Manager that returns only soft-deleted attributes."""def get_queryset( self ):diff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.pyindex d7cb3c93..83d11348 100644--- a/src/hi/apps/attribute/models.py+++ b/src/hi/apps/attribute/models.py@@ -13,7 +13,7 @@ from .enums import (AttributeValueType,AttributeType,)-from .managers import ActiveAttributeManager, DeletedAttributeManager+from .managers import ActiveAttributeModelManager, DeletedAttributeModelManagerfrom .thumbnail import AttributeThumbnail, AttributeThumbnailRuleslogger = logging.getLogger(__name__)@@ -306,9 +306,9 @@ class SoftDeleteAttributeModel(AttributeModel):db_index = True,)- objects = ActiveAttributeManager()+ objects = ActiveAttributeModelManager()all_objects = models.Manager()- deleted_objects = DeletedAttributeManager()+ deleted_objects = DeletedAttributeModelManager()class Meta(AttributeModel.Meta):abstract = Truediff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.htmlindex ab72483b..8a2a708d 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_grid.html@@ -4,7 +4,7 @@{% include "collection/panes/entity_card_title.html" with entity_status_data=entity_status_data %}{% if collection.collection_type.is_cameras %}<div>- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_status_data.entity %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=entity_status_data.entity %}</div>{% else %}{% render_entity_status_panel entity_status_data "grid" %}diff --git a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html b/src/hi/apps/collection/templates/collection/panes/entity_card_list.htmlindex 6d7ca73e..e2d6a6a1 100644--- a/src/hi/apps/collection/templates/collection/panes/entity_card_list.html+++ b/src/hi/apps/collection/templates/collection/panes/entity_card_list.html@@ -7,7 +7,7 @@</div>{% if collection.collection_type.is_cameras %}<div>- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_status_data.entity %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=entity_status_data.entity %}</div>{% else %}<div class="entity-content-section flex-grow-1 ml-3">diff --git a/src/hi/apps/console/console_manager.py b/src/hi/apps/console/console_manager.pyindex a431e962..11ece11c 100644--- a/src/hi/apps/console/console_manager.py+++ b/src/hi/apps/console/console_manager.py@@ -78,11 +78,6 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):return display_data_list- def get_video_stream_entity_list(self) -> List[Entity]:- """Legacy method - now extracts entities from camera control display data."""- display_data_list = self.get_camera_control_display_list()- return [data.entity for data in display_data_list]-def _invalidate_camera_control_cache(self):"""Invalidate cache when entity data changes."""self._camera_control_cache.clear()@@ -91,14 +86,11 @@ class ConsoleManager( Singleton, SettingsMixin, SensorResponseMixin ):def _build_camera_control_display_list(self) -> List[CameraControlDisplayData]:"""Build camera control display data with status entity states.- Listing context: includes the conjunction with is_disabled to- suppress disabled (e.g., disconnected) cameras from the camera- control list. Per-entity views still respect raw has_video_stream.- """- # Get entities with prefetched states in one efficient query+ The displayable-live-view set is owned by the entity-domain+ manager; this method adds display-specific prefetching and+ ordering."""entity_list = list(- Entity.objects- .filter(has_video_stream=True, is_disabled=False)+ EntityManager().get_displayable_live_view_entities().prefetch_related('states').order_by('name'))diff --git a/src/hi/apps/console/templates/console/panes/camera_controls.html b/src/hi/apps/console/templates/console/panes/camera_controls.htmlindex 162acd35..00f04e22 100644--- a/src/hi/apps/console/templates/console/panes/camera_controls.html+++ b/src/hi/apps/console/templates/console/panes/camera_controls.html@@ -3,7 +3,7 @@<div class="row">{% for camera_data in camera_control_display_list %}<div class="w-50 pl-1 pb-1">- <a href="{% url 'console_entity_video_stream_dispatch' entity_id=camera_data.entity.id %}"+ <a href="{% url 'console_entity_video_dispatch' entity_id=camera_data.entity.id %}"data-entity-id="{{ camera_data.entity.id }}"data-async="#main-content"class="btn btn-primary btn-control btn-camera"diff --git a/src/hi/apps/console/templates/console/panes/entity_live_view.html b/src/hi/apps/console/templates/console/panes/entity_live_view.htmlnew file mode 100644index 00000000..e0537243--- /dev/null+++ b/src/hi/apps/console/templates/console/panes/entity_live_view.html@@ -0,0 +1,27 @@+{% load video_tags %}+{% if entity.has_native_video_stream %}+ {% include "console/panes/entity_video_stream.html" with entity=entity %}+{% elif entity.has_streamable_snapshot %}+ {% entity_video_snapshot entity as video_snapshot %}+ {% if video_snapshot and video_snapshot.source_url %}+ {% cache_bust_url video_snapshot.source_url as snapshot_url %}+ <div class="video-container">+ <img class="img-fluid" data-video-snapshot+ data-stream-fps="{{ entity.video_snapshot_stream_fps }}"+ src="{{ snapshot_url }}" alt="{{ entity.name }} Live View">+ </div>+ {% else %}+ {% include "console/panes/video_unavailable_placeholder.html" with heading="Live View Unavailable" subtitle="The integration may be offline or unable to provide a snapshot" %}+ {% endif %}+{% elif entity.has_video_snapshot %}+ {% entity_video_snapshot entity as video_snapshot %}+ {% if video_snapshot and video_snapshot.source_url %}+ {% cache_bust_url video_snapshot.source_url as snapshot_url %}+ <div class="video-container">+ <img class="img-fluid"+ src="{{ snapshot_url }}" alt="{{ entity.name }} Snapshot">+ </div>+ {% else %}+ {% include "console/panes/video_unavailable_placeholder.html" with heading="Snapshot Unavailable" subtitle="The integration may be offline or unable to provide a snapshot" %}+ {% endif %}+{% endif %}diff --git a/src/hi/apps/console/templates/console/panes/entity_live_view_w_link.html b/src/hi/apps/console/templates/console/panes/entity_live_view_w_link.htmlnew file mode 100644index 00000000..80955acd--- /dev/null+++ b/src/hi/apps/console/templates/console/panes/entity_live_view_w_link.html@@ -0,0 +1,9 @@+{% if entity.has_live_view %}+<a href="{% url 'console_entity_video_dispatch' entity_id=entity.id %}"+ data-entity-id="{{ entity.id }}"+ data-async="#main-content"+ class="btn btn-sm btn-outline-primary"+ role="button">+ {% include "console/panes/entity_live_view.html" with entity=entity %}+</a>+{% endif %}diff --git a/src/hi/apps/console/templates/console/panes/entity_video_pane.html b/src/hi/apps/console/templates/console/panes/entity_video_pane.htmlindex 0a8b887c..1f426428 100644--- a/src/hi/apps/console/templates/console/panes/entity_video_pane.html+++ b/src/hi/apps/console/templates/console/panes/entity_video_pane.html@@ -1,37 +1,36 @@{% load video_tags %}{% load icons %}+{% load integration_tags %}<div class="entity-video-pane">- <!-- Unified Tab-Style Header -->- <div class="video-interface-header current-stream mb-3">+ <div class="video-interface-header {% if entity.has_live_feed %}current-stream{% else %}bg-primary{% endif %} mb-3"><div class="d-flex justify-content-between align-items-center"><div class="d-flex align-items-center"><h5 class="entity-title mb-0 mr-3">{{ entity.name }}</h5></div><div class="video-nav-tabs" role="tablist">+ {% if entity.has_live_view %}<span class="video-nav-tab active" role="tab">- {% icon "video" size="sm" css_class="hi-icon-left" %}Current Stream+ {% icon "video" size="sm" css_class="hi-icon-left" %}{% if entity.has_live_feed %}Live Stream{% else %}Snapshot{% endif %}</span>+ {% endif %}{% if video_sensor %}- <a href="{% url 'console_entity_video_sensor_history' entity.id video_sensor.id %}"+ <a href="{% url 'console_entity_video_sensor_history' entity.id video_sensor.id %}"class="video-nav-tab"data-async="#main-content"onclick="sessionStorage.setItem('navigatingFromLiveStream', 'true');"role="tab">{% icon "history" size="sm" css_class="hi-icon-left" %}Event History</a>- {% else %}- <span class="video-nav-tab disabled" title="No video sensors available" role="tab">- {% icon "history" size="sm" css_class="hi-icon-left" %}Event History- </span>{% endif %}</div></div></div>- <!-- Current video stream -->- {% if entity.has_video_stream %}- {% include "console/panes/entity_video_stream.html" with entity=entity %}+ {% integration_health_banner entity.integration_id "Live view may be stale or unavailable until the integration recovers." %}++ {% if entity.has_live_view %}+ {% include "console/panes/entity_live_view.html" with entity=entity %}{% else %}- <div class="text-muted">Video stream not available.</div>+ <div class="text-muted">Live view not available.</div>{% endif %}</div>diff --git a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.htmlindex 38eb3842..4345b1cf 100644--- a/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html+++ b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html@@ -12,7 +12,7 @@<h5 class="entity-title mb-0 mr-3">{{ entity.name }}</h5></div><div class="video-nav-tabs" role="tablist">- <a href="{% url 'console_entity_video_stream' entity.id %}"+ <a href="{% url 'console_entity_video' entity.id %}"class="video-nav-tab"data-async="#main-content"aria-label="Return to live camera stream"@@ -116,7 +116,10 @@{% sensor_response_video_stream sensor_history_data.current_sensor_response as video_stream %}{% if video_stream and video_stream.source_url %}<div class="hi-video-recording">- <img class="img-fluid" data-video-recording src="{{ video_stream.source_url }}" alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}" data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}" onerror="this.style.display='none'; this.outerHTML='<div class=\'alert alert-warning text-center d-flex align-items-center justify-content-center\' style=\'min-height: 240px;\'><div><div class=\'mb-2\'>[VIDEO]</div><h6>Video No Longer Available</h6></div></div>'">+ <img class="img-fluid" data-video-recording+ src="{{ video_stream.source_url }}"+ alt="Video recording from {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:'F j, Y g:i A' }}"+ data-event-id="{{ sensor_history_data.current_sensor_response.sensor_history_id }}">{% include "console/panes/video_recording_replay_button.html" %}</div>{% elif sensor_history_data.current_sensor_response.source_image_url %}@@ -126,19 +129,7 @@<small class="text-muted">Image - video may be processing</small></div>{% else %}- <!-- Fallback when no video stream or snapshot is available -->- <div class="video-placeholder d-flex align-items-center justify-content-center">- <div class="text-center">- <div class="video-placeholder-icon mb-3">- <svg width="64" height="64" fill="currentColor" viewBox="0 0 16 16">- <path d="M10.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z"/>- <path d="M2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4H2zm.5 2a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm9 2.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0z"/>- </svg>- </div>- <h5 class="mb-2">Video Stream Unavailable</h5>- <small class="text-muted">Video recording may not be available for this event</small>- </div>- </div>+ {% include "console/panes/video_unavailable_placeholder.html" with heading="Video Stream Unavailable" subtitle="Video recording may not be available for this event" %}{% endif %}</div>diff --git a/src/hi/apps/console/templates/console/panes/entity_video_stream.html b/src/hi/apps/console/templates/console/panes/entity_video_stream.htmlindex b17c4553..fac84781 100644--- a/src/hi/apps/console/templates/console/panes/entity_video_stream.html+++ b/src/hi/apps/console/templates/console/panes/entity_video_stream.html@@ -3,10 +3,12 @@{% if video_stream and video_stream.source_url %}<div class="video-container">{# ``data-video-stream`` opts this <img> into the connection #}-{# manager's force-close-on-unload lifecycle. ``.video-container`` #}-{# on the parent is purely styling (also used by historical video #}-{# playback containers); the data attribute is the behavior marker. #}+ {# manager's force-close-on-unload lifecycle. ``.video-container`` #}+ {# on the parent is purely styling (also used by historical video #}+ {# playback containers); the data attribute is the behavior marker. #}<img class="img-fluid" data-video-streamsrc="{{ video_stream.source_url }}" alt="{{ entity.name }} Live Video"></div>+{% else %}+{% include "console/panes/video_unavailable_placeholder.html" with heading="Live Stream Unavailable" subtitle="The integration may be offline or the camera unreachable" %}{% endif %}diff --git a/src/hi/apps/console/templates/console/panes/entity_video_stream_w_link.html b/src/hi/apps/console/templates/console/panes/entity_video_stream_w_link.htmldeleted file mode 100644index 53cd3ee9..00000000--- a/src/hi/apps/console/templates/console/panes/entity_video_stream_w_link.html+++ /dev/null@@ -1,9 +0,0 @@-{% if entity.has_video_stream %}-<a href="{% url 'console_entity_video_stream_dispatch' entity_id=entity.id %}"- data-entity-id="{{ entity.id }}"- data-async="#main-content"- class="btn btn-sm btn-outline-primary"- role="button">- {% include "console/panes/entity_video_stream.html" with entity=entity %}-</a>-{% endif %}diff --git a/src/hi/apps/console/templates/console/panes/video_unavailable_placeholder.html b/src/hi/apps/console/templates/console/panes/video_unavailable_placeholder.htmlnew file mode 100644index 00000000..5ea42205--- /dev/null+++ b/src/hi/apps/console/templates/console/panes/video_unavailable_placeholder.html@@ -0,0 +1,26 @@+{% comment %}+Shared server-rendered placeholder for when a live view / video+stream / video snapshot URL is unavailable at template-render time+(integration disabled, gateway returned None, etc.). The JS+``VideoErrorHandler`` builds an identical-looking element for the+img-load-failure case, so both paths look the same to the operator.++Parameters:+ heading : Bold title text. Caller-provided to fit context+ (e.g., "Live View Unavailable",+ "Snapshot Unavailable",+ "Video Stream Unavailable").+ subtitle : Optional muted subtitle.+{% endcomment %}+<div class="video-placeholder d-flex align-items-center justify-content-center">+ <div class="text-center">+ <div class="video-placeholder-icon mb-3">+ <svg width="64" height="64" fill="currentColor" viewBox="0 0 16 16">+ <path d="M10.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z"/>+ <path d="M2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4H2zm.5 2a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm9 2.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0z"/>+ </svg>+ </div>+ <h5 class="mb-2">{{ heading|default:"Live View Unavailable" }}</h5>+ {% if subtitle %}<small class="text-muted">{{ subtitle }}</small>{% endif %}+ </div>+</div>diff --git a/src/hi/apps/console/templatetags/video_tags.py b/src/hi/apps/console/templatetags/video_tags.pyindex 37904a3b..e171d6c3 100644--- a/src/hi/apps/console/templatetags/video_tags.py+++ b/src/hi/apps/console/templatetags/video_tags.py@@ -1,6 +1,10 @@import logging+import time+from django import template+from hi.integrations.integration_manager import IntegrationManager+logger = logging.getLogger(__name__)register = template.Library()@@ -28,10 +32,7 @@ def sensor_response_video_stream(sensor_response):entity = sensor_response.sensor.entity_state.entity- # Get integration gateway for this entity- from hi.integrations.integration_manager import IntegrationManager- integration_manager = IntegrationManager()- gateway = integration_manager.get_integration_gateway(entity.integration_id)+ gateway = IntegrationManager().get_integration_gateway(entity.integration_id)if not gateway:logger.warning(f"No integration gateway found for {entity.integration_id}")@@ -66,21 +67,12 @@ def entity_video_stream(entity):return Nonetry:- # Check if entity has video stream capability- if not entity.has_video_stream:- logger.debug(f"Entity {entity.id} does not have video stream capability")- return None-- # Get integration gateway for this entity- from hi.integrations.integration_manager import IntegrationManager- integration_manager = IntegrationManager()- gateway = integration_manager.get_integration_gateway(entity.integration_id)+ gateway = IntegrationManager().get_integration_gateway(entity.integration_id)if not gateway:logger.warning(f"No integration gateway found for {entity.integration_id}")return None-- # Get live video stream+video_stream = gateway.get_entity_video_stream(entity)if video_stream:@@ -88,7 +80,41 @@ def entity_video_stream(entity):logger.debug(f"No video stream available for entity {entity.id}")return None-+except Exception as e:logger.error(f"Error getting video stream for entity {entity.id}: {e}")return None+++def cache_bust_url(url):+ """Append a unique cache-busting query parameter so each template+ render produces a distinct URL. Snapshot URLs are otherwise stable+ enough (ZM uses 1-second resolution; HA's access_token rotates only+ every few minutes) that the browser serves a stale image when an+ async partial-DOM update revisits the same camera."""+ if not url:+ return url+ sep = '&' if '?' in url else '?'+ return f'{url}{sep}_cb={time.time_ns()}'+++def entity_video_snapshot(entity):+ """Get the current still-image snapshot for an entity, if available.++ Returns a ``VideoSnapshot`` (with ``source_url``) or ``None``.+ Parallel to ``entity_video_stream`` but for the snapshot capability.+ """+ if not entity:+ return None++ try:+ gateway = IntegrationManager().get_integration_gateway(entity.integration_id)+ if not gateway:+ logger.warning(f"No integration gateway found for {entity.integration_id}")+ return None+ return gateway.get_entity_video_snapshot(entity)+ except Exception as e:+ logger.error(f"Error getting video snapshot for entity {entity.id}: {e}")+ return Nonediff --git a/src/hi/apps/console/tests/test_transient_models.py b/src/hi/apps/console/tests/test_transient_models.pyindex e0ba603f..2b8b541c 100644--- a/src/hi/apps/console/tests/test_transient_models.py+++ b/src/hi/apps/console/tests/test_transient_models.py@@ -14,13 +14,13 @@ class TestTransientViewSuggestion(BaseTestCase):def test_transient_view_suggestion_creation(self):"""Test creating a TransientViewSuggestion with basic parameters."""suggestion = TransientViewSuggestion(- url='/console/entity/video-stream/123/',+ url='/console/entity/video/123/',duration_seconds=30,priority=5,trigger_reason='motion_detected')- self.assertEqual(suggestion.url, '/console/entity/video-stream/123/')+ self.assertEqual(suggestion.url, '/console/entity/video/123/')self.assertEqual(suggestion.duration_seconds, 30)self.assertEqual(suggestion.priority, 5)self.assertEqual(suggestion.trigger_reason, 'motion_detected')diff --git a/src/hi/apps/console/tests/test_transient_view_manager.py b/src/hi/apps/console/tests/test_transient_view_manager.pyindex 63386874..9ce59616 100644--- a/src/hi/apps/console/tests/test_transient_view_manager.py+++ b/src/hi/apps/console/tests/test_transient_view_manager.py@@ -204,7 +204,7 @@ class TestTransientViewManager(BaseTestCase):# Verify suggestion contentsuggestion = self.manager.get_current_suggestion()self.assertIsNotNone(suggestion)- self.assertIn('/console/entity/video-stream/', suggestion.url)+ self.assertIn('/console/entity/video/', suggestion.url)self.assertIn(str(entity.id), suggestion.url)self.assertEqual(suggestion.duration_seconds, 30)self.assertEqual(suggestion.priority, motion_alarm.alarm_level.priority)diff --git a/src/hi/apps/console/tests/test_video_stream_browsing_helper.py b/src/hi/apps/console/tests/test_video_stream_browsing_helper.pyindex 3f801bc9..f1e7d6f4 100644--- a/src/hi/apps/console/tests/test_video_stream_browsing_helper.py+++ b/src/hi/apps/console/tests/test_video_stream_browsing_helper.py@@ -14,7 +14,6 @@ from hi.apps.sense.transient_models import SensorResponsefrom hi.apps.sense.enums import CorrelationRolefrom hi.integrations.transient_models import IntegrationKey-from django.core.exceptions import BadRequestlogging.disable(logging.CRITICAL)@@ -738,21 +737,15 @@ class TestVideoDispatchResult(TransactionTestCase):VideoDispatchType.HISTORY_LATER])- def test_get_video_dispatch_result_no_video_sensor_raises_error(self):- """Test error handling when entity has no video sensor."""- with self.assertRaises(BadRequest) as context:- VideoStreamBrowsingHelper.get_video_dispatch_result(- self.non_video_entity, '/any/url/'- )-- self.assertIn('No video sensor found', str(context.exception))-- def test_get_video_dispatch_result_none_entity_raises_error(self):- """Test error handling when entity is None."""- with self.assertRaises(AttributeError):- VideoStreamBrowsingHelper.get_video_dispatch_result(- None, '/any/url/'- )+ def test_get_video_dispatch_result_no_video_sensor_falls_back_to_live_stream(self):+ """Entities without a per-sensor video timeline (e.g., HA cameras+ with snapshot only) fall back to the live-stream dispatch+ instead of raising — the live view is still available."""+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(+ self.non_video_entity, '/any/url/'+ )+ self.assertEqual(result.dispatch_type, VideoDispatchType.LIVE_STREAM)+ self.assertIsNone(result.sensor)def test_get_video_dispatch_result_fallback_to_default(self):"""Test fallback to default dispatch for unrecognized URLs."""diff --git a/src/hi/apps/console/tests/test_view_url_utils.py b/src/hi/apps/console/tests/test_view_url_utils.pyindex 30101194..cffd83fe 100644--- a/src/hi/apps/console/tests/test_view_url_utils.py+++ b/src/hi/apps/console/tests/test_view_url_utils.py@@ -93,7 +93,7 @@ class TestViewUrlUtils(BaseTestCase):view_url = ViewUrlUtils.get_view_url_for_alarm(alarm)self.assertIsNotNone(view_url)- self.assertIn('/console/entity/video-stream/', view_url)+ self.assertIn('/console/entity/video/', view_url)self.assertIn(str(self.video_entity.id), view_url)def test_get_view_url_for_alarm_returns_none_for_non_video_entity(self):@@ -173,7 +173,7 @@ class TestViewUrlUtils(BaseTestCase):view_url = ViewUrlUtils._get_view_url_for_sensor_id(self.video_motion_sensor.id)self.assertIsNotNone(view_url)- self.assertIn('/console/entity/video-stream/', view_url)+ self.assertIn('/console/entity/video/', view_url)self.assertIn(str(self.video_entity.id), view_url)def test_get_view_url_for_sensor_id_returns_none_for_non_video_entity(self):diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.pyindex 0a013cd8..a22a12c3 100644--- a/src/hi/apps/console/tests/test_views.py+++ b/src/hi/apps/console/tests/test_views.py@@ -6,7 +6,7 @@ from django.utils import timezonefrom django.core.exceptions import BadRequestfrom hi.apps.console.views import (- EntityVideoStreamView, EntityVideoSensorHistoryView,+ EntityVideoView, EntityVideoSensorHistoryView,EntityVideoSensorHistoryEarlierView, EntityVideoSensorHistoryLaterView)from hi.apps.console.transient_models import EntitySensorHistoryData@@ -18,8 +18,8 @@ from hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)-class TestEntityVideoStreamView(BaseTestCase):- """Test EntityVideoStreamView for displaying video streams."""+class TestEntityVideoView(BaseTestCase):+ """Test EntityVideoView for displaying video streams."""def setUp(self):super().setUp()@@ -44,7 +44,7 @@ class TestEntityVideoStreamView(BaseTestCase):def test_get_main_template_name_returns_correct_template(self):"""Test that the view returns the correct template name."""- view = EntityVideoStreamView()+ view = EntityVideoView()template_name = view.get_main_template_name()self.assertEqual(template_name, 'console/panes/entity_video_pane.html')@@ -52,14 +52,14 @@ class TestEntityVideoStreamView(BaseTestCase):def test_view_integration_with_url_routing(self):"""Test that the view integrates correctly with URL routing."""# This tests the actual URL pattern and view integration- url = reverse('console_entity_video_stream', kwargs={'entity_id': self.video_entity.id})+ url = reverse('console_entity_video', kwargs={'entity_id': self.video_entity.id})- self.assertIn('/console/entity/video-stream/', url)+ self.assertIn('/console/entity/video/', url)self.assertIn(str(self.video_entity.id), url)def test_view_inheritance_from_higrideview(self):- """Test that EntityVideoStreamView correctly inherits from HiGridView."""- view = EntityVideoStreamView()+ """Test that EntityVideoView correctly inherits from HiGridView."""+ view = EntityVideoView()# Should have HiGridView methodsself.assertTrue(hasattr(view, 'get_main_template_name'))@@ -68,13 +68,13 @@ class TestEntityVideoStreamView(BaseTestCase):self.assertTrue(callable(view.get_main_template_context))def test_view_class_exists_and_is_importable(self):- """Test that the EntityVideoStreamView class exists and can be imported."""+ """Test that the EntityVideoView class exists and can be imported."""# This is a basic smoke test to ensure the view is properly defined- from hi.apps.console.views import EntityVideoStreamView+ from hi.apps.console.views import EntityVideoView- self.assertTrue(EntityVideoStreamView)- self.assertTrue(hasattr(EntityVideoStreamView, 'get_main_template_name'))- self.assertTrue(hasattr(EntityVideoStreamView, 'get_main_template_context'))+ self.assertTrue(EntityVideoView)+ self.assertTrue(hasattr(EntityVideoView, 'get_main_template_name'))+ self.assertTrue(hasattr(EntityVideoView, 'get_main_template_context'))def test_video_entity_has_correct_attributes(self):"""Test that test video entity has correct attributes for testing."""diff --git a/src/hi/apps/console/transient_models.py b/src/hi/apps/console/transient_models.pyindex deff8d45..65b0c481 100644--- a/src/hi/apps/console/transient_models.py+++ b/src/hi/apps/console/transient_models.py@@ -65,7 +65,7 @@ class VideoDispatchResult:Encapsulates the dispatch type and all necessary parameters for routing."""dispatch_type : VideoDispatchType- sensor : Sensor+ sensor : Optional[Sensor] = None # None for live-stream-only entities (e.g., snapshot-only)timestamp : Optional[int] = None # Unix timestamp for earlier/later viewswindow_start : Optional[int] = None # Window start timestamp for context preservationwindow_end : Optional[int] = None # Window end timestamp for context preservation@@ -89,13 +89,15 @@ class VideoDispatchResult:Get the kwargs needed for the target view.Returns dict suitable for updating request kwargs."""- kwargs = { 'sensor_id': self.sensor.id }-+ kwargs = {}+ if self.sensor is not None:+ kwargs['sensor_id'] = self.sensor.id+if self.timestamp is not None:kwargs['timestamp'] = self.timestampif self.window_start is not None:kwargs['window_start'] = self.window_startif self.window_end is not None:kwargs['window_end'] = self.window_end-+return kwargsdiff --git a/src/hi/apps/console/urls.py b/src/hi/apps/console/urls.pyindex b6d175ae..4cc76be4 100644--- a/src/hi/apps/console/urls.py+++ b/src/hi/apps/console/urls.py@@ -5,17 +5,17 @@ from . import viewsurlpatterns = [- path( 'entity/video-stream-dispatch/<int:entity_id>',- views.EntityVideoStreamDispatchView.as_view(),- name='console_entity_video_stream_dispatch'),+ path( 'entity/video-dispatch/<int:entity_id>',+ views.EntityVideoDispatchView.as_view(),+ name='console_entity_video_dispatch'),- path( 'entity/video-stream/<int:entity_id>',- views.EntityVideoStreamView.as_view(),- name='console_entity_video_stream'),+ path( 'entity/video/<int:entity_id>',+ views.EntityVideoView.as_view(),+ name='console_entity_video'),- path( 'entity/video-history/<int:entity_id>',- views.EntityVideoHistoryView.as_view(),- name='console_entity_sendor_video_history_default'),+ path( 'entity/video-history/<int:entity_id>',+ views.EntityVideoHistoryView.as_view(),+ name='console_entity_sensor_video_history_default'),path( 'entity/video-sensor-history/<int:entity_id>/<int:sensor_id>/',views.EntityVideoSensorHistoryView.as_view(),diff --git a/src/hi/apps/console/video_stream_browsing_helper.py b/src/hi/apps/console/video_stream_browsing_helper.pyindex e592d44a..5cc0d8aa 100644--- a/src/hi/apps/console/video_stream_browsing_helper.py+++ b/src/hi/apps/console/video_stream_browsing_helper.py@@ -8,7 +8,6 @@ from datetime import datetime, timedeltafrom typing import Dict, List, Optionalfrom urllib.parse import urlparse-from django.core.exceptions import BadRequestfrom django.utils import timezonefrom django.urls import resolve, Resolver404@@ -32,11 +31,13 @@ class VideoStreamBrowsingHelper:def find_video_sensor_for_entity( cls, entity: Entity ) -> Optional[Sensor]:"""Find the first sensor with video capability for an entity.- Uses priority order to select the best sensor and optimizes queries.+ Uses priority order to select the best sensor and optimizes+ queries. Eligibility is sensor-level (``provides_video_stream``);+ independent of whether the parent entity has its own live feed."""- if not entity or not entity.has_video_stream:+ if not entity:return None-+# Fetch all entity states with their sensors in a single query# Using select_related and prefetch_related to minimize database hitsentity_states = EntityState.objects.filter(@@ -732,8 +733,15 @@ class VideoStreamBrowsingHelper:"""video_sensor = cls.find_video_sensor_for_entity(entity)if not video_sensor:- raise BadRequest( f'No video sensor found for entity {entity.id}.' )-+ # No per-sensor video timeline (e.g., HA camera with snapshot+ # only). Fall back to the live view; the timeline branches+ # below all require a sensor to anchor on.+ return VideoDispatchResult(+ dispatch_type = VideoDispatchType.LIVE_STREAM,+ sensor = None,+ )++# Extract timeline context from referrer URL if availabletry:parsed_url = urlparse(referrer_url)@@ -743,15 +751,14 @@ class VideoStreamBrowsingHelper:url_name = resolved.url_name# Case 1: Referrer has sensor_history_id with window bounds- # Use EntityVideoSensorHistoryEarlierView to preserve timeline+ # Use EntityVideoSensorHistoryEarlierView to preserve timeline.+ # URL converters declare these as ``<int:...>`` so kwargs+ # values arrive already typed as int (not str).if url_name == 'console_entity_video_sensor_history_detail_with_context':- window_start_str = resolved.kwargs.get('window_start', '')- window_end_str = resolved.kwargs.get('window_end', '')- if ( window_start_str- and window_start_str.isdigit()- and window_end_str- and window_end_str.isdigit() ):- timestamp = int(window_start_str)+ window_start = resolved.kwargs.get('window_start')+ window_end = resolved.kwargs.get('window_end')+ if window_start is not None and window_end is not None:+ timestamp = window_start# Try earlier records first (preserve original intent)if cls._has_older_records(video_sensor, timestamp):@@ -779,9 +786,8 @@ class VideoStreamBrowsingHelper:# Case 3: Referrer is "earlier" pagination view# Preserve the same earlier view with same timestampelif url_name == 'console_entity_video_sensor_history_earlier':- timestamp_str = resolved.kwargs.get('timestamp', '')- if timestamp_str and timestamp_str.isdigit():- timestamp = int(timestamp_str)+ timestamp = resolved.kwargs.get('timestamp')+ if timestamp is not None:# Try to preserve earlier viewif cls._has_older_records(video_sensor, timestamp):@@ -798,12 +804,11 @@ class VideoStreamBrowsingHelper:timestamp = timestamp)- # Case 4: Referrer is "later" pagination view+ # Case 4: Referrer is "later" pagination view# Preserve the same later view with same timestampelif url_name == 'console_entity_video_sensor_history_later':- timestamp_str = resolved.kwargs.get('timestamp', '')- if timestamp_str and timestamp_str.isdigit():- timestamp = int(timestamp_str)+ timestamp = resolved.kwargs.get('timestamp')+ if timestamp is not None:# Try to preserve later viewif cls._has_newer_records(video_sensor, timestamp):diff --git a/src/hi/apps/console/view_url_utils.py b/src/hi/apps/console/view_url_utils.pyindex 0ac8c208..b1a2d042 100644--- a/src/hi/apps/console/view_url_utils.py+++ b/src/hi/apps/console/view_url_utils.py@@ -60,17 +60,19 @@ class ViewUrlUtils:# Look up the sensor and its entitysensor = Sensor.objects.select_related('entity_state__entity').get(id=sensor_id)entity = sensor.entity_state.entity-- # Check if entity has video stream capability- if entity.has_video_stream:- # Generate entity-based video stream URL for live video feed- return reverse('console_entity_video_stream', kwargs={'entity_id': entity.id})-++ # Auto-view targets the live feed (motion implies the user+ # wants to *see* what's happening — a static snapshot has+ # no animation to draw attention). Gate on has_live_feed,+ # which covers both native streams and pollable snapshots.+ if entity.has_live_feed:+ return reverse('console_entity_video', kwargs={'entity_id': entity.id})+# Future: Add other view types based on entity state type# elif sensor.entity_state.entity_state_type == EntityStateType.WEATHER:# return reverse('console_weather_view', kwargs={'sensor_id': sensor_id})-- logger.debug(f"Entity {entity.id} for sensor {sensor_id} does not have video stream capability")++ logger.debug(f"Entity {entity.id} for sensor {sensor_id} does not have a live feed")return Noneexcept Sensor.DoesNotExist:diff --git a/src/hi/apps/console/views.py b/src/hi/apps/console/views.pyindex 20158f2e..c8b8b27e 100644--- a/src/hi/apps/console/views.py+++ b/src/hi/apps/console/views.py@@ -7,7 +7,6 @@ from django.utils import timezonefrom hi.apps.entity.view_mixins import EntityViewMixinfrom hi.apps.sense.models import Sensorfrom hi.apps.sense.view_mixins import SenseViewMixin-from hi.integrations.integration_manager import IntegrationManagerfrom hi.enums import ViewTypefrom hi.hi_async_view import HiModalView@@ -19,7 +18,7 @@ from .enums import VideoDispatchTypefrom .video_stream_browsing_helper import VideoStreamBrowsingHelper-class EntityVideoStreamDispatchView( View, EntityViewMixin ):+class EntityVideoDispatchView( View, EntityViewMixin ):"""Simple dispatch view for camera sidebar navigation.Routes to existing views based on referrer context.@@ -28,7 +27,7 @@ class EntityVideoStreamDispatchView( View, EntityViewMixin ):def get( self, request, *args, **kwargs ):if not request.view_parameters.view_type.is_video_browse:- return EntityVideoStreamView().get( request, **kwargs )+ return EntityVideoView().get( request, **kwargs )entity = self.get_entity( request, *args, **kwargs )@@ -44,7 +43,7 @@ class EntityVideoStreamDispatchView( View, EntityViewMixin ):# Route to appropriate view based on dispatch typeif dispatch_result.dispatch_type == VideoDispatchType.LIVE_STREAM:- return EntityVideoStreamView().get( request, **kwargs )+ return EntityVideoView().get( request, **kwargs )elif dispatch_result.dispatch_type == VideoDispatchType.HISTORY_EARLIER:return EntityVideoSensorHistoryEarlierView().get( request, **kwargs )elif dispatch_result.dispatch_type == VideoDispatchType.HISTORY_LATER:@@ -53,7 +52,7 @@ class EntityVideoStreamDispatchView( View, EntityViewMixin ):return EntityVideoSensorHistoryView().get( request, **kwargs )-class EntityVideoStreamView( HiGridView, EntityViewMixin ):+class EntityVideoView( HiGridView, EntityViewMixin ):"""View for displaying entity-based video streams."""def get_main_template_name( self ) -> str:@@ -62,26 +61,16 @@ class EntityVideoStreamView( HiGridView, EntityViewMixin ):def get_main_template_context( self, request, *args, **kwargs ):entity = self.get_entity( request, *args, **kwargs )- # Check if entity has video stream capability- if not entity.has_video_stream:- raise BadRequest( 'Entity does not have video stream capability.' )-- # Get the integration gateway for this entity (Do we really need this check?)- integration_gateway = IntegrationManager().get_integration_gateway( entity.integration_id )- if not integration_gateway:- raise BadRequest( 'Integration not available for video stream.' )-- # Find the first sensor with video capability for history browsingvideo_sensor = VideoStreamBrowsingHelper.find_video_sensor_for_entity(entity)- if not video_sensor:- raise BadRequest( 'Entity does not have any video stream sensors.' )-- request.view_parameters.view_type = ViewType.ENTITY_VIDEO_STREAM+ if not entity.has_live_view and not video_sensor:+ raise BadRequest( 'Entity provides neither a live view nor a video timeline.' )++ request.view_parameters.view_type = ViewType.ENTITY_VIDEOrequest.view_parameters.to_session( request )return {'entity': entity,- 'video_sensor': video_sensor, # May be None if no video sensors+ 'video_sensor': video_sensor,}diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.pyindex 28a386c7..e6915583 100644--- a/src/hi/apps/entity/entity_manager.py+++ b/src/hi/apps/entity/entity_manager.py@@ -3,6 +3,7 @@ from threading import localfrom typing import List, Sequencefrom django.db import transaction+from django.db.models import QuerySetfrom django.db.models.signals import post_save, post_deletefrom django.dispatch import receiver@@ -125,19 +126,13 @@ class EntityManager(Singleton):entity_view_group_list.sort( key = lambda item : item.entity_group_type.label )return entity_view_group_list- def get_view_stream_entities(self) -> List[ Entity ]:- """- Return all entities that have a video-stream capability AND are- not currently disabled. Both conditions are required for an entity- to surface in capability-driven enumerations like the sidebar- Cameras list. Per-entity view sites should keep using the raw- has_video_stream flag — the disabled gate only applies at- listing time.- """- return list(Entity.objects.filter(- has_video_stream = True,- is_disabled = False,- ))+ def get_displayable_live_view_entities(self) -> QuerySet[ Entity ]:+ """Queryset of entities that have any current visual (native+ stream, synthetic snapshot stream, or static snapshot) AND are+ not currently disabled. Used by surfaces that enumerate+ "cameras to show" (e.g., the console sidebar). Returned as a+ queryset so callers can add their own prefetch / ordering."""+ return Entity.objects.with_live_view().filter( is_disabled = False )_thread_local = local()diff --git a/src/hi/apps/entity/managers.py b/src/hi/apps/entity/managers.pynew file mode 100644index 00000000..22cde373--- /dev/null+++ b/src/hi/apps/entity/managers.py@@ -0,0 +1,14 @@+from django.db.models import Q++from hi.integrations.managers import IntegrationDetailsModelManager+++class EntityModelManager( IntegrationDetailsModelManager ):++ def with_live_view( self ):+ """Entities that have *any* current visual — native stream or+ snapshot. Mirrors the ``has_live_view`` property in queryset+ form for filter sites."""+ return self.filter(+ Q( has_video_stream = True ) | Q( has_video_snapshot = True )+ )diff --git a/src/hi/apps/entity/migrations/0019_entity_video_snapshot_stream_fps.py b/src/hi/apps/entity/migrations/0019_entity_video_snapshot_stream_fps.pynew file mode 100644index 00000000..c9682a48--- /dev/null+++ b/src/hi/apps/entity/migrations/0019_entity_video_snapshot_stream_fps.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.14 on 2026-05-16 19:45++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("entity", "0018_backfill_zoneminder_has_video_snapshot"),+ ]++ operations = [+ migrations.AddField(+ model_name="entity",+ name="video_snapshot_stream_fps",+ field=models.FloatField(+ blank=True,+ default=None,+ help_text="When has_video_snapshot is True, the rate at which the snapshot is suitable to be polled to approximate a live feed. None or 0 means snapshot exists but is not suitable for synthetic streaming.",+ null=True,+ verbose_name="Video Snapshot Stream FPS",+ ),+ ),+ ]diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.pyindex 13349ec1..f42ece8e 100644--- a/src/hi/apps/entity/models.py+++ b/src/hi/apps/entity/models.py@@ -20,6 +20,7 @@ from .enums import (EntityStateRole,EntityStateType,)+from .managers import EntityModelManagerclass Entity( IntegrationDetailsModel, LocationItemModelMixin ):@@ -70,6 +71,17 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):'provide either, both, or neither capability.'),)+ video_snapshot_stream_fps = models.FloatField(+ 'Video Snapshot Stream FPS',+ null = True,+ blank = True,+ default = None,+ help_text = (+ 'When has_video_snapshot is True, the rate at which the snapshot '+ 'is suitable to be polled to approximate a live feed. None or 0 '+ 'means snapshot exists but is not suitable for synthetic streaming.'+ ),+ )is_disabled = models.BooleanField('Disabled?',default = False,@@ -84,6 +96,8 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):auto_now_add = True,)+ objects = EntityModelManager()+class Meta:verbose_name = 'Entity'verbose_name_plural = 'Entities'@@ -113,6 +127,33 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):self.entity_type_str = str(entity_type)return+ @property+ def has_native_video_stream(self) -> bool:+ """Explicit-name alias for ``has_video_stream`` for the rare+ native-vs-synthetic disambiguation case. Most callers want+ ``has_live_feed`` instead."""+ return self.has_video_stream++ @property+ def has_streamable_snapshot(self) -> bool:+ """Snapshot exists and is suitable to be polled fast enough to+ approximate a live feed."""+ return self.has_video_snapshot and (self.video_snapshot_stream_fps or 0) > 0++ @property+ def has_live_feed(self) -> bool:+ """A *moving* visual is available: native stream OR a snapshot+ that can be polled. Use this on surfaces that imply motion+ (auto-view trigger, "LIVE" indicators, video-pane "live mode")."""+ return self.has_native_video_stream or self.has_streamable_snapshot++ @property+ def has_live_view(self) -> bool:+ """*Any* current visual exists, moving or static. Use this on+ surfaces that just want to show the camera (side panel buttons,+ state panels, dispatch routing)."""+ return self.has_native_video_stream or self.has_video_snapshot+def get_attribute_map(self):attribute_map = dict()for attribute in self.attributes.all():diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html b/src/hi/apps/entity/templates/entity/state_panels/camera/grid.htmlindex 38ef4928..fb121f0b 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/grid.html@@ -3,8 +3,8 @@<div class="hi-state-panel-camera hi-state-panel-camera--grid"><div class="stream">- {% if entity.has_video_stream %}- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity %}+ {% if entity.has_live_view %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=entity %}{% else %}<div class="stream-unavailable">Offline</div>{% endif %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/list.html b/src/hi/apps/entity/templates/entity/state_panels/camera/list.htmlindex 8a9a769f..78733754 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/list.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/list.html@@ -2,8 +2,8 @@<div class="hi-state-panel-camera hi-state-panel-camera--list"><div class="stream">- {% if entity.has_video_stream %}- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity %}+ {% if entity.has_live_view %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=entity %}{% else %}<div class="stream-unavailable">Offline</div>{% endif %}diff --git a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.htmlindex 2140053c..4b7ffaf8 100644--- a/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html+++ b/src/hi/apps/entity/templates/entity/state_panels/camera/modal.html@@ -7,10 +7,10 @@<div class="hi-state-panel-camera hi-state-panel-camera--modal"><div class="stream">- {% if entity.has_video_stream %}- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity %}+ {% if entity.has_live_view %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=entity %}{% else %}- <div class="stream-unavailable">Video stream not available</div>+ <div class="stream-unavailable">Live view not available</div>{% endif %}</div>diff --git a/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.html b/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.htmlindex d7925b21..bc221a7c 100644--- a/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.html+++ b/src/hi/apps/entity/templates/entity/state_panels/fallback/modal.html@@ -6,7 +6,7 @@{# stream (when present) and the flat state list. #}{% if entity_for_video %}<div>- {% include "console/panes/entity_video_stream_w_link.html" with entity=entity_for_video %}+ {% include "console/panes/entity_live_view_w_link.html" with entity=entity_for_video %}</div>{% endif %}diff --git a/src/hi/apps/monitor/status_data.py b/src/hi/apps/monitor/status_data.pyindex c2f3bede..013bb39f 100644--- a/src/hi/apps/monitor/status_data.py+++ b/src/hi/apps/monitor/status_data.py@@ -38,7 +38,7 @@ class EntityStatusData:display_only_svg_icon_item : SvgIconItem = Nonedef __post_init__(self):- if not self.entity_for_video and self.entity.has_video_stream:+ if not self.entity_for_video and self.entity.has_live_feed:self.entity_for_video = self.entityreturndiff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.pyindex 7a559c9e..544b4b08 100644--- a/src/hi/apps/monitor/status_display_manager.py+++ b/src/hi/apps/monitor/status_display_manager.py@@ -119,14 +119,14 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):# principals when the entity is a delegate.#entity_for_video = None- if entity.has_video_stream:+ if entity.has_live_feed:entity_for_video = entity-+entity_state_set = set( entity.states.all() )for entity_state_delegation in entity.entity_state_delegations.all():entity_state_set.add( entity_state_delegation.entity_state )if ( not entity_for_video- and entity_state_delegation.entity_state.entity.has_video_stream ):+ and entity_state_delegation.entity_state.entity.has_live_feed ):entity_for_video = entity_state_delegation.entity_state.entitycontinuediff --git a/src/hi/apps/notify/managers.py b/src/hi/apps/notify/managers.pyindex 2db612f7..2db1484c 100644--- a/src/hi/apps/notify/managers.py+++ b/src/hi/apps/notify/managers.py@@ -1,7 +1,7 @@from django.db import models-class UnsubscribedEmailManager(models.Manager):+class UnsubscribedEmailModelManager(models.Manager):def exists_by_user( self, user ):if not user.email:diff --git a/src/hi/apps/notify/models.py b/src/hi/apps/notify/models.pyindex 673e6015..10da4f79 100644--- a/src/hi/apps/notify/models.py+++ b/src/hi/apps/notify/models.py@@ -5,7 +5,7 @@ from . import managersclass UnsubscribedEmail( models.Model ):- objects = managers.UnsubscribedEmailManager()+ objects = managers.UnsubscribedEmailModelManager()email = models.EmailField(unique = True,diff --git a/src/hi/apps/notify/tests/test_models.py b/src/hi/apps/notify/tests/test_models.pyindex 8958a78c..fe6fbdc2 100644--- a/src/hi/apps/notify/tests/test_models.py+++ b/src/hi/apps/notify/tests/test_models.py@@ -53,10 +53,10 @@ class TestUnsubscribedEmail(BaseTestCase):def test_unsubscribed_email_manager_usage(self):"""Test custom manager usage - important for query interface."""- from hi.apps.notify.managers import UnsubscribedEmailManager+ from hi.apps.notify.managers import UnsubscribedEmailModelManager# Should use custom manager- self.assertIsInstance(UnsubscribedEmail.objects, UnsubscribedEmailManager)+ self.assertIsInstance(UnsubscribedEmail.objects, UnsubscribedEmailModelManager)returndiff --git a/src/hi/enums.py b/src/hi/enums.pyindex 346099d4..569d035e 100644--- a/src/hi/enums.py+++ b/src/hi/enums.py@@ -10,7 +10,7 @@ class ViewType(LabeledEnum):LOCATION_VIEW = ('Location View', '' )COLLECTION = ('Collection', '' )CONFIGURATION = ('Configuration', '' )- ENTITY_VIDEO_STREAM = ('Entity Video Stream', '' )+ ENTITY_VIDEO = ('Entity Video', '' )SENSOR_VIDEO_BROWSE = ('Sensor Video Browse', '' )@property@@ -26,8 +26,8 @@ class ViewType(LabeledEnum):return bool( self == ViewType.CONFIGURATION )@property- def is_video_stream(self):- return bool( self == ViewType.ENTITY_VIDEO_STREAM )+ def is_video(self):+ return bool( self == ViewType.ENTITY_VIDEO )@propertydef is_video_browse(self):diff --git a/src/hi/integrations/integration_synchronizer.py b/src/hi/integrations/integration_synchronizer.pyindex 52686b9f..afdb9c3c 100644--- a/src/hi/integrations/integration_synchronizer.py+++ b/src/hi/integrations/integration_synchronizer.py@@ -122,6 +122,14 @@ class IntegrationSynchronizer:logger.debug(f'{self.__class__.__name__} sync ended.')self._record_sync_check_complete_if_successful( result = result )+ try:+ self.post_sync( result = result )+ except Exception:+ # Post-sync hook failures must not mask the sync result;+ # log the traceback so the failure is debuggable.+ logger.exception(+ f'{self.__class__.__name__} post_sync hook failed'+ )return resultdef _record_sync_check_complete_if_successful(@@ -150,6 +158,17 @@ class IntegrationSynchronizer:)return+ def post_sync(self, result : IntegrationSyncResult) -> None:+ """Hook for integration-specific work that must happen after a+ sync completes (and after the sync lock has been released).+ Sync mutates entity/sensor records; integrations whose+ process-level state derives from those records should refresh+ here. Default is no-op.++ Runs regardless of result.error_list — partial syncs may have+ committed enough changes to invalidate process-level state."""+ return+def _sync_impl(self, is_initial_import: bool) -> IntegrationSyncResult:"""Integration-specific sync work. Subclasses must override.diff --git a/src/hi/integrations/managers.py b/src/hi/integrations/managers.pyindex 5dd6b95f..7077fb3a 100644--- a/src/hi/integrations/managers.py+++ b/src/hi/integrations/managers.py@@ -6,7 +6,7 @@ from django.db.models import Qfrom .transient_models import IntegrationKey-class IntegrationDetailsManager(models.Manager):+class IntegrationDetailsModelManager(models.Manager):def filter_by_integration_key( self, integration_key : IntegrationKey ):return self.filter( integration_id = integration_key.integration_id,diff --git a/src/hi/integrations/models.py b/src/hi/integrations/models.pyindex aa919061..5f2a5210 100644--- a/src/hi/integrations/models.py+++ b/src/hi/integrations/models.py@@ -5,7 +5,7 @@ from django.db import modelsfrom hi.apps.attribute.models import AttributeModel, AttributeValueHistoryModelfrom .transient_models import IntegrationKey, IntegrationDetails-from .managers import IntegrationDetailsManager+from .managers import IntegrationDetailsModelManagerclass Integration( models.Model ):@@ -87,7 +87,7 @@ class IntegrationDetailsModel( models.Model ):For use in DB objects that need to be associated with an integrationdevice, sensor, controller, attribute, etc."""- objects = IntegrationDetailsManager()+ objects = IntegrationDetailsModelManager()class Meta:abstract = Truediff --git a/src/hi/integrations/tests/test_managers.py b/src/hi/integrations/tests/test_managers.pyindex 9669913d..9d9b18ba 100644--- a/src/hi/integrations/tests/test_managers.py+++ b/src/hi/integrations/tests/test_managers.py@@ -1,12 +1,12 @@"""-Unit tests for IntegrationDetailsManager.+Unit tests for IntegrationDetailsModelManager."""import loggingfrom django.test import TransactionTestCasefrom django.db import models, connection-from hi.integrations.managers import IntegrationDetailsManager+from hi.integrations.managers import IntegrationDetailsModelManagerfrom hi.integrations.models import IntegrationDetailsModelfrom hi.integrations.transient_models import IntegrationKey@@ -14,7 +14,7 @@ logging.disable(logging.CRITICAL)class ManagerTestModel(IntegrationDetailsModel):- """Concrete test model for testing IntegrationDetailsManager."""+ """Concrete test model for testing IntegrationDetailsModelManager."""name = models.CharField(max_length=64, default='test')@@ -23,7 +23,7 @@ class ManagerTestModel(IntegrationDetailsModel):class IntegrationDetailsManagerTestCase(TransactionTestCase):- """Test cases for IntegrationDetailsManager functionality."""+ """Test cases for IntegrationDetailsModelManager functionality."""def setUp(self):"""Set up test data by creating table and test instances."""@@ -305,9 +305,9 @@ class IntegrationDetailsManagerTestCase(TransactionTestCase):self.assertEqual(filtered_result.first().name, 'Extra Model')def test_manager_inheritance_and_usage(self):- """Test that IntegrationDetailsManager is properly inherited and used."""- # Verify that ManagerTestModel uses IntegrationDetailsManager- self.assertIsInstance(ManagerTestModel.objects, IntegrationDetailsManager)+ """Test that IntegrationDetailsModelManager is properly inherited and used."""+ # Verify that ManagerTestModel uses IntegrationDetailsModelManager+ self.assertIsInstance(ManagerTestModel.objects, IntegrationDetailsModelManager)# Verify that manager methods exist and are callableself.assertTrue(hasattr(ManagerTestModel.objects, 'filter_by_integration_key'))diff --git a/src/hi/integrations/tests/test_models.py b/src/hi/integrations/tests/test_models.pyindex 07b57c97..6083d0cf 100644--- a/src/hi/integrations/tests/test_models.py+++ b/src/hi/integrations/tests/test_models.py@@ -571,9 +571,9 @@ class IntegrationDetailsModelTestCase(TestCase):self.assertTrue(mock_obj3.save_called)def test_integration_details_model_manager(self):- """Test that IntegrationDetailsModel uses IntegrationDetailsManager."""+ """Test that IntegrationDetailsModel uses IntegrationDetailsModelManager."""# Test using the concrete test model- self.assertEqual(ConcreteIntegrationDetailsModel.objects.__class__.__name__, 'IntegrationDetailsManager')+ self.assertEqual(ConcreteIntegrationDetailsModel.objects.__class__.__name__, 'IntegrationDetailsModelManager')def test_integration_details_model_fields(self):"""Test IntegrationDetailsModel field definitions."""diff --git a/src/hi/services/hass/hass_converter.py b/src/hi/services/hass/hass_converter.pyindex 7ccda5a5..62521c6c 100644--- a/src/hi/services/hass/hass_converter.py+++ b/src/hi/services/hass/hass_converter.py@@ -542,9 +542,11 @@ class HassConverter:# Integration-owned: re-applied on both fresh-create and# reconnect so the entity reflects current upstream state.+ is_camera = HassApi.CAMERA_DOMAIN in hass_device.domain_setentity.integration_key = entity_integration_keyentity.can_user_delete = HassMetaData.allow_entity_deletion- entity.has_video_snapshot = HassApi.CAMERA_DOMAIN in hass_device.domain_set+ entity.has_video_snapshot = is_camera+ entity.video_snapshot_stream_fps = 1.0 if is_camera else Noneentity.save()insteon_address = cls.hass_device_to_insteon_address( hass_device )@@ -588,12 +590,18 @@ class HassConverter:# Re-derive integration-owned capability flags from the# current upstream device shape. Self-healing if HA's# domain composition changes (e.g., a paired motion sensor- # added or removed), and the only point where pre-PR HA- # cameras pick up has_video_snapshot=True.- has_video_snapshot = HassApi.CAMERA_DOMAIN in hass_device.domain_set- if entity.has_video_snapshot != has_video_snapshot:- entity.has_video_snapshot = has_video_snapshot- entity.save( update_fields = [ 'has_video_snapshot' ] )+ # added or removed).+ is_camera = HassApi.CAMERA_DOMAIN in hass_device.domain_set+ expected_fps = 1.0 if is_camera else None+ update_fields = []+ if entity.has_video_snapshot != is_camera:+ entity.has_video_snapshot = is_camera+ update_fields.append( 'has_video_snapshot' )+ if entity.video_snapshot_stream_fps != expected_fps:+ entity.video_snapshot_stream_fps = expected_fps+ update_fields.append( 'video_snapshot_stream_fps' )+ if update_fields:+ entity.save( update_fields = update_fields )insteon_address = cls.hass_device_to_insteon_address( hass_device )try:diff --git a/src/hi/services/hass/hass_manager.py b/src/hi/services/hass/hass_manager.pyindex da9f8581..caca4dbe 100644--- a/src/hi/services/hass/hass_manager.py+++ b/src/hi/services/hass/hass_manager.py@@ -56,6 +56,9 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusPro)self._latest_attrs_lock = threading.Lock()+ # HI Entity.id -> HA wire entity_id, for camera-domain sensors.+ self._entity_id_to_ha_state_id: Dict[ int, str ] = {}+# Add self as the API health status provider to aggregateself.add_api_health_status_provider(self)@@ -110,6 +113,7 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProself._hass_attr_type_to_attribute = self._load_attributes()self._hass_client = self.create_hass_client( self._hass_attr_type_to_attribute )self.clear_caches()+ self._rebuild_entity_id_to_ha_state_id_map()self.record_healthy('Reloaded')except IntegrationDisabledError:@@ -138,6 +142,18 @@ class HassManager( SingletonManager, AggregateHealthProvider, ApiHealthStatusProself._latest_attrs_by_entity_id.clear()return+ def _rebuild_entity_id_to_ha_state_id_map(self):+ from hi.apps.sense.models import Sensor+ pairs = Sensor.objects.filter(+ integration_id = HassMetaData.integration_id,+ integration_name__startswith = f'{HassApi.CAMERA_DOMAIN}.',+ ).values_list( 'entity_state__entity_id', 'integration_name' )+ self._entity_id_to_ha_state_id = dict( pairs )+ return++ def get_ha_state_id_for_entity( self, entity ) -> Optional[ str ]:+ return self._entity_id_to_ha_state_id.get( entity.id )+def update_latest_attrs_cache( self, hass_state_map : Dict[ str, HassState ] ):"""Refresh per-entity attributes from a polling snapshot.Selective insert: only domains downstream code needsdiff --git a/src/hi/services/hass/hass_sync.py b/src/hi/services/hass/hass_sync.pyindex a39b0e7b..cf36688c 100644--- a/src/hi/services/hass/hass_sync.py+++ b/src/hi/services/hass/hass_sync.py@@ -85,6 +85,13 @@ class HassSynchronizer( IntegrationSynchronizer, HassMixin ):).values_list( 'integration_id', 'integration_name' )}+ def post_sync(self, result):+ hass_manager = self.hass_manager()+ if hass_manager is None:+ return+ hass_manager.reload()+ return+def _sync_impl( self, is_initial_import: bool ) -> IntegrationSyncResult:hass_manager = self.hass_manager()result = IntegrationSyncResult(diff --git a/src/hi/services/hass/integration.py b/src/hi/services/hass/integration.pyindex d2175e58..24dccc2f 100644--- a/src/hi/services/hass/integration.py+++ b/src/hi/services/hass/integration.py@@ -95,11 +95,17 @@ class HassGateway( IntegrationGateway ):return Noneif entity.integration_id != HassMetaData.integration_id:return None- if not entity.integration_name:- return Nonehass_manager = HassManager()- attrs = hass_manager.get_latest_attrs( entity.integration_name )+ # ``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 Nonediff --git a/src/hi/services/hass/tests/test_hass_converter_create.py b/src/hi/services/hass/tests/test_hass_converter_create.pyindex a3deeddd..51e3e04a 100644--- a/src/hi/services/hass/tests/test_hass_converter_create.py+++ b/src/hi/services/hass/tests/test_hass_converter_create.py@@ -441,6 +441,7 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):add_alarm_events=False,)self.assertTrue(entity.has_video_snapshot)+ self.assertEqual(entity.video_snapshot_stream_fps, 1.0)def test_create_leaves_flag_off_for_non_camera_device(self):entity = HassConverter.create_models_for_hass_device(@@ -448,12 +449,14 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):add_alarm_events=False,)self.assertFalse(entity.has_video_snapshot)+ self.assertIsNone(entity.video_snapshot_stream_fps)def test_reconnect_sets_flag_on_existing_entity(self):existing = Entity.objects.create(name='User Renamed Camera',entity_type_str='CAMERA',has_video_snapshot=False,+ video_snapshot_stream_fps=None,)HassConverter.create_models_for_hass_device(hass_device=self._build_camera_device(),@@ -462,6 +465,7 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):)existing.refresh_from_db()self.assertTrue(existing.has_video_snapshot)+ self.assertEqual(existing.video_snapshot_stream_fps, 1.0)def test_update_heals_flag_on_existing_camera_entity(self):"""Pre-PR cameras stay has_video_snapshot=False until the@@ -471,6 +475,7 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):name='User Renamed Camera',entity_type_str='CAMERA',has_video_snapshot=False,+ video_snapshot_stream_fps=None,)# Set integration key so the converter recognizes the# entity as HASS-owned and the update path is well-formed.@@ -485,6 +490,7 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):existing.refresh_from_db()self.assertTrue(existing.has_video_snapshot)+ self.assertEqual(existing.video_snapshot_stream_fps, 1.0)def test_update_clears_flag_when_device_no_longer_camera(self):"""Self-healing in the opposite direction: if upstream@@ -494,6 +500,7 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):name='Was a camera',entity_type_str='LIGHT',has_video_snapshot=True,+ video_snapshot_stream_fps=1.0,)existing.integration_id = HassMetaData.integration_idexisting.integration_name = 'light.kitchen_light'@@ -506,3 +513,4 @@ class CameraDeviceVideoSnapshotFlagTests(TestCase):existing.refresh_from_db()self.assertFalse(existing.has_video_snapshot)+ self.assertIsNone(existing.video_snapshot_stream_fps)diff --git a/src/hi/services/hass/tests/test_integration.py b/src/hi/services/hass/tests/test_integration.pyindex ce0da225..b8089de3 100644--- a/src/hi/services/hass/tests/test_integration.py+++ b/src/hi/services/hass/tests/test_integration.py@@ -5,7 +5,8 @@ from unittest.mock import Mockfrom django.test import TestCase-from hi.apps.entity.models import Entity+from hi.apps.entity.models import Entity, EntityState+from hi.apps.sense.models import Sensorfrom hi.services.hass.hass_manager import HassManagerfrom hi.services.hass.hass_metadata import HassMetaData@@ -33,14 +34,32 @@ class GetEntityVideoSnapshotTests(TestCase):mock_client.api_base_url = self.BASE_URL.rstrip('/')self.manager._hass_client = mock_client- def _camera_entity(self, integration_name='camera.front_door'):- return Entity.objects.create(+ def _camera_entity(self, device_id='front_door', ha_state_id='camera.front_door'):+ """Build a camera-shaped HI Entity + camera-domain Sensor and+ rebuild the manager's entity_id -> ha_state_id map so the+ gateway's lookup resolves."""+ entity = Entity.objects.create(name='Front Door',entity_type_str='CAMERA',integration_id=HassMetaData.integration_id,- integration_name=integration_name,+ integration_name=device_id,has_video_snapshot=True,)+ entity_state = EntityState.objects.create(+ entity=entity,+ entity_state_type_str='VIDEO_STREAM',+ role_str='primary',+ name='Camera',+ )+ Sensor.objects.create(+ name='Camera',+ entity_state=entity_state,+ sensor_type_str='BLOB',+ integration_id=HassMetaData.integration_id,+ integration_name=ha_state_id,+ )+ self.manager._rebuild_entity_id_to_ha_state_id_map()+ return entitydef _prime_cache(self, integration_name, attrs):self.manager.update_latest_attrs_cache({diff --git a/src/hi/simulator/services/zoneminder/views.py b/src/hi/simulator/services/zoneminder/views.pyindex 95dc76cc..021b9417 100644--- a/src/hi/simulator/services/zoneminder/views.py+++ b/src/hi/simulator/services/zoneminder/views.py@@ -70,12 +70,21 @@ class NphZmsView( View ):"""def get(self, request, *args, **kwargs):+ # Real ZoneMinder treats ``mode=single`` as "return a single+ # JPEG frame instead of a multipart MJPEG stream"; this is+ # how HI's ``get_video_snapshot_url`` fetches a still image.+ single_mode = request.GET.get( 'mode' ) == 'single'+event_id_str = request.GET.get( 'event' )if event_id_str is not None:+ if single_mode:+ return self._event_snapshot_response( event_id_str = event_id_str )return self._event_playback_response( event_id_str = event_id_str )monitor_id_str = request.GET.get( 'monitor' )if monitor_id_str is not None:+ if single_mode:+ return self._monitor_snapshot_response( monitor_id_str = monitor_id_str )return self._live_stream_response( monitor_id_str = monitor_id_str )return HttpResponse(@@ -84,6 +93,50 @@ class NphZmsView( View ):content_type = 'text/plain',)+ def _monitor_snapshot_response( self, monitor_id_str : str ) -> HttpResponse:+ text_lines = [ 'Monitor Snapshot (simulator)' ]+ try:+ monitor_id = int( monitor_id_str )+ except ValueError:+ text_lines.append( f'unknown monitor "{monitor_id_str}"' )+ else:+ zm_sim_monitor = ZoneMinderSimulator().find_zm_monitor_by_id(+ monitor_id = monitor_id,+ )+ if zm_sim_monitor is None:+ text_lines.append( f'monitor {monitor_id} (no record)' )+ else:+ text_lines.append( f'monitor: {zm_sim_monitor.name}' )+ text_lines.append( f'id: {monitor_id}' )+ response = HttpResponse(+ render_thumbnail_jpeg( text_lines = text_lines ),+ content_type = 'image/jpeg',+ )+ _apply_no_cache_headers( response )+ return response++ def _event_snapshot_response( self, event_id_str : str ) -> HttpResponse:+ text_lines = [ 'Event Snapshot (simulator)' ]+ try:+ event_id = int( event_id_str )+ except ValueError:+ text_lines.append( f'unknown event "{event_id_str}"' )+ else:+ zm_sim_event = ZmSimEventManager().find_event_by_id( event_id = event_id )+ if zm_sim_event is None:+ text_lines.append( f'event {event_id} (no record)' )+ else:+ text_lines.append(+ f'monitor: {zm_sim_event.zm_sim_monitor.name}',+ )+ text_lines.append( f'event id: {event_id}' )+ response = HttpResponse(+ render_thumbnail_jpeg( text_lines = text_lines ),+ content_type = 'image/jpeg',+ )+ _apply_no_cache_headers( response )+ return response+def _event_playback_response( self, event_id_str : str ) -> StreamingHttpResponse:text_lines = [ 'Event Playback (simulator)' ]playback_start = Nonediff --git a/src/hi/static/css/stream-browser.css b/src/hi/static/css/stream-browser.cssindex e98dd673..db367f3e 100644--- a/src/hi/static/css/stream-browser.css+++ b/src/hi/static/css/stream-browser.css@@ -529,7 +529,8 @@}.video-interface-header.current-stream .entity-title,-.video-interface-header.event-history .entity-title {+.video-interface-header.event-history .entity-title,+.video-interface-header.bg-primary .entity-title {color: inherit;}@@ -547,7 +548,8 @@color: inherit;}-.video-interface-header.event-history .last-activity-badge {+.video-interface-header.event-history .last-activity-badge,+.video-interface-header.bg-primary .last-activity-badge {background-color: rgba(255, 255, 255, 0.1);border-color: rgba(255, 255, 255, 0.2);color: inherit;@@ -612,16 +614,26 @@border-color: rgba(255, 255, 255, 0.9);}+/* Static snapshot uses ``bg-primary`` directly; mirror the active-tab+ * inversion the named banner classes get. */+.video-interface-header.bg-primary .video-nav-tab.active {+ background-color: rgba(255, 255, 255, 0.9);+ color: var(--primary-color);+ border-color: rgba(255, 255, 255, 0.9);+}+/* Inactive tab styling for colored headers */.video-interface-header.current-stream .video-nav-tab:not(.active):not(.disabled),-.video-interface-header.event-history .video-nav-tab:not(.active):not(.disabled) {+.video-interface-header.event-history .video-nav-tab:not(.active):not(.disabled),+.video-interface-header.bg-primary .video-nav-tab:not(.active):not(.disabled) {background-color: rgba(255, 255, 255, 0.1);color: rgba(255, 255, 255, 0.8);border-color: rgba(255, 255, 255, 0.2);}.video-interface-header.current-stream .video-nav-tab:hover:not(.disabled):not(.active),-.video-interface-header.event-history .video-nav-tab:hover:not(.disabled):not(.active) {+.video-interface-header.event-history .video-nav-tab:hover:not(.disabled):not(.active),+.video-interface-header.bg-primary .video-nav-tab:hover:not(.disabled):not(.active) {background-color: rgba(255, 255, 255, 0.2);color: rgba(255, 255, 255, 1);border-color: rgba(255, 255, 255, 0.3);diff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.jsindex 361822f4..cbebe022 100644--- a/src/hi/static/js/video-timeline.js+++ b/src/hi/static/js/video-timeline.js@@ -95,6 +95,232 @@}};+ // Polls ``[data-video-snapshot]`` <img> elements at their declared+ // ``data-stream-fps`` to synthesize a live feed from a still-image+ // endpoint (HA cameras and any future integration that offers a+ // snapshot URL but no native stream). Pauses while the tab is+ // hidden so bandwidth isn't spent rendering frames the user can't+ // see.+ //+ // Marker contract:+ // - ``data-video-snapshot`` : presence opts the <img> into polling.+ // - ``data-stream-fps`` : polling rate (parallel to the Entity+ // model's ``video_snapshot_stream_fps``).+ //+ // Distinct from ``data-video-stream`` / ``data-video-recording``+ // which are continuous MJPEG fetches managed by VideoConnectionManager.+ const SnapshotStreamManager = {++ SELECTOR: 'img[data-video-snapshot]',+ SNAPSHOT_BASE_ATTR: 'snapshotBaseUrl',+ // Defensive cap: faster than 1 fps would risk overlapping+ // preloaders on slow endpoints (a stale older preload could+ // finish after a newer one and swap to an older URL).+ MAX_FPS: 1.0,++ pollers: new Map(), // element -> intervalId++ register: function( element ) {+ if ( ! element ) return;+ if ( this.pollers.has( element )) return;+ const declared = parseFloat( element.dataset.streamFps );+ if ( ! declared || declared <= 0 ) return;+ const fps = Math.min( declared, this.MAX_FPS );+ const intervalMs = Math.round( 1000 / fps );+ // Strip any server-rendered cache-bust so each poll cycle+ // adds its own; otherwise the URL keeps growing.+ element.dataset[ this.SNAPSHOT_BASE_ATTR ] =+ this._stripCacheBust( element.src );+ const manager = this;+ const intervalId = setInterval(function() {+ if ( document.hidden ) return;+ manager._refresh( element );+ }, intervalMs);+ this.pollers.set( element, intervalId );+ },++ unregister: function( element ) {+ if ( ! element ) return;+ const intervalId = this.pollers.get( element );+ if ( intervalId !== undefined ) {+ clearInterval( intervalId );+ }+ this.pollers.delete( element );+ },++ closeWithin: function( $scope ) {+ if ( ! $scope || ! $scope.find ) return;+ const manager = this;+ $scope.find( this.SELECTOR ).each(function() {+ manager.unregister( this );+ });+ },++ reconcile: function() {+ for ( const element of Array.from( this.pollers.keys() )) {+ if ( ! document.contains( element )) {+ this.unregister( element );+ }+ }+ document.querySelectorAll( this.SELECTOR ).forEach(+ (el) => this.register( el )+ );+ },++ cleanup: function() {+ for ( const element of Array.from( this.pollers.keys() )) {+ this.unregister( element );+ }+ },++ _refresh: function( element ) {+ const base = element.dataset[ this.SNAPSHOT_BASE_ATTR ] || element.src;+ const sep = base.includes( '?' ) ? '&' : '?';+ const newUrl = base + sep + '_cb=' + Date.now();+ // Preload pattern: fetch into a hidden Image first, swap the+ // visible <img>'s src only after a successful load. Avoids+ // flicker from in-flight fetches that get aborted by the next+ // poll's src change. On preload failure, assign the failing+ // URL to the visible <img> so VideoErrorHandler surfaces the+ // outage; the next successful preload heals the placeholder.+ const preloader = new Image();+ preloader.onload = function() {+ element.src = newUrl;+ };+ preloader.onerror = function() {+ element.src = newUrl;+ };+ preloader.src = newUrl;+ },++ _stripCacheBust: function( url ) {+ try {+ const u = new URL( url, window.location.href );+ u.searchParams.delete( '_cb' );+ return u.toString();+ } catch ( e ) {+ return url;+ }+ }+ };++ // Generic ``error``-event handler for the three video-marker <img>+ // elements (``data-video-stream``, ``data-video-recording``,+ // ``data-video-snapshot``). On load failure, hides the <img> and+ // inserts a sibling placeholder; on a subsequent successful load,+ // hides the placeholder and reveals the <img> again. Self-healing+ // is important for snapshot polling (transient HA blip shouldn't+ // permanently kill the feed) and harmless for the long-lived+ // streams (the placeholder just shows until the user navigates).+ //+ // Coordinates with VideoConnectionManager.forceClose: that path+ // sets ``src`` to a transparent GIF (``data:image/gif;...``).+ // Browsers don't fire ``error`` on a successfully-loaded data+ // URI, but we also explicitly skip ``data:`` URLs as defense.+ const VideoErrorHandler = {++ SELECTOR: 'img[data-video-stream], img[data-video-recording], img[data-video-snapshot]',+ PLACEHOLDER_CLASS: 'video-load-error-placeholder',+ REGISTERED_FLAG: 'videoErrorHandlerRegistered',++ // Heading + subtitle per marker. Mirrors the server-rendered+ // ``.video-placeholder`` markup in entity_video_sensor_history.html+ // for the no-source case, so the failed-to-load and no-data cases+ // look visually identical.+ MESSAGES: {+ 'data-video-stream': {+ heading: 'Live View Unavailable',+ subtitle: 'The integration may be offline or the camera unreachable',+ },+ 'data-video-recording': {+ heading: 'Video No Longer Available',+ subtitle: 'This recording could not be loaded',+ },+ 'data-video-snapshot': {+ heading: 'Snapshot Unavailable',+ subtitle: 'The integration may be offline or unable to provide a snapshot',+ },+ },++ // Reuses the camera icon from the server-rendered placeholder.+ CAMERA_ICON_SVG:+ '<svg width="64" height="64" fill="currentColor" viewBox="0 0 16 16">' ++ '<path d="M10.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0z"/>' ++ '<path d="M2 4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-1.172a2 2 0 0 1-1.414-.586l-.828-.828A2 2 0 0 0 9.172 2H6.828a2 2 0 0 0-1.414.586l-.828.828A2 2 0 0 1 3.172 4H2zm.5 2a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm9 2.5a3.5 3.5 0 1 1-7 0 3.5 3.5 0 0 1 7 0z"/>' ++ '</svg>',++ register: function( element ) {+ if ( ! element ) return;+ if ( element.dataset[ this.REGISTERED_FLAG ] ) return;+ element.dataset[ this.REGISTERED_FLAG ] = '1';+ const handler = this;+ element.addEventListener( 'error', function() {+ handler._handleError( element );+ });+ element.addEventListener( 'load', function() {+ handler._handleLoad( element );+ });+ },++ _handleError: function( element ) {+ if ( element.src && element.src.startsWith( 'data:' )) return;+ element.style.display = 'none';+ const existing = this._findSiblingPlaceholder( element );+ if ( existing ) return;+ const placeholder = this._buildPlaceholder( element );+ element.insertAdjacentElement( 'afterend', placeholder );+ },++ _handleLoad: function( element ) {+ if ( element.src && element.src.startsWith( 'data:' )) return;+ element.style.display = '';+ const existing = this._findSiblingPlaceholder( element );+ if ( existing ) existing.remove();+ },++ _findSiblingPlaceholder: function( element ) {+ const next = element.nextElementSibling;+ if ( next && next.classList+ && next.classList.contains( this.PLACEHOLDER_CLASS )) {+ return next;+ }+ return null;+ },++ _buildPlaceholder: function( element ) {+ const messages = this._messagesFor( element );+ const wrapper = document.createElement( 'div' );+ wrapper.className =+ 'video-placeholder d-flex align-items-center justify-content-center '+ + this.PLACEHOLDER_CLASS;+ wrapper.innerHTML =+ '<div class="text-center">'+ + '<div class="video-placeholder-icon mb-3">'+ + this.CAMERA_ICON_SVG+ + '</div>'+ + '<h5 class="mb-2"></h5>'+ + '<small class="text-muted"></small>'+ + '</div>';+ wrapper.querySelector( 'h5' ).textContent = messages.heading;+ wrapper.querySelector( 'small' ).textContent = messages.subtitle;+ return wrapper;+ },++ _messagesFor: function( element ) {+ for ( const marker of Object.keys( this.MESSAGES )) {+ if ( element.hasAttribute( marker )) return this.MESSAGES[ marker ];+ }+ return { heading: 'Image Unavailable', subtitle: '' };+ },++ reconcile: function() {+ const handler = this;+ document.querySelectorAll( this.SELECTOR ).forEach(+ (el) => handler.register( el )+ );+ }+ };+// Video Timeline Scrollbar Managementconst VideoTimelineScrollManager = {init: function() {@@ -208,16 +434,17 @@};// Initialize when DOM is ready- if (document.readyState === 'loading') {- document.addEventListener('DOMContentLoaded', () => {- VideoTimelineScrollManager.init();- VideoTimelineScrollManager.tagCurrentVideoWithEventId();- VideoConnectionManager.reconcile();- });- } else {+ function initVideoSubsystems() {VideoTimelineScrollManager.init();VideoTimelineScrollManager.tagCurrentVideoWithEventId();VideoConnectionManager.reconcile();+ SnapshotStreamManager.reconcile();+ VideoErrorHandler.reconcile();+ }+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', initVideoSubsystems);+ } else {+ initVideoSubsystems();}// Hook into antinode lifecycle. ``beforeContentRemoval`` runs@@ -234,23 +461,30 @@}registerHook( 'addBeforeContentRemovalFunction', ($subtree) => {VideoConnectionManager.closeWithin( $subtree );+ SnapshotStreamManager.closeWithin( $subtree );});registerHook( 'addAfterAsyncRenderFunction', () => {VideoTimelineScrollManager.handleAsyncUpdate();VideoConnectionManager.reconcile();+ SnapshotStreamManager.reconcile();+ VideoErrorHandler.reconcile();});registerHook( 'addAfterModalRenderFunction', () => {VideoConnectionManager.reconcile();+ SnapshotStreamManager.reconcile();+ VideoErrorHandler.reconcile();});- // Cleanup on page unload to free connections+ // Cleanup on page unload to free connections and stop pollerswindow.addEventListener('beforeunload', () => {VideoConnectionManager.cleanup();+ SnapshotStreamManager.cleanup();});// Also cleanup on navigation away from video pageswindow.addEventListener('pagehide', () => {VideoConnectionManager.cleanup();+ SnapshotStreamManager.cleanup();});// Replay-from-start for finite recordings. Templates wrap each@@ -263,10 +497,9 @@// cached original URL on each click. The browser sees a new URL,// abandons the previous fetch, and starts a new one. ZoneMinder// serves the recording from the start on each request- // (``replay=single``). Avoids ever blanking the ``src`` —- // some templates carry inline ``onerror`` handlers that fire- // on empty src and replace the <img> with an error message,- // which the empty-src + reset technique would trigger.+ // (``replay=single``). Avoids blanking the ``src`` — an empty+ // src would fire ``error`` and trigger ``VideoErrorHandler``'s+ // placeholder.function videoRecordingReplayBuster( baseUrl ) {const sep = baseUrl.includes('?') ? '&' : '?';return baseUrl + sep + '_replay=' + Date.now();@@ -294,4 +527,6 @@// Expose for potential external use and debuggingwindow.VideoTimelineScrollManager = VideoTimelineScrollManager;window.VideoConnectionManager = VideoConnectionManager;+ window.SnapshotStreamManager = SnapshotStreamManager;+ window.VideoErrorHandler = VideoErrorHandler;})();diff --git a/src/hi/static/state_panels/camera/camera.css b/src/hi/static/state_panels/camera/camera.cssindex 29194d3b..71907b7f 100644--- a/src/hi/static/state_panels/camera/camera.css+++ b/src/hi/static/state_panels/camera/camera.css@@ -31,16 +31,32 @@min-height: 60px;}-/* The existing entity_video_stream wrapper renders an anchor + img. */+/* The live-view wrapper renders an anchor that wraps a+ * .video-container around the <img>. Both intermediate elements+ * must carry height:100% so the <img>'s height:100% / object-fit+ * resolves against the .stream box's aspect-ratio rather than the+ * image's intrinsic height (which would otherwise overflow the+ * 16:9 area and get bottom-clipped by overflow:hidden). */.hi-state-panel-camera .stream a {display: block;text-decoration: none;+ width: 100%;+ height: 100%;+}+.hi-state-panel-camera .stream .video-container {+ width: 100%;+ height: 100%;}.hi-state-panel-camera .stream .video-container img,.hi-state-panel-camera .stream img.img-fluid {width: 100%;height: 100%;- object-fit: cover;+ /* ``contain`` rather than ``cover``: integrations produce+ * arbitrary aspect ratios, and silently cropping pixels from+ * the user's camera feed is the wrong default. Grid/list cards+ * keep their fixed aspect-ratio cell for layout consistency;+ * the image is letterboxed inside. */+ object-fit: contain;display: block;}@@ -48,10 +64,18 @@/* Modal layout *//* ============================================================== */+/* Modal shows one camera at a time, so the box sizes to the image's+ * natural aspect ratio — no cropping, no letterboxing. Grid/list+ * contexts (below) keep their fixed aspect-ratio cell for layout+ * consistency across cameras; ``object-fit: contain`` inherited from+ * the base rule keeps each image whole inside its cell. */.hi-state-panel-camera--modal .stream {- aspect-ratio: 16 / 9;margin-bottom: 16px;}+.hi-state-panel-camera--modal .stream .video-container img,+.hi-state-panel-camera--modal .stream img.img-fluid {+ height: auto;+}/* ============================================================== *//* List card layout */