Skip to content

Add object detection, tracking, mobile notifications, and search to any security camera.

Ui2 (#96)

Rory Clear3593f7b5bf9f
diff --git a/cameraview.html b/cameraview.html
deleted file mode 100644
index 2040906..0000000
--- a/cameraview.html
+++ /dev/null
@@ -1,1293 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
- <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet">
- <style>
- .polygon-point {
- transition: all 0.2s ease;
- }
-
- .polygon-point:hover {
- transform: scale(1.2);
- box-shadow: 0 0 5px rgba(0,0,0,0.5);
- }
-
- .polygon-line path {
- transition: all 0.2s ease;
- }
-
- body {
- font-family: 'Inter', sans-serif;
- margin: 0;
- padding: 0;
- background-color: #f9f9f9;
- color: #333;
- }
-
- .checkbox-container {
- display: grid;
- grid-template-columns: auto auto;
- gap: 8px 16px;
- max-height: 200px;
- overflow-y: auto;
- margin: 0 auto;
- padding: 8px;
- justify-content: center;
- }
-
- .checkbox-container input[type="checkbox"] {
- margin: 0;
- width: 16px;
- height: 16px;
- }
-
- .checkbox-item {
- display: flex;
- align-items: center;
- gap: 8px;
- margin-left: 10px;
- }
-
- .checkbox-item input[type="checkbox"] {
- margin: 0;
- transform: scale(1.2);
- }
-
- .container {
- max-width: 900px;
- margin: 0 auto;
- padding: 20px;
- }
-
- video {
- width: 100%;
- border-radius: 12px;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
- margin-bottom: 20px;
- }
-
- .date-picker-container {
- display: flex;
- justify-content: center;
- align-items: center;
- gap: 10px;
- margin: 20px 0;
- flex-wrap: wrap;
- }
-
- .date-picker-container input[type="date"],
- .date-picker-container button {
- height: 40px;
- font-size: 0.95rem;
- padding: 6px 12px;
- border-radius: 6px;
- border: 1px solid #ccc;
- box-sizing: border-box;
- }
-
- .counts-wrapper {
- display: flex;
- flex-wrap: wrap;
- justify-content: center;
- align-items: center;
- gap: 20px;
- margin: 20px 0;
- }
-
- .controls {
- display: flex;
- flex-wrap: wrap;
- gap: 16px;
- align-items: flex-end;
- justify-content: center;
- margin-bottom: 20px;
- }
-
- .controls label {
- font-size: 0.9rem;
- display: flex;
- flex-direction: column;
- flex: 1 1 auto;
- min-width: 120px;
- }
-
- input[type="date"],
- input[type="time"] {
- padding: 6px 10px;
- border-radius: 8px;
- border: 1px solid #ccc;
- font-size: 1rem;
- }
-
- button {
- background-color: #f0f0f0;
- color: #1a73e8;
- padding: 10px 24px;
- border: none;
- border-radius: 6px;
- font-size: 1rem;
- cursor: pointer;
- transition: all 0.3s ease;
- min-width: 100px;
- text-align: center;
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
- }
-
- button:hover {
- background-color: #e0e0e0;
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
- }
-
- .form-actions button {
- min-width: 80px;
- }
-
- #alertsContainer table button {
- padding: 6px 12px;
- min-width: 90px;
- text-align: center;
- font-size: 0.9rem;
- }
-
- h3 {
- font-size: 1.2rem;
- margin: 20px 0 10px;
- }
-
- #eventImagesContainer {
- display: flex;
- flex-wrap: wrap;
- justify-content: center;
- gap: 14px;
- }
-
- #eventImagesContainer img {
- width: 220px;
- height: auto;
- border-radius: 10px;
- border: 1px solid #ccc;
- transition: transform 0.2s;
- }
-
- #eventImagesContainer img:hover {
- transform: scale(1.05);
- }
-
- /* Modal styles */
- .modal {
- display: none;
- position: fixed;
- z-index: 999;
- left: 0;
- top: 0;
- width: 100%;
- height: 100%;
- background-color: rgba(0, 0, 0, 0.4);
- justify-content: center;
- align-items: center;
- overflow: auto;
- }
-
- .form-group.checkbox-group {
- flex: 1;
- min-height: 0; /* Important for flex children */
- }
-
- .modal-content {
- background-color: #fefefe;
- padding: 20px;
- border-radius: 8px;
- width: 90%;
- max-width: 500px;
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
- }
-
- .modal-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 15px;
- }
-
- .modal-header h3 {
- margin: 0;
- }
-
- .close {
- color: #aaa;
- font-size: 28px;
- font-weight: bold;
- cursor: pointer;
- }
-
- .close:hover {
- color: black;
- }
-
- .form-group {
- margin-bottom: 15px;
- }
-
- .form-group label {
- display: block;
- margin-bottom: 5px;
- font-weight: 500;
- }
-
- .form-group input {
- width: 100%;
- padding: 8px;
- border: 1px solid #ddd;
- border-radius: 4px;
- box-sizing: border-box;
- }
-
- .form-actions {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- margin-top: 20px;
- }
-
- @media (max-width: 600px) {
- button {
- padding: 8px 16px;
- font-size: 0.9rem;
- min-width: 80px;
- }
-
- .form-actions button {
- min-width: 70px;
- }
-
- input[type="date"] {
- width: 100%;
- max-width: 200px;
- padding: 6px 8px;
- font-size: 0.9rem;
- }
-
- input[type="time"] {
- width: 100px;
- padding: 6px 8px;
- font-size: 0.9rem;
- }
-
- .modal-content {
- width: 95%;
- padding: 15px;
- }
-
- .form-group input {
- padding: 6px 8px;
- font-size: 0.9rem;
- }
-
- #alertsContainer table {
- font-size: 0.9rem;
- }
-
- #alertsContainer table button {
- min-width: 80px;
- padding: 5px 10px;
- font-size: 0.8rem;
- }
-
- .controls label {
- min-width: auto;
- width: 100%;
- }
-
- .counts-wrapper {
- flex-direction: column;
- gap: 10px;
- }
-
- .date-picker-container {
- flex-wrap: nowrap;
- }
-
- .date-picker-container input[type="date"],
- .date-picker-container button {
- height: 36px;
- font-size: 0.85rem;
- padding: 6px 10px;
- }
- }
- </style>
-</head>
-<body>
- <div class="container">
- <video id="video" controls></video>
- <div class="date-picker-container">
- <input type="date" id="folderPicker" value="{selected_dir}">
- <label style="display: flex; align-items: center; gap: 6px; margin-left: 10px;">
- <input type="checkbox" id="showDetections" {show_detections_checked}> Show detections
- </label>
- </div>
- <h3>Active Alerts</h3>
- <div id="alertsContainer">
- <p>Loading alerts...</p>
- <div style="display: flex; gap: 10px; justify-content: flex-start; margin-top: 10px;">
- <button onclick="openSettingsEditor()">Settings</button>
- <button onclick="openAlertModal()">Add Alert</button>
- </div>
- </div>
-
- <!-- The Modal -->
- <div id="alertModal" class="modal">
- <div class="modal-content" style="max-width: 400px;">
- <div class="modal-header">
- <h3>Add New Alert</h3>
- <span class="close" onclick="closeAlertModal()">&times;</span>
- </div>
- <form id="alertForm" onsubmit="addAlert(event)" style="display: flex; flex-direction: column; align-items: center;">
- <div class="form-group" style="width: 90%; text-align: center;">
- <label for="maxCount">Trigger if there are more than</label>
- <input type="number" id="maxCount" name="max" min="1" value="1" required
- style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
- <span>objects detected</span>
- </div>
- <div class="form-group checkbox-group" style="width: 90%; text-align: center;">
- <label>of class(es)</label>
- <div id="checkboxContainer" class="checkbox-container"></div>
- </div>
- <div class="form-group" style="width: 90%; text-align: center;">
- <label for="windowMinutes">within this time window</label>
- <input type="number" id="windowMinutes" name="window" min="1" value="1" required
- style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
- <span>minutes</span>
- </div>
-
- <div class="form-group" style="width: 90%; text-align: center;">
- <label>Schedule (optional)</label>
- <div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
- <div>
- <label for="scheduleFrom">From</label><br>
- <input type="time" id="scheduleFrom" name="schedule_from" step="60" style="text-align: center;">
- </div>
- <div>
- <label for="scheduleTo">To</label><br>
- <input type="time" id="scheduleTo" name="schedule_to" step="60" style="text-align: center;">
- </div>
- </div>
- </div>
- <div class="form-group" style="width: 90%; text-align: center;">
- <div style="display: flex; flex-direction: column; align-items: center; gap: 5px; margin-top: 5px;">
- <label><input type="checkbox" name="days" value="0" checked> Mon</label>
- <label><input type="checkbox" name="days" value="1" checked> Tue</label>
- <label><input type="checkbox" name="days" value="2" checked> Wed</label>
- <label><input type="checkbox" name="days" value="3" checked> Thu</label>
- <label><input type="checkbox" name="days" value="4" checked> Fri</label>
- <label><input type="checkbox" name="days" value="5" checked> Sat</label>
- <label><input type="checkbox" name="days" value="6" checked> Sun</label>
- </div>
- </div>
-
- <div class="form-actions" style="display: flex; justify-content: center; gap: 10px; margin-top: 20px; width: 100%;">
- <button type="button" onclick="closeAlertModal()">Cancel</button>
- <button type="submit">Save Alert</button>
- </div>
- </form>
- </div>
- </div>
-
-
- <div id="zoneModal" class="modal">
- <div class="modal-content" style="max-width: 600px;">
- <div class="modal-header">
- <h3>Edit Zone</h3>
- <span class="close" onclick="closeZoneModal()">&times;</span>
- </div>
- <div style="position: relative; display: inline-block; max-width: 100%;">
- <img id="zonePreview" src="/{cam_name}/preview.png"
- style="width: 100%; max-height: 400px; object-fit: contain; border: 1px solid #ccc; border-radius: 6px; user-select: none; -webkit-user-drag: none; cursor: crosshair;">
- <div id="polygonOverlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
- </div>
- <div style="margin: 10px 0; text-align: center; color: #666; font-size: 0.9rem;">
- Click on the image to make a detection zone.
- </div>
- <div class="form-actions" style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;">
- <div style="display: flex; flex-direction: column; gap: 10px;">
- <label style="display: flex; align-items: center; gap: 6px;">
- <input type="checkbox" id="zoneEnabledCheckbox" checked> Enable Zone
- </label>
- <label style="display: flex; align-items: center; gap: 6px;">
- <input type="checkbox" id="outsideZoneCheckbox"> Detect outside of zone
- </label>
- <label style="display: flex; align-items: center; gap: 6px;">
- Detection Threshold:
- <input type="number" id="zoneThreshold" value="50" min="0" max="100" step="1" style="width: 60px;"> %
- </label>
- </div>
- <div style="display: flex; gap: 10px;">
- <button type="button" onclick="clearPolygon()">Clear Zone</button>
- <button type="button" onclick="closeZoneModal()">Cancel</button>
- <button type="button" onclick="saveZone()">Save</button>
- </div>
- </div>
- </div>
- </div>
-
-
- <div class="counts-wrapper">
- <table id="objectCounts" style="font-size: 1rem; border-collapse: collapse;">
- <tbody></tbody>
- </table>
- <button onclick="resetCounts()">Reset</button>
- </div>
-
- <h3>Detected Events</h3>
- <div id="eventImagesContainer">
- {image_links}
- </div>
- <div id="imagePreviewModal" class="modal">
- <span class="close" onclick="closeImagePreview()">&times;</span>
- <img id="previewImage" src="" alt="Preview">
- </div>
- </div>
-
- <script>
- const classLabels = {class_labels};
- const alertModal = document.getElementById("alertModal");
- const folderPicker = document.getElementById("folderPicker");
- const video = document.getElementById("video");
- const startTime = {start_time};
- const cameraName = "{cam_name}";
-
-
- window.onload = function () {
- const container = document.getElementById('checkboxContainer');
- container.innerHTML = '';
-
- for (let i = 0; i < 80; i++) {
- const checkbox = document.createElement('input');
- checkbox.type = 'checkbox';
- checkbox.value = i;
- checkbox.name = 'class_ids';
- checkbox.id = 'class_' + i;
-
- const label = document.createElement('label');
- label.htmlFor = 'class_' + i;
- label.textContent = (classLabels[i] !== undefined) ? `${classLabels[i]}` : `${i}`;
-
- container.appendChild(checkbox);
- container.appendChild(label);
- }
- };
-
- function viewImage(imageSrc) {
- const previewModal = document.getElementById("imagePreviewModal");
- const previewImage = document.getElementById("previewImage");
- previewImage.src = imageSrc;
-
- // Force reasonable size
- previewImage.style.maxWidth = '70%';
- previewImage.style.maxHeight = '70%';
- previewImage.style.width = 'auto';
- previewImage.style.height = 'auto';
-
- previewModal.style.display = "flex";
- }
-
- function closeImagePreview() {
- document.getElementById("imagePreviewModal").style.display = "none";
- }
-
- function playVideoAtTime(timestamp) {
- const params = new URLSearchParams(window.location.search);
- params.set('start', timestamp);
- window.location.search = params.toString();
- }
- window.addEventListener("click", function(event) {
- const modal = document.getElementById("imagePreviewModal");
- if (event.target === modal) {
- closeImagePreview();
- }
- });
- document.addEventListener('keydown', function(event) {
- if (event.key === 'Escape') {
- closeImagePreview();
- }
- });
-
- const zoneModal = document.getElementById("zoneModal");
- const zoneRect = document.getElementById("zoneRect");
- let isDragging = false;
- let isResizing = false;
- let resizeHandle = null;
- let startX, startY;
- let startWidth, startHeight;
- let startLeft, startTop;
-
-function closeZoneModal() {
- zoneModal.style.display = "none";
-}
-
- // Global variables for polygon editing
- // Global variables for polygon editing
- let polygonSvg = null;
- let polygonPath = null;
- let firstPoint = null;
- let isPolygonComplete = false;
-
- function openSettingsEditor() {
- zoneModal.style.display = "flex";
-
- // Initialize the zone editor first
- initZoneEditor();
-
- // Then load the settings
- fetch(`/get_settings?cam=${encodeURIComponent(cameraName)}`)
- .then(res => res.json())
- .then(data => {
- console.log("Received settings data:", data);
- const previewEl = document.getElementById("zonePreview");
-
- if (data && data.coords) {
- console.log("Loading coords:", data.coords);
- // Load existing polygon coordinates
- loadPolygon(data.coords, previewEl);
- }
-
- const zoneEnabledCheckbox = document.getElementById("zoneEnabledCheckbox");
- if (data.is_on !== undefined) {
- zoneEnabledCheckbox.checked = data.is_on;
- } else if (data.length && data[0] && data[0].is_on !== undefined) {
- zoneEnabledCheckbox.checked = data[0].is_on;
- } else {
- zoneEnabledCheckbox.checked = false;
- }
-
- const outsideZoneCheckbox = document.getElementById("outsideZoneCheckbox");
- if (data.outside !== undefined) {
- outsideZoneCheckbox.checked = data.outside;
- } else if (data.length && data[0] && data[0].outside !== undefined) {
- outsideZoneCheckbox.checked = data[0].outside;
- } else {
- outsideZoneCheckbox.checked = false;
- }
-
- const thresholdInput = document.getElementById("zoneThreshold");
- let rawThreshold = undefined;
- if (data.threshold !== undefined) {
- rawThreshold = data.threshold;
- } else if (data.length && data[0] && data[0].threshold !== undefined) {
- rawThreshold = data[0].threshold;
- }
- if (rawThreshold !== undefined) {
- if (rawThreshold <= 1) {
- thresholdInput.value = (rawThreshold * 100).toFixed(0);
- } else {
- thresholdInput.value = rawThreshold.toFixed(0);
- }
- }
- })
- .catch(err => {
- console.error("Failed to load zone:", err);
- });
- }
-
- function closeZoneModal() {
- zoneModal.style.display = "none";
- }
-
- function saveZone() {
- const previewEl = document.getElementById("zonePreview");
- const points = Array.from(document.querySelectorAll('.polygon-point'));
-
- let coords = null;
- if (points.length >= 3) {
- const videoWidth = 1280;
- const videoHeight = 720;
- const previewRect = previewEl.getBoundingClientRect();
-
- coords = points.map(point => {
- const pointRect = point.getBoundingClientRect();
- const centerX = pointRect.left + pointRect.width / 2;
- const centerY = pointRect.top + pointRect.height / 2;
-
- const x = ((centerX - previewRect.left) / previewRect.width) * videoWidth;
- const y = ((centerY - previewRect.top) / previewRect.height) * videoHeight;
-
- return [x, y];
- });
- }
-
- const is_on = document.getElementById("zoneEnabledCheckbox").checked;
- const outside = document.getElementById("outsideZoneCheckbox").checked;
-
- const thresholdPercent = parseFloat(document.getElementById("zoneThreshold").value) || 50;
- const threshold = thresholdPercent / 100;
-
- const params = new URLSearchParams({
- cam: cameraName,
- is_on: is_on,
- threshold: threshold.toFixed(2),
- outside: outside
- });
-
- if (coords) {
- params.set('coords', JSON.stringify(coords));
- }
-
- fetch(`/edit_settings?${params.toString()}`)
- .then(res => {
- if (!res.ok) throw new Error("Failed to save settings");
- console.log("Settings saved successfully");
- closeZoneModal();
- })
- .catch(err => {
- console.error("Save settings failed:", err);
- alert("Failed to save settings.");
- });
- }
-
- function initZoneEditor() {
- const previewEl = document.getElementById("zonePreview");
-
- // Clear any existing polygon
- clearPolygon();
-
- // Initialize SVG overlay
- initPolygonOverlay();
-
- // Add click event listener for adding points
- previewEl.addEventListener('click', handlePreviewClick);
- }
-
- function initPolygonOverlay() {
- const overlay = document.getElementById("polygonOverlay");
- overlay.innerHTML = '';
-
- // Create SVG element
- polygonSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- polygonSvg.style.width = '100%';
- polygonSvg.style.height = '100%';
- polygonSvg.style.position = 'absolute';
- polygonSvg.style.top = '0';
- polygonSvg.style.left = '0';
- polygonSvg.style.pointerEvents = 'none';
-
- polygonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
- polygonPath.setAttribute('fill', 'none');
- polygonPath.setAttribute('stroke', '#ff0000');
- polygonPath.setAttribute('stroke-width', '2');
- polygonPath.setAttribute('stroke-linejoin', 'round');
-
- polygonSvg.appendChild(polygonPath);
- overlay.appendChild(polygonSvg);
- }
-
- function handlePreviewClick(e) {
- const previewEl = document.getElementById("zonePreview");
- const rect = previewEl.getBoundingClientRect();
-
- // Calculate position relative to preview element
- const x = e.clientX - rect.left;
- const y = e.clientY - rect.top;
-
- // Check if we're clicking on the first point (to close polygon)
- if (firstPoint && isClickOnPoint(firstPoint, x, y)) {
- // Complete the polygon
- completePolygon();
- return;
- }
-
- // Create a new point
- createPoint(x, y);
-
- // Update the polygon visualization
- updatePolygonLine();
- }
-
- function isClickOnPoint(point, clickX, clickY) {
- const pointRect = point.getBoundingClientRect();
- const previewRect = document.getElementById("zonePreview").getBoundingClientRect();
- const pointX = parseInt(point.style.left) + 6; // Center of point
- const pointY = parseInt(point.style.top) + 6;
-
- // Check if click is within the point's area
- const distance = Math.sqrt(Math.pow(clickX - pointX, 2) + Math.pow(clickY - pointY, 2));
- return distance <= 10; // Increased tolerance for easier clicking
- }
-
- function completePolygon() {
- console.log("Completing polygon"); // Debug log
- polygonPath.setAttribute('fill', 'rgba(0, 255, 0, 0.3)');
- polygonPath.setAttribute('stroke', '#00ff00');
- const previewEl = document.getElementById("zonePreview");
- previewEl.removeEventListener('click', handlePreviewClick);
- isPolygonComplete = true;
- updatePolygonLine();
- }
-
- function createPoint(x, y) {
- const overlay = document.getElementById("polygonOverlay");
- const point = document.createElement('div');
- point.className = 'polygon-point';
- point.style.position = 'absolute';
- point.style.left = (x - 6) + 'px';
- point.style.top = (y - 6) + 'px';
- point.style.width = '12px';
- point.style.height = '12px';
- point.style.backgroundColor = '#ff0000';
- point.style.borderRadius = '50%';
- point.style.cursor = 'crosshair';
- point.style.zIndex = '20';
- point.style.border = '2px solid #ffffff';
- point.style.boxShadow = '0 0 3px rgba(0,0,0,0.5)';
- point.style.pointerEvents = 'auto';
-
- // Store first point reference
- if (!firstPoint) {
- firstPoint = point;
- // Make first point visually distinct
- point.style.backgroundColor = '#0000ff';
- point.style.border = '2px solid #ffffff';
- point.style.cursor = 'pointer'; // Make first point more clickable
- }
-
- // Add click listener to first point for completion
- if (firstPoint === point) {
- point.addEventListener('click', function(e) {
- e.stopPropagation();
- if (!isPolygonComplete) {
- completePolygon();
- }
- });
- }
-
- overlay.appendChild(point);
- return point;
- }
-
- function updatePolygonLine() {
- const previewEl = document.getElementById("zonePreview");
- const points = Array.from(document.querySelectorAll('.polygon-point'));
-
- if (points.length === 0) {
- polygonPath.setAttribute('d', '');
- firstPoint = null;
- isPolygonComplete = false;
- return;
- }
-
- // Create SVG path for the polygon - just draw lines between points, don't close automatically
- const pathData = points.map((point, index) => {
- const rect = point.getBoundingClientRect();
- const previewRect = previewEl.getBoundingClientRect();
- const x = rect.left - previewRect.left + 6; // Center of point
- const y = rect.top - previewRect.top + 6;
- return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
- }).join(' ');
-
- // Only close the path if polygon is complete
- if (isPolygonComplete) {
- polygonPath.setAttribute('d', pathData + ' Z');
- } else {
- polygonPath.setAttribute('d', pathData);
- }
- }
-
- function loadPolygon(coords, previewEl) {
- const videoWidth = 1280;
- const videoHeight = 720;
-
- // Wait for the image to load to get actual dimensions
- const img = document.getElementById("zonePreview");
- if (img.complete) {
- drawPolygonCoords(coords, img, previewEl);
- } else {
- img.addEventListener('load', function() {
- drawPolygonCoords(coords, img, previewEl);
- });
- }
- }
-
- function drawPolygonCoords(coords, img, previewEl) {
- const videoWidth = 1280;
- const videoHeight = 720;
-
- // Get the actual displayed dimensions of the image
- const displayedWidth = img.clientWidth;
- const displayedHeight = img.clientHeight;
-
- console.log("Loading polygon coords:", coords);
- console.log("Image dimensions:", displayedWidth, displayedHeight);
-
- coords.forEach(coord => {
- const x = (coord[0] / videoWidth) * displayedWidth;
- const y = (coord[1] / videoHeight) * displayedHeight;
- console.log("Creating point at:", x, y, "from coord:", coord);
- createPoint(x, y);
- });
-
- updatePolygonLine();
-
- // If loading an existing polygon, mark it as complete
- if (coords.length >= 3) {
- completePolygon();
- }
- }
-
- function clearPolygon() {
- const overlay = document.getElementById("polygonOverlay");
- const points = overlay.querySelectorAll('.polygon-point');
- points.forEach(point => point.remove());
- firstPoint = null;
- isPolygonComplete = false;
- if (polygonPath) {
- polygonPath.setAttribute('d', '');
- polygonPath.setAttribute('fill', 'none');
- polygonPath.setAttribute('stroke', '#ff0000');
- }
- const previewEl = document.getElementById("zonePreview");
- previewEl.addEventListener('click', handlePreviewClick);
- }
-
- const polygonStyles = `
- .polygon-point:hover {
- transform: scale(1.2); // Keep this if you want, but remove if it suggests draggability
- box-shadow: 0 0 5px rgba(0,0,0,0.5);
- }
- `;
-
- const styleSheet = document.createElement("style");
- styleSheet.textContent = polygonStyles;
- document.head.appendChild(styleSheet);
-
-
- function openAlertModal() {
- alertModal.style.display = "flex";
- }
-
- function closeAlertModal() {
- alertModal.style.display = "none";
- }
-
- window.addEventListener("click", function(event) {
- if (event.target === alertModal) closeAlertModal();
- });
-
- document.getElementById("showDetections").addEventListener("change", function() {
- const currentTime = video.currentTime;
- const params = new URLSearchParams(window.location.search);
- params.set('show_detections', this.checked);
- params.set('start', currentTime);
- window.location.search = params.toString();
- });
-
- function initDetectionSettings() {
- const urlParams = new URLSearchParams(window.location.search);
- const showDetections = urlParams.get('show_detections') === 'true';
-
- if (showDetections) {
- // Send initial request
- fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=1`)
- .then(res => {
- if (!res.ok) throw new Error("Failed to update detection settings");
- console.log("Detection settings updated successfully");
- })
- .catch(err => {
- console.error("Failed to update detection settings:", err);
- });
-
- // Set up interval to send request every 30 seconds
- window.detectionInterval = setInterval(() => {
- fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=1`)
- .then(res => {
- if (!res.ok) throw new Error("Failed to refresh detection settings");
- console.log("Detection settings refreshed");
- })
- .catch(err => {
- console.error("Failed to refresh detection settings:", err);
- });
- }, 30000); // 30 seconds
- }
-}
-
-document.getElementById("showDetections").addEventListener("change", function() {
- const currentTime = video.currentTime;
- const params = new URLSearchParams(window.location.search);
- params.set('show_detections', this.checked);
- window.location.search = params.toString();
-});
-
-window.addEventListener('beforeunload', function() {
- if (window.detectionInterval) {
- clearInterval(window.detectionInterval);
- }
-});
-
-initDetectionSettings();
-
- function loadStream(folder) {
- const showDetections = document.getElementById("showDetections").checked;
- const streamSuffix = showDetections ? "" : "_raw";
- const url = `${cameraName}${streamSuffix}/streams/${folder}/stream.m3u8`;
-
- async function waitForManifest(maxRetries = 30, delay = 2000) {
- for (let i = 0; i < maxRetries; i++) {
- try {
- const res = await fetch(url, { cache: "no-store" });
- if (res.ok) {
- const text = await res.text();
- if (text.includes("#EXTINF")) {
- return true; // playlist has segments
- }
- }
- } catch (err) {
- console.warn("Stream not ready yet:", err);
- }
- await new Promise(r => setTimeout(r, delay));
- }
- return false;
- }
-
- (async () => {
- const ready = await waitForManifest();
- if (!ready) {
- console.error("Stream never became available.");
- return;
- }
-
- if (Hls.isSupported()) {
- const hls = new Hls({
- manifestLoadingTimeOut: 20000,
- manifestLoadingMaxRetry: Infinity,
- manifestLoadingRetryDelay: 2000,
- });
-
- hls.loadSource(url);
- hls.attachMedia(video);
-
- hls.on(Hls.Events.MANIFEST_PARSED, function () {
- if (startTime !== null) video.currentTime = startTime;
- video.play();
- });
-
- hls.on(Hls.Events.ERROR, function (event, data) {
- if (data.fatal) {
- switch (data.type) {
- case Hls.ErrorTypes.NETWORK_ERROR:
- console.warn("Network error, retrying...");
- hls.startLoad(-1);
- break;
- case Hls.ErrorTypes.MEDIA_ERROR:
- console.warn("Media error, recovering...");
- hls.recoverMediaError();
- break;
- default:
- console.error("Fatal error, destroying HLS instance.");
- hls.destroy();
- break;
- }
- }
- });
- } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
- video.src = url;
- video.addEventListener('loadedmetadata', function () {
- if (startTime !== null) video.currentTime = startTime;
- video.play();
- });
- }
- })();
- }
-
-
-function loadEventImages(folder) {
- fetch(`/event_thumbs?cam=${cameraName}&folder=${folder}`)
- .then(res => res.json())
- .then(data => {
- const container = document.getElementById("eventImagesContainer");
-
- // Generate HTML from JSON data
- let html = '';
- if (data.images && data.images.length > 0) {
- data.images.forEach(img => {
- html += `
- <div class="image-item">
- <img src="${img.url}" alt="Event" />
- <div class="image-actions">
- <button onclick="viewImage('${img.url}')">View</button>
- <button onclick="playVideoAtTime(${img.timestamp})">Play</button>
- </div>
- </div>
- `;
- });
- } else {
- html = '<p style="text-align:center; color:#666;">No alerts detected yet.</p>';
- }
-
- // Only update if content changed
- if (container.innerHTML !== html) {
- container.innerHTML = html;
- }
- })
- .catch(err => {
- console.error("Failed to load images:", err);
- const container = document.getElementById("eventImagesContainer");
- container.innerHTML = "<p>No event images found.</p>";
- });
-}
-
- function fetchCounts() {
- fetch(`/get_counts?cam=${encodeURIComponent(cameraName)}`)
- .then(res => res.json())
- .then(data => {
- const tbody = document.querySelector("#objectCounts tbody");
- tbody.innerHTML = "";
-
- const entries = Object.entries(data).sort((a, b) => b[1] - a[1]);
- if (!entries.length) {
- tbody.innerHTML = "<tr><td colspan='2'>No detections.</td></tr>";
- return;
- }
-
- for (const [label, count] of entries) {
- tbody.innerHTML += `
- <tr>
- <td style="padding:6px 12px; border-bottom:1px solid #eee;">${label}</td>
- <td style="padding:6px 12px; border-bottom:1px solid #eee;">${count}</td>
- </tr>`;
- }
- })
- .catch(err => {
- console.error("Failed to fetch counts:", err);
- document.querySelector("#objectCounts tbody").innerHTML = "<tr><td colspan='2'>Error fetching counts.</td></tr>";
- });
- }
-
- function resetCounts() {
- if (!confirm("Are you sure you want to reset the counts for this camera?")) return;
- fetch(`/reset_counts?cam=${encodeURIComponent(cameraName)}`)
- .then(res => res.json())
- .then(() => {
- console.log("Counts reset");
- fetchCounts();
- })
- .catch(err => {
- console.error("Failed to reset counts:", err);
- alert("Failed to reset counts.");
- });
- }
-
- function fetchAlerts() {
- fetch(`/get_alerts?cam=${encodeURIComponent(cameraName)}`)
- .then(res => res.json())
- .then(alerts => {
- const container = document.getElementById("alertsContainer");
- if (!alerts.length) {
- container.innerHTML = `
- <p>No alerts configured.</p>
- <div style="display: flex; gap: 10px; justify-content: center; margin-top: 10px;">
- <button onclick="openSettingsEditor()">Settings</button>
- <button onclick="openAlertModal()">Add Alert</button>
- </div>`;
- return;
- }
-
- let html = `<table style="width:100%; border-collapse:collapse; font-size:0.95rem;">
- <thead>
- <tr>
- <th style="text-align:center; padding:6px; border-bottom:1px solid #ccc;"></th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Occurrences of</th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Within</th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Schedule</th>
- <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;"></th>
- </tr>
- </thead><tbody>`;
-
- for (const alert of alerts) {
- const classNames = alert.classes.map(id => classLabels[id] ?? id).join(", ");
- const h = Math.floor(alert.window / 3600);
- const m = Math.floor((alert.window % 3600) / 60);
- const s = alert.window % 60;
- const windowStr = `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
- const fromH = Math.floor(alert.sched[0][0] / 3600);
- const fromM = Math.floor((alert.sched[0][0] % 3600) / 60);
- let toSec = alert.sched[0][1];
- if (toSec % 60 !== 0) {
- toSec += 60 - (toSec % 60);
- }
- if (toSec >= 86400) {
- toSec = 0;
- }
- const toH = Math.floor(toSec / 3600);
- const toM = Math.floor((toSec % 3600) / 60);
- const timeRange = `${String(fromH).padStart(2,'0')}:${String(fromM).padStart(2,'0')} to ${String(toH).padStart(2,'0')}:${String(toM).padStart(2,'0')}`;
-
- const daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
- const activeDays = alert.sched.slice(1).map((on, idx) => on ? daysOfWeek[idx] : null).filter(Boolean);
- let daysStr;
- if (activeDays.length === 7) {
- daysStr = "Daily";
- } else {
- // compress consecutive ranges (Mon–Fri)
- const indices = alert.sched.slice(1).map((on, i) => on ? i : -1).filter(i => i >= 0);
- let ranges = [];
- let start = null;
- let prev = null;
- for (const idx of indices) {
- if (start === null) {
- start = idx;
- prev = idx;
- } else if (idx === prev + 1) {
- prev = idx;
- } else {
- ranges.push([start, prev]);
- start = idx;
- prev = idx;
- }
- }
- if (start !== null) {
- ranges.push([start, prev]);
- }
- daysStr = ranges.map(([a, b]) => {
- if (a === b) return daysOfWeek[a];
- else return `${daysOfWeek[a]}-${daysOfWeek[b]}`;
- }).join(", ");
- }
- const schedStr = `${timeRange} (${daysStr})`;
- const isOn = alert.hasOwnProperty("is_on") ? alert.is_on : true;
- const checkedAttr = isOn ? "checked" : "";
- html += `<tr>
- <td style="padding:6px; border-bottom:1px solid #eee;">${alert.max}</td>
- <td style="padding:6px; border-bottom:1px solid #eee;">${classNames}</td>
- <td style="padding:6px; border-bottom:1px solid #eee;">${windowStr}</td>
- <td style="padding:6px; border-bottom:1px solid #eee;">${schedStr}</td>
- <td style="padding:6px; border-bottom:1px solid #eee; display:flex; justify-content:center; align-items:center;">
- <input type="checkbox" data-alert-id="${alert.id}" ${checkedAttr}
- onchange="toggleAlert('${alert.id}', this.checked)"
- style="transform:scale(1.2); cursor:pointer;">
- </td>
- <td style="padding:6px; border-bottom:1px solid #eee; text-align:center;">
- <button onclick="deleteAlert('${alert.id}')" style="padding:4px 8px;">Delete</button>
- </td>
- </tr>`;
- }
-
-
- html += `</tbody></table>
- <div style="margin-top:10px; display:flex; gap:10px; justify-content:center;">
- <button onclick="openSettingsEditor()">Settings</button>
- <button onclick="openAlertModal()">Add Alert</button>
- </div>`;
- container.innerHTML = html;
- })
- .catch(err => {
- console.error("Failed to fetch alerts:", err);
- document.getElementById("alertsContainer").innerHTML = "<p>Error loading alerts.</p>";
- });
- }
-
- function toggleAlert(alertId, isOn) {
- fetch(`/edit_alert?cam=${encodeURIComponent(cameraName)}&id=${alertId}&is_on=${isOn}`)
- .then(res => {
- if (!res.ok) throw new Error("Failed to toggle alert");
- console.log(`Alert ${alertId} ${isOn ? 'enabled' : 'disabled'}`);
- })
- .catch(err => {
- console.error("Toggle alert failed:", err);
- alert("Failed to toggle alert status.");
- fetchAlerts();
- });
- }
-
- function deleteAlert(alertId) {
- fetch(`/edit_alert?cam=${encodeURIComponent(cameraName)}&id=${alertId}`)
- .then(res => {
- if (!res.ok) throw new Error("Failed to delete alert");
- fetchAlerts();
- })
- .catch(err => {
- console.error("Delete failed:", err);
- alert("Failed to delete alert.");
- });
- }
-
- function addAlert(event) {
- event.preventDefault();
- const form = event.target;
- const formData = new FormData(form);
-
- const windowMinutes = parseFloat(formData.get('window'));
- const windowSeconds = Math.round(windowMinutes * 60);
-
- const checked = form.querySelectorAll('input[name="class_ids"]:checked');
- const classIds = Array.from(checked).map(cb => cb.value).join(',');
-
- const scheduleFrom = formData.get("schedule_from") || "00:00:00";
- const scheduleTo = formData.get("schedule_to") || "23:59:59";
-
- const toSeconds = (hhmmss) => {
- const parts = hhmmss.split(":").map(Number);
- const [h = 0, m = 0, s = 0] = parts;
- return h * 3600 + m * 60 + s;
- };
-
- const fromSec = toSeconds(scheduleFrom);
- const toSec = toSeconds(scheduleTo);
- const dayChecks = form.querySelectorAll('input[name="days"]');
- const dayBools = Array.from(dayChecks).map(cb => cb.checked);
- const schedArray = [[fromSec, toSec], ...dayBools];
-
- const params = new URLSearchParams({
- cam: cameraName,
- window: windowSeconds,
- max: formData.get('max'),
- class_ids: classIds,
- sched: JSON.stringify(schedArray),
- });
-
- fetch(`/edit_alert?${params.toString()}`)
- .then(res => {
- if (!res.ok) throw new Error("Failed to add alert");
- return res.json();
- })
- .then(() => {
- closeAlertModal();
- form.reset();
- fetchAlerts();
- })
- .catch(err => {
- console.error("Add alert failed:", err);
- alert("Failed to add alert.");
- });
- }
-
-
- folderPicker.addEventListener("change", () => {
- const folder = folderPicker.value;
- const params = new URLSearchParams(window.location.search);
- params.set('date', folder);
- window.location.search = params.toString();
- });
-
- function getCurrentDate() {
- const params = new URLSearchParams(window.location.search);
- return params.get('date') || folderPicker.value;
- }
-
-
- function getQueryParam(name) {
- const urlParams = new URLSearchParams(window.location.search);
- return urlParams.get(name);
- }
-
- const initialDate = getQueryParam('date') || "{selected_dir}";
- folderPicker.value = initialDate;
-
-
- loadStream(getCurrentDate());
- loadEventImages(getCurrentDate());
- fetchAlerts();
- fetchCounts();
- setInterval(fetchCounts, 5000);
- setInterval(() => loadEventImages(getCurrentDate()), 5000);
-</script>
-</body>
-</html>
\ No newline at end of file
diff --git a/mainview.html b/mainview.html
index 620743f..1d0ce6a 100644
--- a/mainview.html
+++ b/mainview.html
@@ -2,6 +2,378 @@
<html>
<head>
<style>
+ .camera-card .detection-toggle {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-left: 10px;
+ font-size: 14px;
+ }
+
+ .camera-card .detection-toggle input[type="checkbox"] {
+ margin: 0;
+ transform: scale(1.1);
+ }
+ #alertsModal .modal-content {
+ max-width: 800px;
+ max-height: 90vh;
+ overflow-y: auto;
+ font-family: sans-serif;
+ }
+
+ #alertsModal .modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 15px;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #eee;
+ }
+
+ #alertsModal .modal-header h3 {
+ margin: 0;
+ font-size: 1.3rem;
+ color: #333;
+ }
+
+ #alertsModal .close {
+ color: #aaa;
+ font-size: 28px;
+ font-weight: bold;
+ cursor: pointer;
+ }
+
+ #alertsModal .close:hover {
+ color: black;
+ }
+
+ #alertsModal .modal-body {
+ padding: 10px 0;
+ }
+
+ #alertsModal h3 {
+ margin: 20px 0 10px;
+ font-size: 1.1rem;
+ color: #333;
+ }
+
+ #alertsContainer table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 0.9rem;
+ margin-bottom: 15px;
+ }
+
+ #alertsContainer th {
+ background: #f8f9fa;
+ padding: 8px;
+ text-align: left;
+ border-bottom: 2px solid #dee2e6;
+ font-weight: 600;
+ }
+
+ .camera-card .icon {
+ width: 20px;
+ height: 20px;
+ }
+
+ #alertsContainer td {
+ padding: 8px;
+ border-bottom: 1px solid #dee2e6;
+ vertical-align: middle;
+ }
+
+ #alertsContainer button {
+ background: #007bff;
+ color: white;
+ border: none;
+ padding: 6px 12px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.85rem;
+ font-family: sans-serif;
+ }
+
+ #alertsContainer button:hover {
+ background: #0056b3;
+ }
+
+ #alertsContainer .delete-button {
+ background: #dc3545;
+ }
+
+ #alertsContainer .delete-button:hover {
+ background: #c82333;
+ }
+
+ #alertsContainer input[type="checkbox"] {
+ transform: scale(1.2);
+ cursor: pointer;
+ }
+
+ .counts-wrapper {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ gap: 20px;
+ margin: 20px 0;
+ padding: 15px;
+ background: #f8f9fa;
+ border-radius: 6px;
+ }
+
+ #objectCounts {
+ font-size: 0.95rem;
+ border-collapse: collapse;
+ }
+
+ #objectCounts td {
+ padding: 6px 12px;
+ border-bottom: 1px solid #dee2e6;
+ }
+
+ .counts-wrapper button {
+ background: #007bff;
+ color: white;
+ border: none;
+ padding: 8px 16px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.9rem;
+ font-family: sans-serif;
+ }
+
+ .counts-wrapper button:hover {
+ background: #0056b3;
+ }
+
+ #alertModal .modal-content {
+ max-width: 450px;
+ font-family: sans-serif;
+ }
+
+ #alertModal .modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 15px;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #eee;
+ }
+
+ #alertModal .modal-header h3 {
+ margin: 0;
+ font-size: 1.3rem;
+ color: #333;
+ }
+
+ #alertModal .close {
+ color: #aaa;
+ font-size: 28px;
+ font-weight: bold;
+ cursor: pointer;
+ }
+
+ #alertModal .close:hover {
+ color: black;
+ }
+
+ #alertModal .form-group {
+ margin-bottom: 15px;
+ width: 100%;
+ }
+
+ #alertModal label {
+ display: block;
+ margin-bottom: 5px;
+ font-weight: 500;
+ color: #333;
+ font-size: 0.95rem;
+ }
+
+ #alertModal input[type="number"],
+ #alertModal input[type="time"] {
+ padding: 6px 8px;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ font-size: 0.9rem;
+ text-align: center;
+ font-family: sans-serif;
+ }
+
+ #alertModal input[type="number"] {
+ width: 70px;
+ }
+
+ #alertModal input[type="time"] {
+ width: 100px;
+ }
+
+ #alertModal .checkbox-container {
+ display: grid;
+ grid-template-columns: auto auto;
+ gap: 8px 16px;
+ max-height: 200px;
+ overflow-y: auto;
+ margin: 8px auto;
+ padding: 8px;
+ border: 1px solid #eee;
+ border-radius: 4px;
+ background: #f9f9f9;
+ }
+
+ #alertModal .checkbox-container label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 0;
+ font-weight: normal;
+ font-size: 0.9rem;
+ cursor: pointer;
+ }
+
+ #alertModal .checkbox-container input[type="checkbox"] {
+ margin: 0;
+ transform: scale(1.1);
+ cursor: pointer;
+ }
+
+ #alertModal .days-container {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ justify-content: center;
+ margin-top: 8px;
+ }
+
+ #alertModal .days-container label {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin: 0;
+ font-weight: normal;
+ font-size: 0.85rem;
+ cursor: pointer;
+ }
+
+ #alertModal .days-container input[type="checkbox"] {
+ margin: 0;
+ transform: scale(1.1);
+ cursor: pointer;
+ }
+
+ #alertModal .form-actions {
+ display: flex;
+ justify-content: center;
+ gap: 10px;
+ margin-top: 20px;
+ width: 100%;
+ }
+
+ #alertModal button {
+ padding: 8px 16px;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.9rem;
+ font-family: sans-serif;
+ transition: background-color 0.2s;
+ }
+
+ #alertModal button[type="button"] {
+ background: #6c757d;
+ color: white;
+ }
+
+ #alertModal button[type="button"]:hover {
+ background: #5a6268;
+ }
+
+ #alertModal button[type="submit"] {
+ background: #007bff;
+ color: white;
+ }
+
+ #alertModal button[type="submit"]:hover {
+ background: #0056b3;
+ }
+
+ #alertsContainer table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 0.9rem;
+ margin-bottom: 15px;
+ }
+
+ #alertsContainer th {
+ background: #f8f9fa;
+ padding: 8px;
+ text-align: left;
+ border-bottom: 2px solid #dee2e6;
+ font-weight: 600;
+ }
+
+ #alertsContainer td {
+ padding: 8px;
+ border-bottom: 1px solid #dee2e6;
+ vertical-align: middle;
+ }
+
+ #alertsContainer .delete-button {
+ background: #dc3545;
+ color: white;
+ border: none;
+ padding: 4px 8px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.8rem;
+ }
+
+ #alertsContainer .delete-button:hover {
+ background: #c82333;
+ }
+
+ #alertsContainer input[type="checkbox"] {
+ transform: scale(1.2);
+ cursor: pointer;
+ }
+ .counts-wrapper {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ align-items: center;
+ gap: 20px;
+ margin: 20px 0;
+ padding: 15px;
+ background: #f8f9fa;
+ border-radius: 6px;
+ }
+
+ #objectCounts {
+ font-size: 0.95rem;
+ border-collapse: collapse;
+ }
+
+ #objectCounts td {
+ padding: 6px 12px;
+ border-bottom: 1px solid #dee2e6;
+ }
+
+ .counts-wrapper button {
+ background: #007bff;
+ color: white;
+ border: none;
+ padding: 8px 16px;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 0.9rem;
+ }
+
+ .counts-wrapper button:hover {
+ background: #0056b3;
+ }
+
.camera-grid {
display: flex;
flex-wrap: wrap;
@@ -50,17 +422,18 @@
}
.camera-card .camera-name {
font-weight: bold;
- cursor: pointer;
- color: #007bff;
+ color: #333;
text-decoration: none;
font-size: 18px;
+ cursor: default;
}
.camera-card .camera-name:hover {
- text-decoration: underline;
+ text-decoration: none;
+ color: #333;
}
.camera-card button {
padding: 8px 16px;
- background: #dc3545;
+ background: #007bff;
color: white;
border: none;
border-radius: 4px;
@@ -68,8 +441,16 @@
font-size: 14px;
}
.camera-card button:hover {
+ background: #0056b3;
+ }
+
+ .camera-card button.delete-button {
+ background: #dc3545;
+ }
+ .camera-card button.delete-button:hover {
background: #c82333;
}
+
.form-section {
margin-top: 20px;
font-family: sans-serif;
@@ -96,6 +477,62 @@
margin-top: 20px;
}
+ #zoneModal button {
+ padding: 8px 16px;
+ background: #007bff;
+ color: white;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ font-size: 14px;
+ font-family: sans-serif;
+ }
+
+ #zoneModal button:hover {
+ background: #0056b3;
+ }
+
+ #zoneModal button.clear-zone-button {
+ background: #dc3545;
+ }
+
+ #zoneModal button.clear-zone-button:hover {
+ background: #c82333;
+ }
+
+ #zoneModal label {
+ font-family: sans-serif;
+ font-size: 14px;
+ }
+
+ #zoneModal input[type="number"] {
+ padding: 6px;
+ border: 1px solid #ccc;
+ border-radius: 4px;
+ font-size: 14px;
+ font-family: sans-serif;
+ }
+
+ #zoneModal input[type="checkbox"] {
+ margin: 0;
+ }
+ #zoneModal h3 {
+ font-family: sans-serif;
+ margin: 0;
+ }
+
+ #zoneModal .modal-header h3 {
+ font-family: sans-serif;
+ }
+
+ #zoneModal div {
+ font-family: sans-serif;
+ }
+
+ #zoneModal {
+ font-family: sans-serif;
+ }
+
/* Multi-view overlay grid */
#multiView {
display: none;
@@ -240,6 +677,10 @@
max-height: 90%;
object-fit: contain;
}
+ .modal-content {
+ width: 95%;
+ padding: 15px;
+ }
.close-preview {
position: absolute;
top: 20px;
@@ -264,6 +705,51 @@
height: 100%;
fill: currentColor;
}
+
+ .modal {
+ display: none;
+ position: fixed;
+ z-index: 10000;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.7);
+ justify-content: center;
+ align-items: center;
+ }
+
+ .modal-content {
+ background-color: #fefefe;
+ padding: 20px;
+ border-radius: 8px;
+ max-width: 600px;
+ width: 90%;
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
+ margin: auto;
+ }
+
+ .modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 15px;
+ }
+
+ .modal-header h3 {
+ margin: 0;
+ }
+
+ .close {
+ color: #aaa;
+ font-size: 28px;
+ font-weight: bold;
+ cursor: pointer;
+ }
+
+ .close:hover {
+ color: black;
+ }
</style>
</head>
<body>
@@ -299,7 +785,7 @@
<p style="text-align:center; color:#666; width:100%;">No events detected yet.</p>
</div>
</div>
-
+
<div id="multiView"></div>
<!-- Image Preview Modal -->
@@ -307,6 +793,123 @@
<span class="close-preview" onclick="closeImagePreview()">&times;</span>
<img id="previewImage" src="" alt="Preview">
</div>
+
+ <div id="zoneModal" class="modal">
+ <div class="modal-content" style="max-width: 600px;">
+ <div class="modal-header">
+ <h3>Edit Zone</h3>
+ <span class="close" onclick="closeZoneModal()">&times;</span>
+ </div>
+ <div style="position: relative; display: inline-block; max-width: 100%;">
+ <img id="zonePreview" src="/testcam/preview.png"
+ style="width: 100%; max-height: 400px; object-fit: contain; border: 1px solid #ccc; border-radius: 6px; user-select: none; -webkit-user-drag: none; cursor: crosshair;">
+ <div id="polygonOverlay" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none;"></div>
+ </div>
+ <div style="margin: 10px 0; text-align: center; color: #666; font-size: 0.9rem;">
+ Click on the image to make a detection zone.
+ </div>
+ <div class="form-actions" style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; width: 100%;">
+ <div style="display: flex; flex-direction: column; gap: 10px;">
+ <label style="display: flex; align-items: center; gap: 6px;">
+ <input type="checkbox" id="zoneEnabledCheckbox" checked> Enable Zone
+ </label>
+ <label style="display: flex; align-items: center; gap: 6px;">
+ <input type="checkbox" id="outsideZoneCheckbox"> Detect outside of zone
+ </label>
+ <label style="display: flex; align-items: center; gap: 6px;">
+ Detection Threshold:
+ <input type="number" id="zoneThreshold" value="50" min="0" max="100" step="1" style="width: 60px;"> %
+ </label>
+ </div>
+ <div style="display: flex; gap: 10px;">
+ <button type="button" class="clear-zone-button" onclick="clearPolygon()">Clear Zone</button>
+ <button type="button" onclick="closeZoneModal()">Cancel</button>
+ <button type="button" onclick="saveZone()">Save</button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div id="alertsModal" class="modal">
+ <div class="modal-content" style="max-width: 800px; max-height: 90vh; overflow-y: auto;">
+ <div class="modal-header">
+ <h3>Alerts & Counts - <span id="alertsCameraName"></span></h3>
+ <span class="close" onclick="closeAlertsModal()">&times;</span>
+ </div>
+ <div class="modal-body">
+ <h3>Active Alerts</h3>
+ <div id="alertsContainer">
+ <p>Loading alerts...</p>
+ <div style="display: flex; gap: 10px; justify-content: flex-start; margin-top: 10px;">
+ <button onclick="openAlertModal()">Add Alert</button>
+ </div>
+ </div>
+
+ <div class="counts-wrapper" style="display: flex; flex-wrap: wrap; justify-content: center; align-items: center; gap: 20px; margin: 20px 0;">
+ <table id="objectCounts" style="font-size: 1rem; border-collapse: collapse;">
+ <tbody></tbody>
+ </table>
+ <button onclick="resetCounts()">Reset</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div id="alertModal" class="modal">
+ <div class="modal-content" style="max-width: 400px;">
+ <div class="modal-header">
+ <h3>Add New Alert</h3>
+ <span class="close" onclick="closeAlertModal()">&times;</span>
+ </div>
+ <form id="alertForm" onsubmit="addAlert(event)" style="display: flex; flex-direction: column; align-items: center;">
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <label for="maxCount">Trigger if there are</label>
+ <input type="number" id="maxCount" name="max" min="1" value="1" required
+ style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
+ <span>objects detected</span>
+ </div>
+ <div class="form-group checkbox-group" style="width: 90%; text-align: center;">
+ <label>of class(es)</label>
+ <div id="checkboxContainer" class="checkbox-container" style="display: grid; grid-template-columns: auto auto; gap: 8px 16px; max-height: 200px; overflow-y: auto; margin: 0 auto; padding: 8px; justify-content: center;"></div>
+ </div>
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <label for="windowMinutes">within this time window</label>
+ <input type="number" id="windowMinutes" name="window" min="1" value="1" required
+ style="width: 80px; margin: 0 6px; text-align: center; display: inline-block;">
+ <span>minutes</span>
+ </div>
+
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <label>Schedule (optional)</label>
+ <div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
+ <div>
+ <label for="scheduleFrom">From</label><br>
+ <input type="time" id="scheduleFrom" name="schedule_from" step="60" style="text-align: center;">
+ </div>
+ <div>
+ <label for="scheduleTo">To</label><br>
+ <input type="time" id="scheduleTo" name="schedule_to" step="60" style="text-align: center;">
+ </div>
+ </div>
+ </div>
+ <div class="form-group" style="width: 90%; text-align: center;">
+ <div style="display: flex; flex-direction: column; align-items: center; gap: 5px; margin-top: 5px;">
+ <label><input type="checkbox" name="days" value="0" checked> Mon</label>
+ <label><input type="checkbox" name="days" value="1" checked> Tue</label>
+ <label><input type="checkbox" name="days" value="2" checked> Wed</label>
+ <label><input type="checkbox" name="days" value="3" checked> Thu</label>
+ <label><input type="checkbox" name="days" value="4" checked> Fri</label>
+ <label><input type="checkbox" name="days" value="5" checked> Sat</label>
+ <label><input type="checkbox" name="days" value="6" checked> Sun</label>
+ </div>
+ </div>
+
+ <div class="form-actions" style="display: flex; justify-content: center; gap: 10px; margin-top: 20px; width: 100%;">
+ <button type="button" onclick="closeAlertModal()">Cancel</button>
+ <button type="submit">Save Alert</button>
+ </div>
+ </form>
+ </div>
+ </div>
<svg style="display: none;">
<symbol id="icon-magnify" viewBox="0 0 24 24">
@@ -316,22 +919,361 @@
<symbol id="icon-play" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</symbol>
-
- <symbol id="icon-play-all" viewBox="0 0 24 24">
- <rect x="2" y="2" width="8" height="8" fill="currentColor"/>
- <rect x="14" y="2" width="8" height="8" fill="currentColor"/>
- <rect x="2" y="14" width="8" height="8" fill="currentColor"/>
- <rect x="14" y="14" width="8" height="8" fill="currentColor"/>
- </symbol>
- </svg>
+
+ <symbol id="icon-cog" viewBox="0 0 24 24">
+ <g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="3" />
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33
+ 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51
+ 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82
+ 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1
+ 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33
+ 1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51
+ 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82
+ 1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
+ </g>
+ </symbol>
+
+
+ <symbol id="icon-bell" viewBox="0 0 24 24">
+ <g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M12 22a2 2 0 0 0 2-2H10a2 2 0 0 0 2 2z" />
+ <path d="M18 16V11a6 6 0 0 0-12 0v5l-2 2h16l-2-2z" />
+ </g>
+ </symbol>
+
+ <symbol id="icon-bin" viewBox="0 0 24 24">
+ <g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M3 6h18" />
+ <path d="M8 6V4h8v2" />
+ <path d="M6 6v14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6" />
+ <line x1="10" y1="11" x2="10" y2="17" />
+ <line x1="14" y1="11" x2="14" y2="17" />
+ </g>
+ </symbol>
+
+ <symbol id="icon-play-all" viewBox="0 0 24 24">
+ <rect x="2" y="2" width="8" height="8" fill="currentColor"/>
+ <rect x="14" y="2" width="8" height="8" fill="currentColor"/>
+ <rect x="2" y="14" width="8" height="8" fill="currentColor"/>
+ <rect x="14" y="14" width="8" height="8" fill="currentColor"/>
+ </symbol>
+ </svg>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
- <script>
+<script>
+
+ const classLabels = {
+ 0: 'person',
+ 1: 'bicycle',
+ 2: 'car',
+ 3: 'motorbike',
+ 4: 'aeroplane',
+ 5: 'bus',
+ 6: 'train',
+ 7: 'truck',
+ 8: 'boat',
+ 14: 'bird',
+ 15: 'cat',
+ 16: 'dog',
+ 17: 'horse',
+ 18: 'sheep',
+ 19: 'cow',
+ 20: 'elephant',
+ 21: 'bear',
+ 22: 'zebra',
+ 23: 'giraffe',
+ 24: 'backpack',
+ 25: 'umbrella',
+ 26: 'handbag',
+ 28: 'suitcase',
+ 30: 'skis',
+ 31: 'snowboard',
+ 32: 'sports ball',
+ 63: 'laptop',
+ 64: 'mouse',
+ 66: 'keyboard',
+ 67: 'cell phone',
+ };
+
+ function openAlertsModal(cameraName) {
+ currentAlertsCamera = cameraName;
+ document.getElementById('alertsCameraName').textContent = cameraName;
+ document.getElementById("alertsModal").style.display = "flex";
+ if (document.getElementById('checkboxContainer').children.length === 0) {
+ initAlertCheckboxes();
+ }
+ fetchAlerts();
+ fetchCounts();
+ }
+
+
+ function initAlertCheckboxes() {
+ const container = document.getElementById('checkboxContainer');
+ container.innerHTML = '';
+
+ for (let i = 0; i < 80; i++) { // todo unhardcode 80 for other models
+ if (!classLabels[i]) continue; // skip useless classes
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ checkbox.value = i;
+ checkbox.name = 'class_ids';
+ checkbox.id = 'class_' + i;
+ const label = document.createElement('label');
+ label.htmlFor = 'class_' + i;
+ label.textContent = classLabels[i];
+
+ container.appendChild(checkbox);
+ container.appendChild(label);
+ }
+ }
+
+ function fetchAlerts() {
+ if (!currentAlertsCamera) return;
+
+ fetch(`/get_alerts?cam=${encodeURIComponent(currentAlertsCamera)}`)
+ .then(res => res.json())
+ .then(alerts => {
+ const container = document.getElementById("alertsContainer");
+ if (!alerts || !alerts.length) {
+ container.innerHTML = `
+ <p>No alerts configured.</p>
+ <div style="display: flex; gap: 10px; justify-content: center; margin-top: 10px;">
+ <button onclick="openAlertModal()">Add Alert</button>
+ </div>`;
+ return;
+ }
+
+ let html = `<table style="width:100%; border-collapse:collapse; font-size:0.95rem;">
+ <thead>
+ <tr>
+ <th style="text-align:center; padding:6px; border-bottom:1px solid #ccc;">Max</th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Classes</th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Window</th>
+ <th style="text-align:left; padding:6px; border-bottom:1px solid #ccc;">Schedule</th>
+ <th style="text-align:center; padding:6px; border-bottom:1px solid #ccc;">Enabled</th>
+ <th style="text-align:center; padding:6px; border-bottom:1px solid #ccc;">Actions</th>
+ </tr>
+ </thead><tbody>`;
+
+ for (const alert of alerts) {
+ const classNames = alert.classes.map(id => classLabels[id] ?? id).join(", ");
+ const h = Math.floor(alert.window / 3600);
+ const m = Math.floor((alert.window % 3600) / 60);
+ const s = alert.window % 60;
+ const windowStr = `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
+
+ // Format schedule
+ let scheduleStr = "Always";
+ if (alert.sched && alert.sched.length > 0) {
+ const fromSec = alert.sched[0][0];
+ const toSec = alert.sched[0][1];
+ const fromH = Math.floor(fromSec / 3600);
+ const fromM = Math.floor((fromSec % 3600) / 60);
+ const toH = Math.floor(toSec / 3600);
+ const toM = Math.floor((toSec % 3600) / 60);
+ const timeRange = `${String(fromH).padStart(2,'0')}:${String(fromM).padStart(2,'0')} to ${String(toH).padStart(2,'0')}:${String(toM).padStart(2,'0')}`;
+
+ const daysOfWeek = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
+ const activeDays = alert.sched.slice(1).map((on, idx) => on ? daysOfWeek[idx] : null).filter(Boolean);
+
+ if (activeDays.length === 7) {
+ scheduleStr = `${timeRange} (Daily)`;
+ } else {
+ scheduleStr = `${timeRange} (${activeDays.join(', ')})`;
+ }
+ }
+
+ const isOn = alert.hasOwnProperty("is_on") ? alert.is_on : true;
+ const checkedAttr = isOn ? "checked" : "";
+
+ html += `<tr>
+ <td style="padding:6px; border-bottom:1px solid #eee; text-align:center;">${alert.max}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${classNames}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${windowStr}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee;">${scheduleStr}</td>
+ <td style="padding:6px; border-bottom:1px solid #eee; text-align:center;">
+ <input type="checkbox" data-alert-id="${alert.id}" ${checkedAttr}
+ onchange="toggleAlert('${alert.id}', this.checked)"
+ style="transform:scale(1.2); cursor:pointer;">
+ </td>
+ <td style="padding:6px; border-bottom:1px solid #eee; text-align:center;">
+ <button onclick="deleteAlert('${alert.id}')" style="padding:4px 8px;">Delete</button>
+ </td>
+ </tr>`;
+ }
+
+ html += `</tbody></table>
+ <div style="margin-top:10px; display:flex; gap:10px; justify-content:center;">
+ <button onclick="openAlertModal()">Add Alert</button>
+ </div>`;
+ container.innerHTML = html;
+ })
+ .catch(err => {
+ console.error("Failed to fetch alerts:", err);
+ document.getElementById("alertsContainer").innerHTML = "<p>Error loading alerts.</p>";
+ });
+ }
+
+ function fetchCounts() {
+ if (!currentAlertsCamera) return;
+
+ fetch(`/get_counts?cam=${encodeURIComponent(currentAlertsCamera)}`)
+ .then(res => res.json())
+ .then(data => {
+ const tbody = document.querySelector("#objectCounts tbody");
+ tbody.innerHTML = "";
+
+ const entries = Object.entries(data).sort((a, b) => b[1] - a[1]);
+ if (!entries.length) {
+ tbody.innerHTML = "<tr><td colspan='2'>No detections.</td></tr>";
+ return;
+ }
+
+ for (const [label, count] of entries) {
+ tbody.innerHTML += `
+ <tr>
+ <td style="padding:6px 12px; border-bottom:1px solid #eee;">${label}</td>
+ <td style="padding:6px 12px; border-bottom:1px solid #eee;">${count}</td>
+ </tr>`;
+ }
+ })
+ .catch(err => {
+ console.error("Failed to fetch counts:", err);
+ document.querySelector("#objectCounts tbody").innerHTML = "<tr><td colspan='2'>Error fetching counts.</td></tr>";
+ });
+ }
+
+ function addAlert(event) {
+ event.preventDefault();
+ if (!currentAlertsCamera) return;
+
+ const form = event.target;
+ const formData = new FormData(form);
+
+ const windowMinutes = parseFloat(formData.get('window'));
+ const windowSeconds = Math.round(windowMinutes * 60);
+
+ const checked = form.querySelectorAll('input[name="class_ids"]:checked');
+ const classIds = Array.from(checked).map(cb => cb.value).join(',');
+
+ const scheduleFrom = formData.get("schedule_from") || "00:00";
+ const scheduleTo = formData.get("schedule_to") || "23:59";
+
+ const toSeconds = (hhmm) => {
+ const parts = hhmm.split(":").map(Number);
+ const [h = 0, m = 0] = parts;
+ return h * 3600 + m * 60;
+ };
+
+ const fromSec = toSeconds(scheduleFrom);
+ const toSec = toSeconds(scheduleTo);
+ const dayChecks = form.querySelectorAll('input[name="days"]');
+ const dayBools = Array.from(dayChecks).map(cb => cb.checked);
+ const schedArray = [[fromSec, toSec], ...dayBools];
+
+ const params = new URLSearchParams({
+ cam: currentAlertsCamera,
+ window: windowSeconds,
+ max: formData.get('max'),
+ class_ids: classIds,
+ sched: JSON.stringify(schedArray),
+ });
+
+ fetch(`/edit_alert?${params.toString()}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to add alert");
+ return res.json();
+ })
+ .then(() => {
+ closeAlertModal();
+ form.reset();
+ fetchAlerts();
+ })
+ .catch(err => {
+ console.error("Add alert failed:", err);
+ alert("Failed to add alert.");
+ });
+ }
+
+ let currentAlertsCamera = null;
+ function toggleAlert(alertId, isOn) {
+ if (!currentAlertsCamera) return;
+
+ fetch(`/edit_alert?cam=${encodeURIComponent(currentAlertsCamera)}&id=${alertId}&is_on=${isOn}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to toggle alert");
+ console.log(`Alert ${alertId} ${isOn ? 'enabled' : 'disabled'}`);
+ })
+ .catch(err => {
+ console.error("Toggle alert failed:", err);
+ alert("Failed to toggle alert status.");
+ fetchAlerts();
+ });
+ }
+ document.addEventListener('DOMContentLoaded', function() {
+ initAlertCheckboxes();
+ });
+
+ function resetCounts() {
+ if (!currentAlertsCamera) return;
+
+ if (!confirm("Are you sure you want to reset the counts for this camera?")) return;
+ fetch(`/reset_counts?cam=${encodeURIComponent(currentAlertsCamera)}`)
+ .then(res => res.json())
+ .then(() => {
+ console.log("Counts reset");
+ fetchCounts();
+ })
+ .catch(err => {
+ console.error("Failed to reset counts:", err);
+ alert("Failed to reset counts.");
+ });
+ }
+
+ function closeAlertsModal() {
+ document.getElementById("alertsModal").style.display = "none";
+ currentAlertsCamera = null;
+ }
+
+ function deleteAlert(alertId) {
+ if (!currentAlertsCamera) return;
+
+ fetch(`/edit_alert?cam=${encodeURIComponent(currentAlertsCamera)}&id=${alertId}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to delete alert");
+ fetchAlerts();
+ })
+ .catch(err => {
+ console.error("Delete failed:", err);
+ alert("Failed to delete alert.");
+ });
+ }
+
+ function openAlertModal() {
+ document.getElementById("alertModal").style.display = "flex";
+ }
+
+ function closeAlertModal() {
+ document.getElementById("alertModal").style.display = "none";
+ }
+
+ const zoneModal = document.getElementById("zoneModal");
+
const activeVideoStreams = new Map();
let wasHidden = false;
let currentStreamDate = new Date().toLocaleDateString('en-CA');
let userIsInteracting = false;
+
+
+ let zoneEditorState = {
+ polygonSvg: null,
+ polygonPath: null,
+ firstPoint: null,
+ isPolygonComplete: false
+ };
+
document.addEventListener('DOMContentLoaded', function() {
const datePicker = document.getElementById('streamDatePicker');
datePicker.value = currentStreamDate;
@@ -341,14 +1283,11 @@
currentStreamDate = selectedDate;
console.log('Date changed to:', currentStreamDate);
restartAllStreams();
- loadEventImages(); // Reload events for the new date
+ loadEventImages();
}
});
- // Load initial events
loadEventImages();
-
- // Set up interval to refresh events every 5 seconds
setInterval(loadEventImages, 5000);
});
@@ -429,15 +1368,13 @@
container.innerHTML = '';
newCards.forEach(card => container.appendChild(card));
}
-
- // Start streams for new cameras
+
cams.forEach(cam => {
if (!activeVideoStreams.has(cam)) {
startCameraStream(cam);
}
});
-
- // Clean up streams for removed cameras
+
previousCameras.forEach(cameraName => {
if (!cams.includes(cameraName)) {
cleanupCameraStream(cameraName);
@@ -459,14 +1396,346 @@
<div class="video-placeholder" id="${placeholderId}">Loading stream...</div>
</div>
<div class="camera-info">
- <a href="/?cam=${encodeURIComponent(camName)}" class="camera-name" target="_blank">${camName}</a>
- <button onclick="deleteCamera('${camName}')">Delete</button>
+ <span class="camera-name">${camName}</span>
+ <div style="display: flex; gap: 6px; align-items: center;">
+ <label class="detection-toggle">
+ <input type="checkbox" class="show-detections-checkbox" data-camera="${camName}">
+ Show detections
+ </label>
+ <div class="button-group">
+ <button class="icon-button" onclick="openSettingsEditor('${camName}')" title="Settings">
+ <span class="icon">
+ <svg><use href="#icon-cog"></use></svg>
+ </span>
+ </button>
+ <button class="icon-button" onclick="openAlertsModal('${camName}')" title="Alerts">
+ <span class="icon">
+ <svg><use href="#icon-bell"></use></svg>
+ </span>
+ </button>
+ <button class="icon-button delete-button" onclick="deleteCamera('${camName}')" title="Delete">
+ <span class="icon">
+ <svg><use href="#icon-bin"></use></svg>
+ </span>
+ </button>
+ </div>
+ </div>
</div>
`;
-
+ setTimeout(() => initDetectionSettings(camName), 100);
return card;
}
+ let currentEditingCamera = null;
+ function openSettingsEditor(cameraName) {
+ currentEditingCamera = cameraName;
+ zoneEditorState = {
+ polygonSvg: null,
+ polygonPath: null,
+ firstPoint: null,
+ isPolygonComplete: false
+ };
+ const zonePreview = document.getElementById("zonePreview");
+ zonePreview.src = `/${cameraName}/preview.png`;
+ zoneModal.style.display = "flex";
+ initZoneEditor();
+ fetch(`/get_settings?cam=${cameraName}`)
+ .then(res => res.json())
+ .then(data => {
+ console.log("Received settings data:", data);
+ const previewEl = document.getElementById("zonePreview");
+ previewEl.onload = function() {
+ if (data && data.coords) {
+ console.log("Loading coords:", data.coords);
+ loadPolygon(data.coords, previewEl);
+ }
+ };
+ if (previewEl.complete) {
+ if (data && data.coords) {
+ console.log("Loading coords:", data.coords);
+ loadPolygon(data.coords, previewEl);
+ }
+ }
+
+ const zoneEnabledCheckbox = document.getElementById("zoneEnabledCheckbox");
+ if (data.is_on !== undefined) {
+ zoneEnabledCheckbox.checked = data.is_on;
+ } else if (data.length && data[0] && data[0].is_on !== undefined) {
+ zoneEnabledCheckbox.checked = data[0].is_on;
+ } else {
+ zoneEnabledCheckbox.checked = false;
+ }
+
+ const outsideZoneCheckbox = document.getElementById("outsideZoneCheckbox");
+ if (data.outside !== undefined) {
+ outsideZoneCheckbox.checked = data.outside;
+ } else if (data.length && data[0] && data[0].outside !== undefined) {
+ outsideZoneCheckbox.checked = data[0].outside;
+ } else {
+ outsideZoneCheckbox.checked = false;
+ }
+
+ const thresholdInput = document.getElementById("zoneThreshold");
+ let rawThreshold = undefined;
+ if (data.threshold !== undefined) {
+ rawThreshold = data.threshold;
+ } else if (data.length && data[0] && data[0].threshold !== undefined) {
+ rawThreshold = data[0].threshold;
+ }
+ if (rawThreshold !== undefined) {
+ if (rawThreshold <= 1) {
+ thresholdInput.value = (rawThreshold * 100).toFixed(0);
+ } else {
+ thresholdInput.value = rawThreshold.toFixed(0);
+ }
+ }
+ })
+ .catch(err => {
+ console.error("Failed to load zone:", err);
+ });
+ }
+
+ function closeZoneModal() {
+ zoneModal.style.display = "none";
+ currentEditingCamera = null;
+ zoneEditorState = {
+ polygonSvg: null,
+ polygonPath: null,
+ firstPoint: null,
+ isPolygonComplete: false
+ };
+ }
+
+ function isClickOnPoint(point, clickX, clickY) {
+ const pointRect = point.getBoundingClientRect();
+ const previewRect = document.getElementById("zonePreview").getBoundingClientRect();
+ const pointX = parseInt(point.style.left) + 6;
+ const pointY = parseInt(point.style.top) + 6;
+ const distance = Math.sqrt(Math.pow(clickX - pointX, 2) + Math.pow(clickY - pointY, 2));
+ return distance <= 10;
+ }
+
+ function initZoneEditor() {
+ const previewEl = document.getElementById("zonePreview");
+ clearPolygon();
+ initPolygonOverlay();
+ previewEl.addEventListener('click', handlePreviewClick);
+ }
+
+ function saveZone() {
+ if (!currentEditingCamera) {
+ console.error("No camera is currently being edited");
+ alert("Error: No camera selected for editing.");
+ return;
+ }
+
+ const previewEl = document.getElementById("zonePreview");
+ const points = Array.from(document.querySelectorAll('.polygon-point'));
+
+ let coords = null;
+ if (points.length >= 3) {
+ const videoWidth = 1280;
+ const videoHeight = 720;
+ const previewRect = previewEl.getBoundingClientRect();
+
+ coords = points.map(point => {
+ const pointRect = point.getBoundingClientRect();
+ const centerX = pointRect.left + pointRect.width / 2;
+ const centerY = pointRect.top + pointRect.height / 2;
+
+ const x = ((centerX - previewRect.left) / previewRect.width) * videoWidth;
+ const y = ((centerY - previewRect.top) / previewRect.height) * videoHeight;
+
+ return [x, y];
+ });
+ }
+
+ const is_on = document.getElementById("zoneEnabledCheckbox").checked;
+ const outside = document.getElementById("outsideZoneCheckbox").checked;
+
+ const thresholdPercent = parseFloat(document.getElementById("zoneThreshold").value) || 50;
+ const threshold = thresholdPercent / 100;
+
+ const params = new URLSearchParams({
+ cam: currentEditingCamera,
+ is_on: is_on,
+ threshold: threshold.toFixed(2),
+ outside: outside
+ });
+
+ if (coords) {
+ params.set('coords', JSON.stringify(coords));
+ }
+
+ fetch(`/edit_settings?${params.toString()}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to save settings");
+ console.log("Settings saved successfully for camera:", currentEditingCamera);
+ closeZoneModal();
+ })
+ .catch(err => {
+ console.error("Save settings failed:", err);
+ alert("Failed to save settings.");
+ });
+ }
+
+ function loadPolygon(coords, previewEl) {
+ const videoWidth = 1280;
+ const videoHeight = 720;
+ const img = document.getElementById("zonePreview");
+ if (img.complete) {
+ drawPolygonCoords(coords, img, previewEl);
+ } else {
+ img.addEventListener('load', function() {
+ drawPolygonCoords(coords, img, previewEl);
+ });
+ }
+ }
+
+ function drawPolygonCoords(coords, img, previewEl) {
+ const videoWidth = 1280;
+ const videoHeight = 720;
+ const displayedWidth = img.clientWidth;
+ const displayedHeight = img.clientHeight;
+ clearPolygon();
+ coords.forEach(coord => {
+ const x = (coord[0] / videoWidth) * displayedWidth;
+ const y = (coord[1] / videoHeight) * displayedHeight;
+ console.log("Creating point at:", x, y, "from coord:", coord);
+ createPoint(x, y);
+ });
+ updatePolygonLine();
+ if (coords.length >= 3) {
+ completePolygon();
+ }
+ }
+
+ function initPolygonOverlay() {
+ const overlay = document.getElementById("polygonOverlay");
+ overlay.innerHTML = '';
+ zoneEditorState.polygonSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ zoneEditorState.polygonSvg.style.width = '100%';
+ zoneEditorState.polygonSvg.style.height = '100%';
+ zoneEditorState.polygonSvg.style.position = 'absolute';
+ zoneEditorState.polygonSvg.style.top = '0';
+ zoneEditorState.polygonSvg.style.left = '0';
+ zoneEditorState.polygonSvg.style.pointerEvents = 'none';
+
+ zoneEditorState.polygonPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+ zoneEditorState.polygonPath.setAttribute('fill', 'none');
+ zoneEditorState.polygonPath.setAttribute('stroke', '#ff0000');
+ zoneEditorState.polygonPath.setAttribute('stroke-width', '2');
+ zoneEditorState.polygonPath.setAttribute('stroke-linejoin', 'round');
+
+ zoneEditorState.polygonSvg.appendChild(zoneEditorState.polygonPath);
+ overlay.appendChild(zoneEditorState.polygonSvg);
+ }
+
+ function clearPolygon() {
+ const overlay = document.getElementById("polygonOverlay");
+ const points = overlay.querySelectorAll('.polygon-point');
+ points.forEach(point => point.remove());
+ zoneEditorState.firstPoint = null;
+ zoneEditorState.isPolygonComplete = false;
+ if (zoneEditorState.polygonPath) {
+ zoneEditorState.polygonPath.setAttribute('d', '');
+ zoneEditorState.polygonPath.setAttribute('fill', 'none');
+ zoneEditorState.polygonPath.setAttribute('stroke', '#ff0000');
+ }
+ const previewEl = document.getElementById("zonePreview");
+ previewEl.addEventListener('click', handlePreviewClick);
+ }
+
+ function handlePreviewClick(e) {
+ const previewEl = document.getElementById("zonePreview");
+ const rect = previewEl.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ const y = e.clientY - rect.top;
+ if (zoneEditorState.firstPoint && isClickOnPoint(zoneEditorState.firstPoint, x, y)) {
+ completePolygon();
+ return;
+ }
+ createPoint(x, y);
+ updatePolygonLine();
+ }
+
+ function completePolygon() {
+ console.log("Completing polygon");
+ if (zoneEditorState.polygonPath) {
+ zoneEditorState.polygonPath.setAttribute('fill', 'rgba(0, 255, 0, 0.3)');
+ zoneEditorState.polygonPath.setAttribute('stroke', '#00ff00');
+ }
+ const previewEl = document.getElementById("zonePreview");
+ previewEl.removeEventListener('click', handlePreviewClick);
+ zoneEditorState.isPolygonComplete = true;
+ updatePolygonLine();
+ }
+
+ function createPoint(x, y) {
+ const overlay = document.getElementById("polygonOverlay");
+ const point = document.createElement('div');
+ point.className = 'polygon-point';
+ point.style.position = 'absolute';
+ point.style.left = (x - 6) + 'px';
+ point.style.top = (y - 6) + 'px';
+ point.style.width = '12px';
+ point.style.height = '12px';
+ point.style.backgroundColor = '#ff0000';
+ point.style.borderRadius = '50%';
+ point.style.cursor = 'crosshair';
+ point.style.zIndex = '20';
+ point.style.border = '2px solid #ffffff';
+ point.style.boxShadow = '0 0 3px rgba(0,0,0,0.5)';
+ point.style.pointerEvents = 'auto';
+ if (!zoneEditorState.firstPoint) {
+ zoneEditorState.firstPoint = point;
+ point.style.backgroundColor = '#0000ff';
+ point.style.border = '2px solid #ffffff';
+ point.style.cursor = 'pointer';
+ }
+ if (zoneEditorState.firstPoint === point) {
+ point.addEventListener('click', function(e) {
+ e.stopPropagation();
+ if (!zoneEditorState.isPolygonComplete) {
+ completePolygon();
+ }
+ });
+ }
+
+ overlay.appendChild(point);
+ return point;
+ }
+
+ function updatePolygonLine() {
+ const previewEl = document.getElementById("zonePreview");
+ const points = Array.from(document.querySelectorAll('.polygon-point'));
+
+ if (points.length === 0) {
+ if (zoneEditorState.polygonPath) {
+ zoneEditorState.polygonPath.setAttribute('d', '');
+ }
+ zoneEditorState.firstPoint = null;
+ zoneEditorState.isPolygonComplete = false;
+ return;
+ }
+ const pathData = points.map((point, index) => {
+ const rect = point.getBoundingClientRect();
+ const previewRect = previewEl.getBoundingClientRect();
+ const x = rect.left - previewRect.left + 6; // Center of point
+ const y = rect.top - previewRect.top + 6;
+ return `${index === 0 ? 'M' : 'L'} ${x} ${y}`;
+ }).join(' ');
+ if (zoneEditorState.isPolygonComplete) {
+ if (zoneEditorState.polygonPath) {
+ zoneEditorState.polygonPath.setAttribute('d', pathData + ' Z');
+ }
+ } else {
+ if (zoneEditorState.polygonPath) {
+ zoneEditorState.polygonPath.setAttribute('d', pathData);
+ }
+ }
+ }
+
function startCameraStream(camName) {
const videoId = `video-${camName}`;
const placeholderId = `placeholder-${camName}`;
@@ -477,13 +1746,13 @@
console.warn(`Video element not found for ${camName}`);
return;
}
-
- // Setup user interaction tracking for this video
- setupUserInteractionTracking(video);
+ const checkbox = document.querySelector(`.show-detections-checkbox[data-camera="${camName}"]`);
+ const showDetections = checkbox ? checkbox.checked : false;
+ const streamSuffix = showDetections ? "" : "_raw";
const encoded = encodeURIComponent(camName);
const baseUrl = window.location.origin;
- const streamUrl = `${baseUrl}/${encoded}_raw/streams/${currentStreamDate}/stream.m3u8`;
+ const streamUrl = `${baseUrl}/${encoded}${streamSuffix}/streams/${currentStreamDate}/stream.m3u8`;
activeVideoStreams.set(camName, {
video: video,
@@ -558,6 +1827,89 @@
});
}
+ const detectionIntervals = new Map();
+ function initDetectionSettings(cameraName) {
+ const checkbox = document.querySelector(`.show-detections-checkbox[data-camera="${cameraName}"]`);
+ if (!checkbox) return;
+ fetch(`/get_settings?cam=${encodeURIComponent(cameraName)}`)
+ .then(res => res.json())
+ .then(data => {
+ const showDetections = data.show_dets === 1 || data.show_dets === true;
+ checkbox.checked = showDetections;
+ updateCameraStream(cameraName, showDetections);
+ if (showDetections) {
+ startDetectionHeartbeat(cameraName);
+ }
+ })
+ .catch(err => {
+ console.error(`Failed to load detection settings for ${cameraName}:`, err);
+ });
+
+ checkbox.addEventListener('change', function() {
+ const showDetections = this.checked;
+ updateCameraStream(cameraName, showDetections);
+ fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=${showDetections ? 1 : 0}`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to update detection settings");
+ if (showDetections) {
+ startDetectionHeartbeat(cameraName);
+ } else {
+ stopDetectionHeartbeat(cameraName);
+ }
+ })
+ .catch(err => {
+ console.error(`Failed to update detection settings for ${cameraName}:`, err);
+ this.checked = !showDetections;
+ });
+ });
+ }
+
+ function updateCameraStream(cameraName, showDetections) {
+ const streamInfo = activeVideoStreams.get(cameraName);
+ if (!streamInfo) return;
+
+ const streamSuffix = showDetections ? "" : "_raw";
+ const newStreamUrl = `${window.location.origin}/${encodeURIComponent(cameraName)}${streamSuffix}/streams/${currentStreamDate}/stream.m3u8`;
+ if (streamInfo.streamUrl !== newStreamUrl) {
+ console.log(`Updating stream for ${cameraName} to ${showDetections ? 'with' : 'without'} detections`);
+ cleanupCameraStream(cameraName);
+ setTimeout(() => startCameraStream(cameraName), 100);
+ }
+ }
+
+ function startDetectionHeartbeat(cameraName) {
+ stopDetectionHeartbeat(cameraName);
+ fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=1`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to update detection settings");
+ console.log(`Detection heartbeat started for ${cameraName}`);
+ })
+ .catch(err => {
+ console.error(`Failed to start detection heartbeat for ${cameraName}:`, err);
+ });
+ const interval = setInterval(() => {
+ fetch(`/edit_settings?cam=${encodeURIComponent(cameraName)}&show_dets=1`)
+ .then(res => {
+ if (!res.ok) throw new Error("Failed to refresh detection settings");
+ console.log(`Detection settings refreshed for ${cameraName}`);
+ })
+ .catch(err => {
+ console.error(`Failed to refresh detection settings for ${cameraName}:`, err);
+ });
+ }, 30000);
+
+ detectionIntervals.set(cameraName, interval);
+ }
+
+ function stopDetectionHeartbeat(cameraName) {
+ const interval = detectionIntervals.get(cameraName);
+ if (interval) {
+ clearInterval(interval);
+ detectionIntervals.delete(cameraName);
+ console.log(`Detection heartbeat stopped for ${cameraName}`);
+ }
+ }
+
function cleanupCameraStream(camName) {
const streamInfo = activeVideoStreams.get(camName);
if (streamInfo) {
@@ -571,14 +1923,12 @@
}
activeVideoStreams.delete(camName);
}
+ stopDetectionHeartbeat(camName);
}
async function deleteCamera(cam) {
if (!confirm(`Are you sure you want to delete ${cam}?`)) return;
-
- // Clean up the stream first
cleanupCameraStream(cam);
-
const res = await fetch(`/delete_camera?cam_name=${cam}`);
if (res.ok) {
fetchCameras();
@@ -589,8 +1939,6 @@
async function shutdownServer() {
if (!confirm("Are you sure you want to shut down the server?")) return;
-
- // Clean up all streams
activeVideoStreams.forEach((stream, camName) => {
cleanupCameraStream(camName);
});
@@ -627,10 +1975,7 @@
await fetch(`/set_max_storage?max=${newVal}`);
fetchMaxStorage();
}
-
document.getElementById('setMaxStorageBtn').addEventListener('click', setMaxStorage);
-
- // Refresh storage field every 10 seconds
fetchMaxStorage();
setInterval(fetchMaxStorage, 10000);
@@ -859,21 +2204,15 @@
}
function playVideoAtTime(camName, timestamp) {
- // Find the video element for this camera
const videoId = `video-${camName}`;
const video = document.getElementById(videoId);
if (video) {
- // Calculate the time position in the video (assuming timestamp is in seconds)
video.currentTime = timestamp;
video.play().catch(e => console.log('Auto-play prevented:', e));
-
- // Scroll to the camera card
const cameraCard = video.closest('.camera-card');
if (cameraCard) {
cameraCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
-
- // Add a highlight effect
cameraCard.style.boxShadow = '0 0 0 3px #007bff';
setTimeout(() => {
cameraCard.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
@@ -885,9 +2224,6 @@
}
function playAllCamerasAtTime(timestamp) {
- console.log(`Playing all cameras at timestamp: ${timestamp}`);
-
- // Play all available cameras at the same timestamp
if (window.currentCameras && window.currentCameras.length > 0) {
window.currentCameras.forEach(camName => {
const videoId = `video-${camName}`;
@@ -898,14 +2234,10 @@
video.play().catch(e => console.log(`Auto-play prevented for ${camName}:`, e));
}
});
-
- // Scroll to the first camera card
const firstCameraCard = document.querySelector('.camera-card');
if (firstCameraCard) {
firstCameraCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
-
- // Highlight all camera cards briefly
document.querySelectorAll('.camera-card').forEach(card => {
card.style.boxShadow = '0 0 0 3px #6f42c1';
setTimeout(() => {
@@ -916,16 +2248,12 @@
alert("No cameras available to play");
}
}
-
- // Close modal when clicking outside the image
window.addEventListener("click", function(event) {
const modal = document.getElementById("imagePreviewModal");
if (event.target === modal) {
closeImagePreview();
}
});
-
- // Close modal with Escape key
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
closeImagePreview();