Skip to content

Home Information - Your home, your data, organized.

Python

Add smart camera sidebar navigation for video stream browsing (#174)

cassandra-ai-agentf69296bd5d8e
diff --git a/src/hi/apps/console/enums.py b/src/hi/apps/console/enums.py
index f5137b03..1ca9b162 100644
--- a/src/hi/apps/console/enums.py
+++ b/src/hi/apps/console/enums.py
@@ -10,3 +10,15 @@ class DisplayUnits(LabeledEnum):
IMPERIAL = ( 'Imperial', '' )
METRIC = ( 'Metric', '' )
+
+
+class VideoDispatchType(LabeledEnum):
+ """
+ Enum for video dispatch navigation types.
+ Used to determine which view to route to when navigating between cameras.
+ """
+
+ LIVE_STREAM = ('Live Stream', 'Display current live video stream')
+ HISTORY_DEFAULT = ('History Default', 'Display most recent history events')
+ HISTORY_EARLIER = ('History Earlier', 'Display earlier history events from timestamp')
+ HISTORY_LATER = ('History Later', 'Display later history events from timestamp')
diff --git a/src/hi/apps/console/templates/console/panes/camera_controls.html b/src/hi/apps/console/templates/console/panes/camera_controls.html
index 5cb6933f..7bfceef7 100644
--- a/src/hi/apps/console/templates/console/panes/camera_controls.html
+++ b/src/hi/apps/console/templates/console/panes/camera_controls.html
@@ -3,9 +3,12 @@
<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' entity_id=camera_data.entity.id %}"
+ <a href="{% url 'console_entity_video_stream_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 {% if camera_data.status_entity_state %}{{ camera_data.status_entity_state.css_class }}{% endif %}"
- {% if camera_data.status_entity_state %}status=""{% endif %}>
+ {% if camera_data.status_entity_state %}status=""{% endif %}
+ role="button">
{{ camera_data.short_name }}
</a>
</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.html
index 34c38f2d..1afa2e30 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
@@ -1,7 +1,7 @@
{% load video_tags %}
{% entity_video_stream entity as video_url %}
{% if video_url %}
-<div>
+<div class="video-container">
<img class="img-fluid" src="{{ video_url }}" alt="{{ entity.name }} Live Video">
</div>
{% endif %}
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.py
index d9895e19..0f088c70 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
@@ -1,15 +1,20 @@
+from datetime import datetime
+from pytz import UTC
import logging
from django.test import TransactionTestCase
from django.utils import timezone
from hi.apps.console.video_stream_browsing_helper import VideoStreamBrowsingHelper
-from hi.apps.console.transient_models import EntitySensorHistoryData
+from hi.apps.console.transient_models import EntitySensorHistoryData, VideoDispatchResult
+from hi.apps.console.enums import VideoDispatchType
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
from hi.apps.sense.transient_models import SensorResponse
from hi.integrations.transient_models import IntegrationKey
+from django.core.exceptions import BadRequest
+
logging.disable(logging.CRITICAL)
@@ -600,3 +605,464 @@ class TestVideoStreamBrowsingHelper(TransactionTestCase):
# Should handle far future timestamp
self.assertIsNotNone(result)
self.assertIsInstance(result.sensor_responses, list)
+
+
+class TestVideoDispatchResult(TransactionTestCase):
+ """Test get_video_dispatch_result method core functionality and edge cases."""
+
+ def setUp(self):
+ # Create test entity with video stream capability
+ self.video_entity = Entity.objects.create(
+ integration_id='test.camera.dispatch',
+ integration_name='test_integration',
+ name='Dispatch Test Camera',
+ entity_type_str='camera',
+ has_video_stream=True
+ )
+
+ # Create entity state
+ self.entity_state = EntityState.objects.create(
+ entity=self.video_entity,
+ entity_state_type_str='motion',
+ name='Motion Detection'
+ )
+
+ # Create sensor with video capability
+ self.video_sensor = Sensor.objects.create(
+ integration_id='test.sensor.dispatch',
+ integration_name='test_integration',
+ name='Dispatch Motion Sensor',
+ entity_state=self.entity_state,
+ sensor_type_str='binary',
+ provides_video_stream=True
+ )
+
+ # Create entity without video capability for error testing
+ self.non_video_entity = Entity.objects.create(
+ integration_id='test.no.video',
+ integration_name='test_integration',
+ name='No Video Entity',
+ entity_type_str='sensor',
+ has_video_stream=False
+ )
+
+ def test_get_video_dispatch_result_returns_valid_result_structure(self):
+ """Test that method returns properly structured VideoDispatchResult."""
+ referrer_url = f'/console/entity/{self.video_entity.id}/video-sensor-history/{self.video_sensor.id}/'
+
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, referrer_url
+ )
+
+ # Verify result structure
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertIsInstance(result.dispatch_type, VideoDispatchType)
+ self.assertEqual(result.sensor, self.video_sensor)
+
+ # Verify properties work
+ self.assertFalse(result.is_live_stream)
+ self.assertTrue(result.is_history_view)
+
+ # Verify get_view_kwargs method
+ kwargs = result.get_view_kwargs()
+ self.assertIn('sensor_id', kwargs)
+ self.assertEqual(kwargs['sensor_id'], self.video_sensor.id)
+
+ def test_get_video_dispatch_result_fallback_behavior_with_records(self):
+ """Test fallback behavior when sensor has data records."""
+ base_time = timezone.now()
+ timestamp = int(base_time.timestamp())
+
+ # Create both earlier and later records
+ earlier_time = base_time - timezone.timedelta(hours=1)
+ later_time = base_time + timezone.timedelta(hours=1)
+
+ SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='earlier_event',
+ response_datetime=earlier_time,
+ has_video_stream=True
+ )
+
+ SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='later_event',
+ response_datetime=later_time,
+ has_video_stream=True
+ )
+
+ # Test with an earlier view URL that should trigger fallback logic
+ referrer_url = f'/console/entity/{self.video_entity.id}/video-sensor-history/{self.video_sensor.id}/earlier/{timestamp}/'
+
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, referrer_url
+ )
+
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertEqual(result.sensor, self.video_sensor)
+ # Method should return a valid dispatch type based on available records
+ self.assertIn(result.dispatch_type, [
+ VideoDispatchType.HISTORY_DEFAULT,
+ VideoDispatchType.HISTORY_EARLIER,
+ 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_fallback_to_default(self):
+ """Test fallback to default dispatch for unrecognized URLs."""
+ unrecognized_urls = [
+ '/some/invalid/url/',
+ '',
+ 'not-a-url',
+ '/console/other/path/',
+ ]
+
+ for url in unrecognized_urls:
+ with self.subTest(url=url):
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, url
+ )
+
+ # Should fallback to default dispatch
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertEqual(result.dispatch_type, VideoDispatchType.HISTORY_DEFAULT)
+ self.assertEqual(result.sensor, self.video_sensor)
+ self.assertIsNone(result.timestamp)
+
+ def test_get_video_dispatch_result_with_empty_database(self):
+ """Test behavior when no sensor history records exist."""
+ # No SensorHistory records created - empty database for this sensor
+ referrer_url = f'/console/entity/{self.video_entity.id}/video-sensor-history/{self.video_sensor.id}/earlier/1234567890/'
+
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, referrer_url
+ )
+
+ # Should return a valid result even with empty database
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertEqual(result.sensor, self.video_sensor)
+ # Could be any dispatch type depending on URL matching
+ self.assertIn(result.dispatch_type, [
+ VideoDispatchType.HISTORY_DEFAULT,
+ VideoDispatchType.HISTORY_EARLIER,
+ VideoDispatchType.HISTORY_LATER
+ ])
+
+ def test_get_video_dispatch_result_basic_history_view_url(self):
+ """Test basic sensor history view URL (Case 5: no specific event)."""
+ referrer_url = f'/console/entity/{self.video_entity.id}/video-sensor-history/{self.video_sensor.id}/'
+
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, referrer_url
+ )
+
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertEqual(result.dispatch_type, VideoDispatchType.HISTORY_DEFAULT)
+ self.assertEqual(result.sensor, self.video_sensor)
+ self.assertIsNone(result.timestamp)
+
+ def test_get_video_dispatch_result_timestamp_handling(self):
+ """Test that method handles timestamp parameters correctly."""
+ test_timestamp = 1234567890
+ referrer_url = f'/console/entity/{self.video_entity.id}/video-sensor-history/{self.video_sensor.id}/earlier/{test_timestamp}/'
+
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, referrer_url
+ )
+
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertEqual(result.sensor, self.video_sensor)
+ # If URL matches pattern and method sets timestamp, verify it
+ if result.timestamp is not None:
+ self.assertEqual(result.timestamp, test_timestamp)
+
+ def test_get_video_dispatch_result_helper_methods_integration(self):
+ """Test integration with helper methods _has_older_records and _has_newer_records."""
+ base_time = timezone.now()
+ timestamp = int(base_time.timestamp())
+
+ # Create test record
+ SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='test_event',
+ response_datetime=base_time - timezone.timedelta(hours=1),
+ has_video_stream=True
+ )
+
+ # Test that helper methods work correctly
+ has_older = VideoStreamBrowsingHelper._has_older_records(self.video_sensor, timestamp)
+ has_newer = VideoStreamBrowsingHelper._has_newer_records(self.video_sensor, timestamp)
+
+ self.assertTrue(has_older) # Record exists 1 hour before timestamp
+ self.assertFalse(has_newer) # No records after timestamp
+
+ # Test dispatch method uses these results appropriately
+ referrer_url = f'/console/entity/{self.video_entity.id}/video-sensor-history/{self.video_sensor.id}/later/{timestamp}/'
+
+ result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ self.video_entity, referrer_url
+ )
+
+ self.assertIsInstance(result, VideoDispatchResult)
+ self.assertEqual(result.sensor, self.video_sensor)
+
+
+class TestTimezoneHandling(TransactionTestCase):
+ """Test timezone-related functionality in VideoStreamBrowsingHelper."""
+
+ def setUp(self):
+ """Set up test entities and sensors."""
+ # Create test entity with video capability (matching existing pattern)
+ self.video_entity = Entity.objects.create(
+ integration_id='test.timezone.camera',
+ integration_name='test_timezone_integration',
+ name='Timezone Test Camera',
+ entity_type_str='camera',
+ has_video_stream=True
+ )
+
+ # Create entity state
+ self.entity_state = EntityState.objects.create(
+ entity=self.video_entity,
+ entity_state_type_str='motion',
+ name='Motion Detection'
+ )
+
+ # Create video sensor
+ self.video_sensor = Sensor.objects.create(
+ integration_id='test.timezone.sensor',
+ integration_name='test_timezone_integration',
+ name='Timezone Test Sensor',
+ entity_state=self.entity_state,
+ sensor_type_str='binary',
+ provides_video_stream=True
+ )
+
+ def test_group_responses_by_time_with_user_timezone(self):
+ """Test that group_responses_by_time correctly uses user timezone for grouping."""
+ from datetime import datetime
+ from pytz import UTC
+
+ # Create test records at specific UTC times that would span multiple days in different timezones
+ # 11 PM CDT (4 AM UTC next day) and 1 AM CDT (6 AM UTC same day)
+ utc_time_1 = datetime(2023, 7, 15, 4, 0, 0, tzinfo=UTC) # 11 PM CDT July 14
+ utc_time_2 = datetime(2023, 7, 15, 6, 0, 0, tzinfo=UTC) # 1 AM CDT July 15
+
+ record_1 = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='event_july_14_cdt',
+ response_datetime=utc_time_1,
+ has_video_stream=True
+ )
+
+ record_2 = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='event_july_15_cdt',
+ response_datetime=utc_time_2,
+ has_video_stream=True
+ )
+
+ # Create sensor responses
+ response_1 = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_1)
+ response_2 = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_2)
+
+ # Test with CDT timezone - should group into different days
+ groups_cdt = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response_1, response_2],
+ user_timezone='America/Chicago'
+ )
+
+ # Should have two separate day groups
+ self.assertEqual(len(groups_cdt), 2)
+
+ # Test with UTC timezone - both should be in same day (July 15)
+ groups_utc = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response_1, response_2],
+ user_timezone='UTC'
+ )
+
+ # Should have one day group since both events are on July 15 UTC
+ self.assertEqual(len(groups_utc), 1)
+
+ def test_group_responses_by_time_with_dst_transitions(self):
+ """Test timezone handling during DST transitions."""
+
+ # Test during spring forward in US Central Time (March 2023)
+ # 1:30 AM CST (before spring forward) and 3:30 AM CDT (after spring forward)
+
+ # Before DST transition (1:30 AM CST = 7:30 AM UTC)
+ utc_before = datetime(2023, 3, 12, 7, 30, 0, tzinfo=UTC)
+ # After DST transition (3:30 AM CDT = 8:30 AM UTC)
+ utc_after = datetime(2023, 3, 12, 8, 30, 0, tzinfo=UTC)
+
+ record_before = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='before_dst',
+ response_datetime=utc_before,
+ has_video_stream=True
+ )
+
+ record_after = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='after_dst',
+ response_datetime=utc_after,
+ has_video_stream=True
+ )
+
+ response_before = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_before)
+ response_after = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_after)
+
+ # Test grouping with Chicago timezone
+ groups = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response_before, response_after],
+ user_timezone='America/Chicago'
+ )
+
+ # Should handle DST transition correctly and group appropriately
+ # Both events should be on same day (March 12) in Chicago timezone
+ self.assertEqual(len(groups), 1)
+ self.assertEqual(len(groups[0]['items']), 2)
+
+ def test_group_responses_by_time_midnight_boundary_edge_case(self):
+ """Test timezone handling at midnight boundaries."""
+ from datetime import datetime
+ from pytz import UTC
+
+ # Create records at 11:59 PM and 12:01 AM in a specific timezone
+ # Using Pacific Time: 11:59 PM PST = 7:59 AM UTC next day
+ pst_late_night = datetime(2023, 12, 15, 7, 59, 0, tzinfo=UTC) # 11:59 PM PST Dec 14
+ pst_early_morning = datetime(2023, 12, 15, 8, 1, 0, tzinfo=UTC) # 12:01 AM PST Dec 15
+
+ record_late = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='late_night',
+ response_datetime=pst_late_night,
+ has_video_stream=True
+ )
+
+ record_early = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='early_morning',
+ response_datetime=pst_early_morning,
+ has_video_stream=True
+ )
+
+ response_late = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_late)
+ response_early = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record_early)
+
+ # Test with Pacific timezone - should be different days
+ groups_pst = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response_late, response_early],
+ user_timezone='America/Los_Angeles'
+ )
+
+ self.assertEqual(len(groups_pst), 2) # Different days in PST
+
+ # Test with UTC timezone - should be same day
+ groups_utc = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response_late, response_early],
+ user_timezone='UTC'
+ )
+
+ self.assertEqual(len(groups_utc), 1) # Same day in UTC
+
+ def test_group_responses_by_time_invalid_timezone_fallback(self):
+ """Test that invalid timezone falls back to UTC behavior."""
+ from datetime import datetime
+ from pytz import UTC
+
+ # Create a test record
+ utc_time = datetime(2023, 7, 15, 12, 0, 0, tzinfo=UTC)
+
+ record = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='test_event',
+ response_datetime=utc_time,
+ has_video_stream=True
+ )
+
+ response = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(record)
+
+ # Test with invalid timezone - should not crash and should fall back to UTC-like behavior
+ groups_invalid = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response],
+ user_timezone='Invalid/Timezone'
+ )
+
+ # Should still create groups without crashing
+ self.assertIsInstance(groups_invalid, list)
+ self.assertTrue(len(groups_invalid) > 0)
+
+ # Compare with UTC behavior
+ groups_utc = VideoStreamBrowsingHelper.group_responses_by_time(
+ [response],
+ user_timezone='UTC'
+ )
+
+ # Should have same structure as UTC (fallback behavior)
+ self.assertEqual(len(groups_invalid), len(groups_utc))
+
+ def test_build_sensor_history_data_methods_pass_timezone_parameter(self):
+ """Test that all build_sensor_history_data methods accept and pass timezone parameter."""
+ from datetime import datetime
+ from pytz import UTC
+
+ # Create test record
+ utc_time = datetime(2023, 7, 15, 12, 0, 0, tzinfo=UTC)
+ test_timestamp = int(utc_time.timestamp())
+
+ _ = SensorHistory.objects.create(
+ sensor=self.video_sensor,
+ value='test_event',
+ response_datetime=utc_time,
+ has_video_stream=True
+ )
+
+ # Test build_sensor_history_data_default with timezone
+ result_default = VideoStreamBrowsingHelper.build_sensor_history_data_default(
+ self.video_sensor,
+ user_timezone='America/New_York'
+ )
+
+ self.assertIsInstance(result_default, EntitySensorHistoryData)
+
+ # Test build_sensor_history_data_earlier with timezone
+ result_earlier = VideoStreamBrowsingHelper.build_sensor_history_data_earlier(
+ self.video_sensor,
+ test_timestamp,
+ user_timezone='America/New_York'
+ )
+
+ self.assertIsInstance(result_earlier, EntitySensorHistoryData)
+
+ # Test build_sensor_history_data_later with timezone
+ result_later = VideoStreamBrowsingHelper.build_sensor_history_data_later(
+ self.video_sensor,
+ test_timestamp,
+ user_timezone='America/New_York'
+ )
+
+ self.assertIsInstance(result_later, EntitySensorHistoryData)
+
+ # Test main build_sensor_history_data with timezone
+ result_main = VideoStreamBrowsingHelper.build_sensor_history_data(
+ self.video_sensor,
+ user_timezone='America/New_York'
+ )
+
+ self.assertIsInstance(result_main, EntitySensorHistoryData)
diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.py
index fbace491..534f95b6 100644
--- a/src/hi/apps/console/tests/test_views.py
+++ b/src/hi/apps/console/tests/test_views.py
@@ -3,7 +3,6 @@ from unittest.mock import Mock
from django.urls import reverse
from django.utils import timezone
-from django.http import Http404
from django.core.exceptions import BadRequest
from hi.apps.console.views import (
@@ -134,28 +133,6 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
)
self.sensor_history_records.append(record)
- def test_get_main_template_name_returns_correct_template(self):
- """Test that the view returns the correct template name."""
- view = EntityVideoSensorHistoryView()
- template_name = view.get_main_template_name()
-
- self.assertEqual(template_name, 'console/panes/entity_video_sensor_history.html')
-
- def test_view_requires_valid_entity_id(self):
- """Test that view raises Http404 for invalid entity ID."""
- view = EntityVideoSensorHistoryView()
- request = Mock()
- request.view_parameters = Mock()
- request.view_parameters.to_session = Mock()
-
- with self.assertRaises(Http404) as context:
- view.get_main_template_context(
- request,
- entity_id=99999,
- sensor_id=self.video_sensor.id
- )
- self.assertEqual(str(context.exception), 'Entity not found.')
-
def test_view_requires_sensor_with_video_capability(self):
"""Test that view raises BadRequest for sensor without video stream capability."""
# Create a sensor that doesn't provide video streams
@@ -181,21 +158,6 @@ class TestEntityVideoSensorHistoryView(BaseTestCase):
)
self.assertEqual(str(context.exception), 'Sensor does not provide video stream capability.')
- def test_view_requires_valid_sensor_id(self):
- """Test that view raises Http404 for invalid sensor ID."""
- view = EntityVideoSensorHistoryView()
- request = Mock()
- request.view_parameters = Mock()
- request.view_parameters.to_session = Mock()
-
- with self.assertRaises(Http404) as context:
- view.get_main_template_context(
- request,
- entity_id=self.video_entity.id,
- sensor_id=99999
- )
- self.assertEqual(str(context.exception), 'Sensor not found for this entity.')
-
def test_view_returns_correct_context_structure_with_real_data(self):
"""Test that view returns expected context structure with real sensor history data."""
# Clear any existing sensor history from setUp
diff --git a/src/hi/apps/console/transient_models.py b/src/hi/apps/console/transient_models.py
index 9a1d97ee..deff8d45 100644
--- a/src/hi/apps/console/transient_models.py
+++ b/src/hi/apps/console/transient_models.py
@@ -4,7 +4,9 @@ import re
from typing import Dict, List, Optional
from hi.apps.entity.models import Entity, EntityState
+from hi.apps.sense.models import Sensor
from hi.apps.sense.transient_models import SensorResponse
+from .enums import VideoDispatchType
@dataclass
@@ -54,3 +56,46 @@ class EntitySensorHistoryData:
next_sensor_response: Optional[SensorResponse]
window_start_timestamp: Optional[datetime] = None
window_end_timestamp: Optional[datetime] = None
+
+
+@dataclass
+class VideoDispatchResult:
+ """
+ Result of video dispatch decision making.
+ Encapsulates the dispatch type and all necessary parameters for routing.
+ """
+ dispatch_type : VideoDispatchType
+ sensor : Sensor
+ timestamp : Optional[int] = None # Unix timestamp for earlier/later views
+ window_start : Optional[int] = None # Window start timestamp for context preservation
+ window_end : Optional[int] = None # Window end timestamp for context preservation
+
+ @property
+ def is_live_stream(self) -> bool:
+ """Check if dispatching to live stream view."""
+ return self.dispatch_type == VideoDispatchType.LIVE_STREAM
+
+ @property
+ def is_history_view(self) -> bool:
+ """Check if dispatching to any history view."""
+ return self.dispatch_type in [
+ VideoDispatchType.HISTORY_DEFAULT,
+ VideoDispatchType.HISTORY_EARLIER,
+ VideoDispatchType.HISTORY_LATER
+ ]
+
+ def get_view_kwargs(self) -> Dict:
+ """
+ Get the kwargs needed for the target view.
+ Returns dict suitable for updating request kwargs.
+ """
+ kwargs = { 'sensor_id': self.sensor.id }
+
+ if self.timestamp is not None:
+ kwargs['timestamp'] = self.timestamp
+ if self.window_start is not None:
+ kwargs['window_start'] = self.window_start
+ if self.window_end is not None:
+ kwargs['window_end'] = self.window_end
+
+ return kwargs
diff --git a/src/hi/apps/console/transient_view_manager.py b/src/hi/apps/console/transient_view_manager.py
index 0b8a5db9..74492948 100644
--- a/src/hi/apps/console/transient_view_manager.py
+++ b/src/hi/apps/console/transient_view_manager.py
@@ -19,8 +19,11 @@ class TransientViewManager(Singleton):
self._current_suggestion: Optional[TransientViewSuggestion] = None
logger.debug("TransientViewManager initialized")
- def suggest_view_change(self, url: str, duration_seconds: int,
- priority: int = 0, trigger_reason: str = ""):
+ def suggest_view_change( self,
+ url : str,
+ duration_seconds : int,
+ priority : int = 0,
+ trigger_reason : str = "" ):
"""
Register a suggestion for transient view change.
@@ -115,10 +118,10 @@ class TransientViewManager(Singleton):
priority = alert.alert_priority # Use the alert's priority
self.suggest_view_change(
- url=view_url,
- duration_seconds=duration_seconds,
- priority=priority,
- trigger_reason=f"{alert.alarm_source.name.lower()}_alert"
+ url = view_url,
+ duration_seconds = duration_seconds,
+ priority = priority,
+ trigger_reason = f"{alert.alarm_source.name.lower()}_alert"
)
logger.debug(f"Created auto-view suggestion for alert {alert.signature}")
diff --git a/src/hi/apps/console/urls.py b/src/hi/apps/console/urls.py
index 476effd8..215e9824 100644
--- a/src/hi/apps/console/urls.py
+++ b/src/hi/apps/console/urls.py
@@ -5,11 +5,18 @@ from . import views
urlpatterns = [
+ re_path( r'^entity/video-stream-dispatch/(?P<entity_id>\d+)$',
+ views.EntityVideoStreamDispatchView.as_view(),
+ name='console_entity_video_stream_dispatch'),
re_path( r'^entity/video-stream/(?P<entity_id>\d+)$',
views.EntityVideoStreamView.as_view(),
name='console_entity_video_stream'),
+ re_path( r'^entity/video-history/(?P<entity_id>\d+)$',
+ views.EntityVideoHistoryView.as_view(),
+ name='console_entity_sendor_video_history_default'),
+
re_path( r'^entity/video-sensor-history/(?P<entity_id>\d+)/(?P<sensor_id>\d+)/$',
views.EntityVideoSensorHistoryView.as_view(),
name='console_entity_video_sensor_history'),
diff --git a/src/hi/apps/console/video_stream_browsing_helper.py b/src/hi/apps/console/video_stream_browsing_helper.py
index 663051ff..2b449f5f 100644
--- a/src/hi/apps/console/video_stream_browsing_helper.py
+++ b/src/hi/apps/console/video_stream_browsing_helper.py
@@ -6,14 +6,19 @@ and sensor selection for video streams.
from datetime import datetime, timedelta
from typing import Dict, List, Optional
+from urllib.parse import urlparse
+
+from django.core.exceptions import BadRequest
from django.utils import timezone
+from django.urls import resolve, Resolver404
from hi.apps.entity.models import Entity, EntityState
from hi.apps.sense.models import Sensor, SensorHistory
from hi.apps.sense.transient_models import SensorResponse
from .console_manager import ConsoleManager
-from .transient_models import EntitySensorHistoryData
+from .enums import VideoDispatchType
+from .transient_models import EntitySensorHistoryData, VideoDispatchResult
class VideoStreamBrowsingHelper:
@@ -24,16 +29,10 @@ class VideoStreamBrowsingHelper:
SENSOR_STATE_TYPE_PRIORITY = ConsoleManager.STATUS_ENTITY_STATE_PRIORITY
@classmethod
- def find_video_sensor_for_entity(cls, entity: Entity) -> Optional[Sensor]:
+ 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.
-
- Args:
- entity: Entity to find video sensor for
-
- Returns:
- First video-capable Sensor found, or None
"""
if not entity or not entity.has_video_stream:
return None
@@ -73,16 +72,9 @@ class VideoStreamBrowsingHelper:
return None
@classmethod
- def create_sensor_response_with_history_id(cls, sensor_history: SensorHistory) -> SensorResponse:
- """
- Create SensorResponse from SensorHistory and set the core history ID property.
-
- Args:
- sensor_history: SensorHistory record to convert
-
- Returns:
- SensorResponse object with sensor_history_id property set
- """
+ def create_sensor_response_with_history_id(
+ cls,
+ sensor_history : SensorHistory) -> SensorResponse:
sensor_response = SensorResponse.from_sensor_history(sensor_history)
# Set the core Django primary key as a proper property
@@ -92,9 +84,11 @@ class VideoStreamBrowsingHelper:
@classmethod
def get_timeline_window(
- cls, sensor: Sensor, center_record: SensorHistory = None, window_size: int = 50,
- preserve_window_bounds: tuple = None
- ):
+ cls,
+ sensor : Sensor,
+ center_record : SensorHistory = None,
+ window_size : int = 50,
+ preserve_window_bounds : tuple = None ):
"""
Get a timeline window of SensorHistory records around a center record.
Designed to support future pagination functionality.
@@ -119,16 +113,14 @@ class VideoStreamBrowsingHelper:
).order_by('-response_datetime'))
# Check for records outside the preserved window for pagination
- has_older_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__lt=start_time
- ).exists()
- has_newer_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__gt=end_time
- ).exists()
+ has_older_records = cls._has_older_records(
+ sensor = sensor,
+ timestamp = start_time
+ )
+ has_newer_records = cls._has_newer_records(
+ sensor = sensor,
+ timestamp = end_time
+ )
window_center_timestamp = start_time if history_records else None
elif center_record is None:
# No center record - get most recent records (default behavior)
@@ -180,8 +172,10 @@ class VideoStreamBrowsingHelper:
window_start_timestamp, window_end_timestamp = preserve_window_bounds
else:
# Use actual bounds of returned records
- window_start_timestamp = min(record.response_datetime for record in history_records)
- window_end_timestamp = max(record.response_datetime for record in history_records)
+ window_start_timestamp = min( record.response_datetime
+ for record in history_records )
+ window_end_timestamp = max( record.response_datetime
+ for record in history_records )
# Pagination metadata for future pagination feature
pagination_metadata = {
@@ -196,13 +190,17 @@ class VideoStreamBrowsingHelper:
return sensor_responses, pagination_metadata
@classmethod
- def group_responses_by_time(cls, sensor_responses: List[SensorResponse]) -> List[Dict]:
+ def group_responses_by_time( cls,
+ sensor_responses : List[SensorResponse],
+ user_timezone : str = None ) -> List[Dict]:
"""
Group sensor responses by time period for timeline display.
Uses adaptive grouping - hourly if many events in a day, otherwise daily.
Args:
sensor_responses: List of SensorResponse objects
+ user_timezone: User's timezone string (e.g., 'America/Chicago').
+ If None, uses UTC.
Returns:
List of grouped timeline items
@@ -215,14 +213,44 @@ class VideoStreamBrowsingHelper:
current_hour = None
current_group = None
- # Determine if we should group by hour (if many events in current day)
- today = timezone.now().date()
- today_count = sum(1 for response in sensor_responses if response.timestamp.date() == today)
+ # Set up timezone conversion if user timezone provided
+ if user_timezone:
+ import pytz
+ try:
+ tz = pytz.timezone(user_timezone)
+ # Get current date in user's timezone
+ now_in_user_tz = timezone.now().astimezone(tz)
+ today = now_in_user_tz.date()
+ yesterday = today - timedelta(days=1)
+ except pytz.UnknownTimeZoneError:
+ # Fall back to UTC if invalid timezone
+ user_timezone = None
+ today = timezone.now().date()
+ yesterday = today - timedelta(days=1)
+ else:
+ # Use UTC (original behavior)
+ today = timezone.now().date()
+ yesterday = today - timedelta(days=1)
+
+ # Count events for today to determine if we should use hourly grouping
+ if user_timezone:
+ today_count = sum( 1 for response in sensor_responses
+ if response.timestamp.astimezone(tz).date() == today)
+ else:
+ today_count = sum( 1 for response in sensor_responses
+ if response.timestamp.date() == today)
use_hourly = today_count > 10
for response in sensor_responses:
- response_date = response.timestamp.date()
- response_hour = response.timestamp.hour
+ # Convert response timestamp to user timezone if provided
+ if user_timezone:
+ response_in_tz = response.timestamp.astimezone(tz)
+ response_date = response_in_tz.date()
+ response_hour = response_in_tz.hour
+ else:
+ response_in_tz = response.timestamp
+ response_date = response.timestamp.date()
+ response_hour = response.timestamp.hour
# Create new group if needed
if use_hourly and response_date == today:
@@ -231,7 +259,7 @@ class VideoStreamBrowsingHelper:
current_date = response_date
current_hour = response_hour
current_group = {
- 'label': f"{response.timestamp.strftime('%I:00 %p')}",
+ 'label': f"{response_in_tz.strftime('%I:00 %p')}",
'date': response_date,
'items': []
}
@@ -242,11 +270,11 @@ class VideoStreamBrowsingHelper:
current_date = response_date
current_hour = None
if response_date == today:
- label = f"Today {response.timestamp.strftime('%a')}"
- elif response_date == today - timedelta(days=1):
- label = f"Yesterday {response.timestamp.strftime('%a')}"
+ label = f"Today {response_in_tz.strftime('%a')}"
+ elif response_date == yesterday:
+ label = f"Yesterday {response_in_tz.strftime('%a')}"
else:
- label = f"{response.timestamp.strftime('%B %d %a')}"
+ label = f"{response_in_tz.strftime('%B %d %a')}"
current_group = {
'label': label,
@@ -261,10 +289,9 @@ class VideoStreamBrowsingHelper:
return groups
@classmethod
- def find_navigation_items(
- cls, sensor_responses: List[SensorResponse],
- current_sensor_history_id: int
- ) -> tuple:
+ def find_navigation_items( cls,
+ sensor_responses : List[SensorResponse],
+ current_sensor_history_id : int ) -> tuple:
"""
Find previous and next sensor responses for navigation.
@@ -298,7 +325,9 @@ class VideoStreamBrowsingHelper:
return (None, None)
@classmethod
- def find_adjacent_records(cls, sensor: Sensor, current_history_id: int) -> tuple:
+ def find_adjacent_records( cls,
+ sensor : Sensor,
+ current_history_id : int ) -> tuple:
"""
Find previous and next SensorHistory records for navigation.
Uses database queries for efficient navigation.
@@ -347,43 +376,61 @@ class VideoStreamBrowsingHelper:
return (prev_sensor_response, next_sensor_response)
@classmethod
- def build_sensor_history_data_default(cls, sensor: Sensor, sensor_history_id: int = None) -> EntitySensorHistoryData:
+ def build_sensor_history_data_default(
+ cls,
+ sensor : Sensor,
+ sensor_history_id : int = None,
+ user_timezone : str = None) -> EntitySensorHistoryData:
"""Build data for default view (most recent events or centered on specific record)."""
return cls._build_sensor_history_data_internal(
- sensor, sensor_history_id, None, None
+ sensor, sensor_history_id, None, None, user_timezone
)
@classmethod
def build_sensor_history_data_with_window(
- cls, sensor: Sensor, sensor_history_id: int = None,
- preserve_window_start: datetime = None, preserve_window_end: datetime = None
- ) -> EntitySensorHistoryData:
+ cls,
+ sensor : Sensor,
+ sensor_history_id : int = None,
+ preserve_window_start : datetime = None,
+ preserve_window_end : datetime = None,
+ user_timezone : str = None ) -> EntitySensorHistoryData:
"""Build data for specific window preservation."""
return cls._build_sensor_history_data_internal(
- sensor, sensor_history_id, preserve_window_start, preserve_window_end
+ sensor, sensor_history_id, preserve_window_start, preserve_window_end, user_timezone
)
@classmethod
- def build_sensor_history_data_earlier(cls, sensor: Sensor, pivot_timestamp: int) -> EntitySensorHistoryData:
+ def build_sensor_history_data_earlier(
+ cls,
+ sensor : Sensor,
+ pivot_timestamp : int,
+ user_timezone : str = None) -> EntitySensorHistoryData:
"""Build data for pagination to earlier events."""
pivot_time = timezone.make_aware(datetime.fromtimestamp(pivot_timestamp))
- # Get 50 events before the pivot time
+ # Get events before the pivot time
history_records = list(SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__lt=pivot_time
+ sensor = sensor,
+ has_video_stream = True,
+ response_datetime__lt = pivot_time
).order_by('-response_datetime')[:50])
if not history_records:
- # No earlier records found - return empty data
+ # No earlier records found - check for newer records to set pagination accurately
+ has_newer_records = cls._has_newer_records(
+ sensor = sensor,
+ timestamp = pivot_timestamp
+ )
+
return EntitySensorHistoryData(
- sensor_responses=[],
- current_sensor_response=None,
- timeline_groups=[],
- pagination_metadata={'has_older_records': False, 'has_newer_records': True},
- prev_sensor_response=None,
- next_sensor_response=None
+ sensor_responses = [],
+ current_sensor_response = None,
+ timeline_groups = [],
+ pagination_metadata = {'has_older_records': False, 'has_newer_records': has_newer_records},
+ prev_sensor_response = None,
+ next_sensor_response = None,
+ window_start_timestamp = None,
+ window_end_timestamp = pivot_timestamp if has_newer_records else None,
)
# Convert to SensorResponse objects
@@ -396,7 +443,7 @@ class VideoStreamBrowsingHelper:
current_sensor_response = sensor_responses[0] if sensor_responses else None
# Group sensor responses by time period
- timeline_groups = cls.group_responses_by_time(sensor_responses)
+ timeline_groups = cls.group_responses_by_time(sensor_responses, user_timezone)
# Calculate pagination metadata
timestamps = [record.response_datetime for record in history_records]
@@ -404,17 +451,15 @@ class VideoStreamBrowsingHelper:
window_end = max(timestamps)
# Check for more records beyond this window
- has_older_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__lt=window_start
- ).exists()
+ has_older_records = cls._has_older_records(
+ sensor = sensor,
+ timestamp = window_start
+ )
- has_newer_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__gt=window_end
- ).exists()
+ has_newer_records = cls._has_newer_records(
+ sensor = sensor,
+ timestamp = window_end
+ )
pagination_metadata = {
'has_older_records': has_older_records,
@@ -441,26 +486,36 @@ class VideoStreamBrowsingHelper:
)
@classmethod
- def build_sensor_history_data_later(cls, sensor: Sensor, pivot_timestamp: int) -> EntitySensorHistoryData:
+ def build_sensor_history_data_later( cls,
+ sensor : Sensor,
+ pivot_timestamp : int,
+ user_timezone : str = None ) -> EntitySensorHistoryData:
"""Build data for pagination to later events."""
pivot_time = timezone.make_aware(datetime.fromtimestamp(pivot_timestamp))
# Get 50 events after the pivot time (ordered chronologically, oldest first)
- history_records = list(SensorHistory.objects.filter(
+ history_records = list( SensorHistory.objects.filter(
sensor=sensor,
has_video_stream=True,
response_datetime__gt=pivot_time
).order_by('response_datetime')[:50])
if not history_records:
- # No later records found - return empty data
+ # No later records found - check for older records to set pagination accurately
+ has_older_records = cls._has_older_records(
+ sensor = sensor,
+ timestamp = pivot_timestamp
+ )
+
return EntitySensorHistoryData(
sensor_responses=[],
current_sensor_response=None,
timeline_groups=[],
- pagination_metadata={'has_older_records': True, 'has_newer_records': False},
+ pagination_metadata={'has_older_records': has_older_records, 'has_newer_records': False},
prev_sensor_response=None,
- next_sensor_response=None
+ next_sensor_response=None,
+ window_start_timestamp = pivot_timestamp if has_older_records else None,
+ window_end_timestamp = None,
)
# Reverse to newest first for display (matching our standard ordering)
@@ -476,7 +531,7 @@ class VideoStreamBrowsingHelper:
current_sensor_response = sensor_responses[0] if sensor_responses else None
# Group sensor responses by time period
- timeline_groups = cls.group_responses_by_time(sensor_responses)
+ timeline_groups = cls.group_responses_by_time(sensor_responses, user_timezone)
# Calculate pagination metadata
timestamps = [record.response_datetime for record in history_records]
@@ -484,17 +539,15 @@ class VideoStreamBrowsingHelper:
window_end = max(timestamps)
# Check for more records beyond this window
- has_older_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__lt=window_start
- ).exists()
+ has_older_records = cls._has_older_records(
+ sensor = sensor,
+ timestamp = window_start
+ )
- has_newer_records = SensorHistory.objects.filter(
- sensor=sensor,
- has_video_stream=True,
- response_datetime__gt=window_end
- ).exists()
+ has_newer_records = cls._has_newer_records(
+ sensor = sensor,
+ timestamp = window_end
+ )
pagination_metadata = {
'has_older_records': has_older_records,
@@ -522,19 +575,25 @@ class VideoStreamBrowsingHelper:
@classmethod
def build_sensor_history_data(
- cls, sensor: Sensor, sensor_history_id: int = None,
- preserve_window_start: datetime = None, preserve_window_end: datetime = None
- ) -> EntitySensorHistoryData:
+ cls,
+ sensor : Sensor,
+ sensor_history_id : int = None,
+ preserve_window_start : datetime = None,
+ preserve_window_end : datetime = None,
+ user_timezone : str = None ) -> EntitySensorHistoryData:
"""Legacy method - delegates to window preservation method."""
return cls.build_sensor_history_data_with_window(
- sensor, sensor_history_id, preserve_window_start, preserve_window_end
+ sensor, sensor_history_id, preserve_window_start, preserve_window_end, user_timezone
)
@classmethod
def _build_sensor_history_data_internal(
- cls, sensor: Sensor, sensor_history_id: int = None,
- preserve_window_start: datetime = None, preserve_window_end: datetime = None
- ) -> EntitySensorHistoryData:
+ cls,
+ sensor : Sensor,
+ sensor_history_id : int = None,
+ preserve_window_start : datetime = None,
+ preserve_window_end : datetime = None,
+ user_timezone : str = None ) -> EntitySensorHistoryData:
"""
Build all data needed for the sensor history view.
High-level method that encapsulates the business logic.
@@ -544,6 +603,7 @@ class VideoStreamBrowsingHelper:
sensor_history_id: Optional specific record ID to display
preserve_window_start: Start timestamp for timeline preservation
preserve_window_end: End timestamp for timeline preservation
+ user_timezone: User's timezone string for display grouping
Returns:
EntitySensorHistoryData containing all view data
@@ -603,7 +663,7 @@ class VideoStreamBrowsingHelper:
current_sensor_response = sensor_responses[0] if sensor_responses else None
# Group sensor responses by time period
- timeline_groups = cls.group_responses_by_time(sensor_responses)
+ timeline_groups = cls.group_responses_by_time(sensor_responses, user_timezone)
# Find previous and next responses for navigation
current_history_id = sensor_history_id if sensor_history_id else None
@@ -627,3 +687,154 @@ class VideoStreamBrowsingHelper:
window_start_timestamp=pagination_metadata.get('window_start_timestamp'),
window_end_timestamp=pagination_metadata.get('window_end_timestamp'),
)
+
+ @classmethod
+ def _has_older_records(cls, sensor: Sensor, timestamp: int) -> bool:
+ """Check if sensor has records earlier than the given timestamp."""
+ if isinstance( timestamp, datetime):
+ pivot_datetime = timestamp
+ else:
+ pivot_datetime = timezone.make_aware(datetime.fromtimestamp(timestamp))
+ return SensorHistory.objects.filter(
+ sensor = sensor,
+ has_video_stream = True,
+ response_datetime__lt = pivot_datetime
+ ).exists()
+
+ @classmethod
+ def _has_newer_records(cls, sensor: Sensor, timestamp: int) -> bool:
+ """Check if sensor has records later than the given timestamp."""
+ if isinstance( timestamp, datetime):
+ pivot_datetime = timestamp
+ else:
+ pivot_datetime = timezone.make_aware(datetime.fromtimestamp(timestamp))
+ return SensorHistory.objects.filter(
+ sensor = sensor,
+ has_video_stream = True,
+ response_datetime__gt = pivot_datetime
+ ).exists()
+
+ @classmethod
+ def get_video_dispatch_result( cls,
+ entity : Entity,
+ referrer_url : str ) -> VideoDispatchResult:
+ """
+ Determine the appropriate video dispatch based on referrer URL context.
+
+ Logic:
+ - If referrer has sensor_history_id with window bounds, use earlier view with start time
+ - If referrer has sensor_history_id without bounds, use default view
+ - If referrer is "earlier" view, preserve it with same timestamp
+ - If referrer is "later" view, preserve it with same timestamp
+ - Otherwise use default (latest events)
+
+ Returns:
+ VideoDispatchResult with dispatch type and necessary parameters
+ """
+ video_sensor = cls.find_video_sensor_for_entity(entity)
+ if not video_sensor:
+ raise BadRequest( f'No video sensor found for entity {entity.id}.' )
+
+ # Extract timeline context from referrer URL if available
+ try:
+ parsed_url = urlparse(referrer_url)
+ path = parsed_url.path
+
+ resolved = resolve(path)
+ url_name = resolved.url_name
+
+ # Case 1: Referrer has sensor_history_id with window bounds
+ # Use EntityVideoSensorHistoryEarlierView to preserve timeline
+ 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)
+
+ # Try earlier records first (preserve original intent)
+ if cls._has_older_records(video_sensor, timestamp):
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_EARLIER,
+ sensor = video_sensor,
+ timestamp = timestamp,
+ )
+ # Fallback: show later records (closest in time)
+ else:
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_LATER,
+ sensor = video_sensor,
+ timestamp = timestamp,
+ )
+
+ # Case 2: Referrer has sensor_history_id without window bounds
+ # Use default view (it will center around most recent)
+ elif url_name == 'console_entity_video_sensor_history_detail':
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_DEFAULT,
+ sensor = video_sensor
+ )
+
+ # Case 3: Referrer is "earlier" pagination view
+ # Preserve the same earlier view with same timestamp
+ elif 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)
+
+ # Try to preserve earlier view
+ if cls._has_older_records(video_sensor, timestamp):
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_EARLIER,
+ sensor = video_sensor,
+ timestamp = timestamp
+ )
+ # Fallback: show later records (closest in time)
+ else:
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_LATER,
+ sensor = video_sensor,
+ timestamp = timestamp
+ )
+
+ # Case 4: Referrer is "later" pagination view
+ # Preserve the same later view with same timestamp
+ elif 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)
+
+ # Try to preserve later view
+ if cls._has_newer_records(video_sensor, timestamp):
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_LATER,
+ sensor = video_sensor,
+ timestamp = timestamp
+ )
+ # Fallback: show earlier records (closest in time)
+ else:
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_EARLIER,
+ sensor = video_sensor,
+ timestamp = timestamp
+ )
+
+ # Case 5: Basic sensor history view (no specific event)
+ # Use default view
+ elif url_name == 'console_entity_video_sensor_history':
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_DEFAULT,
+ sensor = video_sensor
+ )
+
+ except (Resolver404, ValueError, KeyError):
+ # No timeline context available - use default behavior
+ pass
+
+ # Default fallback - use most recent history
+ return VideoDispatchResult(
+ dispatch_type = VideoDispatchType.HISTORY_DEFAULT,
+ sensor = video_sensor
+ )
diff --git a/src/hi/apps/console/views.py b/src/hi/apps/console/views.py
index b3b3dcb3..e3079651 100644
--- a/src/hi/apps/console/views.py
+++ b/src/hi/apps/console/views.py
@@ -1,11 +1,12 @@
from django.core.exceptions import BadRequest
-from django.http import Http404
+from django.http import Http404, HttpRequest
from django.views.generic import View
from datetime import datetime
from django.utils import timezone
-from hi.apps.entity.models import Entity
+from hi.apps.entity.view_mixins import EntityViewMixin
from hi.apps.sense.models import Sensor
+from hi.apps.sense.view_mixins import SenseViewMixin
from hi.integrations.integration_manager import IntegrationManager
from hi.enums import ViewType
@@ -14,37 +15,67 @@ from hi.hi_grid_view import HiGridView
from .constants import ConsoleConstants
from .console_helper import ConsoleSettingsHelper
+from .enums import VideoDispatchType
from .video_stream_browsing_helper import VideoStreamBrowsingHelper
-class EntityVideoStreamView( HiGridView ):
+class EntityVideoStreamDispatchView( View, EntityViewMixin ):
+ """
+ Simple dispatch view for camera sidebar navigation.
+ Routes to existing views based on referrer context.
+ """
+
+ def get( self, request, *args, **kwargs ):
+
+ if not request.view_parameters.view_type.is_video_browse:
+ return EntityVideoStreamView().get( request, **kwargs )
+
+ entity = self.get_entity( request, *args, **kwargs )
+
+ # Get video dispatch decision based on referrer context
+ referrer_url = request.META.get('HTTP_REFERER', '')
+ dispatch_result = VideoStreamBrowsingHelper.get_video_dispatch_result(
+ entity = entity,
+ referrer_url = referrer_url,
+ )
+
+ # Update kwargs with the dispatch parameters
+ kwargs.update( dispatch_result.get_view_kwargs() )
+
+ # Route to appropriate view based on dispatch type
+ if dispatch_result.dispatch_type == VideoDispatchType.LIVE_STREAM:
+ return EntityVideoStreamView().get( request, **kwargs )
+ elif dispatch_result.dispatch_type == VideoDispatchType.HISTORY_EARLIER:
+ return EntityVideoSensorHistoryEarlierView().get( request, **kwargs )
+ elif dispatch_result.dispatch_type == VideoDispatchType.HISTORY_LATER:
+ return EntityVideoSensorHistoryLaterView().get( request, **kwargs )
+ else: # VideoDispatchType.HISTORY_DEFAULT
+ return EntityVideoSensorHistoryView().get( request, **kwargs )
+
+
+class EntityVideoStreamView( HiGridView, EntityViewMixin ):
"""View for displaying entity-based video streams."""
def get_main_template_name( self ) -> str:
return 'console/panes/entity_video_pane.html'
def get_main_template_context( self, request, *args, **kwargs ):
- entity_id = kwargs.get('entity_id')
- try:
- entity = Entity.objects.get( id = entity_id )
- except Entity.DoesNotExist:
- raise Http404('Entity not found.')
+ 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
+ # 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.' )
- # Get the video stream using the integration gateway
- if not entity.has_video_stream:
- raise BadRequest( 'Video stream is not currently available.' )
-
# Find the first sensor with video capability for history browsing
video_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
request.view_parameters.to_session( request )
@@ -53,8 +84,26 @@ class EntityVideoStreamView( HiGridView ):
'video_sensor': video_sensor, # May be None if no video sensors
}
+
+class EntityVideoHistoryView( View, EntityViewMixin ):
+ """For sensor history for an entity's default sensor (with video).
+ Note: An entity having a video stream is independent of whether
+ it may have sensors with video streams.
+ """
-class BaseEntityVideoSensorHistoryView( HiGridView ):
+ def get( self, request, *args, **kwargs ):
+ entity = self.get_entity( request, *args, **kwargs )
+ sensor = VideoStreamBrowsingHelper.find_video_sensor_for_entity(
+ entity = entity,
+ )
+ if not sensor:
+ raise Http404( request )
+
+ kwargs.update({ 'sensor_id': sensor.id })
+ return EntityVideoSensorHistoryView().get( request = request, *args, **kwargs )
+
+
+class BaseEntityVideoSensorHistoryView( HiGridView, EntityViewMixin, SenseViewMixin ):
"""Base view for browsing sensor history records with video streams."""
def get_main_template_name( self ) -> str:
@@ -62,29 +111,22 @@ class BaseEntityVideoSensorHistoryView( HiGridView ):
def get_main_template_context( self, request, *args, **kwargs ):
"""Common context building logic shared by all sensor history views."""
- entity_id = kwargs.get('entity_id')
- sensor_id = kwargs.get('sensor_id')
-
- # Get the entity
- try:
- entity = Entity.objects.get( id = entity_id )
- except Entity.DoesNotExist:
- raise Http404('Entity not found.')
-
- # Get the sensor
- try:
- sensor = Sensor.objects.get( id = sensor_id, entity_state__entity = entity )
- except Sensor.DoesNotExist:
- raise Http404('Sensor not found for this entity.')
+
+ entity = self.get_entity( request, *args, **kwargs )
+ sensor = self.get_sensor( request, *args, **kwargs )
# Check if sensor provides video stream capability
if not sensor.provides_video_stream:
raise BadRequest( 'Sensor does not provide video stream capability.' )
-
+
# Build sensor history data using subclass-specific method
- sensor_history_data = self.get_sensor_history_data(sensor, request, **kwargs)
+ sensor_history_data = self.get_sensor_history_data(
+ sensor = sensor,
+ request = request,
+ **kwargs,
+ )
- request.view_parameters.view_type = ViewType.ENTITY_VIDEO_STREAM
+ request.view_parameters.view_type = ViewType.SENSOR_VIDEO_BROWSE
request.view_parameters.to_session( request )
return {
@@ -93,7 +135,7 @@ class BaseEntityVideoSensorHistoryView( HiGridView ):
'sensor_history_data': sensor_history_data,
}
- def get_sensor_history_data(self, sensor, request, **kwargs):
+ def get_sensor_history_data( self, sensor : Sensor, request : HttpRequest, **kwargs ):
"""Override in subclasses to provide specific sensor history data building logic."""
raise NotImplementedError("Subclasses must implement get_sensor_history_data")
@@ -101,7 +143,7 @@ class BaseEntityVideoSensorHistoryView( HiGridView ):
class EntityVideoSensorHistoryView( BaseEntityVideoSensorHistoryView ):
"""Default view for browsing sensor history records with video streams."""
- def get_sensor_history_data(self, sensor, request, **kwargs):
+ def get_sensor_history_data(self, sensor : Sensor, request : HttpRequest, **kwargs):
"""Get default sensor history data or handle window context."""
sensor_history_id = kwargs.get('sensor_history_id')
window_start = kwargs.get('window_start')
@@ -115,31 +157,41 @@ class EntityVideoSensorHistoryView( BaseEntityVideoSensorHistoryView ):
preserve_window_end = timezone.make_aware(
datetime.fromtimestamp(int(window_end))
)
+ # Get user timezone for proper timeline grouping
+ user_timezone = ConsoleSettingsHelper().get_tz_name()
+
return VideoStreamBrowsingHelper.build_sensor_history_data_with_window(
- sensor, sensor_history_id, preserve_window_start, preserve_window_end
+ sensor, sensor_history_id, preserve_window_start, preserve_window_end, user_timezone
)
except (ValueError, OSError):
# Invalid timestamp format - fall back to default
pass
- # Default behavior
+ # Get user timezone for proper timeline grouping
+ user_timezone = ConsoleSettingsHelper().get_tz_name()
+
return VideoStreamBrowsingHelper.build_sensor_history_data_default(
- sensor, sensor_history_id
+ sensor = sensor,
+ sensor_history_id = sensor_history_id,
+ user_timezone = user_timezone
)
class EntityVideoSensorHistoryEarlierView( BaseEntityVideoSensorHistoryView ):
"""View for browsing earlier sensor history records (pagination)."""
- def get_sensor_history_data(self, sensor, request, **kwargs):
+ def get_sensor_history_data(self, sensor : Sensor, request : HttpRequest, **kwargs):
"""Get earlier sensor history data based on timestamp."""
timestamp = kwargs.get('timestamp')
if not timestamp:
raise BadRequest('Timestamp parameter is required for earlier pagination.')
+ # Get user timezone for proper timeline grouping
+ user_timezone = ConsoleSettingsHelper().get_tz_name()
+
try:
return VideoStreamBrowsingHelper.build_sensor_history_data_earlier(
- sensor, int(timestamp)
+ sensor, int(timestamp), user_timezone
)
except (ValueError, TypeError):
raise BadRequest('Invalid timestamp format.')
@@ -148,15 +200,18 @@ class EntityVideoSensorHistoryEarlierView( BaseEntityVideoSensorHistoryView ):
class EntityVideoSensorHistoryLaterView( BaseEntityVideoSensorHistoryView ):
"""View for browsing later sensor history records (pagination)."""
- def get_sensor_history_data(self, sensor, request, **kwargs):
+ def get_sensor_history_data(self, sensor : Sensor, request : HttpRequest, **kwargs):
"""Get later sensor history data based on timestamp."""
timestamp = kwargs.get('timestamp')
if not timestamp:
raise BadRequest('Timestamp parameter is required for later pagination.')
+ # Get user timezone for proper timeline grouping
+ user_timezone = ConsoleSettingsHelper().get_tz_name()
+
try:
return VideoStreamBrowsingHelper.build_sensor_history_data_later(
- sensor, int(timestamp)
+ sensor, int(timestamp), user_timezone
)
except (ValueError, TypeError):
raise BadRequest('Invalid timestamp format.')
diff --git a/src/hi/apps/entity/templates/entity/modals/entity_status.html b/src/hi/apps/entity/templates/entity/modals/entity_status.html
index b3165cbc..4e053311 100644
--- a/src/hi/apps/entity/templates/entity/modals/entity_status.html
+++ b/src/hi/apps/entity/templates/entity/modals/entity_status.html
@@ -6,7 +6,29 @@
{% endblock %}
{% block body %}
-{% if entity_for_video %}
+<div class="d-flex justify-content-between mb-2">
+ <div class="display-only-svg-icon pr-2">
+ {% if display_only_svg_icon_item %}
+ {% include "entity/panes/entity_display_only_svg_icon.html" with svg_icon_item=display_only_svg_icon_item %}
+ {% endif %}
+ </div>
+ {% if entity_for_video.has_video_stream %}
+ <div>
+ <a href="{% url 'console_entity_video_stream_dispatch' entity_id=entity_for_video.id %}"
+ data-entity-id="{{ entity_for_video.id }}"
+ data-async="#main-content"
+ class="btn btn-sm btn-outline-primary"
+ role="button">
+ View Stream
+ </a>
+ </div>
+ {% endif %}
+ <div>
+ <div class="h5 text-muted">{{ entity.entity_type.label }}</div>
+ </div>
+</div>
+
+{% if entity_for_video.has_video_stream %}
{% include "console/panes/entity_video_stream.html" with entity=entity_for_video %}
{% endif %}
diff --git a/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html b/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html
index 862fc378..14774794 100644
--- a/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html
+++ b/src/hi/apps/entity/templates/entity/panes/entity_state_status_card.html
@@ -31,7 +31,7 @@
<small>
<a href="{% url 'console_entity_video_sensor_history' entity_id=sensor_response.sensor.entity_state.entity.id sensor_id=sensor_response.sensor.id %}"
data-async="true" class="text-muted">
- {% icon "video" size="sm" css_class="hi-icon-left" %}Browse Video
+ {% icon "video" size="sm" css_class="hi-icon-left" %}Browse History
</a>
</small>
{% endif %}
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index 3d2c6b75..733835dc 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -30,13 +30,13 @@ class EntityStatusView( HiModalView, EntityViewMixin ):
request : HttpRequest,
*args : Any,
**kwargs: Any ) -> HttpResponse:
- entity: Entity = self.get_entity( request, *args, **kwargs )
+ entity = self.get_entity( request, *args, **kwargs )
entity_status_data = StatusDisplayManager().get_entity_status_data( entity = entity )
if not entity_status_data.entity_state_status_data_list:
return EntityEditView().get( request, *args, **kwargs )
- context: Dict[str, Any] = entity_status_data.to_template_context()
+ context = entity_status_data.to_template_context()
return self.modal_response( request, context )
diff --git a/src/hi/apps/monitor/status_display_manager.py b/src/hi/apps/monitor/status_display_manager.py
index 6a19cdba..1f25adad 100644
--- a/src/hi/apps/monitor/status_display_manager.py
+++ b/src/hi/apps/monitor/status_display_manager.py
@@ -7,6 +7,7 @@ from hi.apps.entity.enums import EntityStateType
from hi.apps.entity.models import Entity, EntityState
from hi.apps.location.enums import LocationViewType
from hi.apps.location.models import LocationView
+from hi.apps.location.svg_item_factory import SvgItemFactory
from hi.apps.sense.models import Sensor
from hi.apps.sense.sensor_response_manager import SensorResponseMixin
from hi.apps.sense.transient_models import SensorResponse
@@ -112,10 +113,16 @@ class StatusDisplayManager( Singleton, SensorResponseMixin ):
entity_state_to_status_data = self._get_entity_state_to_entity_state_status_data(
entity_states = entity_state_set,
)
+
+ svg_item_factory = SvgItemFactory()
+ svg_icon_item = svg_item_factory.get_display_only_svg_icon_item(
+ entity = entity,
+ )
return EntityStatusData(
entity = entity,
entity_state_status_data_list = list( entity_state_to_status_data.values() ),
entity_for_video = entity_for_video,
+ display_only_svg_icon_item = svg_icon_item,
)
def get_entity_status_data_list(
diff --git a/src/hi/apps/monitor/transient_models.py b/src/hi/apps/monitor/transient_models.py
index 9b2d57d6..ebbcd58b 100644
--- a/src/hi/apps/monitor/transient_models.py
+++ b/src/hi/apps/monitor/transient_models.py
@@ -37,6 +37,7 @@ class EntityStatusData:
'entity': self.entity,
'entity_state_status_data_list': self.entity_state_status_data_list,
'entity_for_video': self.entity_for_video,
+ 'display_only_svg_icon_item': self.display_only_svg_icon_item,
}
return context
diff --git a/src/hi/enums.py b/src/hi/enums.py
index b65a1ffe..346099d4 100644
--- a/src/hi/enums.py
+++ b/src/hi/enums.py
@@ -11,6 +11,7 @@ class ViewType(LabeledEnum):
COLLECTION = ('Collection', '' )
CONFIGURATION = ('Configuration', '' )
ENTITY_VIDEO_STREAM = ('Entity Video Stream', '' )
+ SENSOR_VIDEO_BROWSE = ('Sensor Video Browse', '' )
@property
def is_location_view(self):
@@ -28,6 +29,10 @@ class ViewType(LabeledEnum):
def is_video_stream(self):
return bool( self == ViewType.ENTITY_VIDEO_STREAM )
+ @property
+ def is_video_browse(self):
+ return bool( self == ViewType.SENSOR_VIDEO_BROWSE )
+
@property
def allows_edit_mode(self):
return bool( self in [ ViewType.LOCATION_VIEW,
diff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.js
index 0588cbe8..11a82639 100644
--- a/src/hi/static/js/video-timeline.js
+++ b/src/hi/static/js/video-timeline.js
@@ -239,6 +239,7 @@
VideoConnectionManager.cleanup();
});
+
// Expose for potential external use and debugging
window.VideoTimelineScrollManager = VideoTimelineScrollManager;
window.VideoConnectionManager = VideoConnectionManager;