mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-23 22:07:07 +03:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
297ec2ace9 | ||
|
|
550276e430 | ||
|
|
3bca9b8676 |
@@ -22,3 +22,6 @@ add_header Set-Cookie $auth_cookie;
|
||||
## Pass the location header back up if it exists
|
||||
auth_request_set $redirection_url $upstream_http_location;
|
||||
add_header Location $redirection_url;
|
||||
|
||||
## The add_header lines above stop this location inheriting server-level headers
|
||||
include security_headers.conf;
|
||||
|
||||
@@ -152,7 +152,6 @@ http {
|
||||
sub_filter '.m4s' '.m4s$is_args$args';
|
||||
sub_filter '.mp4"' '.mp4$is_args$args"';
|
||||
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
|
||||
@@ -161,7 +160,6 @@ http {
|
||||
|
||||
location /stream/ {
|
||||
include auth_request.conf;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
|
||||
@@ -185,7 +183,6 @@ http {
|
||||
}
|
||||
|
||||
expires 7d;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "public";
|
||||
autoindex on;
|
||||
root /media/frigate;
|
||||
@@ -226,7 +223,7 @@ http {
|
||||
|
||||
location /ws {
|
||||
include auth_request.conf;
|
||||
proxy_pass http://mqtt_ws/;
|
||||
proxy_pass http://mqtt_ws;
|
||||
include proxy.conf;
|
||||
}
|
||||
|
||||
@@ -290,7 +287,6 @@ http {
|
||||
|
||||
location /api/ {
|
||||
include auth_request.conf;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
proxy_pass http://frigate_api/;
|
||||
|
||||
@@ -47,7 +47,10 @@ from frigate.const import (
|
||||
STREAM_TYPE_SUB,
|
||||
)
|
||||
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
|
||||
from frigate.output.preview import get_most_recent_preview_frame
|
||||
from frigate.output.preview import (
|
||||
get_most_recent_preview_frame,
|
||||
is_camera_preview_frame,
|
||||
)
|
||||
from frigate.track.object_processing import TrackedObjectProcessor
|
||||
from frigate.util.ffmpeg import terminate_ffmpeg_stream
|
||||
from frigate.util.file import (
|
||||
@@ -1603,7 +1606,7 @@ async def preview_gif(
|
||||
camera_files = [
|
||||
entry.name
|
||||
for entry in os.scandir(preview_dir)
|
||||
if entry.name.startswith(file_start)
|
||||
if is_camera_preview_frame(entry.name, camera_name)
|
||||
]
|
||||
camera_files.sort()
|
||||
|
||||
@@ -1794,7 +1797,7 @@ async def preview_mp4(
|
||||
camera_files = [
|
||||
entry.name
|
||||
for entry in os.scandir(preview_dir)
|
||||
if entry.name.startswith(file_start)
|
||||
if is_camera_preview_frame(entry.name, camera_name)
|
||||
]
|
||||
camera_files.sort()
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ from frigate.api.defs.response.preview_response import (
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
|
||||
from frigate.models import Previews
|
||||
from frigate.output.preview import is_camera_preview_frame
|
||||
from frigate.util.time import get_normalized_tz_name
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -187,7 +188,7 @@ def get_preview_frames_from_cache(camera_name: str, start_ts: float, end_ts: flo
|
||||
left = bisect.bisect_left(files, start_file)
|
||||
right = bisect.bisect_right(files, end_file)
|
||||
selected_previews = [
|
||||
file for file in files[left:right] if file.startswith(file_start)
|
||||
file for file in files[left:right] if is_camera_preview_frame(file, camera_name)
|
||||
]
|
||||
|
||||
return JSONResponse(
|
||||
|
||||
@@ -581,6 +581,7 @@ class WebPushClient(Communicator):
|
||||
sorted_objects.add(obj)
|
||||
|
||||
sorted_objects.update(payload["after"]["data"]["sub_labels"])
|
||||
sorted_objects.update(payload["after"]["data"]["audio"])
|
||||
|
||||
image = f"{payload['after']['thumb_path'].replace(BASE_DIR, '')}"
|
||||
ended = state == "end" or state == "genai"
|
||||
@@ -617,7 +618,14 @@ class WebPushClient(Communicator):
|
||||
else:
|
||||
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
|
||||
|
||||
title = f"{titlecase(', '.join(sorted_objects).replace('_', ' '))}{' was' if state == 'end' else ''} detected in {', '.join(formatted_zone_names)}"
|
||||
object_names = titlecase(
|
||||
", ".join(sorted(sorted_objects)).replace("_", " ")
|
||||
)
|
||||
title = f"{object_names}{' was' if state == 'end' else ''} detected"
|
||||
|
||||
if formatted_zone_names:
|
||||
title += f" in {', '.join(formatted_zone_names)}"
|
||||
|
||||
message = f"Detected on {camera_name}"
|
||||
|
||||
if ended:
|
||||
|
||||
@@ -379,7 +379,7 @@ def move_preview_frames(loc: str) -> None:
|
||||
src,
|
||||
dst,
|
||||
)
|
||||
except shutil.Error:
|
||||
except OSError:
|
||||
logger.error(
|
||||
"Failed to move preview restart cache from %s to %s",
|
||||
src,
|
||||
|
||||
@@ -1333,7 +1333,7 @@ class RecordingExporter(threading.Thread):
|
||||
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
|
||||
|
||||
for file in sorted(os.listdir(preview_dir)):
|
||||
if not file.startswith(file_start):
|
||||
if not is_camera_preview_frame(file, self.camera):
|
||||
continue
|
||||
|
||||
if file < start_file:
|
||||
|
||||
@@ -4,6 +4,7 @@ from unittest.mock import Mock, patch
|
||||
|
||||
import frigate.genai
|
||||
from frigate.config import GenAIProviderEnum
|
||||
from frigate.config.config import RuntimeFilterConfig
|
||||
from frigate.const import MODEL_CACHE_DIR, REDACTED_CREDENTIAL_SENTINEL
|
||||
from frigate.genai import GenAIClient
|
||||
from frigate.models import Event, Recordings, ReviewSegment
|
||||
@@ -98,6 +99,32 @@ class TestHttpApp(BaseTestHttp):
|
||||
assert response.status_code == 200
|
||||
assert app.frigate_config.cameras["front_door"].objects.track == ["person"]
|
||||
|
||||
def test_config_set_in_memory_adds_filters_for_new_tracked_labels(self):
|
||||
self.minimal_config["cameras"]["front_door"]["objects"] = {
|
||||
"track": ["person"],
|
||||
}
|
||||
app = super().create_app()
|
||||
app.config_publisher = Mock()
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.put(
|
||||
"/config/set",
|
||||
json={
|
||||
"requires_restart": 0,
|
||||
"skip_save": True,
|
||||
"update_topic": "config/cameras/front_door/objects",
|
||||
"config_data": {
|
||||
"cameras": {
|
||||
"front_door": {"objects": {"track": ["person", "cat"]}}
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
filters = app.frigate_config.cameras["front_door"].objects.filters
|
||||
assert isinstance(filters["cat"], RuntimeFilterConfig)
|
||||
|
||||
@patch("frigate.detectors.detector_config.load_labels")
|
||||
def test_config_set_in_memory_rebinds_replay_model_on_scene_change(
|
||||
self, mock_labels
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Current-hour preview frame routes only return the requested camera's frames."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from frigate.const import PREVIEW_FRAME_TYPE
|
||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||
|
||||
CAMERA = "front_door"
|
||||
|
||||
# camera names that extend CAMERA with "-" share its file name prefix
|
||||
SIBLINGS = (f"{CAMERA}-2", f"{CAMERA}-door")
|
||||
|
||||
|
||||
class TestHttpPreviewFrames(BaseTestHttp):
|
||||
def setUp(self):
|
||||
super().setUp([])
|
||||
self.app = super().create_app()
|
||||
|
||||
self.cache_dir = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
|
||||
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
|
||||
os.makedirs(self.preview_dir)
|
||||
|
||||
for target, value in (
|
||||
("frigate.api.media.CACHE_DIR", self.cache_dir),
|
||||
("frigate.api.preview.CACHE_DIR", self.cache_dir),
|
||||
("frigate.api.preview._preview_listing_cache", (-1.0, [])),
|
||||
):
|
||||
patcher = patch(target, value)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
# ahead of now so the media routes never fall back to stored previews
|
||||
|
||||
self.start_ts = time.time() + 60
|
||||
self._write_frame(CAMERA, self.start_ts - 10)
|
||||
self.own_frames = [self._write_frame(CAMERA, self.start_ts + 1)]
|
||||
|
||||
for sibling in SIBLINGS:
|
||||
self._write_frame(sibling, self.start_ts + 1)
|
||||
|
||||
def _write_frame(self, camera: str, frame_time: float) -> str:
|
||||
name = f"preview_{camera}-{frame_time}.{PREVIEW_FRAME_TYPE}"
|
||||
with open(os.path.join(self.preview_dir, name), "wb") as f:
|
||||
f.write(b"frame")
|
||||
return name
|
||||
|
||||
def _concat_files(self, mock_run: MagicMock) -> set[str]:
|
||||
concat = mock_run.call_args.kwargs["input"].decode()
|
||||
return {
|
||||
os.path.basename(line.split("'")[1])
|
||||
for line in concat.splitlines()
|
||||
if line.startswith("file ")
|
||||
}
|
||||
|
||||
def test_frames_listing_excludes_sibling_camera(self):
|
||||
with AuthTestClient(self.app) as client:
|
||||
response = client.get(
|
||||
f"/preview/{CAMERA}/start/{self.start_ts}/end/inf/frames"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == self.own_frames
|
||||
|
||||
def test_preview_gif_excludes_sibling_camera(self):
|
||||
result = MagicMock(returncode=0, stdout=b"GIF89a")
|
||||
|
||||
with (
|
||||
patch("frigate.api.media.sp.run", return_value=result) as mock_run,
|
||||
AuthTestClient(self.app) as client,
|
||||
):
|
||||
response = client.get(
|
||||
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.gif"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert self._concat_files(mock_run) == set(self.own_frames)
|
||||
|
||||
def test_preview_mp4_excludes_sibling_camera(self):
|
||||
def fake_run(cmd, **kwargs):
|
||||
with open(cmd[-1], "wb") as f:
|
||||
f.write(b"mp4")
|
||||
return MagicMock(returncode=0)
|
||||
|
||||
with (
|
||||
patch("frigate.api.media.sp.run", side_effect=fake_run) as mock_run,
|
||||
AuthTestClient(self.app) as client,
|
||||
):
|
||||
response = client.get(
|
||||
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.mp4"
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert self._concat_files(mock_run) == set(self.own_frames)
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Tests for export progress tracking, broadcast, and FFmpeg parsing."""
|
||||
|
||||
import datetime
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
@@ -7,11 +8,14 @@ import tempfile
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.jobs.export import (
|
||||
PROGRESS_BROADCAST_MIN_INTERVAL,
|
||||
ExportJob,
|
||||
ExportJobManager,
|
||||
)
|
||||
from frigate.models import Previews
|
||||
from frigate.record.export import (
|
||||
ExportStreamEnum,
|
||||
PlaybackSourceEnum,
|
||||
@@ -557,5 +561,38 @@ class TestChapterMetadataInProgressReview(unittest.TestCase):
|
||||
assert "title=Alert: person" in content
|
||||
|
||||
|
||||
class TestPreviewExportCommandCameraMatch(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.cache_dir = tempfile.mkdtemp(prefix="frigate_preview_export_test_")
|
||||
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
|
||||
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
|
||||
os.makedirs(self.preview_dir)
|
||||
|
||||
def _write_frame(self, camera: str, frame_time: float) -> str:
|
||||
path = os.path.join(self.preview_dir, f"preview_{camera}-{frame_time}.webp")
|
||||
with open(path, "wb") as f:
|
||||
f.write(b"fake-webp-bytes")
|
||||
return path
|
||||
|
||||
def test_current_hour_playlist_excludes_sibling_camera(self) -> None:
|
||||
exporter = _make_exporter()
|
||||
exporter.playback_source = PlaybackSourceEnum.preview
|
||||
exporter.start_time = datetime.datetime.now(datetime.UTC).timestamp()
|
||||
exporter.end_time = 9_999_999_999
|
||||
own = self._write_frame(exporter.camera, exporter.start_time + 1)
|
||||
self._write_frame(f"{exporter.camera}-2", exporter.start_time + 1)
|
||||
|
||||
db = SqliteDatabase(":memory:")
|
||||
with (
|
||||
patch("frigate.record.export.CACHE_DIR", self.cache_dir),
|
||||
db.bind_ctx([Previews]),
|
||||
):
|
||||
Previews.create_table()
|
||||
_, playlist_lines = exporter.get_preview_export_command("out.mp4")
|
||||
|
||||
files = {line for line in playlist_lines if line.startswith("file ")}
|
||||
assert files == {f"file '{own}'"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
|
||||
|
||||
from frigate.config import BirdseyeModeEnum, FrigateConfig
|
||||
from frigate.config.camera.profile import CameraProfileConfig
|
||||
from frigate.config.config import RuntimeFilterConfig
|
||||
from frigate.config.profile import ProfileDefinitionConfig
|
||||
from frigate.config.profile_manager import PERSISTENCE_FILE, ProfileManager
|
||||
from frigate.const import MODEL_CACHE_DIR
|
||||
@@ -502,6 +503,16 @@ class TestProfileManager(unittest.TestCase):
|
||||
back = self.config.cameras["back"]
|
||||
assert back.notifications.enabled is True
|
||||
|
||||
@patch.object(ProfileManager, "_persist_active_profile")
|
||||
def test_activate_profile_adds_filters_for_new_tracked_labels(self, mock_persist):
|
||||
"""Labels a profile adds to objects.track get default filters."""
|
||||
err = self.manager.activate_profile("armed")
|
||||
assert err is None
|
||||
|
||||
filters = self.config.cameras["front"].objects.filters
|
||||
for label in ["person", "car", "package"]:
|
||||
assert isinstance(filters[label], RuntimeFilterConfig)
|
||||
|
||||
@patch.object(ProfileManager, "_persist_active_profile")
|
||||
def test_deactivate_profile(self, mock_persist):
|
||||
"""Deactivating a profile restores base config."""
|
||||
|
||||
@@ -1191,7 +1191,11 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
|
||||
Returns:
|
||||
None on success, or an error message string on failure.
|
||||
"""
|
||||
from frigate.config.config import RuntimeFilterConfig, RuntimeMotionConfig
|
||||
from frigate.config.config import (
|
||||
FilterConfig,
|
||||
RuntimeFilterConfig,
|
||||
RuntimeMotionConfig,
|
||||
)
|
||||
|
||||
current = getattr(camera_config, section, None)
|
||||
if current is None:
|
||||
@@ -1224,6 +1228,9 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
for label in new_objects.track:
|
||||
new_objects.filters.setdefault(label, FilterConfig())
|
||||
|
||||
# Rebuild RuntimeFilterConfig with merged global + per-object masks
|
||||
for obj_name, filt in new_objects.filters.items():
|
||||
merged_mask = dict(filt.mask)
|
||||
|
||||
@@ -184,8 +184,8 @@ export default function ObjectSettingsView({
|
||||
{config?.cameras[cameraConfig.name]?.webui_url && (
|
||||
<div className="mb-5 text-sm text-muted-foreground">
|
||||
<div className="mt-2 flex flex-row items-center text-primary">
|
||||
<Link
|
||||
to={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
|
||||
<a
|
||||
href={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline"
|
||||
@@ -194,7 +194,7 @@ export default function ObjectSettingsView({
|
||||
camera: cameraName,
|
||||
})}
|
||||
<LuExternalLink className="ml-2 inline-flex size-3" />
|
||||
</Link>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user