Home Information - Your home, your data, organized.
Python
Implement dual-mode camera interface with live stream and event browser (#112)
Tony Ccc4c03329253
diff --git a/src/hi/apps/alert/templates/alert/tests/ui/home.html b/src/hi/apps/alert/templates/alert/tests/ui/home.htmlindex 73b7e809..4be14201 100644--- a/src/hi/apps/alert/templates/alert/tests/ui/home.html+++ b/src/hi/apps/alert/templates/alert/tests/ui/home.html@@ -36,7 +36,7 @@</li><li><a href="{% url 'alert_tests_ui_alert_details' alert_type='event_based' %}" data-async="modal">- Event-Based Alert (door sensor)+ Trigger-Based Alert (door sensor)</a></li><li>diff --git a/src/hi/apps/config/enums.py b/src/hi/apps/config/enums.pyindex 32769993..19c1170d 100644--- a/src/hi/apps/config/enums.py+++ b/src/hi/apps/config/enums.py@@ -17,7 +17,7 @@ class ConfigPageType(LabeledEnum):returnSETTINGS = ('Settings' , '' , 'config_settings' )- EVENTS = ('Events' , '' , 'event_definitions' )+ EVENTS = ('Triggers' , '' , 'event_definitions' )INTEGRATIONS = ('Integrations' , '' , 'integrations_home' )def default(self):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 5c83c665..d36fd97e 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,7 +1,36 @@{% load video_tags %}-<div class="h6">{{ entity.name }}</div>-{% if entity.has_video_stream %}-{% include "console/panes/entity_video_stream.html" with entity=entity %}-{% else %}-<div class="text-muted">Video stream not available.</div>-{% endif %}+<div class="entity-video-pane">+ <!-- Unified Tab-Style Header -->+ <div class="video-interface-header current-stream 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">+ <span class="video-nav-tab active" role="tab">+ <i class="fas fa-video mr-1"></i>Current Stream+ </span>+ {% if video_sensor %}+ <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">+ <i class="fas fa-history mr-1"></i>Event History+ </a>+ {% else %}+ <span class="video-nav-tab disabled" title="No video sensors available" role="tab">+ <i class="fas fa-history mr-1"></i>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 %}+ {% else %}+ <div class="text-muted">Video stream 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.htmlnew file mode 100644index 00000000..b874dc2d--- /dev/null+++ b/src/hi/apps/console/templates/console/panes/entity_video_sensor_history.html@@ -0,0 +1,173 @@+{% load video_tags %}+{% load tz %}++{% timezone USER_TIMEZONE %}+<div class="entity-video-sensor-history">+ <!-- Unified Tab-Style Header -->+ <div class="video-interface-header event-history 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">+ <a href="{% url 'console_entity_video_stream' entity.id %}"+ class="video-nav-tab"+ data-async="#main-content"+ aria-label="Return to live camera stream"+ role="tab">+ <i class="fas fa-video mr-1"></i>Current Stream+ </a>+ <span class="video-nav-tab active" role="tab">+ <i class="fas fa-history mr-1"></i>Event History+ </span>+ </div>+ </div>+ </div>++ <!-- Main content area split into timeline and video -->+ <div class="row">+ <!-- Timeline sidebar -->+ <div class="col-md-3">+ <nav class="timeline-container preserve-scroll-bar" id="event-timeline"+ role="navigation"+ aria-label="Event timeline navigation">+ <h6 id="timeline-heading">Event Timeline</h6>++ <!-- Pagination: Load Later Events -->+ {% if sensor_history_data.pagination_metadata.has_newer_records %}+ <div class="timeline-pagination-top mb-2">+ <a href="{% url 'console_entity_video_sensor_history_later' entity.id sensor.id sensor_history_data.window_end_timestamp|date:'U' %}"+ class="btn btn-sm btn-outline-primary w-100"+ data-async="#main-content">+ Later ↑+ </a>+ </div>+ {% endif %}++ {% for group in sensor_history_data.timeline_groups %}+ <div class="timeline-group mb-3">+ <div class="timeline-group-label font-weight-bold">+ {{ group.label }}+ </div>++ <div class="timeline-items" role="list">+ {% for response in group.items %}+ <div class="timeline-item {% if response.sensor_history_id == sensor_history_data.current_sensor_response.sensor_history_id %}active{% endif %}"+ role="listitem">+ {% if sensor_history_data.window_start_timestamp and sensor_history_data.window_end_timestamp %}+ <a href="{% url 'console_entity_video_sensor_history_detail_with_context' entity.id sensor.id response.sensor_history_id sensor_history_data.window_start_timestamp|date:'U' sensor_history_data.window_end_timestamp|date:'U' %}"+ {% else %}+ <a href="{% url 'console_entity_video_sensor_history_detail' entity.id sensor.id response.sensor_history_id %}"+ {% endif %}+ data-async="#main-content"+ class="text-decoration-none"+ aria-label="View event from {{ response.timestamp|localtime|date:'g:i A' }}{% if response.sensor_history_id == sensor_history_data.current_sensor_response.sensor_history_id %} - Currently viewing{% endif %}">+ <div>+ <span class="time">{{ response.timestamp|localtime|date:"g:i A" }}</span>+ {% if response.sensor_history_id == sensor_history_data.current_sensor_response.sensor_history_id %}+ <small class="text-muted d-block" aria-current="page">→ Currently viewing</small>+ {% endif %}+ </div>+ </a>+ </div>+ {% endfor %}+ </div>+ </div>+ {% empty %}+ <p class="text-muted">No events available</p>+ {% endfor %}++ <!-- Pagination: Load Earlier Events -->+ {% if sensor_history_data.pagination_metadata.has_older_records %}+ <div class="timeline-pagination-bottom mt-2">+ <a href="{% url 'console_entity_video_sensor_history_earlier' entity.id sensor.id sensor_history_data.window_start_timestamp|date:'U' %}"+ class="btn btn-sm btn-outline-primary w-100"+ data-async="#main-content"+ onclick="sessionStorage.setItem('scrollTimelineToTop', 'true');">+ Earlier ↓+ </a>+ </div>+ {% endif %}+ </nav>+ </div>++ <!-- Video and details area -->+ <div class="col-md-9" role="main" aria-labelledby="event-history-title">+ {% if sensor_history_data.current_sensor_response %}+ <div class="video-detail-container">+ <!-- Event header -->+ <div class="response-header mb-3">+ <h6>{{ sensor.entity_state.entity_state_type.label }} Event</h6>+ <div class="text-muted">+ {{ sensor_history_data.current_sensor_response.timestamp|localtime|date:"F j, Y g:i A" }}+ </div>+ </div>++ <!-- Video display area -->+ <div class="video-container mb-3" role="img" aria-label="Event video playback">+ {% sensor_response_video_stream sensor_history_data.current_sensor_response as video_url %}+ {% if video_url %}+ <img class="img-fluid" src="{{ video_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\'>📹</div><h6>Video No Longer Available</h6></div></div>'">+ {% else %}+ <!-- Fallback when no video stream 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>+ {% endif %}+ </div>++ <!-- Integration-specific details (collapsible) -->+ {% if sensor_history_data.current_sensor_response.detail_attrs %}+ <div class="response-details-bar">+ <a class="details-expander" data-toggle="collapse" href="#eventDetails"+ role="button" aria-expanded="false" aria-controls="eventDetails">+ <span class="details-label">Integration Details</span>+ <span class="details-chevron">▼</span>+ </a>+ <div class="collapse" id="eventDetails">+ <div class="details-content">+ {% for key, value in sensor_history_data.current_sensor_response.detail_attrs.items %}+ {% if key != "sensor_history_id" %}+ <div class="detail-row">+ <div class="detail-label">{{ key|title|cut:"_" }}:</div>+ <div class="detail-value">{{ value }}</div>+ </div>+ {% endif %}+ {% endfor %}+ </div>+ </div>+ </div>+ {% endif %}++ </div>+ {% else %}+ <div class="alert alert-info">+ No events available for this item.+ </div>+ {% endif %}+ </div>+ </div>+</div>++<script>+// Handle scroll to top for Earlier button+$(document).ready(function() {+ if (sessionStorage.getItem('scrollTimelineToTop') === 'true') {+ // Clear the flag+ sessionStorage.removeItem('scrollTimelineToTop');+ // Scroll the timeline container to top+ $('#event-timeline').scrollTop(0);+ }+});+</script>++{% endtimezone %}diff --git a/src/hi/apps/console/templates/console/panes/hi_grid_side.html b/src/hi/apps/console/templates/console/panes/hi_grid_side.htmlindex 119816aa..77b79cfd 100644--- a/src/hi/apps/console/templates/console/panes/hi_grid_side.html+++ b/src/hi/apps/console/templates/console/panes/hi_grid_side.html@@ -26,7 +26,7 @@<a href="{% url 'event_history' %}"class="btn btn-primary btn-control" role="button"data-async="true" >- EVENT HISTORY+ TRIGGER HISTORY</a></div></div>diff --git a/src/hi/apps/console/tests/test_dataclass_functionality.py b/src/hi/apps/console/tests/test_dataclass_functionality.pynew file mode 100644index 00000000..3f8fa486--- /dev/null+++ b/src/hi/apps/console/tests/test_dataclass_functionality.py@@ -0,0 +1,395 @@+import logging+from datetime import datetime+from unittest.mock import Mock++from django.test import TestCase+from django.utils import timezone++from hi.apps.console.transient_models import EntitySensorHistoryData+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKey++logging.disable(logging.CRITICAL)+++class TestEntitySensorHistoryData(TestCase):+ """Test EntitySensorHistoryData dataclass functionality."""++ def setUp(self):+ # Create mock sensor responses for testing+ self.mock_sensor = Mock()+ self.mock_sensor.id = 123++ # Create sample sensor responses+ base_time = timezone.now()+ self.sensor_responses = []++ for i in range(3):+ integration_key = IntegrationKey(+ integration_id='test_integration',+ integration_name=f'test_response_{i}'+ )++ response = SensorResponse(+ integration_key=integration_key,+ value=f'value_{i}',+ timestamp=base_time - timezone.timedelta(hours=i),+ sensor=self.mock_sensor,+ detail_attrs={+ 'duration_seconds': str(60 + i * 30)+ },+ has_video_stream=True,+ sensor_history_id=1000 + i # Set as direct property+ )+ self.sensor_responses.append(response)++ # Create sample timeline groups+ self.timeline_groups = [+ {+ 'label': 'Today',+ 'date': base_time.date(),+ 'items': self.sensor_responses[:2]+ },+ {+ 'label': 'Yesterday',+ 'date': (base_time - timezone.timedelta(days=1)).date(),+ 'items': self.sensor_responses[2:]+ }+ ]++ # Sample pagination metadata+ self.pagination_metadata = {+ 'has_older_records': True,+ 'has_newer_records': False,+ 'window_center_timestamp': base_time,+ 'window_size': 50,+ 'window_start_timestamp': base_time - timezone.timedelta(hours=2),+ 'window_end_timestamp': base_time+ }++ def test_dataclass_timeline_group_navigation_logic(self):+ """Test business logic for timeline navigation in template rendering."""+ # Create timeline groups with different date patterns+ base_time = timezone.now()+ today_responses = self.sensor_responses[:2]+ yesterday_responses = self.sensor_responses[2:]++ timeline_groups = [+ {+ 'label': 'Today',+ 'date': base_time.date(),+ 'items': today_responses+ },+ {+ 'label': 'Yesterday',+ 'date': (base_time - timezone.timedelta(days=1)).date(),+ 'items': yesterday_responses+ }+ ]++ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=self.sensor_responses[0],+ timeline_groups=timeline_groups,+ pagination_metadata=self.pagination_metadata,+ prev_sensor_response=self.sensor_responses[1],+ next_sensor_response=None+ )++ # Test business logic for timeline navigation+ # Verify navigation relationships work correctly+ current_response = data.current_sensor_response+ prev_response = data.prev_sensor_response++ # Current should be newer than previous (business rule)+ self.assertGreater(current_response.timestamp, prev_response.timestamp)++ # Test timeline group structure for template rendering+ self.assertEqual(len(data.timeline_groups), 2)++ # Verify today's group comes first (chronological ordering)+ today_group = data.timeline_groups[0]+ yesterday_group = data.timeline_groups[1]++ self.assertEqual(today_group['label'], 'Today')+ self.assertEqual(len(today_group['items']), 2)+ self.assertEqual(yesterday_group['label'], 'Yesterday')+ self.assertEqual(len(yesterday_group['items']), 1)++ # Test that items within groups maintain chronological order+ today_items = today_group['items']+ if len(today_items) > 1:+ self.assertGreaterEqual(today_items[0].timestamp, today_items[1].timestamp)++ def test_dataclass_handles_empty_and_edge_case_states(self):+ """Test dataclass behavior in edge cases and empty states."""+ # Test empty timeline state (no sensor history available)+ empty_data = EntitySensorHistoryData(+ sensor_responses=[],+ current_sensor_response=None,+ timeline_groups=[],+ pagination_metadata={'has_older_records': False, 'has_newer_records': False},+ prev_sensor_response=None,+ next_sensor_response=None+ )++ # Template should handle empty state gracefully+ self.assertEqual(len(empty_data.sensor_responses), 0)+ self.assertEqual(len(empty_data.timeline_groups), 0)+ self.assertIsNone(empty_data.current_sensor_response)++ # Test single record state (common for new sensors)+ single_record_data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses[:1],+ current_sensor_response=self.sensor_responses[0],+ timeline_groups=[{+ 'label': 'Today',+ 'date': timezone.now().date(),+ 'items': self.sensor_responses[:1]+ }],+ pagination_metadata={'has_older_records': False, 'has_newer_records': False},+ prev_sensor_response=None,+ next_sensor_response=None+ )++ # Verify single record navigation logic+ self.assertEqual(len(single_record_data.sensor_responses), 1)+ self.assertIsNotNone(single_record_data.current_sensor_response)+ self.assertIsNone(single_record_data.prev_sensor_response)+ self.assertIsNone(single_record_data.next_sensor_response)++ # Template pagination buttons should be disabled+ pagination = single_record_data.pagination_metadata+ self.assertFalse(pagination['has_older_records'])+ self.assertFalse(pagination['has_newer_records'])++ def test_dataclass_supports_none_values_for_optional_fields(self):+ """Test that dataclass properly handles None values for optional fields."""+ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=None, # Can be None if no records+ timeline_groups=[], # Can be empty+ pagination_metadata=self.pagination_metadata,+ prev_sensor_response=None,+ next_sensor_response=None,+ window_start_timestamp=None,+ window_end_timestamp=None+ )++ # Should not raise any errors+ self.assertIsNone(data.current_sensor_response)+ self.assertEqual(data.timeline_groups, [])+ self.assertIsNone(data.prev_sensor_response)+ self.assertIsNone(data.next_sensor_response)+ self.assertIsNone(data.window_start_timestamp)+ self.assertIsNone(data.window_end_timestamp)++ def test_dataclass_fields_are_accessible(self):+ """Test that all dataclass fields are properly accessible."""+ window_start = timezone.now() - timezone.timedelta(hours=1)+ window_end = timezone.now()++ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=self.sensor_responses[1],+ timeline_groups=self.timeline_groups,+ pagination_metadata=self.pagination_metadata,+ prev_sensor_response=self.sensor_responses[2],+ next_sensor_response=self.sensor_responses[0],+ window_start_timestamp=window_start,+ window_end_timestamp=window_end+ )++ # Test field access+ self.assertIsInstance(data.sensor_responses, list)+ self.assertIsInstance(data.current_sensor_response, SensorResponse)+ self.assertIsInstance(data.timeline_groups, list)+ self.assertIsInstance(data.pagination_metadata, dict)+ self.assertIsInstance(data.prev_sensor_response, SensorResponse)+ self.assertIsInstance(data.next_sensor_response, SensorResponse)+ self.assertIsInstance(data.window_start_timestamp, datetime)+ self.assertIsInstance(data.window_end_timestamp, datetime)++ def test_dataclass_supports_timezone_aware_datetimes(self):+ """Test that dataclass properly handles timezone-aware datetime objects."""+ # Create timezone-aware timestamps+ window_start = timezone.now() - timezone.timedelta(hours=2)+ window_end = timezone.now()++ # Ensure they are timezone-aware+ self.assertIsNotNone(window_start.tzinfo)+ self.assertIsNotNone(window_end.tzinfo)++ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=self.sensor_responses[0],+ timeline_groups=self.timeline_groups,+ pagination_metadata=self.pagination_metadata,+ prev_sensor_response=None,+ next_sensor_response=None,+ window_start_timestamp=window_start,+ window_end_timestamp=window_end+ )++ # Verify timezone information is preserved+ self.assertIsNotNone(data.window_start_timestamp.tzinfo)+ self.assertIsNotNone(data.window_end_timestamp.tzinfo)+ self.assertEqual(data.window_start_timestamp, window_start)+ self.assertEqual(data.window_end_timestamp, window_end)++ def test_dataclass_can_be_used_in_template_context(self):+ """Test that dataclass can be properly used in template context patterns."""+ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=self.sensor_responses[0],+ timeline_groups=self.timeline_groups,+ pagination_metadata=self.pagination_metadata,+ prev_sensor_response=self.sensor_responses[1],+ next_sensor_response=None+ )++ # Simulate template context usage patterns+ context = {+ 'entity': Mock(),+ 'sensor': self.mock_sensor,+ 'sensor_history_data': data+ }++ # Verify template-style access works+ sensor_history_data = context['sensor_history_data']+ self.assertEqual(sensor_history_data.sensor_responses, self.sensor_responses)++ # Test accessing nested data (like templates would)+ if sensor_history_data.current_sensor_response:+ current_value = sensor_history_data.current_sensor_response.value+ self.assertEqual(current_value, 'value_0')++ # Test timeline group access+ for group in sensor_history_data.timeline_groups:+ self.assertIn('label', group)+ self.assertIn('items', group)++ def test_dataclass_pagination_state_management(self):+ """Test pagination state preservation across requests."""+ # Test window boundary preservation logic+ window_start = timezone.now() - timezone.timedelta(hours=2)+ window_end = timezone.now() - timezone.timedelta(hours=1)++ pagination_metadata = {+ 'has_older_records': True,+ 'has_newer_records': True,+ 'window_start_timestamp': window_start,+ 'window_end_timestamp': window_end,+ 'window_size': 50+ }++ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=self.sensor_responses[1], # Middle response+ timeline_groups=self.timeline_groups,+ pagination_metadata=pagination_metadata,+ prev_sensor_response=self.sensor_responses[2],+ next_sensor_response=self.sensor_responses[0],+ window_start_timestamp=window_start,+ window_end_timestamp=window_end+ )++ # Test business logic for pagination state+ # Verify window boundaries are preserved for timeline navigation+ self.assertEqual(data.window_start_timestamp, window_start)+ self.assertEqual(data.window_end_timestamp, window_end)++ # Test pagination metadata accuracy for UI state management+ self.assertTrue(data.pagination_metadata['has_older_records'])+ self.assertTrue(data.pagination_metadata['has_newer_records'])++ # Verify navigation state consistency+ # Current response should be between prev and next chronologically+ current = data.current_sensor_response.timestamp+ prev = data.prev_sensor_response.timestamp+ next_time = data.next_sensor_response.timestamp++ self.assertLess(prev, current) # Previous is older+ self.assertGreater(next_time, current) # Next is newer++ # Test window boundary business rules+ # All sensor responses should be within or span the window boundaries+ for response in data.sensor_responses:+ # Responses can extend beyond window for context, but check reasonable bounds+ self.assertIsNotNone(response.timestamp)++ def test_dataclass_integration_with_template_context(self):+ """Test dataclass usage in real template rendering scenarios."""+ # Simulate complex template context scenarios+ window_start = timezone.now() - timezone.timedelta(hours=3)+ window_end = timezone.now()++ # Create data that represents different video sensor history browsing states+ browsing_states = [+ # State 1: Default view (recent records)+ {+ 'current_sensor_response': self.sensor_responses[0],+ 'has_older': True,+ 'has_newer': False+ },+ # State 2: Historical browsing (middle of timeline)+ {+ 'current_sensor_response': self.sensor_responses[1],+ 'has_older': True,+ 'has_newer': True+ },+ # State 3: Oldest records (end of pagination)+ {+ 'current_sensor_response': self.sensor_responses[2],+ 'has_older': False,+ 'has_newer': True+ }+ ]++ for state in browsing_states:+ pagination_metadata = {+ 'has_older_records': state['has_older'],+ 'has_newer_records': state['has_newer'],+ 'window_start_timestamp': window_start,+ 'window_end_timestamp': window_end+ }++ data = EntitySensorHistoryData(+ sensor_responses=self.sensor_responses,+ current_sensor_response=state['current_sensor_response'],+ timeline_groups=self.timeline_groups,+ pagination_metadata=pagination_metadata,+ prev_sensor_response=None,+ next_sensor_response=None+ )++ # Test template context usage patterns+ template_context = {+ 'entity': Mock(),+ 'sensor': self.mock_sensor,+ 'sensor_history_data': data+ }++ # Verify data accessibility patterns used in templates+ history_data = template_context['sensor_history_data']++ # Test accessing sensor_history_id for navigation URLs (critical for templates)+ if history_data.current_sensor_response:+ history_id = history_data.current_sensor_response.sensor_history_id+ self.assertIsNotNone(history_id)++ # Test pagination button logic (template conditional rendering)+ can_go_earlier = history_data.pagination_metadata.get('has_older_records', False)+ can_go_later = history_data.pagination_metadata.get('has_newer_records', False)++ self.assertEqual(can_go_earlier, state['has_older'])+ self.assertEqual(can_go_later, state['has_newer'])++ # Test timeline iteration patterns (template for loops)+ for group in history_data.timeline_groups:+ self.assertIn('label', group) # Template displays group labels+ self.assertIn('items', group) # Template iterates over items+ for item in group['items']:+ # Template accesses sensor history ID for URLs+ self.assertIsNotNone(item.sensor_history_id)+diff --git a/src/hi/apps/console/tests/test_integration_error_handling.py b/src/hi/apps/console/tests/test_integration_error_handling.pynew file mode 100644index 00000000..c12e2f98--- /dev/null+++ b/src/hi/apps/console/tests/test_integration_error_handling.py@@ -0,0 +1,257 @@+import logging+from unittest.mock import Mock, patch+from django.db import IntegrityError, transaction+from django.test import TransactionTestCase+from django.utils import timezone++from hi.apps.console.video_stream_browsing_helper import VideoStreamBrowsingHelper+from hi.apps.console.views import EntityVideoSensorHistoryView+from hi.apps.entity.models import Entity, EntityState+from hi.apps.sense.models import Sensor, SensorHistory++logging.disable(logging.CRITICAL)+++class TestIntegrationErrorHandling(TransactionTestCase):+ """Test integration error scenarios and helper method failure handling."""++ def setUp(self):+ super().setUp()++ # Create test entity with video stream capability+ self.video_entity = Entity.objects.create(+ integration_id='test.camera.error_test',+ integration_name='test_integration',+ name='Error Test Camera',+ entity_type_str='camera',+ has_video_stream=True+ )++ # Create entity state and sensor+ self.entity_state = EntityState.objects.create(+ entity=self.video_entity,+ entity_state_type_str='motion',+ name='Motion Detection'+ )++ self.video_sensor = Sensor.objects.create(+ integration_id='test.sensor.error_test',+ integration_name='test_integration',+ name='Error Test Sensor',+ entity_state=self.entity_state,+ sensor_type_str='binary',+ provides_video_stream=True+ )++ def test_helper_method_database_constraint_violations(self):+ """Test integration error: database constraint violations during helper operations."""+ # Create a sensor history record+ base_record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=timezone.now(),+ has_video_stream=True+ )++ # Test constraint violation scenarios+ with self.assertRaises(IntegrityError):+ with transaction.atomic():+ # Attempt to create duplicate record with same primary key+ SensorHistory.objects.create(+ id=base_record.id, # Duplicate primary key+ sensor=self.video_sensor,+ value='duplicate',+ response_datetime=timezone.now(),+ has_video_stream=True+ )++ def test_helper_method_failure_recovery(self):+ """Test integration error: helper method failures with graceful recovery."""+ # Create some valid data first+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='valid_record',+ response_datetime=timezone.now(),+ has_video_stream=True+ )++ # Test that view handles helper method exceptions gracefully+ with patch.object(VideoStreamBrowsingHelper, 'build_sensor_history_data_default') as mock_helper:+ # Simulate helper method failure+ mock_helper.side_effect = Exception("Simulated helper failure")++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ # View should handle helper failure gracefully+ with self.assertRaises(Exception) as context:+ view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id+ )++ # Verify the exception propagates (expected behavior for debugging)+ self.assertIn("Simulated helper failure", str(context.exception))++ def test_database_connection_error_scenarios(self):+ """Test integration error: database connection issues during queries."""+ # Create test data+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='connection_test',+ response_datetime=timezone.now(),+ has_video_stream=True+ )++ # Test database query failure simulation+ with patch('hi.apps.sense.models.SensorHistory.objects.filter') as mock_filter:+ # Simulate database connection error+ mock_filter.side_effect = Exception("Database connection error")++ # Helper method should propagate database errors+ with self.assertRaises(Exception) as context:+ VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)++ self.assertIn("Database connection error", str(context.exception))++ def test_concurrent_access_scenarios(self):+ """Test integration error: concurrent access to sensor history data."""+ # Create base data+ base_time = timezone.now()+ original_record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='concurrent_test',+ response_datetime=base_time,+ has_video_stream=True+ )++ # Test concurrent modification by modifying record between queries+ # This simulates real-world concurrent access scenarios++ # Modify record after creation+ original_record.value = 'modified_concurrently'+ original_record.save()++ # Helper should handle record modifications gracefully+ result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)++ # Should still return valid data structure+ self.assertIsNotNone(result)+ self.assertIsInstance(result.sensor_responses, list)++ # Should reflect the modified value+ if result.sensor_responses:+ self.assertEqual(result.sensor_responses[0].value, 'modified_concurrently')++ def test_memory_pressure_with_large_datasets(self):+ """Test performance boundary: memory pressure with very large result sets."""+ # Create a moderately large dataset to test memory handling+ base_time = timezone.now()+ batch_size = 1000 # Large enough to test memory handling++ # Create records in batches for efficiency+ records_to_create = []+ for i in range(batch_size):+ records_to_create.append(SensorHistory(+ sensor=self.video_sensor,+ value=f'memory_test_{i}',+ response_datetime=base_time - timezone.timedelta(minutes=i),+ has_video_stream=True,+ details=f'{{"memory_test": {i}}}'+ ))++ SensorHistory.objects.bulk_create(records_to_create)++ # Test that helper methods handle large datasets efficiently+ result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)++ # Should limit results to prevent memory issues+ self.assertIsNotNone(result)+ self.assertLessEqual(len(result.sensor_responses), 100) # Should be limited+ self.assertIsInstance(result.pagination_metadata, dict)++ # Should indicate more records available+ self.assertTrue(result.pagination_metadata.get('has_older_records', False))++ def test_sensor_state_integrity_validation(self):+ """Test integration error: sensor and entity state integrity validation."""+ # Test scenario where entity state gets deleted (cascade deletes sensor)++ # Delete entity state (this will cascade delete the sensor due to FK constraint)+ self.video_sensor.entity_state.delete()++ # Verify sensor was cascade deleted+ with self.assertRaises(Sensor.DoesNotExist):+ Sensor.objects.get(id=self.video_sensor.id)++ # Helper should handle missing sensors gracefully (entity has no sensors now)+ result = VideoStreamBrowsingHelper.find_video_sensor_for_entity(self.video_entity)+ self.assertIsNone(result) # Should return None when no sensors exist++ def test_timezone_aware_edge_cases(self):+ """Test integration error: timezone-aware datetime edge cases."""+ # Test with records spanning DST transitions and timezone boundaries+ base_time = timezone.now()++ # Create records with challenging timezone scenarios+ challenging_times = [+ base_time.replace(hour=0, minute=0, second=0, microsecond=0), # Midnight+ base_time.replace(hour=23, minute=59, second=59, microsecond=999999), # End of day+ ]++ for i, test_time in enumerate(challenging_times):+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'timezone_edge_{i}',+ response_datetime=test_time,+ has_video_stream=True,+ details=f'{{"timezone_test": {i}}}'+ )++ # Helper should handle timezone edge cases correctly+ result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)++ # Should return valid data without timezone conversion errors+ self.assertIsNotNone(result)+ self.assertGreater(len(result.sensor_responses), 0)++ # All timestamps should remain timezone-aware+ for response in result.sensor_responses:+ self.assertIsNotNone(response.timestamp.tzinfo)++ def test_pagination_boundary_conditions(self):+ """Test performance boundary: pagination with extreme boundary conditions."""+ # Test pagination at exact boundaries (e.g., exactly 50 records)+ base_time = timezone.now()++ # Create exactly 50 records (common pagination boundary)+ boundary_records = []+ for i in range(50):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'boundary_record_{i}',+ response_datetime=base_time - timezone.timedelta(minutes=i),+ has_video_stream=True+ )+ boundary_records.append(record)++ # Test pagination at the exact boundary+ result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)++ # Should handle exact boundary correctly+ self.assertLessEqual(len(result.sensor_responses), 50)++ # Test earlier pagination from the boundary+ oldest_record = boundary_records[-1]+ pivot_timestamp = int(oldest_record.response_datetime.timestamp())++ earlier_result = VideoStreamBrowsingHelper.build_sensor_history_data_earlier(+ self.video_sensor, pivot_timestamp+ )++ # Should handle boundary pagination gracefully+ self.assertIsNotNone(earlier_result)+ self.assertIsInstance(earlier_result.pagination_metadata, dict)diff --git a/src/hi/apps/console/tests/test_timeline_preservation.py b/src/hi/apps/console/tests/test_timeline_preservation.pynew file mode 100644index 00000000..f2787338--- /dev/null+++ b/src/hi/apps/console/tests/test_timeline_preservation.py@@ -0,0 +1,318 @@+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.entity.models import Entity, EntityState+from hi.apps.sense.models import Sensor, SensorHistory+from hi.apps.sense.tests.synthetic_data import SensorHistorySyntheticData++logging.disable(logging.CRITICAL)+++class TestTimelinePreservationLogic(TransactionTestCase):+ """Test timeline preservation functionality with real database operations."""++ def setUp(self):+ # Create test entity and sensor+ self.video_entity = Entity.objects.create(+ integration_id='test.camera.timeline',+ integration_name='test_integration',+ name='Timeline Test Camera',+ entity_type_str='camera',+ has_video_stream=True+ )++ self.entity_state = EntityState.objects.create(+ entity=self.video_entity,+ entity_state_type_str='motion',+ name='Motion Detection'+ )++ self.video_sensor = Sensor.objects.create(+ integration_id='test.sensor.timeline',+ integration_name='test_integration',+ name='Timeline Test Sensor',+ entity_state=self.entity_state,+ sensor_type_str='binary',+ provides_video_stream=True+ )++ def test_timeline_preserved_when_target_record_within_window(self):+ """Test that timeline is preserved when target record falls within preserve window."""+ # Create comprehensive test data+ records, window_start, window_end = SensorHistorySyntheticData.create_timeline_preservation_test_data(+ self.video_sensor+ )++ # Select target record that falls within the window (4 hours ago)+ target_record = records[4] # Should be within window (2-6 hours ago)++ # Build sensor history data with preservation+ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor,+ sensor_history_id=target_record.id,+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Verify timeline preservation behavior+ self.assertIsInstance(result, EntitySensorHistoryData)++ # Should preserve the window timestamps+ self.assertEqual(result.window_start_timestamp, window_start)+ self.assertEqual(result.window_end_timestamp, window_end)++ # Current response should be the target record+ self.assertEqual(+ result.current_sensor_response.sensor_history_id,+ target_record.id+ )++ # Should include only records within the preserve window (records 2-6)+ sensor_response_ids = [+ r.sensor_history_id for r in result.sensor_responses+ ]++ # Records 2, 3, 4, 5, 6 should be included (within 2-6 hours ago)+ expected_records = [records[i] for i in range(2, 7)]+ for expected_record in expected_records:+ self.assertIn(expected_record.id, sensor_response_ids)++ # Records 0, 1 (too recent) and 7, 8, 9 (too old) should not be included+ excluded_records = [records[i] for i in [0, 1, 7, 8, 9]]+ for excluded_record in excluded_records:+ self.assertNotIn(excluded_record.id, sensor_response_ids)++ def test_timeline_recenters_when_target_record_outside_window(self):+ """Test that timeline re-centers when target record falls outside preserve window."""+ # Create boundary test scenario+ all_records, record_inside, record_outside, window_start, window_end = \+ SensorHistorySyntheticData.create_window_boundary_test_scenario(self.video_sensor)++ # Use record outside window as target+ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor,+ sensor_history_id=record_outside.id,+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Should re-center around the target record instead of preserving window+ self.assertIsInstance(result, EntitySensorHistoryData)++ # Current response should be the outside record+ self.assertEqual(+ result.current_sensor_response.sensor_history_id,+ record_outside.id+ )++ # Window boundaries should be recalculated based on actual returned records+ self.assertIsNotNone(result.window_start_timestamp)+ self.assertIsNotNone(result.window_end_timestamp)++ # Should not use the preserve window boundaries+ self.assertNotEqual(result.window_start_timestamp, window_start)+ self.assertNotEqual(result.window_end_timestamp, window_end)++ # Should include the target record in results+ sensor_response_ids = [+ r.sensor_history_id for r in result.sensor_responses+ ]+ self.assertIn(record_outside.id, sensor_response_ids)++ def test_pagination_metadata_reflects_preserve_window_boundaries(self):+ """Test that pagination metadata correctly reflects preserve window boundaries."""+ # Create test data with many records+ records, middle_index = SensorHistorySyntheticData.create_pagination_test_data(+ self.video_sensor, total_records=15, window_size=5+ )++ # Define preserve window that includes middle records (indices 5-10)+ base_time = timezone.now().replace(minute=0, second=0, microsecond=0)+ window_start = base_time - timezone.timedelta(hours=10)+ window_end = base_time - timezone.timedelta(hours=5)++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor,+ sensor_history_id=records[7].id, # Target within window+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Verify pagination metadata indicates records exist outside window+ self.assertTrue(result.pagination_metadata['has_newer_records']) # Records 0-4 exist+ self.assertTrue(result.pagination_metadata['has_older_records']) # Records 11-14 exist++ # Verify window boundaries match preserve window+ self.assertEqual(+ result.pagination_metadata['window_start_timestamp'],+ window_start+ )+ self.assertEqual(+ result.pagination_metadata['window_end_timestamp'],+ window_end+ )++ def test_timeline_groups_use_preserved_records_only(self):+ """Test that timeline groups are created only from preserved records."""+ # Create test data spanning multiple days but preserve only recent records+ base_time = timezone.now().replace(hour=12, minute=0, second=0, microsecond=0)++ # Create records: today (0), yesterday (-1 day), and older (-3 days)+ today_records = []+ for hour in [8, 10, 14, 16]:+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=base_time.replace(hour=hour),+ has_video_stream=True,+ details='{"day": "today"}'+ )+ today_records.append(record)++ # Yesterday records+ yesterday = base_time - timezone.timedelta(days=1)+ yesterday_record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=yesterday,+ has_video_stream=True,+ details='{"day": "yesterday"}'+ )++ # Older records+ old_time = base_time - timezone.timedelta(days=3)+ old_record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=old_time,+ has_video_stream=True,+ details='{"day": "old"}'+ )++ # Preserve window that includes only today's records+ window_start = base_time.replace(hour=6) # Start of today+ window_end = base_time.replace(hour=18) # End of today++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor,+ sensor_history_id=today_records[0].id,+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Timeline groups should only include today's records+ all_response_values = []+ for group in result.timeline_groups:+ for item in group['items']:+ all_response_values.append(item.value)++ # Should have 4 responses from today, none from yesterday or older+ self.assertEqual(len(all_response_values), 4)++ # Verify that only today's records are represented+ response_ids = [+ r.sensor_history_id for r in result.sensor_responses+ ]+ for today_record in today_records:+ self.assertIn(today_record.id, response_ids)++ # Yesterday and old records should not be included+ self.assertNotIn(yesterday_record.id, response_ids)+ self.assertNotIn(old_record.id, response_ids)++ def test_adjacent_records_navigation_respects_database_ordering(self):+ """Test that prev/next navigation uses actual database timestamp ordering."""+ # Create records with specific timestamps for navigation testing+ base_time = timezone.now().replace(minute=0, second=0, microsecond=0)++ # Create 5 records at 1-hour intervals+ records = []+ for i in range(5):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'nav_test_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True,+ details=f'{{"nav_order": "{i}"}}'+ )+ records.append(record)++ # Test navigation from middle record (index 2)+ middle_record = records[2] # 2 hours ago++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor,+ sensor_history_id=middle_record.id+ )++ # Previous should be older record (records[3] - 3 hours ago)+ self.assertIsNotNone(result.prev_sensor_response)+ self.assertEqual(result.prev_sensor_response.value, 'nav_test_3')++ # Next should be newer record (records[1] - 1 hour ago)+ self.assertIsNotNone(result.next_sensor_response)+ self.assertEqual(result.next_sensor_response.value, 'nav_test_1')++ def test_timezone_awareness_in_window_comparisons(self):+ """Test that all datetime comparisons are timezone-aware."""+ # Create timezone-aware sensor responses+ base_time = timezone.now()+ responses = SensorHistorySyntheticData.create_timezone_aware_sensor_responses(+ self.video_sensor,+ num_responses=3,+ start_time=base_time+ )++ # Create corresponding SensorHistory records+ records = []+ for i, response in enumerate(responses):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=response.value,+ response_datetime=response.timestamp,+ has_video_stream=True,+ details='{"timezone": "aware"}'+ )+ records.append(record)++ # Create timezone-aware preserve window+ window_start = base_time - timezone.timedelta(hours=2)+ window_end = base_time - timezone.timedelta(hours=1)++ # Ensure all timestamps are timezone-aware+ self.assertIsNotNone(window_start.tzinfo)+ self.assertIsNotNone(window_end.tzinfo)+ for record in records:+ self.assertIsNotNone(record.response_datetime.tzinfo)++ # This should not raise any timezone comparison errors+ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor,+ sensor_history_id=records[1].id, # Middle record+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Verify result is successful and timestamps are timezone-aware+ self.assertIsInstance(result, EntitySensorHistoryData)+ self.assertIsNotNone(result.window_start_timestamp.tzinfo)+ self.assertIsNotNone(result.window_end_timestamp.tzinfo)++ def test_empty_sensor_history_handled_gracefully(self):+ """Test that empty sensor history is handled gracefully."""+ # Don't create any SensorHistory records++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ sensor=self.video_sensor+ )++ # Should return valid dataclass with empty/None values+ self.assertIsInstance(result, EntitySensorHistoryData)+ self.assertEqual(len(result.sensor_responses), 0)+ self.assertIsNone(result.current_sensor_response)+ self.assertEqual(len(result.timeline_groups), 0)+ self.assertIsNone(result.prev_sensor_response)+ self.assertIsNone(result.next_sensor_response)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.pynew file mode 100644index 00000000..d9895e19--- /dev/null+++ b/src/hi/apps/console/tests/test_video_stream_browsing_helper.py@@ -0,0 +1,602 @@+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.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++logging.disable(logging.CRITICAL)+++class TestVideoStreamBrowsingHelper(TransactionTestCase):+ """Test VideoStreamBrowsingHelper for timeline preservation and business logic."""++ def setUp(self):+ # Create test entity with video stream capability+ self.video_entity = Entity.objects.create(+ integration_id='test.camera.security',+ integration_name='test_integration',+ name='Security 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.motion',+ integration_name='test_integration',+ name='Motion Sensor',+ entity_state=self.entity_state,+ sensor_type_str='binary',+ provides_video_stream=True+ )++ # Create another entity without video capability for find_video_sensor tests+ self.non_video_entity = Entity.objects.create(+ integration_id='test.sensor.temp',+ integration_name='test_integration',+ name='Temperature Sensor',+ entity_type_str='sensor',+ has_video_stream=False+ )++ def test_find_video_sensor_for_entity_returns_none_for_non_video_entity(self):+ """Test that find_video_sensor returns None for entity without video capability."""+ result = VideoStreamBrowsingHelper.find_video_sensor_for_entity(self.non_video_entity)+ self.assertIsNone(result)++ def test_find_video_sensor_for_entity_returns_none_for_none_entity(self):+ """Test that find_video_sensor returns None for None entity."""+ result = VideoStreamBrowsingHelper.find_video_sensor_for_entity(None)+ self.assertIsNone(result)++ def test_find_video_sensor_for_entity_returns_video_sensor(self):+ """Test that find_video_sensor returns correct video sensor for video entity."""+ result = VideoStreamBrowsingHelper.find_video_sensor_for_entity(self.video_entity)+ self.assertEqual(result, self.video_sensor)++ def test_create_sensor_response_with_history_id_adds_history_id_to_detail_attrs(self):+ """Test that sensor response has history ID added to detail_attrs."""+ sensor_history = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=timezone.now(),+ has_video_stream=True,+ details='{"original": "data"}'+ )++ sensor_response = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(sensor_history)++ self.assertIsInstance(sensor_response, SensorResponse)+ self.assertEqual(sensor_response.sensor, self.video_sensor)+ self.assertEqual(sensor_response.value, 'active')+ self.assertIsNotNone(sensor_response.sensor_history_id)+ self.assertEqual(sensor_response.sensor_history_id, sensor_history.id)++ def test_create_sensor_response_with_history_id_preserves_existing_detail_attrs(self):+ """Test that existing detail_attrs are preserved when adding history ID."""+ sensor_history = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=timezone.now(),+ has_video_stream=True,+ details='{"existing": "value", "duration": "120"}'+ )++ sensor_response = VideoStreamBrowsingHelper.create_sensor_response_with_history_id(sensor_history)++ # Verify existing attributes are preserved+ self.assertEqual(sensor_response.detail_attrs['existing'], 'value')+ self.assertEqual(sensor_response.detail_attrs['duration'], '120')+ # Verify sensor_history_id is set as property, not in detail_attrs+ self.assertEqual(sensor_response.sensor_history_id, sensor_history.id)+ self.assertNotIn('sensor_history_id', sensor_response.detail_attrs)++ def test_get_timeline_window_returns_recent_records_when_no_center(self):+ """Test that get_timeline_window returns most recent records when no center provided."""+ # Create test records+ base_time = timezone.now()+ records = []+ for i in range(3):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ sensor_responses, pagination_metadata = VideoStreamBrowsingHelper.get_timeline_window(+ self.video_sensor, None, window_size=5+ )++ # Should return all records, most recent first+ self.assertEqual(len(sensor_responses), 3)+ self.assertEqual(sensor_responses[0].value, 'value_0') # Most recent+ self.assertEqual(sensor_responses[2].value, 'value_2') # Oldest++ # Verify pagination metadata+ self.assertFalse(pagination_metadata['has_newer_records'])+ self.assertFalse(pagination_metadata['has_older_records']) # Only 3 records, window is 5++ def test_get_timeline_window_with_preserve_bounds_queries_within_range(self):+ """Test that get_timeline_window respects preserve_window_bounds."""+ # Create records spanning 6 hours+ base_time = timezone.now()+ records = []+ for i in range(6):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ # Set preserve bounds to include middle records+ # Records: 0 (0h), 1 (-1h), 2 (-2h), 3 (-3h), 4 (-4h), 5 (-5h)+ # Window: -3h to -1h inclusive should include records 1, 2, 3+ window_start = base_time - timezone.timedelta(hours=3)+ window_end = base_time - timezone.timedelta(hours=1)+ preserve_bounds = (window_start, window_end)++ sensor_responses, pagination_metadata = VideoStreamBrowsingHelper.get_timeline_window(+ self.video_sensor, None, window_size=50, preserve_window_bounds=preserve_bounds+ )++ # Should return records within the preserve window (records 1, 2, and 3)+ self.assertEqual(len(sensor_responses), 3)+ self.assertEqual(sensor_responses[0].value, 'value_1') # Most recent within range+ self.assertEqual(sensor_responses[1].value, 'value_2') # Middle within range+ self.assertEqual(sensor_responses[2].value, 'value_3') # Oldest within range++ # Verify pagination metadata indicates more records exist+ self.assertTrue(pagination_metadata['has_newer_records'])+ self.assertTrue(pagination_metadata['has_older_records'])++ def test_get_timeline_window_centered_around_record(self):+ """Test that get_timeline_window centers correctly around specific record."""+ # Create 5 records+ base_time = timezone.now()+ records = []+ for i in range(5):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ # Center around middle record (index 2)+ center_record = records[2]++ sensor_responses, pagination_metadata = VideoStreamBrowsingHelper.get_timeline_window(+ self.video_sensor, center_record, window_size=5+ )++ # Should return all 5 records with center record included+ self.assertEqual(len(sensor_responses), 5)++ # Find center record in results+ center_in_results = next(+ r for r in sensor_responses+ if r.sensor_history_id == center_record.id+ )+ self.assertEqual(center_in_results.value, 'value_2')++ def test_group_responses_by_time_creates_daily_groups(self):+ """Test that group_responses_by_time creates appropriate daily groups."""+ # Create sensor responses spanning multiple days+ base_time = timezone.now()+ sensor_responses = []++ # Create a few responses for today, yesterday, and older+ for days_ago in [0, 1, 3]:+ for hour_offset in [8, 14]:+ if days_ago == 0:+ # For today, use a fixed time to ensure it's always today+ # regardless of when the test runs+ timestamp = base_time.replace(hour=hour_offset, minute=0, second=0, microsecond=0)+ else:+ # For other days, subtract full days then set specific hour+ date_base = base_time - timezone.timedelta(days=days_ago)+ timestamp = date_base.replace(hour=hour_offset, minute=0, second=0, microsecond=0)++ integration_key = IntegrationKey(+ integration_id='test',+ integration_name=f'response_{days_ago}_{hour_offset}'+ )+ response = SensorResponse(+ integration_key=integration_key,+ value='active',+ timestamp=timestamp,+ sensor=self.video_sensor,+ detail_attrs={'duration_seconds': '120', 'details': f'Motion event {days_ago}_{hour_offset}'},+ has_video_stream=True,+ sensor_history_id=int(f'{days_ago}{hour_offset}') # Use unique ID for test+ )+ sensor_responses.append(response)++ timeline_groups = VideoStreamBrowsingHelper.group_responses_by_time(sensor_responses)++ # Should create groups for Today, Yesterday, and older date+ self.assertEqual(len(timeline_groups), 3)++ # Verify group labels (now include day abbreviations)+ group_labels = [group['label'] for group in timeline_groups]++ # Check that Today and Yesterday labels contain the expected base text+ today_label = next((label for label in group_labels if label.startswith('Today')), None)+ yesterday_label = next((label for label in group_labels if label.startswith('Yesterday')), None)++ self.assertIsNotNone(today_label, f"Expected a label starting with 'Today', got: {group_labels}")+ self.assertIsNotNone(yesterday_label, f"Expected a label starting with 'Yesterday', got: {group_labels}")++ # Verify the day abbreviation is included (3 characters for day)+ self.assertTrue(today_label.split()[-1], "Today label should include day abbreviation")+ self.assertTrue(yesterday_label.split()[-1], "Yesterday label should include day abbreviation")++ def test_group_responses_by_time_uses_hourly_grouping_for_busy_day(self):+ """Test that group_responses_by_time uses hourly grouping when many events today."""+ # Create 15 responses for today to trigger hourly grouping (> 10)+ base_time = timezone.now()+ sensor_responses = []++ for hour in range(15):+ timestamp = base_time.replace(hour=hour, minute=0, second=0, microsecond=0)+ integration_key = IntegrationKey(+ integration_id='test',+ integration_name=f'response_{hour}'+ )+ response = SensorResponse(+ integration_key=integration_key,+ value='active',+ timestamp=timestamp,+ sensor=self.video_sensor,+ detail_attrs={'duration_seconds': '90', 'details': f'Motion event hour {hour}'},+ has_video_stream=True,+ sensor_history_id=hour+ )+ sensor_responses.append(response)++ timeline_groups = VideoStreamBrowsingHelper.group_responses_by_time(sensor_responses)++ # Should create hourly groups (15 different hours)+ self.assertEqual(len(timeline_groups), 15)++ # Verify some groups have hourly labels (AM/PM format)+ group_labels = [group['label'] for group in timeline_groups]+ self.assertTrue(any('AM' in label or 'PM' in label for label in group_labels))++ def test_find_adjacent_records_returns_correct_navigation(self):+ """Test that find_adjacent_records returns correct prev/next records."""+ # Create 3 sequential records+ base_time = timezone.now()+ records = []+ for i in range(3):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ # Test navigation for middle record+ middle_record = records[1]+ prev_response, next_response = VideoStreamBrowsingHelper.find_adjacent_records(+ self.video_sensor, middle_record.id+ )++ # Previous should be the older record (records[2])+ self.assertIsNotNone(prev_response)+ self.assertEqual(prev_response.value, 'value_2')++ # Next should be the newer record (records[0])+ self.assertIsNotNone(next_response)+ self.assertEqual(next_response.value, 'value_0')++ def test_find_adjacent_records_handles_boundary_conditions(self):+ """Test that find_adjacent_records handles first/last records correctly."""+ # Create 2 records+ base_time = timezone.now()+ records = []+ for i in range(2):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ # Test first (newest) record - should only have previous+ newest_record = records[0]+ prev_response, next_response = VideoStreamBrowsingHelper.find_adjacent_records(+ self.video_sensor, newest_record.id+ )++ self.assertIsNotNone(prev_response)+ self.assertEqual(prev_response.value, 'value_1')+ self.assertIsNone(next_response) # No newer records++ # Test last (oldest) record - should only have next+ oldest_record = records[1]+ prev_response, next_response = VideoStreamBrowsingHelper.find_adjacent_records(+ self.video_sensor, oldest_record.id+ )++ self.assertIsNone(prev_response) # No older records+ self.assertIsNotNone(next_response)+ self.assertEqual(next_response.value, 'value_0')++ def test_build_sensor_history_data_returns_correct_dataclass_structure(self):+ """Test that build_sensor_history_data returns properly structured dataclass."""+ # Create test records+ base_time = timezone.now()+ for i in range(3):+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )++ result = VideoStreamBrowsingHelper.build_sensor_history_data(self.video_sensor)++ # Verify result is correct dataclass type+ self.assertIsInstance(result, EntitySensorHistoryData)++ # Verify all required fields are present+ self.assertIsNotNone(result.sensor_responses)+ self.assertIsNotNone(result.current_sensor_response)+ self.assertIsNotNone(result.timeline_groups)+ self.assertIsNotNone(result.pagination_metadata)+ # prev/next may be None depending on data++ # Verify window timestamps are populated+ self.assertIsNotNone(result.window_start_timestamp)+ self.assertIsNotNone(result.window_end_timestamp)++ def test_build_sensor_history_data_timeline_preservation_logic(self):+ """Test timeline preservation logic in build_sensor_history_data."""+ # Create test records spanning 4 hours+ base_time = timezone.now()+ records = []+ for i in range(4):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ # Test with preserve window that includes middle record+ target_record = records[2] # 2 hours ago+ window_start = base_time - timezone.timedelta(hours=3)+ window_end = base_time - timezone.timedelta(hours=1)++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ self.video_sensor,+ sensor_history_id=target_record.id,+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Should use preserved timeline since target record is within window+ self.assertIsInstance(result, EntitySensorHistoryData)++ # Current response should be the target record+ self.assertEqual(+ result.current_sensor_response.sensor_history_id,+ target_record.id+ )++ # Should include records within preserve window+ response_values = [r.value for r in result.sensor_responses]+ self.assertIn('value_1', response_values) # Within window+ self.assertIn('value_2', response_values) # Target record++ def test_build_sensor_history_data_recenters_when_record_outside_window(self):+ """Test that build_sensor_history_data re-centers when target record outside preserve window."""+ # Create test records spanning 6 hours+ base_time = timezone.now()+ records = []+ for i in range(6):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )+ records.append(record)++ # Test with preserve window that excludes target record+ target_record = records[5] # 5 hours ago+ window_start = base_time - timezone.timedelta(hours=2)+ window_end = base_time - timezone.timedelta(hours=1)++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ self.video_sensor,+ sensor_history_id=target_record.id,+ preserve_window_start=window_start,+ preserve_window_end=window_end+ )++ # Should re-center around target record since it's outside preserve window+ self.assertIsInstance(result, EntitySensorHistoryData)++ # Current response should be the target record+ self.assertEqual(+ result.current_sensor_response.sensor_history_id,+ target_record.id+ )++ # Should include records around the target (centered timeline)+ response_values = [r.value for r in result.sensor_responses]+ self.assertIn('value_5', response_values) # Target record should be included++ def test_build_sensor_history_data_handles_nonexistent_sensor_history_id(self):+ """Test that build_sensor_history_data handles nonexistent sensor_history_id gracefully."""+ # Create test records+ base_time = timezone.now()+ for i in range(2):+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'value_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True+ )++ result = VideoStreamBrowsingHelper.build_sensor_history_data(+ self.video_sensor,+ sensor_history_id=99999 # Nonexistent ID+ )++ # Should fall back to most recent window+ self.assertIsInstance(result, EntitySensorHistoryData)+ self.assertIsNotNone(result.sensor_responses)+ self.assertIsNotNone(result.current_sensor_response)++ # Should select most recent record as current+ self.assertEqual(result.current_sensor_response.value, 'value_0')++ def test_find_video_sensor_handles_corrupted_entity_states(self):+ """Test error boundary: find_video_sensor with corrupted entity state relationships."""+ # Create entity with corrupted state (no sensors)+ corrupted_entity = Entity.objects.create(+ integration_id='test.corrupted',+ integration_name='test_integration',+ name='Corrupted Entity',+ has_video_stream=True # Claims to have video but has no sensors+ )++ # Should handle gracefully when entity claims video capability but has no sensors+ result = VideoStreamBrowsingHelper.find_video_sensor_for_entity(corrupted_entity)+ self.assertIsNone(result)++ def test_get_timeline_window_handles_invalid_preserve_bounds(self):+ """Test error boundary: timeline window with invalid preservation bounds."""+ # Create test data+ base_time = timezone.now()+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='test_value',+ response_datetime=base_time,+ has_video_stream=True+ )++ # Test with invalid window bounds (end before start)+ invalid_start = base_time+ invalid_end = base_time - timezone.timedelta(hours=1) # End before start+ invalid_bounds = (invalid_start, invalid_end)++ # Should handle invalid bounds gracefully+ sensor_responses, metadata = VideoStreamBrowsingHelper.get_timeline_window(+ self.video_sensor, preserve_window_bounds=invalid_bounds+ )++ # Should return empty results or handle gracefully+ self.assertIsInstance(sensor_responses, list)+ self.assertIsInstance(metadata, dict)++ def test_group_responses_by_time_handles_same_timestamp_records(self):+ """Test performance boundary: grouping with many records at same timestamp."""+ base_time = timezone.now()+ same_timestamp = base_time.replace(hour=12, minute=0, second=0, microsecond=0)++ # Create multiple sensor responses at exactly the same timestamp+ sensor_responses = []+ for i in range(10):+ integration_key = IntegrationKey(+ integration_id='test_integration',+ integration_name=f'same_time_response_{i}'+ )++ response = SensorResponse(+ integration_key=integration_key,+ value=f'same_time_value_{i}',+ timestamp=same_timestamp, # Same timestamp for all+ sensor=self.video_sensor,+ detail_attrs={'sensor_history_id': str(1000 + i)},+ has_video_stream=True+ )+ sensor_responses.append(response)++ # Should group all same-timestamp records correctly+ timeline_groups = VideoStreamBrowsingHelper.group_responses_by_time(sensor_responses)++ self.assertIsInstance(timeline_groups, list)+ self.assertEqual(len(timeline_groups), 1) # All in same time group++ # All responses should be in the single group+ single_group = timeline_groups[0]+ self.assertEqual(len(single_group['items']), 10)++ def test_build_sensor_history_data_handles_extreme_timestamp_ranges(self):+ """Test error boundary: extreme timestamp ranges and edge cases."""+ # Create records with extreme timestamp ranges+ base_time = timezone.now()++ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='extreme_past',+ response_datetime=timezone.datetime(1970, 1, 1, tzinfo=timezone.utc),+ has_video_stream=True+ )++ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='recent',+ response_datetime=base_time,+ has_video_stream=True+ )++ # Should handle extreme timestamp ranges+ result = VideoStreamBrowsingHelper.build_sensor_history_data_default(self.video_sensor)++ self.assertIsNotNone(result)+ self.assertGreater(len(result.sensor_responses), 0)++ # Should handle timeline grouping with extreme ranges+ self.assertIsInstance(result.timeline_groups, list)++ def test_pagination_methods_handle_edge_case_timestamps(self):+ """Test performance boundary: pagination with edge case timestamp values."""+ # Test with Unix epoch timestamp (edge case)+ epoch_timestamp = 0 # January 1, 1970++ # Should handle epoch timestamp without errors+ result = VideoStreamBrowsingHelper.build_sensor_history_data_earlier(+ self.video_sensor, epoch_timestamp+ )++ # Should return valid empty result for epoch (no records before 1970)+ self.assertIsNotNone(result)+ self.assertEqual(len(result.sensor_responses), 0)+ self.assertFalse(result.pagination_metadata['has_older_records'])++ # Test with very large timestamp (far future)+ future_timestamp = 2147483647 # 32-bit max timestamp (2038)++ result = VideoStreamBrowsingHelper.build_sensor_history_data_later(+ self.video_sensor, future_timestamp+ )++ # Should handle far future timestamp+ self.assertIsNotNone(result)+ self.assertIsInstance(result.sensor_responses, list)diff --git a/src/hi/apps/console/tests/test_views.py b/src/hi/apps/console/tests/test_views.pyindex 940b9b10..fbace491 100644--- a/src/hi/apps/console/tests/test_views.py+++ b/src/hi/apps/console/tests/test_views.py@@ -1,9 +1,18 @@import logging+from unittest.mock import Mockfrom 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 EntityVideoStreamView-from hi.apps.entity.models import Entity+from hi.apps.console.views import (+ EntityVideoStreamView, EntityVideoSensorHistoryView,+ EntityVideoSensorHistoryEarlierView, EntityVideoSensorHistoryLaterView+)+from hi.apps.console.transient_models import EntitySensorHistoryData+from hi.apps.entity.models import Entity, EntityState+from hi.apps.sense.models import Sensor, SensorHistoryfrom hi.testing.base_test_case import BaseTestCaselogging.disable(logging.CRITICAL)@@ -78,3 +87,607 @@ class TestEntityVideoStreamView(BaseTestCase):self.assertEqual(self.non_video_entity.name, 'Temperature Sensor')self.assertFalse(self.non_video_entity.has_video_stream)self.assertEqual(self.non_video_entity.integration_id, 'test.sensor.temp')+++class TestEntityVideoSensorHistoryView(BaseTestCase):+ """Test EntityVideoSensorHistoryView for timeline preservation functionality."""++ def setUp(self):+ super().setUp()++ # Create test entity with video stream capability+ self.video_entity = Entity.objects.create(+ integration_id='test.camera.security',+ integration_name='test_integration',+ name='Security Camera',+ entity_type_str='camera',+ has_video_stream=True+ )++ # Create entity state for the video entity+ 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.motion',+ integration_name='test_integration',+ name='Motion Sensor',+ entity_state=self.entity_state,+ sensor_type_str='binary',+ provides_video_stream=True+ )++ # Create sensor history records for testing+ base_time = timezone.now()+ self.sensor_history_records = []+ for i in range(5):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active' if i % 2 == 0 else 'idle',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True,+ details='{"test": "data"}'+ )+ 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+ non_video_sensor = Sensor.objects.create(+ integration_id='test.sensor.temp',+ integration_name='test_integration',+ name='Temperature Sensor',+ entity_state=self.entity_state,+ sensor_type_str='sensor',+ provides_video_stream=False+ )++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ with self.assertRaises(BadRequest) as context:+ view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=non_video_sensor.id+ )+ 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+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ # Create real sensor history records for testing+ base_time = timezone.now()+ test_records = []+ for i in range(3):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'motion_detected_{i}',+ response_datetime=base_time - timezone.timedelta(hours=i),+ has_video_stream=True,+ details=f'{{"event": "test_{i}", "confidence": 0.9}}'+ )+ test_records.append(record)++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id+ )++ # Verify context structure with real data+ self.assertEqual(context['entity'], self.video_entity)+ self.assertEqual(context['sensor'], self.video_sensor)++ # Test actual EntitySensorHistoryData content+ sensor_history_data = context['sensor_history_data']+ self.assertIsInstance(sensor_history_data, EntitySensorHistoryData)+ self.assertEqual(len(sensor_history_data.sensor_responses), 3)++ # Verify sensor responses contain real data+ first_response = sensor_history_data.sensor_responses[0]+ self.assertTrue(hasattr(first_response, 'sensor_history_id'))+ self.assertIn('motion_detected', first_response.value)++ # Verify timeline groups are created+ self.assertIsInstance(sensor_history_data.timeline_groups, list)++ # Verify pagination metadata is present+ self.assertIsInstance(sensor_history_data.pagination_metadata, dict)+ self.assertIn('has_older_records', sensor_history_data.pagination_metadata)+ self.assertIn('has_newer_records', sensor_history_data.pagination_metadata)++ # Verify view parameters were set+ request.view_parameters.to_session.assert_called_once_with(request)++ def test_view_handles_earlier_pagination_with_real_data(self):+ """Test that view handles 'earlier' pagination with actual sensor history data."""+ # Clear any existing sensor history+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ # Create real sensor history records across a time range+ base_time = timezone.now()+ older_records = []+ newer_records = []++ # Create 10 older records (more than 2 hours ago)+ for i in range(10):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'older_motion_{i}',+ response_datetime=base_time - timezone.timedelta(hours=3 + i),+ has_video_stream=True,+ details=f'{{"event": "older_{i}", "confidence": 0.8}}'+ )+ older_records.append(record)++ # Create 5 newer records (within last 2 hours)+ for i in range(5):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'newer_motion_{i}',+ response_datetime=base_time - timezone.timedelta(minutes=30 * i),+ has_video_stream=True,+ details=f'{{"event": "newer_{i}", "confidence": 0.9}}'+ )+ newer_records.append(record)++ # Test pagination to earlier records using timestamp from 2 hours ago+ pivot_time = base_time - timezone.timedelta(hours=2)+ pivot_timestamp = str(int(pivot_time.timestamp()))++ view = EntityVideoSensorHistoryEarlierView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id,+ timestamp=pivot_timestamp+ )++ # Test actual pagination behavior+ sensor_history_data = context['sensor_history_data']+ self.assertIsInstance(sensor_history_data, EntitySensorHistoryData)++ # Should return earlier records (from older_records)+ self.assertGreater(len(sensor_history_data.sensor_responses), 0)++ # All returned records should be older than pivot time+ for response in sensor_history_data.sensor_responses:+ self.assertLess(response.timestamp, pivot_time)++ # Verify pagination metadata indicates more records available+ pagination_meta = sensor_history_data.pagination_metadata+ self.assertIn('has_older_records', pagination_meta)+ self.assertIn('has_newer_records', pagination_meta)+ self.assertTrue(pagination_meta['has_newer_records']) # Should have newer records available++ def test_view_handles_later_pagination_with_real_data(self):+ """Test that view handles 'later' pagination with actual sensor history data."""+ # Clear any existing sensor history+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ # Create real sensor history records across a time range+ base_time = timezone.now()+ older_records = []+ newer_records = []++ # Create 8 older records (more than 4 hours ago)+ for i in range(8):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'older_motion_{i}',+ response_datetime=base_time - timezone.timedelta(hours=5 + i),+ has_video_stream=True,+ details=f'{{"event": "older_{i}", "confidence": 0.7}}'+ )+ older_records.append(record)++ # Create 6 newer records (within last 3 hours) with more spacing+ for i in range(6):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'newer_motion_{i}',+ response_datetime=base_time - timezone.timedelta(hours=2.5) + timezone.timedelta(minutes=15 * i),+ has_video_stream=True,+ details=f'{{"event": "newer_{i}", "confidence": 0.95}}'+ )+ newer_records.append(record)++ # Test pagination to later records using timestamp from 4 hours ago+ pivot_time = base_time - timezone.timedelta(hours=4)+ pivot_timestamp = str(int(pivot_time.timestamp()))++ view = EntityVideoSensorHistoryLaterView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id,+ timestamp=pivot_timestamp+ )++ # Test actual pagination behavior+ sensor_history_data = context['sensor_history_data']+ self.assertIsInstance(sensor_history_data, EntitySensorHistoryData)++ # Should return later records (from newer_records)+ self.assertGreater(len(sensor_history_data.sensor_responses), 0)++ # All returned records should be newer than pivot time+ for response in sensor_history_data.sensor_responses:+ self.assertGreater(response.timestamp, pivot_time)++ # Verify pagination metadata indicates more records available+ pagination_meta = sensor_history_data.pagination_metadata+ self.assertIn('has_older_records', pagination_meta)+ self.assertIn('has_newer_records', pagination_meta)+ self.assertTrue(pagination_meta['has_older_records']) # Should have older records available++ # Test that responses contain expected newer data+ response_values = [r.value for r in sensor_history_data.sensor_responses]+ self.assertTrue(any('newer_motion' in value for value in response_values))++ def test_view_handles_window_context_parameters_with_real_data(self):+ """Test that view handles window context parameters with actual sensor history data."""+ # Clear any existing sensor history+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ # Create real sensor history records within specific time windows+ base_time = timezone.now()++ # Records outside the window (should not appear in results)+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='outside_before_window',+ response_datetime=base_time - timezone.timedelta(hours=4),+ has_video_stream=True+ )++ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='outside_after_window',+ response_datetime=base_time,+ has_video_stream=True+ )++ # Records inside the window (should appear in results)+ window_records = []+ for i in range(3):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'inside_window_{i}',+ response_datetime=base_time - timezone.timedelta(hours=2) + timezone.timedelta(minutes=20 * i),+ has_video_stream=True,+ details=f'{{"window_test": "record_{i}"}}'+ )+ window_records.append(record)++ # Define window boundaries (2.5 hours ago to 1.5 hours ago)+ window_start_time = base_time - timezone.timedelta(hours=2.5)+ window_end_time = base_time - timezone.timedelta(hours=1.5)+ window_start_timestamp = str(int(window_start_time.timestamp()))+ window_end_timestamp = str(int(window_end_time.timestamp()))++ # Use the middle record as the target+ target_record = window_records[1]++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id,+ sensor_history_id=target_record.id,+ window_start=window_start_timestamp,+ window_end=window_end_timestamp+ )++ # Test actual window preservation behavior+ sensor_history_data = context['sensor_history_data']+ self.assertIsInstance(sensor_history_data, EntitySensorHistoryData)++ # Should only return records within the window+ response_values = [r.value for r in sensor_history_data.sensor_responses]++ # Verify only window records are included+ self.assertTrue(any('inside_window' in value for value in response_values))+ self.assertNotIn('outside_before_window', response_values)+ self.assertNotIn('outside_after_window', response_values)++ # Verify window timestamps are preserved+ self.assertIsNotNone(sensor_history_data.window_start_timestamp)+ self.assertIsNotNone(sensor_history_data.window_end_timestamp)++ # Verify current sensor response corresponds to target record+ if sensor_history_data.current_sensor_response:+ self.assertEqual(sensor_history_data.current_sensor_response.sensor_history_id, target_record.id)++ def test_view_integration_with_url_routing_basic(self):+ """Test basic URL routing integration."""+ url = reverse('console_entity_video_sensor_history', kwargs={+ 'entity_id': self.video_entity.id,+ 'sensor_id': self.video_sensor.id+ })++ self.assertIn('/console/entity/video-sensor-history/', url)+ self.assertIn(str(self.video_entity.id), url)+ self.assertIn(str(self.video_sensor.id), url)++ def test_view_integration_with_url_routing_with_history_id(self):+ """Test URL routing integration with sensor history ID."""+ url = reverse('console_entity_video_sensor_history_detail', kwargs={+ 'entity_id': self.video_entity.id,+ 'sensor_id': self.video_sensor.id,+ 'sensor_history_id': 123+ })++ self.assertIn('/console/entity/video-sensor-history/', url)+ self.assertIn(str(self.video_entity.id), url)+ self.assertIn(str(self.video_sensor.id), url)+ self.assertIn('123', url)++ def test_view_integration_with_url_routing_with_window_context(self):+ """Test URL routing integration with window context parameters."""+ url = reverse('console_entity_video_sensor_history_detail_with_context', kwargs={+ 'entity_id': self.video_entity.id,+ 'sensor_id': self.video_sensor.id,+ 'sensor_history_id': 123,+ 'window_start': '1640995200', # Example timestamp+ 'window_end': '1641081600'+ })++ self.assertIn('/console/entity/video-sensor-history/', url)+ self.assertIn(str(self.video_entity.id), url)+ self.assertIn(str(self.video_sensor.id), url)+ self.assertIn('123', url)+ self.assertIn('1640995200', url)+ self.assertIn('1641081600', url)++ def test_view_handles_malformed_sensor_data_gracefully(self):+ """Test error boundary: malformed sensor data with invalid details JSON."""+ # Create sensor history with malformed JSON details+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='active',+ response_datetime=timezone.now(),+ has_video_stream=True,+ details='invalid-json-format{not valid}'+ )++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ # Current behavior: malformed JSON causes JSONDecodeError+ # This test documents the current behavior and identifies improvement opportunity+ with self.assertRaises(Exception) as context_manager:+ view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id+ )++ # Verify it's a JSON decode error as expected+ exception = context_manager.exception+ self.assertTrue(+ 'JSON' in str(type(exception)) or 'json' in str(exception).lower(),+ f"Expected JSON-related error, got: {type(exception)} - {exception}"+ )++ def test_view_handles_timezone_conversion_edge_cases(self):+ """Test error boundary: timezone conversion with various timestamp formats."""+ view = EntityVideoSensorHistoryEarlierView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ # Test edge case timestamps+ edge_case_timestamps = [+ '0', # Unix epoch+ '2147483647', # 32-bit max timestamp+ str(int(timezone.now().timestamp())), # Current time+ ]++ for timestamp in edge_case_timestamps:+ with self.subTest(timestamp=timestamp):+ # Should handle various timestamp formats without errors+ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id,+ timestamp=timestamp+ )++ # Should return valid context structure+ self.assertIsInstance(context['sensor_history_data'], EntitySensorHistoryData)+ self.assertIsInstance(context['sensor_history_data'].pagination_metadata, dict)++ def test_view_handles_empty_result_sets_gracefully(self):+ """Test error boundary: empty sensor history with no video records."""+ # Clear all sensor history+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id+ )++ # Should handle empty results gracefully+ sensor_history_data = context['sensor_history_data']+ self.assertIsInstance(sensor_history_data, EntitySensorHistoryData)+ self.assertEqual(len(sensor_history_data.sensor_responses), 0)+ self.assertEqual(len(sensor_history_data.timeline_groups), 0)+ self.assertIsNone(sensor_history_data.current_sensor_response)++ # Pagination should reflect no data available+ pagination = sensor_history_data.pagination_metadata+ self.assertFalse(pagination.get('has_older_records', True))+ self.assertFalse(pagination.get('has_newer_records', True))++ def test_view_handles_large_dataset_pagination_boundaries(self):+ """Test performance boundary: pagination with large number of records."""+ # Clear existing data and create large dataset+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ # Create 100+ sensor records to test pagination boundaries+ base_time = timezone.now()+ large_dataset = []+ for i in range(150):+ record = SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'large_dataset_record_{i}',+ response_datetime=base_time - timezone.timedelta(minutes=i * 10),+ has_video_stream=True,+ details=f'{{"large_test": true, "index": {i}}}'+ )+ large_dataset.append(record)++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ # Test default pagination handles large dataset+ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id+ )++ sensor_history_data = context['sensor_history_data']++ # Should limit results to reasonable window size (typically 50)+ self.assertLessEqual(len(sensor_history_data.sensor_responses), 50)+ self.assertGreater(len(sensor_history_data.sensor_responses), 0)++ # Should indicate more records available+ pagination = sensor_history_data.pagination_metadata+ self.assertTrue(pagination.get('has_older_records', False))++ # Timeline groups should be created efficiently+ self.assertIsInstance(sensor_history_data.timeline_groups, list)++ def test_view_handles_timeline_grouping_edge_cases(self):+ """Test performance boundary: timeline grouping with edge case date patterns."""+ # Clear existing data+ SensorHistory.objects.filter(sensor=self.video_sensor).delete()++ base_time = timezone.now()++ # Create edge case scenarios:+ # 1. Many events at exact same timestamp+ same_timestamp = base_time - timezone.timedelta(hours=1)+ for i in range(5):+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value=f'same_time_{i}',+ response_datetime=same_timestamp,+ has_video_stream=True,+ details=f'{{"same_timestamp_test": {i}}}'+ )++ # 2. Events spanning midnight boundary+ midnight_boundary = base_time.replace(hour=0, minute=1, second=0, microsecond=0)+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='after_midnight',+ response_datetime=midnight_boundary,+ has_video_stream=True+ )++ before_midnight = midnight_boundary - timezone.timedelta(minutes=2)+ SensorHistory.objects.create(+ sensor=self.video_sensor,+ value='before_midnight',+ response_datetime=before_midnight,+ has_video_stream=True+ )++ view = EntityVideoSensorHistoryView()+ request = Mock()+ request.view_parameters = Mock()+ request.view_parameters.to_session = Mock()++ context = view.get_main_template_context(+ request,+ entity_id=self.video_entity.id,+ sensor_id=self.video_sensor.id+ )++ # Should handle edge cases without errors+ sensor_history_data = context['sensor_history_data']+ self.assertIsInstance(sensor_history_data.timeline_groups, list)+ self.assertGreater(len(sensor_history_data.sensor_responses), 0)++ # Timeline groups should handle midnight boundary correctly+ for group in sensor_history_data.timeline_groups:+ self.assertIn('label', group)+ self.assertIn('items', group)+ self.assertIsInstance(group['items'], list)diff --git a/src/hi/apps/console/transient_models.py b/src/hi/apps/console/transient_models.pyindex 3cc4262e..2b179eeb 100644--- a/src/hi/apps/console/transient_models.py+++ b/src/hi/apps/console/transient_models.py@@ -1,8 +1,9 @@from dataclasses import dataclassfrom datetime import datetime-from typing import Optional+from typing import Dict, List, Optionalfrom hi.apps.entity.models import Entity, EntityState+from hi.apps.sense.transient_models import SensorResponse@dataclass@@ -30,3 +31,19 @@ class CameraControlDisplayData:"""entity: Entitystatus_entity_state: Optional[EntityState] = None+++@dataclass+class EntitySensorHistoryData:+ """+ Data container for entity sensor history browsing functionality.+ Encapsulates all data needed for video sensor history view rendering.+ """+ sensor_responses: List[SensorResponse]+ current_sensor_response: Optional[SensorResponse]+ timeline_groups: List[Dict]+ pagination_metadata: Dict+ prev_sensor_response: Optional[SensorResponse]+ next_sensor_response: Optional[SensorResponse]+ window_start_timestamp: Optional[datetime] = None+ window_end_timestamp: Optional[datetime] = Nonediff --git a/src/hi/apps/console/urls.py b/src/hi/apps/console/urls.pyindex a887ceea..476effd8 100644--- a/src/hi/apps/console/urls.py+++ b/src/hi/apps/console/urls.py@@ -10,6 +10,29 @@ urlpatterns = [views.EntityVideoStreamView.as_view(),name='console_entity_video_stream'),+ 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'),++ re_path(+ r'^entity/video-sensor-history/(?P<entity_id>\d+)/(?P<sensor_id>\d+)/(?P<sensor_history_id>\d+)/$',+ views.EntityVideoSensorHistoryView.as_view(),+ name='console_entity_video_sensor_history_detail'),++ re_path(+ r'^entity/video-sensor-history/(?P<entity_id>\d+)/(?P<sensor_id>\d+)/(?P<sensor_history_id>\d+)/'+ r'(?P<window_start>\d+)/(?P<window_end>\d+)/$',+ views.EntityVideoSensorHistoryView.as_view(),+ name='console_entity_video_sensor_history_detail_with_context'),++ re_path(r'^entity/video-sensor-history/(?P<entity_id>\d+)/(?P<sensor_id>\d+)/earlier/(?P<timestamp>\d+)/$',+ views.EntityVideoSensorHistoryEarlierView.as_view(),+ name='console_entity_video_sensor_history_earlier'),++ re_path(r'^entity/video-sensor-history/(?P<entity_id>\d+)/(?P<sensor_id>\d+)/later/(?P<timestamp>\d+)/$',+ views.EntityVideoSensorHistoryLaterView.as_view(),+ name='console_entity_video_sensor_history_later'),+re_path( r'^lock$',views.ConsoleLockView.as_view(),name='console_lock'),diff --git a/src/hi/apps/console/video_stream_browsing_helper.py b/src/hi/apps/console/video_stream_browsing_helper.pynew file mode 100644index 00000000..663051ff--- /dev/null+++ b/src/hi/apps/console/video_stream_browsing_helper.py@@ -0,0 +1,629 @@+"""+Helper class for video stream browsing functionality.+Encapsulates business logic for sensor history browsing, timeline grouping,+and sensor selection for video streams.+"""++from datetime import datetime, timedelta+from typing import Dict, List, Optional+from django.utils import timezone++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+++class VideoStreamBrowsingHelper:+ """Helper class for video stream browsing operations."""++ # Use ConsoleManager's priority list as the single source of truth+ # This ensures consistency across the application+ SENSOR_STATE_TYPE_PRIORITY = ConsoleManager.STATUS_ENTITY_STATE_PRIORITY++ @classmethod+ 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++ # Fetch all entity states with their sensors in a single query+ # Using select_related and prefetch_related to minimize database hits+ entity_states = EntityState.objects.filter(+ entity=entity+ ).prefetch_related(+ 'sensors'+ )++ # Build a map of state types to their sensors for efficient lookup+ state_type_to_sensors: Dict[str, List[Sensor]] = {}+ for state in entity_states:+ state_type_str = state.entity_state_type_str+ if state_type_str not in state_type_to_sensors:+ state_type_to_sensors[state_type_str] = []+ state_type_to_sensors[state_type_str].extend(+ sensor for sensor in state.sensors.all()+ if sensor.provides_video_stream+ )++ # Check sensors in priority order+ for state_type in cls.SENSOR_STATE_TYPE_PRIORITY:+ state_type_str = str(state_type)+ if state_type_str in state_type_to_sensors:+ sensors = state_type_to_sensors[state_type_str]+ if sensors:+ return sensors[0]++ # If no prioritized sensor found, return any video-capable sensor+ for sensors in state_type_to_sensors.values():+ if sensors:+ return sensors[0]++ 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+ """+ sensor_response = SensorResponse.from_sensor_history(sensor_history)++ # Set the core Django primary key as a proper property+ sensor_response.sensor_history_id = sensor_history.id++ return sensor_response++ @classmethod+ def get_timeline_window(+ 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.++ Args:+ sensor: Sensor to get records for+ center_record: Record to center the window around (None for most recent)+ window_size: Total number of records to include+ preserve_window_bounds: Tuple of (start_datetime, end_datetime) for timeline preservation++ Returns:+ Tuple of (sensor_responses_list, pagination_metadata)+ """+ if preserve_window_bounds:+ # Preserve existing timeline window - query records within bounds+ start_time, end_time = preserve_window_bounds+ history_records = list(SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__gte=start_time,+ response_datetime__lte=end_time+ ).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()+ window_center_timestamp = start_time if history_records else None+ elif center_record is None:+ # No center record - get most recent records (default behavior)+ history_records = SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True+ ).order_by('-response_datetime')[:window_size]++ has_older_records = len(history_records) == window_size+ has_newer_records = False+ window_center_timestamp = history_records[0].response_datetime if history_records else None+ else:+ # Center window around specific record+ half_window = window_size // 2++ # Get records before center (older timestamps)+ before_records = list(SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__lt=center_record.response_datetime+ ).order_by('-response_datetime')[:half_window])++ # Get records after center (newer timestamps)+ after_records = list(SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__gt=center_record.response_datetime+ ).order_by('response_datetime')[:half_window])++ # Combine all records in chronological order (newest first)+ history_records = list(reversed(after_records)) + [center_record] + before_records++ # Pagination metadata for future use+ has_older_records = len(before_records) == half_window+ has_newer_records = len(after_records) == half_window+ window_center_timestamp = center_record.response_datetime++ # Convert to SensorResponse objects+ sensor_responses = []+ for record in history_records:+ sensor_response = cls.create_sensor_response_with_history_id(record)+ sensor_responses.append(sensor_response)++ # Calculate actual window bounds for timeline preservation+ window_start_timestamp = None+ window_end_timestamp = None+ if history_records:+ if preserve_window_bounds:+ 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)++ # Pagination metadata for future pagination feature+ pagination_metadata = {+ 'has_older_records': has_older_records,+ 'has_newer_records': has_newer_records,+ 'window_center_timestamp': window_center_timestamp,+ 'window_size': window_size,+ 'window_start_timestamp': window_start_timestamp,+ 'window_end_timestamp': window_end_timestamp,+ }++ return sensor_responses, pagination_metadata++ @classmethod+ def group_responses_by_time(cls, sensor_responses: List[SensorResponse]) -> 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++ Returns:+ List of grouped timeline items+ """+ if not sensor_responses:+ return []++ groups = []+ current_date = None+ 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)+ use_hourly = today_count > 10++ for response in sensor_responses:+ response_date = response.timestamp.date()+ response_hour = response.timestamp.hour++ # Create new group if needed+ if use_hourly and response_date == today:+ # Group by hour for today if many events+ if current_date != response_date or current_hour != response_hour:+ current_date = response_date+ current_hour = response_hour+ current_group = {+ 'label': f"{response.timestamp.strftime('%I:00 %p')}",+ 'date': response_date,+ 'items': []+ }+ groups.append(current_group)+ else:+ # Group by day+ if current_date != response_date:+ 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')}"+ else:+ label = f"{response.timestamp.strftime('%B %d %a')}"++ current_group = {+ 'label': label,+ 'date': response_date,+ 'items': []+ }+ groups.append(current_group)++ if current_group:+ current_group['items'].append(response)++ return groups++ @classmethod+ def find_navigation_items(+ cls, sensor_responses: List[SensorResponse],+ current_sensor_history_id: int+ ) -> tuple:+ """+ Find previous and next sensor responses for navigation.++ Args:+ sensor_responses: List of SensorResponse objects (with sensor_history_id in detail_attrs)+ current_sensor_history_id: SensorHistory ID of current response++ Returns:+ Tuple of (previous_response, next_response), either can be None+ """+ if not sensor_responses or not current_sensor_history_id:+ return (None, None)++ current_response = next(+ (r for r in sensor_responses+ if r.sensor_history_id == current_sensor_history_id),+ None+ )+ if not current_response:+ return (None, None)++ try:+ current_idx = sensor_responses.index(current_response)+ prev_response = sensor_responses[current_idx - 1] if current_idx > 0 else None+ next_response = (+ sensor_responses[current_idx + 1]+ if current_idx < len(sensor_responses) - 1 else None+ )+ return (prev_response, next_response)+ except (ValueError, IndexError):+ return (None, None)++ @classmethod+ 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.++ Args:+ sensor: Sensor to find records for+ current_history_id: ID of current SensorHistory record++ Returns:+ Tuple of (prev_sensor_response, next_sensor_response), either can be None+ """+ if not current_history_id:+ return (None, None)++ try:+ current_record = SensorHistory.objects.get(+ id=current_history_id,+ sensor=sensor,+ has_video_stream=True+ )+ except SensorHistory.DoesNotExist:+ return (None, None)++ # Find previous record (older timestamp)+ prev_record = SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__lt=current_record.response_datetime+ ).order_by('-response_datetime').first()++ prev_sensor_response = None+ if prev_record:+ prev_sensor_response = cls.create_sensor_response_with_history_id(prev_record)++ # Find next record (newer timestamp)+ next_record = SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__gt=current_record.response_datetime+ ).order_by('response_datetime').first()++ next_sensor_response = None+ if next_record:+ next_sensor_response = cls.create_sensor_response_with_history_id(next_record)++ return (prev_sensor_response, next_sensor_response)++ @classmethod+ def build_sensor_history_data_default(cls, sensor: Sensor, sensor_history_id: int = 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+ )++ @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:+ """Build data for specific window preservation."""+ return cls._build_sensor_history_data_internal(+ sensor, sensor_history_id, preserve_window_start, preserve_window_end+ )++ @classmethod+ def build_sensor_history_data_earlier(cls, sensor: Sensor, pivot_timestamp: int) -> EntitySensorHistoryData:+ """Build data for pagination to earlier events."""+ pivot_time = timezone.make_aware(datetime.fromtimestamp(pivot_timestamp))++ # Get 50 events before the pivot time+ history_records = list(SensorHistory.objects.filter(+ 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+ 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+ )++ # Convert to SensorResponse objects+ sensor_responses = []+ for record in history_records:+ sensor_response = cls.create_sensor_response_with_history_id(record)+ sensor_responses.append(sensor_response)++ # Use the most recent record as current (first in the list due to DESC ordering)+ 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)++ # Calculate pagination metadata+ timestamps = [record.response_datetime for record in history_records]+ window_start = min(timestamps)+ 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_newer_records = SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__gt=window_end+ ).exists()++ pagination_metadata = {+ 'has_older_records': has_older_records,+ 'has_newer_records': has_newer_records,+ 'window_start_timestamp': window_start,+ 'window_end_timestamp': window_end,+ }++ # Find navigation items+ current_history_id = current_sensor_response.sensor_history_id if current_sensor_response else None+ prev_sensor_response, next_sensor_response = cls.find_adjacent_records(+ sensor, current_history_id+ )++ return EntitySensorHistoryData(+ sensor_responses=sensor_responses,+ current_sensor_response=current_sensor_response,+ timeline_groups=timeline_groups,+ pagination_metadata=pagination_metadata,+ prev_sensor_response=prev_sensor_response,+ next_sensor_response=next_sensor_response,+ window_start_timestamp=window_start,+ window_end_timestamp=window_end,+ )++ @classmethod+ def build_sensor_history_data_later(cls, sensor: Sensor, pivot_timestamp: int) -> 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(+ 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+ return EntitySensorHistoryData(+ sensor_responses=[],+ current_sensor_response=None,+ timeline_groups=[],+ pagination_metadata={'has_older_records': True, 'has_newer_records': False},+ prev_sensor_response=None,+ next_sensor_response=None+ )++ # Reverse to newest first for display (matching our standard ordering)+ history_records.reverse()++ # Convert to SensorResponse objects+ sensor_responses = []+ for record in history_records:+ sensor_response = cls.create_sensor_response_with_history_id(record)+ sensor_responses.append(sensor_response)++ # Use the most recent record as current (first in the list after reversal)+ 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)++ # Calculate pagination metadata+ timestamps = [record.response_datetime for record in history_records]+ window_start = min(timestamps)+ 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_newer_records = SensorHistory.objects.filter(+ sensor=sensor,+ has_video_stream=True,+ response_datetime__gt=window_end+ ).exists()++ pagination_metadata = {+ 'has_older_records': has_older_records,+ 'has_newer_records': has_newer_records,+ 'window_start_timestamp': window_start,+ 'window_end_timestamp': window_end,+ }++ # Find navigation items+ current_history_id = current_sensor_response.sensor_history_id if current_sensor_response else None+ prev_sensor_response, next_sensor_response = cls.find_adjacent_records(+ sensor, current_history_id+ )++ return EntitySensorHistoryData(+ sensor_responses=sensor_responses,+ current_sensor_response=current_sensor_response,+ timeline_groups=timeline_groups,+ pagination_metadata=pagination_metadata,+ prev_sensor_response=prev_sensor_response,+ next_sensor_response=next_sensor_response,+ window_start_timestamp=window_start,+ window_end_timestamp=window_end,+ )++ @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:+ """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+ )++ @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:+ """+ Build all data needed for the sensor history view.+ High-level method that encapsulates the business logic.++ Args:+ sensor: Sensor to get data for+ 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++ Returns:+ EntitySensorHistoryData containing all view data+ """+ # Determine window strategy: preserve existing timeline or create new one+ preserve_window_bounds = None+ if preserve_window_start and preserve_window_end:+ preserve_window_bounds = (preserve_window_start, preserve_window_end)++ # Convert sensor_history_id to int if it's a string (from URL kwargs)+ if sensor_history_id:+ if isinstance(sensor_history_id, str):+ sensor_history_id = int(sensor_history_id)++ # Smart query strategy based on context and record availability+ if sensor_history_id:+ # Specific record requested+ try:+ current_history_record = SensorHistory.objects.get(+ id=sensor_history_id,+ sensor=sensor,+ has_video_stream=True+ )++ # Check if we should preserve timeline (record is within preserve window)+ if preserve_window_bounds:+ start_time, end_time = preserve_window_bounds+ if start_time <= current_history_record.response_datetime <= end_time:+ # Record is within preserve window - use preserved timeline+ sensor_responses, pagination_metadata = cls.get_timeline_window(+ sensor, preserve_window_bounds=preserve_window_bounds+ )+ else:+ # Record is outside preserve window - center around it+ sensor_responses, pagination_metadata = cls.get_timeline_window(+ sensor, current_history_record+ )+ else:+ # No preserve context - center around the record+ sensor_responses, pagination_metadata = cls.get_timeline_window(+ sensor, current_history_record+ )++ # Find current record in the timeline+ current_sensor_response = next(+ (r for r in sensor_responses+ if r.sensor_history_id == sensor_history_id),+ None+ )+ except SensorHistory.DoesNotExist:+ # Record not found - fall back to most recent window+ sensor_responses, pagination_metadata = cls.get_timeline_window(sensor, None)+ current_sensor_response = sensor_responses[0] if sensor_responses else None+ else:+ # No specific record - get most recent window+ sensor_responses, pagination_metadata = cls.get_timeline_window(sensor, None)+ 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)++ # Find previous and next responses for navigation+ current_history_id = sensor_history_id if sensor_history_id else None++ # If no specific sensor_history_id, try to get it from current_sensor_response+ if not current_history_id and current_sensor_response:+ # Extract sensor_history_id from the current response+ current_history_id = current_sensor_response.sensor_history_id++ prev_sensor_response, next_sensor_response = cls.find_adjacent_records(+ sensor, current_history_id+ )++ return EntitySensorHistoryData(+ sensor_responses=sensor_responses,+ current_sensor_response=current_sensor_response,+ timeline_groups=timeline_groups,+ pagination_metadata=pagination_metadata,+ prev_sensor_response=prev_sensor_response,+ next_sensor_response=next_sensor_response,+ window_start_timestamp=pagination_metadata.get('window_start_timestamp'),+ window_end_timestamp=pagination_metadata.get('window_end_timestamp'),+ )diff --git a/src/hi/apps/console/views.py b/src/hi/apps/console/views.pyindex 9d2b2dd9..b3b3dcb3 100644--- a/src/hi/apps/console/views.py+++ b/src/hi/apps/console/views.py@@ -1,8 +1,11 @@from django.core.exceptions import BadRequestfrom django.http import Http404from django.views.generic import View+from datetime import datetime+from django.utils import timezonefrom hi.apps.entity.models import Entity+from hi.apps.sense.models import Sensorfrom hi.integrations.integration_manager import IntegrationManagerfrom hi.enums import ViewType@@ -11,6 +14,7 @@ from hi.hi_grid_view import HiGridViewfrom .constants import ConsoleConstantsfrom .console_helper import ConsoleSettingsHelper+from .video_stream_browsing_helper import VideoStreamBrowsingHelperclass EntityVideoStreamView( HiGridView ):@@ -39,13 +43,125 @@ class EntityVideoStreamView( HiGridView ):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)++ request.view_parameters.view_type = ViewType.ENTITY_VIDEO_STREAM+ request.view_parameters.to_session( request )+ return {+ 'entity': entity,+ 'video_sensor': video_sensor, # May be None if no video sensors+ }+++class BaseEntityVideoSensorHistoryView( HiGridView ):+ """Base view for browsing sensor history records with video streams."""++ def get_main_template_name( self ) -> str:+ return 'console/panes/entity_video_sensor_history.html'++ 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.')++ # 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)+request.view_parameters.view_type = ViewType.ENTITY_VIDEO_STREAMrequest.view_parameters.to_session( request )+return {'entity': entity,+ 'sensor': sensor,+ 'sensor_history_data': sensor_history_data,}++ def get_sensor_history_data(self, sensor, request, **kwargs):+ """Override in subclasses to provide specific sensor history data building logic."""+ raise NotImplementedError("Subclasses must implement get_sensor_history_data")+++class EntityVideoSensorHistoryView( BaseEntityVideoSensorHistoryView ):+ """Default view for browsing sensor history records with video streams."""++ def get_sensor_history_data(self, sensor, request, **kwargs):+ """Get default sensor history data or handle window context."""+ sensor_history_id = kwargs.get('sensor_history_id')+ window_start = kwargs.get('window_start')+ window_end = kwargs.get('window_end')++ if window_start and window_end:+ try:+ preserve_window_start = timezone.make_aware(+ datetime.fromtimestamp(int(window_start))+ )+ preserve_window_end = timezone.make_aware(+ datetime.fromtimestamp(int(window_end))+ )+ return VideoStreamBrowsingHelper.build_sensor_history_data_with_window(+ sensor, sensor_history_id, preserve_window_start, preserve_window_end+ )+ except (ValueError, OSError):+ # Invalid timestamp format - fall back to default+ pass++ # Default behavior+ return VideoStreamBrowsingHelper.build_sensor_history_data_default(+ sensor, sensor_history_id+ )++class EntityVideoSensorHistoryEarlierView( BaseEntityVideoSensorHistoryView ):+ """View for browsing earlier sensor history records (pagination)."""++ def get_sensor_history_data(self, sensor, request, **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.')++ try:+ return VideoStreamBrowsingHelper.build_sensor_history_data_earlier(+ sensor, int(timestamp)+ )+ except (ValueError, TypeError):+ raise BadRequest('Invalid timestamp format.')+++class EntityVideoSensorHistoryLaterView( BaseEntityVideoSensorHistoryView ):+ """View for browsing later sensor history records (pagination)."""++ def get_sensor_history_data(self, sensor, request, **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.')+ try:+ return VideoStreamBrowsingHelper.build_sensor_history_data_later(+ sensor, int(timestamp)+ )+ except (ValueError, TypeError):+ raise BadRequest('Invalid timestamp format.')++class ConsoleLockView( View ):def post( self, request, *args, **kwargs ):diff --git a/src/hi/apps/event/edit/forms.py b/src/hi/apps/event/edit/forms.pyindex c43e3189..ddc526c6 100644--- a/src/hi/apps/event/edit/forms.py+++ b/src/hi/apps/event/edit/forms.py@@ -27,7 +27,7 @@ class EventDefinitionForm( forms.ModelForm ):)event_type_str = forms.ChoiceField(- label = 'Event Type',+ label = 'Trigger Type',choices = EventType.choices,initial = EventType.default_value(),required = True,diff --git a/src/hi/apps/event/models.py b/src/hi/apps/event/models.pyindex 35a44cca..0c41fc13 100644--- a/src/hi/apps/event/models.py+++ b/src/hi/apps/event/models.py@@ -17,7 +17,7 @@ class EventDefinition( IntegrationDetailsModel ):max_length = 64,)event_type_str = models.CharField(- 'Event Type',+ 'Trigger Type',max_length = 32,null = False, blank = False,)@@ -26,7 +26,7 @@ class EventDefinition( IntegrationDetailsModel ):# need to satisfied.#event_window_secs = models.PositiveIntegerField(- 'Event Window Secs',+ 'Trigger Window Secs',)# Rate limits how many events will be generated for this@@ -52,8 +52,8 @@ class EventDefinition( IntegrationDetailsModel ):)class Meta:- verbose_name = 'Event Definition'- verbose_name_plural = 'Event Definitions'+ verbose_name = 'Trigger Definition'+ verbose_name_plural = 'Trigger Definitions'@propertydef event_type(self):@@ -70,7 +70,7 @@ class EventClause( models.Model ):event_definition = models.ForeignKey(EventDefinition,related_name = 'event_clauses',- verbose_name = 'Event Definition',+ verbose_name = 'Trigger Definition',on_delete = models.CASCADE,)entity_state = models.ForeignKey(@@ -95,8 +95,8 @@ class EventClause( models.Model ):)class Meta:- verbose_name = 'Event Clause'- verbose_name_plural = 'Event Clauses'+ verbose_name = 'Trigger Clause'+ verbose_name_plural = 'Trigger Clauses'class AlarmAction( models.Model ):@@ -104,7 +104,7 @@ class AlarmAction( models.Model ):event_definition = models.ForeignKey(EventDefinition,related_name = 'alarm_actions',- verbose_name = 'Event Definition',+ verbose_name = 'Trigger Definition',on_delete = models.CASCADE,)security_level_str = models.CharField(@@ -165,7 +165,7 @@ class ControlAction( models.Model ):event_definition = models.ForeignKey(EventDefinition,related_name = 'control_actions',- verbose_name = 'Event Definition',+ verbose_name = 'Trigger Definition',on_delete = models.CASCADE,)controller = models.ForeignKey(@@ -199,7 +199,7 @@ class EventHistory( models.Model ):event_definition = models.ForeignKey(EventDefinition,related_name = 'history',- verbose_name = 'Event Definition',+ verbose_name = 'Trigger Definition',on_delete = models.CASCADE,)event_datetime = models.DateTimeField(@@ -208,6 +208,6 @@ class EventHistory( models.Model ):)class Meta:- verbose_name = 'Event History'- verbose_name_plural = 'Event History'+ verbose_name = 'Trigger History'+ verbose_name_plural = 'Trigger History'ordering = [ '-event_datetime' ]diff --git a/src/hi/apps/event/templates/event/edit/modals/event_definition_add.html b/src/hi/apps/event/templates/event/edit/modals/event_definition_add.htmlindex 756e9657..233d795d 100644--- a/src/hi/apps/event/templates/event/edit/modals/event_definition_add.html+++ b/src/hi/apps/event/templates/event/edit/modals/event_definition_add.html@@ -8,7 +8,7 @@{% endblock %}{% block title_text %}-New Event Rule+New Trigger Rule{% endblock %}{% block body %}diff --git a/src/hi/apps/event/templates/event/edit/modals/event_definition_delete.html b/src/hi/apps/event/templates/event/edit/modals/event_definition_delete.htmlindex a0eacaeb..e277a942 100644--- a/src/hi/apps/event/templates/event/edit/modals/event_definition_delete.html+++ b/src/hi/apps/event/templates/event/edit/modals/event_definition_delete.html@@ -8,12 +8,12 @@{% endblock %}{% block title_text %}-Delete Event Rule?+Delete Trigger Rule?{% endblock %}{% block body %}<p>-Please confirm that you want to delete this event rule.+Please confirm that you want to delete this trigger rule.</p><p class="lead"><ul>diff --git a/src/hi/apps/event/templates/event/edit/modals/event_definition_edit.html b/src/hi/apps/event/templates/event/edit/modals/event_definition_edit.htmlindex 86e1bb1a..bc28838e 100644--- a/src/hi/apps/event/templates/event/edit/modals/event_definition_edit.html+++ b/src/hi/apps/event/templates/event/edit/modals/event_definition_edit.html@@ -8,7 +8,7 @@{% endblock %}{% block title_text %}-Edit Event Rule+Edit Trigger Rule{% endblock %}{% block body %}diff --git a/src/hi/apps/event/templates/event/modals/event_history.html b/src/hi/apps/event/templates/event/modals/event_history.htmlindex ffc6d9ce..fd4849ee 100644--- a/src/hi/apps/event/templates/event/modals/event_history.html+++ b/src/hi/apps/event/templates/event/modals/event_history.html@@ -1,11 +1,11 @@{% extends "modals/action_done.html" %}{% block title_text %}-Event History+Trigger History{% endblock %}{% block body %}-<h5>Event History</h5>+<h5>Trigger History</h5>{% include "event/panes/event_history_list.html" with event_history_list=event_history_list %}{% include "common/panes/pagination.html" with pagination=pagination %}{% endblock %}diff --git a/src/hi/apps/event/templates/event/panes/event_definitions.html b/src/hi/apps/event/templates/event/panes/event_definitions.htmlindex c7f0b8ef..d0c75c8f 100644--- a/src/hi/apps/event/templates/event/panes/event_definitions.html+++ b/src/hi/apps/event/templates/event/panes/event_definitions.html@@ -3,7 +3,7 @@{% block config_content %}<div class="container-fluid"><div class="d-flex justify-content-between my-1">- <div class="h3">Event Rules</div>+ <div class="h3">Trigger Rules</div><div><a role="button" class="btn btn-primary"href="{% url 'event_definition_add' %}"diff --git a/src/hi/apps/event/templates/event/panes/event_history_list.html b/src/hi/apps/event/templates/event/panes/event_history_list.htmlindex 576f16ba..a3613047 100644--- a/src/hi/apps/event/templates/event/panes/event_history_list.html+++ b/src/hi/apps/event/templates/event/panes/event_history_list.html@@ -6,7 +6,7 @@<thead><tr><th>Timestamp</th>- <th>Event Name</th>+ <th>Trigger Name</th></tr></thead><tbody>diff --git a/src/hi/apps/sense/tests/synthetic_data.py b/src/hi/apps/sense/tests/synthetic_data.pynew file mode 100644index 00000000..ef21f780--- /dev/null+++ b/src/hi/apps/sense/tests/synthetic_data.py@@ -0,0 +1,359 @@+"""+Synthetic data generators for testing sensor-related functionality.+These generators create mock/synthetic data that can be reused across+tests and development scenarios.+"""++from datetime import datetime, timedelta+from typing import Dict, List, Optional, Tuple++from django.utils import timezone++from hi.apps.sense.models import Sensor, SensorHistory+from hi.apps.sense.transient_models import SensorResponse+from hi.integrations.transient_models import IntegrationKey+++class SensorHistorySyntheticData:+ """Generate synthetic sensor response data for testing and development."""++ @staticmethod+ def create_mock_sensor_responses(+ sensor: Sensor,+ num_items: int = 15,+ days_span: int = 3,+ current_id: Optional[int] = None+ ) -> List[SensorResponse]:+ """+ Create mock sensor response data for demonstration and testing.++ Args:+ sensor: The sensor to create responses for+ num_items: Number of response items to create+ days_span: Number of days to span the responses over+ current_id: Optional ID to include in the generated items++ Returns:+ List of SensorResponse objects+ """+ now = datetime.now()+ mock_responses = []++ for i in range(num_items):+ # Create timestamps with varying intervals to simulate realistic data+ if i < 5:+ # Recent items within last few hours+ timestamp = now - timedelta(hours=i * 2, minutes=i * 15)+ elif i < 10:+ # Yesterday's items+ timestamp = now - timedelta(days=1, hours=i - 5, minutes=i * 10)+ else:+ # Older items distributed over remaining days+ days_offset = 2 + (i - 10) * (days_span - 2) / max(1, num_items - 10)+ timestamp = now - timedelta(days=days_offset, hours=(i - 10) * 3)++ # Simulate different activity patterns+ is_active = i % 3 == 0 # Every third item is "active"++ # Create mock integration key+ integration_key = IntegrationKey(+ integration_id='mock_integration',+ integration_name=f'sensor_{sensor.id}_response_{i}'+ )++ # Create additional attributes for detail_attrs+ mock_sensor_history_id = 1000 + i # Mock SensorHistory ID for testing+ detail_attrs = {+ 'sensor_history_id': str(mock_sensor_history_id), # Mock SensorHistory ID+ 'duration_seconds': str(60 + (i * 15)), # Varying durations+ 'details': f'Motion detected in {sensor.entity_state.entity.name}' if is_active else 'No activity',+ }++ sensor_response = SensorResponse(+ integration_key=integration_key,+ value='active' if is_active else 'idle',+ timestamp=timestamp,+ sensor=sensor,+ detail_attrs=detail_attrs,+ source_image_url=f'/static/mock/video_{i}.mp4' if is_active else None,+ has_video_stream=True,+ )++ mock_responses.append(sensor_response)++ return mock_responses++ @staticmethod+ def create_mock_sensor_response(+ sensor: Sensor,+ value: str = 'active',+ timestamp: Optional[datetime] = None,+ has_video: bool = True+ ) -> Dict:+ """+ Create a single mock sensor response.++ Args:+ sensor: The sensor that generated this response+ value: The sensor value (e.g., 'active', 'idle')+ timestamp: Response timestamp (defaults to now)+ has_video: Whether this response has associated video++ Returns:+ Dictionary representing a mock sensor response+ """+ if timestamp is None:+ timestamp = datetime.now()++ return {+ 'sensor': sensor,+ 'value': value,+ 'timestamp': timestamp,+ 'has_video_stream': has_video,+ 'details': f'{value.capitalize()} state detected',+ 'source_image_url': f'/static/mock/snapshot_{timestamp.timestamp()}.jpg' if has_video else None,+ }++ @staticmethod+ def create_timeline_test_data(sensor: Sensor, dense_events: bool = True) -> List[Dict]:+ """+ Create test data specifically for timeline grouping scenarios.+ Supports both dense (many events) and sparse (few events) patterns.++ Args:+ sensor: The sensor to create test data for+ dense_events: If True, creates many events today; if False, creates sparse events++ Returns:+ List of mock sensor history items for timeline testing+ """+ now = datetime.now()+ mock_items = []+ item_counter = 1000++ if dense_events:+ # Create dense events today (3 events per hour for 12 hours = 36 events)+ # Simplified from nested loops to single loop with calculation+ for event_num in range(36):+ hour = event_num // 3 # 0-11 hours+ minute_offset = (event_num % 3) * 20 # 0, 20, 40 minutes++ timestamp = now.replace(hour=hour, minute=minute_offset, second=0, microsecond=0)+ mock_items.append({+ 'id': item_counter + event_num,+ 'sensor': sensor,+ 'value': 'active' if minute_offset == 0 else 'idle',+ 'timestamp': timestamp,+ 'duration_seconds': 120,+ 'has_video_stream': True,+ 'details': f'Event at {timestamp.strftime("%H:%M")}',+ })+ item_counter += 36++ # Add yesterday's events (always sparse for contrast)+ yesterday = now - timedelta(days=1)+ yesterday_hours = [8, 14, 20]+ for i, hour in enumerate(yesterday_hours):+ timestamp = yesterday.replace(hour=hour, minute=0, second=0, microsecond=0)+ mock_items.append({+ 'id': item_counter + i,+ 'sensor': sensor,+ 'value': 'active',+ 'timestamp': timestamp,+ 'duration_seconds': 180,+ 'has_video_stream': True,+ 'details': f'Yesterday event at {hour}:00',+ })+ item_counter += len(yesterday_hours)++ # Add older events+ older_days = [3, 5, 7]+ for i, days_ago in enumerate(older_days):+ timestamp = now - timedelta(days=days_ago, hours=12)+ mock_items.append({+ 'id': item_counter + i,+ 'sensor': sensor,+ 'value': 'idle',+ 'timestamp': timestamp,+ 'duration_seconds': 90,+ 'has_video_stream': True,+ 'details': f'Event {days_ago} days ago',+ })++ # Sort by timestamp descending (most recent first)+ mock_items.sort(key=lambda x: x['timestamp'], reverse=True)++ return mock_items++ @staticmethod+ def create_timeline_test_scenario(+ sensor: Sensor,+ scenario_type: str = 'preservation',+ total_records: int = None,+ window_size: int = None,+ **kwargs+ ):+ """+ Unified method for creating timeline test scenarios.++ Args:+ sensor: The sensor to create test data for+ scenario_type: Type of scenario - 'preservation', 'boundary', or 'pagination'+ total_records: Override default record count for scenario+ window_size: Override default window size for scenario+ **kwargs: Additional scenario-specific parameters++ Returns:+ Scenario-specific tuple of test data and metadata++ Scenario Types:+ - 'preservation': Returns (records, window_start, window_end)+ - 'boundary': Returns (all_records, inside_record, outside_record, window_start, window_end)+ - 'pagination': Returns (records, middle_record_index)+ """+ base_time = timezone.now().replace(minute=0, second=0, microsecond=0)++ if scenario_type == 'preservation':+ # Timeline preservation scenario+ record_count = total_records or 10+ records = []++ for hours_ago in range(record_count):+ timestamp = base_time - timezone.timedelta(hours=hours_ago)+ record = SensorHistory.objects.create(+ sensor=sensor,+ value='active' if hours_ago % 3 == 0 else 'idle',+ response_datetime=timestamp,+ has_video_stream=True,+ details=f'{{"event_id": "{hours_ago}", "duration_seconds": "{60 + hours_ago * 15}"}}'+ )+ records.append(record)++ # Define window boundaries (hours 2-6 ago)+ window_start = base_time - timezone.timedelta(hours=6)+ window_end = base_time - timezone.timedelta(hours=2)++ return records, window_start, window_end++ elif scenario_type == 'boundary':+ # Window boundary testing scenario+ record_count = total_records or 8+ all_records = []++ for hours_ago in range(record_count):+ timestamp = base_time - timezone.timedelta(hours=hours_ago)+ record = SensorHistory.objects.create(+ sensor=sensor,+ value=f'event_{hours_ago}',+ response_datetime=timestamp,+ has_video_stream=True,+ details=f'{{"hours_ago": "{hours_ago}"}}'+ )+ all_records.append(record)++ # Define window boundaries (3-5 hours ago)+ window_start = base_time - timezone.timedelta(hours=5)+ window_end = base_time - timezone.timedelta(hours=3)++ # Identify specific records for testing+ record_inside_window = all_records[4] # 4 hours ago - inside window+ record_outside_window = all_records[1] # 1 hour ago - outside window++ return all_records, record_inside_window, record_outside_window, window_start, window_end++ elif scenario_type == 'pagination':+ # Pagination testing scenario+ record_count = total_records or 20+ window = window_size or 5 # Default window size+ records = []++ for i in range(record_count):+ timestamp = base_time - timezone.timedelta(hours=i)+ record = SensorHistory.objects.create(+ sensor=sensor,+ value=f'record_{i}',+ response_datetime=timestamp,+ has_video_stream=True,+ details=f'{{"record_index": "{i}", "window_size": "{window}"}}'+ )+ records.append(record)++ middle_index = record_count // 2+ return records, middle_index++ else:+ raise ValueError(f"Unknown scenario_type: {scenario_type}. Must be 'preservation', 'boundary', or 'pagination'.")++ @staticmethod+ def create_timezone_aware_sensor_responses(+ sensor: Sensor,+ num_responses: int = 5,+ start_time: Optional[datetime] = None,+ time_interval_hours: int = 1+ ) -> List[SensorResponse]:+ """+ Create timezone-aware sensor responses for testing datetime operations.++ Args:+ sensor: The sensor to create responses for+ num_responses: Number of responses to create+ start_time: Starting timestamp (defaults to now)+ time_interval_hours: Hours between each response++ Returns:+ List of timezone-aware SensorResponse objects+ """+ if start_time is None:+ start_time = timezone.now()++ # Ensure start_time is timezone-aware+ if start_time.tzinfo is None:+ start_time = timezone.make_aware(start_time)++ responses = []+ for i in range(num_responses):+ timestamp = start_time - timezone.timedelta(hours=i * time_interval_hours)+ integration_key = IntegrationKey(+ integration_id='test_integration',+ integration_name=f'sensor_{sensor.id}_response_{i}'+ )++ response = SensorResponse(+ integration_key=integration_key,+ value='active' if i % 2 == 0 else 'idle',+ timestamp=timestamp,+ sensor=sensor,+ detail_attrs={+ 'sensor_history_id': str(1000 + i),+ 'duration_seconds': str(90 + i * 30),+ 'details': f'Test event {i} - {timestamp.strftime("%Y-%m-%d %H:%M:%S %Z")}'+ },+ has_video_stream=True+ )+ responses.append(response)++ return responses++ # Legacy methods for backward compatibility - use create_timeline_test_scenario instead+ @staticmethod+ def create_timeline_preservation_test_data(sensor: Sensor) -> Tuple[List[SensorHistory], datetime, datetime]:+ """Legacy method - use create_timeline_test_scenario(scenario_type='preservation') instead."""+ return SensorHistorySyntheticData.create_timeline_test_scenario(sensor, 'preservation')++ @staticmethod+ def create_window_boundary_test_scenario(+ sensor: Sensor+ ) -> Tuple[List[SensorHistory], SensorHistory, SensorHistory, datetime, datetime]:+ """Legacy method - use create_timeline_test_scenario(scenario_type='boundary') instead."""+ return SensorHistorySyntheticData.create_timeline_test_scenario(sensor, 'boundary')++ @staticmethod+ def create_pagination_test_data(+ sensor: Sensor,+ total_records: int = 20,+ window_size: int = 5+ ) -> Tuple[List[SensorHistory], int]:+ """Legacy method - use create_timeline_test_scenario(scenario_type='pagination') instead."""+ return SensorHistorySyntheticData.create_timeline_test_scenario(+ sensor, 'pagination', total_records=total_records, window_size=window_size+ )diff --git a/src/hi/apps/sense/transient_models.py b/src/hi/apps/sense/transient_models.pyindex 081cffe3..17ebdd5b 100644--- a/src/hi/apps/sense/transient_models.py+++ b/src/hi/apps/sense/transient_models.py@@ -19,6 +19,7 @@ class SensorResponse:detail_attrs : Dict[ str, str ] = Nonesource_image_url : str = Nonehas_video_stream : bool = False+ sensor_history_id : int = None # Core Django SensorHistory primary keydef __str__(self):return json.dumps( self.to_dict() )@@ -41,6 +42,7 @@ class SensorResponse:'detail_attrs': self.detail_attrs,'source_image_url': self.source_image_url,'has_video_stream': self.has_video_stream,+ 'sensor_history_id': self.sensor_history_id,}def to_sensor_history(self):diff --git a/src/hi/services/zoneminder/tests/test_zm_manager.py b/src/hi/services/zoneminder/tests/test_zm_manager.pyindex 2e7cde58..3fd02579 100644--- a/src/hi/services/zoneminder/tests/test_zm_manager.py+++ b/src/hi/services/zoneminder/tests/test_zm_manager.py@@ -578,11 +578,17 @@ class TestZoneMinderManagerUrlGeneration(TestCase):def test_get_event_video_stream_url(self):"""Test event video stream URL generation"""event_id = 456- expected_url = 'https://test.com/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event=456'+ expected_base_url = 'https://test.com/zm/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event=456&_t='result = self.manager.get_event_video_stream_url(event_id)- self.assertEqual(result, expected_url)+ # Check that URL starts with expected base and includes timestamp+ self.assertTrue(result.startswith(expected_base_url))++ # Extract and validate timestamp parameter+ timestamp_part = result[len(expected_base_url):]+ self.assertTrue(timestamp_part.isdigit())+ self.assertGreater(int(timestamp_part), 0)class TestZoneMinderManagerBooleanConversion(TestCase):diff --git a/src/hi/services/zoneminder/zm_manager.py b/src/hi/services/zoneminder/zm_manager.pyindex 82769bac..1f0005c6 100644--- a/src/hi/services/zoneminder/zm_manager.py+++ b/src/hi/services/zoneminder/zm_manager.py@@ -249,4 +249,7 @@ class ZoneMinderManager( Singleton ):return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&monitor={monitor_id}'def get_event_video_stream_url( self, event_id : int ):- return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event={event_id}'+ # Add timestamp for cache busting to help with connection management+ import time+ timestamp = int(time.time())+ return f'{self.zm_client.portal_url}/cgi-bin/nph-zms?mode=jpeg&scale=100&rate=5&maxfps=5&replay=single&source=event&event={event_id}&_t={timestamp}'diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex 32579f71..ee3b84c4 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -248,6 +248,7 @@ PIPELINE = {'js/settings.js','js/audio.js','js/attribute-changes.js',+ 'js/video-timeline.js',),'output_filename': 'js/js_before_content.js',},diff --git a/src/hi/static/css/main.css b/src/hi/static/css/main.cssindex 8e3f1fd7..b73515c1 100644--- a/src/hi/static/css/main.css+++ b/src/hi/static/css/main.css@@ -776,3 +776,600 @@ form[data-dirty] {color: var(--primary-color);padding: 0 0.25rem;}++/* ==========================================+ Video Interface - Camera Event History+ ========================================== */++/* Timeline Container */+.timeline-container {+ max-height: 600px;+ overflow-y: auto;+ background-color: var(--white);+ border-right: 1px solid var(--line-color);+ padding-right: 1rem;+}++/* Timeline Groups */+.timeline-group-label {+ color: var(--primary-color);+ padding: 8px 0;+ border-bottom: 2px solid var(--primary-color);+ margin-bottom: 12px;+ font-weight: 600;+ font-size: 0.875rem;+ text-transform: uppercase;+ letter-spacing: 0.5px;+}++/* Timeline Items */+.timeline-item {+ padding: 10px;+ margin-bottom: 6px;+ border-left: 3px solid var(--line-color);+ transition: all 0.2s ease;+ border-radius: 0 4px 4px 0;+}++.timeline-item:hover {+ background-color: var(--edit-primary-bg-color);+ border-left-color: var(--primary-highlight-color);+ transform: translateX(2px);+}++.timeline-item.active {+ background-color: var(--edit-primary-bg-color);+ border-left-color: var(--secondary-color);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);+}++.timeline-item .time {+ font-weight: 500;+ color: var(--black);+}++.timeline-item.active .time {+ color: var(--primary-color);+}++/* Video Container */+.video-container {+ border: 2px solid var(--line-color);+ border-radius: 8px;+ overflow: hidden;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);+ background-color: var(--black);+}++.video-container img {+ display: block;+ width: 100%;+ height: auto;+}++/* Event Header */+.response-header {+ border-bottom: 1px solid var(--line-color);+ padding-bottom: 0.75rem;+}++.response-header h6 {+ color: var(--primary-color);+ font-weight: 600;+ margin-bottom: 0.25rem;+}++/* Event Details Expansion Bar */+.response-details-bar {+ border-top: 1px solid var(--line-color);+ margin-top: 1.5rem;+}++.details-expander {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.75rem 1rem;+ background: linear-gradient(to bottom, #f8f9fa, #f1f3f5);+ text-decoration: none;+ color: #6c757d;+ transition: all 0.2s ease;+ cursor: pointer;+}++.details-expander:hover {+ background: #e9ecef;+ text-decoration: none;+ color: #495057;+}++.details-expander:focus {+ outline: 2px solid var(--primary-color);+ outline-offset: -2px;+ text-decoration: none;+}++.details-label {+ font-size: 0.9rem;+ font-weight: 500;+ letter-spacing: 0.5px;+ text-transform: uppercase;+}++.details-chevron {+ font-size: 0.8rem;+ transition: transform 0.2s ease;+}++.details-expander[aria-expanded="true"] .details-chevron {+ transform: rotate(180deg);+}++.details-content {+ padding: 1rem;+ background-color: #f8f9fa;+ border-top: 1px solid #e9ecef;+}++.detail-row {+ display: grid;+ grid-template-columns: minmax(120px, 1fr) 2fr;+ gap: 1rem;+ padding: 0.5rem 0;+ border-bottom: 1px solid #e9ecef;+}++.detail-row:last-child {+ border-bottom: none;+}++.detail-label {+ font-size: 0.85rem;+ color: #6c757d;+ font-weight: 500;+}++.detail-value {+ font-size: 0.85rem;+ color: #212529;+ word-break: break-word;+}++/* Timeline Pagination */+.timeline-pagination-top,+.timeline-pagination-bottom {+ padding: 0.25rem;+}++.timeline-pagination-top .btn,+.timeline-pagination-bottom .btn {+ font-size: 0.8rem;+ padding: 0.4rem;+ transition: all 0.2s ease;+ border-color: var(--primary-color);+ color: var(--primary-color);+}++.timeline-pagination-top .btn:hover,+.timeline-pagination-bottom .btn:hover {+ transform: translateY(-1px);+ background-color: var(--primary-color);+ color: var(--on-primary-color);+}+++/* ==========================================+ Loading States & Error Handling+ ========================================== */++/* Video Placeholder/Error State */+.video-placeholder {+ min-height: 400px;+ background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);+ border-radius: 8px;+ position: relative;+}++.video-placeholder-icon {+ color: var(--primary-color);+ opacity: 0.5;+}++.video-placeholder h5 {+ color: var(--primary-color);+ font-weight: 600;+}++.video-placeholder p {+ color: var(--black);+ opacity: 0.8;+}++/* Loading Animation for Video */+.video-container.loading {+ position: relative;+ min-height: 400px;+}++.video-container.loading::before {+ content: '';+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);+ background-size: 200% 100%;+ animation: loading 1.5s infinite;+ border-radius: 8px;+}++.video-container.loading::after {+ content: 'Loading video stream...';+ position: absolute;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ color: var(--primary-color);+ font-weight: 500;+}++@keyframes loading {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}++/* Error State for Timeline */+.timeline-container.error {+ background-color: var(--edit-secondary-bg-color);+ padding: 1rem;+ text-align: center;+}++.timeline-container.error::before {+ content: '⚠ Unable to load event history';+ color: var(--error-color);+ font-weight: 600;+}++/* ==========================================+ Accessibility & Keyboard Navigation+ ========================================== */++/* Focus indicators for keyboard navigation */+.timeline-item a:focus {+ outline: 2px solid var(--secondary-color);+ outline-offset: 2px;+ border-radius: 4px;+}+++/* High contrast mode support */+@media (prefers-contrast: high) {+ .timeline-item.active {+ border-left-width: 4px;+ font-weight: bold;+ }++ .timeline-group-label {+ border-bottom-width: 3px;+ }+}++/* Reduced motion support */+@media (prefers-reduced-motion: reduce) {+ .timeline-item,+ .video-container.loading::before {+ transition: none;+ animation: none;+ }+}++/* Screen reader only content */+.sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++/* ==========================================+ Responsive Design - Landscape Optimized+ ========================================== */++/* Small landscape devices (landscape phones, 568px and up) */+@media (min-width: 568px) and (orientation: landscape) {+ .timeline-container {+ max-height: 400px; /* Reduce height for smaller landscape screens */+ }+}++/* Medium landscape devices (tablets, 768px and up) */+@media (min-width: 768px) and (orientation: landscape) {+ .timeline-container {+ max-height: 500px;+ }++ /* Optimize column widths for landscape tablets */+ .entity-video-sensor-history .col-md-3 {+ flex: 0 0 25%;+ max-width: 25%;+ }++ .entity-video-sensor-history .col-md-9 {+ flex: 0 0 75%;+ max-width: 75%;+ }+}++/* Large landscape devices (laptops/desktops, 992px and up) */+@media (min-width: 992px) and (orientation: landscape) {+ .timeline-container {+ max-height: 600px;+ }++ /* Wider timeline on larger screens */+ .entity-video-sensor-history .col-md-3 {+ flex: 0 0 20%;+ max-width: 20%;+ }++ .entity-video-sensor-history .col-md-9 {+ flex: 0 0 80%;+ max-width: 80%;+ }+}++/* Extra large landscape devices (large desktops, 1200px and up) */+@media (min-width: 1200px) {+ .video-container {+ max-width: 1000px; /* Limit video size on very large screens */+ margin: 0 auto;+ }+}++/* Landscape-specific optimizations */+@media (orientation: landscape) {+ /* Compact timeline items for landscape */+ .timeline-item {+ padding: 8px;+ margin-bottom: 4px;+ }++ .timeline-group-label {+ padding: 6px 0;+ margin-bottom: 8px;+ }+++ /* Compact details bar in landscape */+ .details-expander {+ padding: 0.5rem 0.75rem;+ }++ .details-content {+ padding: 0.75rem;+ }+}++/* Handle small screens that don't meet minimum requirements */+@media (max-width: 767px) {+ /* Stack detail rows on mobile */+ .detail-row {+ grid-template-columns: 1fr;+ gap: 0.25rem;+ }++ .detail-label {+ font-weight: 600;+ color: #495057;+ }++ .details-expander {+ padding: 0.6rem 0.75rem;+ }++ .details-label {+ font-size: 0.85rem;+ }+ /* Stack layout vertically on very small screens */+ .entity-video-sensor-history .row {+ flex-direction: column;+ }++ .entity-video-sensor-history .col-md-3,+ .entity-video-sensor-history .col-md-9 {+ max-width: 100%;+ width: 100%;+ }++ .timeline-container {+ max-height: 200px;+ margin-bottom: 1rem;+ border-right: none;+ border-bottom: 1px solid var(--line-color);+ }+}++/* Video Interface Header Styles */+.video-interface-header {+ border-bottom: 2px solid #e9ecef;+ padding: 0.75rem;+ margin: -0.75rem -0.75rem 0.75rem -0.75rem;+ border-radius: 0.5rem 0.5rem 0 0;+}++/* Page-specific header backgrounds */+.video-interface-header.current-stream {+ background-color: var(--secondary-color);+ color: var(--on-secondary-color);+ border-bottom-color: var(--secondary-color);+}++.video-interface-header.event-history {+ background-color: var(--tertiary-color);+ color: var(--on-tertiary-color);+ border-bottom-color: var(--tertiary-color);+}++.entity-title {+ color: #343a40;+ font-weight: 600;+ font-size: 1.1rem;+}++.video-interface-header.current-stream .entity-title,+.video-interface-header.event-history .entity-title {+ color: inherit;+}++.last-activity-badge {+ font-size: 0.85rem;+ padding: 0.25rem 0.5rem;+ background-color: #f8f9fa;+ border-radius: 12px;+ border: 1px solid #e9ecef;+}++.video-interface-header.current-stream .last-activity-badge {+ background-color: rgba(255, 255, 255, 0.2);+ border-color: rgba(255, 255, 255, 0.3);+ color: inherit;+}++.video-interface-header.event-history .last-activity-badge {+ background-color: rgba(255, 255, 255, 0.1);+ border-color: rgba(255, 255, 255, 0.2);+ color: inherit;+}++.video-nav-tabs {+ display: flex;+ gap: 0;+}++.video-nav-tab {+ padding: 0.5rem 1rem;+ text-decoration: none;+ color: #6c757d;+ border: 1px solid #dee2e6;+ background-color: #f8f9fa;+ transition: all 0.15s ease-in-out;+ position: relative;+ font-size: 0.9rem;+ font-weight: 500;+ cursor: pointer;+}++.video-nav-tab:first-child {+ border-top-left-radius: 0.375rem;+ border-bottom-left-radius: 0.375rem;+}++.video-nav-tab:last-child {+ border-top-right-radius: 0.375rem;+ border-bottom-right-radius: 0.375rem;+ border-left: none;+}++.video-nav-tab:not(:first-child):not(:last-child) {+ border-left: none;+}++.video-nav-tab:hover:not(.disabled):not(.active) {+ color: #495057;+ background-color: #e9ecef;+ text-decoration: none;+}++.video-nav-tab.active {+ color: #fff;+ background-color: #007bff;+ border-color: #007bff;+ z-index: 1;+}++/* Active tab styling for colored headers */+.video-interface-header.current-stream .video-nav-tab.active {+ background-color: rgba(255, 255, 255, 0.9);+ color: var(--secondary-color);+ border-color: rgba(255, 255, 255, 0.9);+}++.video-interface-header.event-history .video-nav-tab.active {+ background-color: rgba(255, 255, 255, 0.9);+ color: var(--tertiary-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) {+ 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) {+ background-color: rgba(255, 255, 255, 0.2);+ color: rgba(255, 255, 255, 1);+ border-color: rgba(255, 255, 255, 0.3);+}++.video-nav-tab.disabled {+ color: #6c757d;+ background-color: #f8f9fa;+ border-color: #dee2e6;+ cursor: not-allowed;+ opacity: 0.6;+}++/* Responsive adjustments */+@media (max-width: 768px) {+ .video-interface-header .d-flex {+ flex-direction: column;+ align-items: flex-start !important;+ gap: 0.75rem;+ }++ .video-nav-tabs {+ width: 100%;+ justify-content: center;+ }++ .video-nav-tab {+ flex: 1;+ text-align: center;+ font-size: 0.85rem;+ padding: 0.4rem 0.6rem;+ }++ .entity-title {+ font-size: 1rem;+ }++ .last-activity-badge {+ font-size: 0.8rem;+ }+}++@media (max-width: 480px) {+ .video-nav-tab i {+ display: none; /* Hide icons on very small screens */+ }++ .video-nav-tab {+ padding: 0.4rem 0.5rem;+ font-size: 0.8rem;+ }+}diff --git a/src/hi/static/js/video-timeline.js b/src/hi/static/js/video-timeline.jsnew file mode 100644index 00000000..0588cbe8--- /dev/null+++ b/src/hi/static/js/video-timeline.js@@ -0,0 +1,245 @@+// Video Timeline Scrollbar Management+// Handles scroll behavior for the dual-mode camera interface timeline+// Also manages video stream connections to prevent browser connection limit issues++(function() {+ 'use strict';++ // Video Connection Management+ const VideoConnectionManager = {+ currentVideo: null,+ previousVideos: [],+ maxCachedVideos: 3, // Keep a few previous videos cached for back navigation++ registerVideo: function(videoElement) {+ if (!videoElement) return;++ // Clean up old videos before registering new one+ this.cleanupOldVideos();++ // Store reference to current video+ this.currentVideo = videoElement;++ // Add error handling and load event listeners+ videoElement.addEventListener('error', this.handleVideoError.bind(this));+ videoElement.addEventListener('loadstart', this.handleVideoLoadStart.bind(this));+ },++ cleanupOldVideos: function() {+ // If we have a current video, move it to the previous videos cache+ if (this.currentVideo && this.currentVideo.src) {+ this.previousVideos.unshift(this.currentVideo);++ // Keep only the most recent N videos cached+ if (this.previousVideos.length > this.maxCachedVideos) {+ const videosToCleanup = this.previousVideos.splice(this.maxCachedVideos);+ videosToCleanup.forEach(video => this.forceCloseVideo(video));+ }+ }+ },++ forceCloseVideo: function(videoElement) {+ if (!videoElement || !videoElement.src) return;++ try {+ // Create a 1x1 pixel transparent GIF data URL to replace the stream+ const transparentGif = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';++ // Replace the streaming URL with the data URL to close the connection+ videoElement.src = transparentGif;++ // Also set srcset if present+ if (videoElement.srcset) {+ videoElement.srcset = '';+ }++ console.debug('Video connection closed:', videoElement.getAttribute('data-event-id') || 'unknown');+ } catch (e) {+ console.warn('Error closing video connection:', e);+ }+ },++ handleVideoError: function(event) {+ const video = event.target;+ console.warn('Video error for event:', video.getAttribute('data-event-id'), event);++ // If we've hit connection limits, try to free up connections+ if (this.previousVideos.length > 0) {+ console.info('Video error detected, cleaning up old connections...');+ const oldVideo = this.previousVideos.pop();+ this.forceCloseVideo(oldVideo);++ // Try to reload the current video after a brief delay+ setTimeout(() => {+ if (video.src && !video.src.startsWith('data:')) {+ video.load();+ }+ }, 500);+ }+ },++ handleVideoLoadStart: function(event) {+ const video = event.target;+ console.debug('Video loading started for event:', video.getAttribute('data-event-id'));+ },++ // Force cleanup all connections (for page unload)+ cleanup: function() {+ if (this.currentVideo) {+ this.forceCloseVideo(this.currentVideo);+ }+ this.previousVideos.forEach(video => this.forceCloseVideo(video));+ this.previousVideos = [];+ this.currentVideo = null;+ }+ };++ // Video Timeline Scrollbar Management+ const VideoTimelineScrollManager = {+ init: function() {+ this.timeline = document.getElementById('event-timeline');+ if (!this.timeline) return;++ // Handle initial page loads - scroll to active item if needed+ this.handleInitialLoad();++ },++ handleInitialLoad: function() {+ const activeItem = this.timeline.querySelector('.timeline-item.active');+ if (!activeItem) return;++ // Check if coming from live stream+ const fromLive = sessionStorage.getItem('navigatingFromLiveStream');+ if (fromLive) {+ sessionStorage.removeItem('navigatingFromLiveStream');+ // Force scroll to active item - should start at top (case D)+ setTimeout(() => this.scrollToItem(activeItem, 'from-live'), 50);+ } else if (!window.videoTimelineInitialized) {+ // First time loading - center active item (case A)+ window.videoTimelineInitialized = true;+ setTimeout(() => this.scrollToItem(activeItem, 'initial'), 50);+ }+ },+++ scrollToItem: function(item, context) {+ if (!item) return;++ const timeline = this.timeline;+ const timelineRect = timeline.getBoundingClientRect();+ const itemRect = item.getBoundingClientRect();++ const isVisible = (+ itemRect.top >= timelineRect.top &&+ itemRect.bottom <= timelineRect.bottom+ );++ if (context === 'initial') {+ // For initial page loads, center the item (unless already visible)+ if (!isVisible) {+ const itemTop = item.offsetTop;+ const timelineHeight = timeline.clientHeight;+ const itemHeight = item.clientHeight;++ const targetScroll = itemTop - (timelineHeight / 2) + (itemHeight / 2);++ timeline.scrollTo({+ top: Math.max(0, targetScroll),+ behavior: 'auto'+ });+ }+ } else if (context === 'from-live') {+ // For "Recent Event" button, scroll to top (case D)+ timeline.scrollTo({+ top: 0,+ behavior: 'auto'+ });+ } else {+ // For button navigation, minimal scroll to bring into view+ if (!isVisible) {+ const itemTop = item.offsetTop;+ const itemHeight = item.clientHeight;+ const timelineHeight = timeline.clientHeight;+ const margin = 20; // Small margin from edge++ let targetScroll;++ if (itemRect.top < timelineRect.top) {+ // Item is above visible area - scroll up to show it near top+ targetScroll = itemTop - margin;+ } else {+ // Item is below visible area - scroll down to show it near bottom+ targetScroll = itemTop - timelineHeight + itemHeight + margin;+ }++ timeline.scrollTo({+ top: Math.max(0, targetScroll),+ behavior: 'smooth'+ });+ }+ }+ },++ handleAsyncUpdate: function() {+ // Register the new video element with connection manager+ this.registerCurrentVideo();+ },++ registerCurrentVideo: function() {+ // Find the main video element in the video detail container+ const videoElement = document.querySelector('.video-container img');+ if (videoElement && videoElement.src && !videoElement.src.startsWith('data:')) {+ // Set event ID for debugging if available+ const eventId = this.extractEventIdFromUrl(videoElement.src);+ if (eventId) {+ videoElement.setAttribute('data-event-id', eventId);+ }++ VideoConnectionManager.registerVideo(videoElement);+ }+ },++ extractEventIdFromUrl: function(url) {+ // Extract event ID from ZoneMinder URL pattern: ...&event=12345+ const match = url.match(/[&?]event=(\d+)/);+ return match ? match[1] : null;+ }+ };++ // Initialize when DOM is ready+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => {+ VideoTimelineScrollManager.init();+ VideoTimelineScrollManager.registerCurrentVideo();+ });+ } else {+ VideoTimelineScrollManager.init();+ VideoTimelineScrollManager.registerCurrentVideo();+ }++ // Hook into antinode.js updates+ if (typeof addAfterAsyncRenderFunction === 'function') {+ addAfterAsyncRenderFunction(() => VideoTimelineScrollManager.handleAsyncUpdate());+ } else {+ const original = window.handlePostAsyncUpdate;+ window.handlePostAsyncUpdate = function() {+ if (original) original();+ VideoTimelineScrollManager.handleAsyncUpdate();+ };+ }++ // Cleanup on page unload to free connections+ window.addEventListener('beforeunload', () => {+ VideoConnectionManager.cleanup();+ });++ // Also cleanup on navigation away from video pages+ window.addEventListener('pagehide', () => {+ VideoConnectionManager.cleanup();+ });++ // Expose for potential external use and debugging+ window.VideoTimelineScrollManager = VideoTimelineScrollManager;+ window.VideoConnectionManager = VideoConnectionManager;+})();\ No newline at end of file