mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 06:17:12 +03:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0157d7515 | ||
|
|
f6eae237bf |
@@ -22,6 +22,3 @@ 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,6 +152,7 @@ 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;
|
||||
|
||||
@@ -160,6 +161,7 @@ http {
|
||||
|
||||
location /stream/ {
|
||||
include auth_request.conf;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
|
||||
@@ -183,6 +185,7 @@ http {
|
||||
}
|
||||
|
||||
expires 7d;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "public";
|
||||
autoindex on;
|
||||
root /media/frigate;
|
||||
@@ -223,7 +226,7 @@ http {
|
||||
|
||||
location /ws {
|
||||
include auth_request.conf;
|
||||
proxy_pass http://mqtt_ws;
|
||||
proxy_pass http://mqtt_ws/;
|
||||
include proxy.conf;
|
||||
}
|
||||
|
||||
@@ -287,6 +290,7 @@ http {
|
||||
|
||||
location /api/ {
|
||||
include auth_request.conf;
|
||||
include security_headers.conf;
|
||||
add_header Cache-Control "no-store";
|
||||
expires off;
|
||||
proxy_pass http://frigate_api/;
|
||||
|
||||
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
|
||||
|
||||
# Metrics
|
||||
|
||||
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance.
|
||||
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance. On the authenticated port (8971), the endpoint requires an admin user, so point scrapers at the internal port (5000) as shown below.
|
||||
|
||||
## Enabling Telemetry
|
||||
|
||||
|
||||
Vendored
+3
-3
@@ -2546,7 +2546,7 @@ paths:
|
||||
- App
|
||||
summary: Metrics
|
||||
description: |-
|
||||
**Access:** Any authenticated user.
|
||||
**Access:** Admin role required.
|
||||
|
||||
Expose Prometheus metrics endpoint and update metrics with latest stats
|
||||
operationId: metrics_metrics_get
|
||||
@@ -2557,8 +2557,8 @@ paths:
|
||||
application/json:
|
||||
schema: {}
|
||||
security:
|
||||
- frigateUserAuth: []
|
||||
x-required-role: any
|
||||
- frigateAdminAuth: []
|
||||
x-required-role: admin
|
||||
/genai/models:
|
||||
get:
|
||||
tags:
|
||||
|
||||
+46
-35
@@ -64,6 +64,7 @@ from frigate.util.builtin import (
|
||||
is_masked_camera_path,
|
||||
load_labels,
|
||||
process_config_query_string,
|
||||
scope_stats_for_non_admin,
|
||||
split_config_key_path,
|
||||
update_yaml_file_bulk,
|
||||
)
|
||||
@@ -131,37 +132,12 @@ def stats(
|
||||
):
|
||||
stats_data = request.app.stats_emitter.get_latest_stats()
|
||||
|
||||
# Admins see the full snapshot
|
||||
if request.headers.get("remote-role") == "admin":
|
||||
return JSONResponse(content=stats_data)
|
||||
|
||||
allowed_set = set(allowed_cameras)
|
||||
|
||||
# Shallow-copy so we don't mutate the cached stats history entry.
|
||||
filtered = {**stats_data}
|
||||
|
||||
cameras = stats_data.get("cameras")
|
||||
if cameras is not None:
|
||||
filtered["cameras"] = {
|
||||
name: data for name, data in cameras.items() if name in allowed_set
|
||||
}
|
||||
|
||||
bandwidth = stats_data.get("bandwidth_usages")
|
||||
if bandwidth is not None:
|
||||
filtered["bandwidth_usages"] = {
|
||||
name: data for name, data in bandwidth.items() if name in allowed_set
|
||||
}
|
||||
|
||||
# cmdline can leak camera URLs/paths; strip but keep cpu/mem so
|
||||
# client-side problem heuristics still work.
|
||||
cpu_usages = stats_data.get("cpu_usages")
|
||||
if cpu_usages is not None:
|
||||
filtered["cpu_usages"] = {
|
||||
pid: {k: v for k, v in usage.items() if k != "cmdline"}
|
||||
for pid, usage in cpu_usages.items()
|
||||
}
|
||||
|
||||
return JSONResponse(content=filtered)
|
||||
return JSONResponse(
|
||||
content=scope_stats_for_non_admin(stats_data, set(allowed_cameras))
|
||||
)
|
||||
|
||||
|
||||
@router.get("/stats/history", dependencies=[Depends(require_role(["admin"]))])
|
||||
@@ -172,7 +148,7 @@ def stats_history(request: Request, keys: str = None):
|
||||
return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys))
|
||||
|
||||
|
||||
@router.get("/metrics", dependencies=[Depends(allow_any_authenticated())])
|
||||
@router.get("/metrics", dependencies=[Depends(require_role(["admin"]))])
|
||||
def metrics(request: Request):
|
||||
"""Expose Prometheus metrics endpoint and update metrics with latest stats"""
|
||||
# Retrieve the latest statistics and update the Prometheus metrics
|
||||
@@ -320,10 +296,12 @@ def config(request: Request):
|
||||
|
||||
is_admin = request.headers.get("remote-role") == "admin"
|
||||
|
||||
# hide environment_vars and the notification email from non-admin users
|
||||
# hide environment_vars, the notification email and ffmpeg args (which
|
||||
# can carry auth headers) from non-admin users
|
||||
if not is_admin:
|
||||
config.pop("environment_vars", None)
|
||||
redact_credential(config["notifications"], "email")
|
||||
_drop_ffmpeg_args(config.get("ffmpeg", {}))
|
||||
|
||||
# redact mqtt credentials
|
||||
redact_credential(config["mqtt"], "password")
|
||||
@@ -331,11 +309,15 @@ def config(request: Request):
|
||||
# redact proxy secret
|
||||
redact_credential(config["proxy"], "auth_secret")
|
||||
|
||||
# redact genai api keys
|
||||
# redact genai api keys; base_url and provider_options can carry proxy auth
|
||||
for _genai_name, genai_cfg in config.get("genai", {}).items():
|
||||
if isinstance(genai_cfg, dict):
|
||||
redact_credential(genai_cfg, "api_key")
|
||||
|
||||
if not is_admin:
|
||||
genai_cfg.pop("base_url", None)
|
||||
genai_cfg.pop("provider_options", None)
|
||||
|
||||
for camera_name, camera in request.app.frigate_config.cameras.items():
|
||||
camera_dict = config["cameras"][camera_name]
|
||||
|
||||
@@ -353,6 +335,19 @@ def config(request: Request):
|
||||
for cmd in camera_dict["ffmpeg_cmds"]:
|
||||
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
|
||||
|
||||
# masking misses vendor-specific credentials in paths and args, and the
|
||||
# non-admin UI never reads them
|
||||
if not is_admin:
|
||||
ffmpeg = camera_dict.get("ffmpeg", {})
|
||||
_drop_ffmpeg_args(ffmpeg)
|
||||
|
||||
for input in ffmpeg.get("inputs", []):
|
||||
input["path"] = ""
|
||||
_drop_ffmpeg_args(input)
|
||||
|
||||
camera_dict["ffmpeg_cmds"] = []
|
||||
camera_dict.pop("webui_url", None)
|
||||
|
||||
# ensure that zones are relative
|
||||
for zone_name, zone in config_obj.cameras[camera_name].zones.items():
|
||||
camera_dict["zones"][zone_name]["color"] = zone.color
|
||||
@@ -363,11 +358,13 @@ def config(request: Request):
|
||||
# over the camera's actual base values (e.g. threshold=20).
|
||||
if camera.profiles:
|
||||
for profile_name, profile_config in camera.profiles.items():
|
||||
camera_dict.setdefault("profiles", {})[profile_name] = (
|
||||
profile_config.model_dump(
|
||||
mode="json", warnings="none", exclude_unset=True
|
||||
)
|
||||
profile_dict = profile_config.model_dump(
|
||||
mode="json", warnings="none", exclude_unset=True
|
||||
)
|
||||
camera_dict.setdefault("profiles", {})[profile_name] = profile_dict
|
||||
|
||||
if not is_admin:
|
||||
redact_credential(profile_dict.get("notifications") or {}, "email")
|
||||
|
||||
# When a profile is active, the top-level camera sections contain
|
||||
# profile-merged (effective) values. Include the original base
|
||||
@@ -409,6 +406,15 @@ def config(request: Request):
|
||||
|
||||
_redact_go2rtc_credentials(config["go2rtc"])
|
||||
|
||||
if not is_admin:
|
||||
# go2rtc allows arbitrary extra keys, so non-admins get only what the
|
||||
# UI reads: stream names, and webrtc, whose ice_servers credentials
|
||||
# the browser needs
|
||||
config["go2rtc"] = {
|
||||
"streams": {name: [] for name in config["go2rtc"].get("streams", {})},
|
||||
"webrtc": config["go2rtc"].get("webrtc", {}),
|
||||
}
|
||||
|
||||
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
|
||||
|
||||
for index, model in enumerate(config_obj.models):
|
||||
@@ -435,6 +441,11 @@ def config(request: Request):
|
||||
return JSONResponse(content=config)
|
||||
|
||||
|
||||
def _drop_ffmpeg_args(ffmpeg: dict[str, Any]) -> None:
|
||||
for key in ("global_args", "input_args", "output_args"):
|
||||
ffmpeg.pop(key, None)
|
||||
|
||||
|
||||
def _redact_go2rtc_credentials(go2rtc: dict[str, Any]) -> None:
|
||||
"""Redact go2rtc secrets outside of stream URLs, in place."""
|
||||
for section in ("rtsp", "api", "mqtt"):
|
||||
|
||||
+3
-2
@@ -81,10 +81,11 @@ def require_admin_by_default():
|
||||
"/",
|
||||
"/version",
|
||||
"/config/schema.json",
|
||||
# Authenticated user endpoints (allow_any_authenticated)
|
||||
# Admin endpoints that enforce require_role on the route
|
||||
"/metrics",
|
||||
"/stats",
|
||||
"/stats/history",
|
||||
# Authenticated user endpoints (allow_any_authenticated)
|
||||
"/stats",
|
||||
"/config",
|
||||
"/vainfo",
|
||||
"/nvinfo",
|
||||
|
||||
+24
-8
@@ -6,6 +6,7 @@ import logging
|
||||
import re
|
||||
from importlib.util import find_spec
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
import httpx
|
||||
@@ -82,6 +83,23 @@ def _is_valid_host(host: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _clean_stream(request: Request, stream: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Mask producer urls for admins; others get only producer medias.
|
||||
|
||||
Producer and consumer urls and sources can carry credentials that masking
|
||||
misses, and the non-admin UI only reads producer medias.
|
||||
"""
|
||||
producers = stream.get("producers") or []
|
||||
|
||||
if request.headers.get("remote-role") != "admin":
|
||||
return {"producers": [{"medias": p.get("medias")} for p in producers]}
|
||||
|
||||
for producer in producers:
|
||||
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
||||
|
||||
return stream
|
||||
|
||||
|
||||
@router.get("/go2rtc/streams", dependencies=[Depends(allow_any_authenticated())])
|
||||
async def go2rtc_streams(request: Request):
|
||||
try:
|
||||
@@ -114,10 +132,11 @@ async def go2rtc_streams(request: Request):
|
||||
if _get_stream_owner_cameras(request, name) & allowed_cameras
|
||||
}
|
||||
|
||||
for data in stream_data.values():
|
||||
for producer in data.get("producers") or []:
|
||||
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
||||
return JSONResponse(content=stream_data)
|
||||
return JSONResponse(
|
||||
content={
|
||||
name: _clean_stream(request, data) for name, data in stream_data.items()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -155,10 +174,7 @@ def go2rtc_camera_stream(request: Request, stream_name: str):
|
||||
content=({"success": False, "message": "Error fetching stream data"}),
|
||||
status_code=500,
|
||||
)
|
||||
stream_data = r.json()
|
||||
for producer in stream_data.get("producers", []):
|
||||
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
||||
return JSONResponse(content=stream_data)
|
||||
return JSONResponse(content=_clean_stream(request, r.json()))
|
||||
|
||||
|
||||
@router.put(
|
||||
|
||||
@@ -9,8 +9,8 @@ class MediaRecordingsSummaryQueryParams(BaseModel):
|
||||
|
||||
class MediaRecordingsAvailabilityQueryParams(BaseModel):
|
||||
cameras: str = "all"
|
||||
before: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
|
||||
after: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
|
||||
before: float | SkipJsonSchema[None] = None
|
||||
after: float | SkipJsonSchema[None] = None
|
||||
scale: int = Field(default=30, ge=1)
|
||||
|
||||
|
||||
|
||||
@@ -166,13 +166,10 @@ def imagestream(
|
||||
time.sleep(1 / fps)
|
||||
frame = detected_frames_processor.get_current_frame(camera_name, draw_options)
|
||||
if frame is None:
|
||||
frame = np.zeros((360, 640, 3), np.uint8)
|
||||
frame = np.zeros((height, int(height * 16 / 9), 3), np.uint8)
|
||||
|
||||
frame_height = min(height, frame.shape[0])
|
||||
width = int(frame_height * frame.shape[1] / frame.shape[0])
|
||||
frame = cv2.resize(
|
||||
frame, dsize=(width, frame_height), interpolation=cv2.INTER_LINEAR
|
||||
)
|
||||
width = int(height * frame.shape[1] / frame.shape[0])
|
||||
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
|
||||
yield (
|
||||
@@ -281,7 +278,7 @@ async def latest_frame(
|
||||
status_code=500,
|
||||
)
|
||||
|
||||
height = min(params.height or frame.shape[0], frame.shape[0])
|
||||
height = int(params.height or str(frame.shape[0]))
|
||||
width = int(height * frame.shape[1] / frame.shape[0])
|
||||
|
||||
if height < 1 or width < 1:
|
||||
@@ -323,7 +320,7 @@ async def latest_frame(
|
||||
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
|
||||
|
||||
height = min(params.height or frame.shape[0], frame.shape[0])
|
||||
height = int(params.height or str(frame.shape[0]))
|
||||
width = int(height * frame.shape[1] / frame.shape[0])
|
||||
|
||||
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
|
||||
|
||||
@@ -20,7 +20,7 @@ from urllib.parse import unquote
|
||||
from peewee import DoesNotExist, Field
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.const import CLIPS_DIR, EXPORT_DIR, SUB_CACHE_TAG
|
||||
from frigate.const import CLIPS_DIR, EXPORT_DIR
|
||||
from frigate.models import Export, User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -137,12 +137,11 @@ def _resolve_recording(
|
||||
# /recordings/{date} → neutral
|
||||
# /recordings/{date}/{hour} → multi-camera listing
|
||||
# /recordings/{date}/{hour}/{cam}/... → camera
|
||||
# /recordings/{date}/{hour}/{cam}@sub/... → camera (sub stream)
|
||||
if len(parts) <= 2:
|
||||
return MediaAuthResolution.LISTING_NEUTRAL, None
|
||||
if len(parts) == 3:
|
||||
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
|
||||
return MediaAuthResolution.CAMERA, parts[3].removesuffix(SUB_CACHE_TAG)
|
||||
return MediaAuthResolution.CAMERA, parts[3]
|
||||
|
||||
|
||||
def _resolve_clip(
|
||||
@@ -151,7 +150,6 @@ def _resolve_clip(
|
||||
# /clips → multi-camera listing
|
||||
# /clips/thumbs/{cam}/... → camera
|
||||
# /clips/previews/{cam}/... → camera
|
||||
# /clips/triggers/{cam}/... → camera
|
||||
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
|
||||
# /clips/export/{export_id}.{ext} → camera (DB lookup)
|
||||
# /clips/faces/... → admin-only
|
||||
@@ -165,7 +163,7 @@ def _resolve_clip(
|
||||
|
||||
second = parts[1]
|
||||
|
||||
if second in ("thumbs", "previews", "triggers"):
|
||||
if second in ("thumbs", "previews"):
|
||||
if len(parts) == 2:
|
||||
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
|
||||
return MediaAuthResolution.CAMERA, parts[2]
|
||||
|
||||
+35
-29
@@ -2,7 +2,6 @@
|
||||
|
||||
import datetime as dt
|
||||
import logging
|
||||
import math
|
||||
from datetime import datetime, timedelta
|
||||
from functools import reduce
|
||||
from pathlib import Path
|
||||
@@ -444,38 +443,45 @@ async def no_recordings(
|
||||
else:
|
||||
covered.append((rec_start, rec_end))
|
||||
|
||||
# A scale-sized bucket counts as empty when it fits inside a gap between
|
||||
# covered intervals. Walking the gaps keeps the work proportional to the
|
||||
# recordings found rather than to the requested span.
|
||||
bucket_count = math.ceil((before - after) / scale)
|
||||
gaps: list[list[float]] = []
|
||||
free_start = -math.inf
|
||||
# Iterate through time segments and check if each has any recording
|
||||
no_recording_segments = []
|
||||
current = after
|
||||
current_gap_start = None
|
||||
idx = 0
|
||||
covered_count = len(covered)
|
||||
|
||||
for rec_start, rec_end in covered + [(math.inf, math.inf)]:
|
||||
first = 0 if free_start <= after else math.ceil((free_start - after) / scale)
|
||||
while current < before:
|
||||
segment_end = min(current + scale, before)
|
||||
|
||||
if rec_start >= before:
|
||||
last = bucket_count - 1
|
||||
# Advance past covered intervals that end before this segment begins;
|
||||
# they cannot overlap this or any later segment.
|
||||
while idx < covered_count and covered[idx][1] <= current:
|
||||
idx += 1
|
||||
|
||||
# A covered interval overlaps the segment when it starts before the
|
||||
# segment ends (its end is already known to be > current).
|
||||
has_recording = idx < covered_count and covered[idx][0] < segment_end
|
||||
|
||||
if not has_recording:
|
||||
# This segment has no recordings
|
||||
if current_gap_start is None:
|
||||
current_gap_start = current # Start a new gap
|
||||
else:
|
||||
last = min(math.floor((rec_start - after) / scale), bucket_count) - 1
|
||||
# This segment has recordings
|
||||
if current_gap_start is not None:
|
||||
# End the current gap and append it
|
||||
no_recording_segments.append(
|
||||
{"start_time": int(current_gap_start), "end_time": int(current)}
|
||||
)
|
||||
current_gap_start = None
|
||||
|
||||
if first <= last:
|
||||
gap_start = after + first * scale
|
||||
gap_end = before if last == bucket_count - 1 else after + (last + 1) * scale
|
||||
current = segment_end
|
||||
|
||||
if gaps and gaps[-1][1] == gap_start:
|
||||
gaps[-1][1] = gap_end
|
||||
else:
|
||||
gaps.append([gap_start, gap_end])
|
||||
|
||||
free_start = rec_end
|
||||
if free_start >= before:
|
||||
break
|
||||
|
||||
no_recording_segments = [
|
||||
{"start_time": int(gap_start), "end_time": int(gap_end)}
|
||||
for gap_start, gap_end in gaps
|
||||
]
|
||||
# Append the last gap if it exists
|
||||
if current_gap_start is not None:
|
||||
no_recording_segments.append(
|
||||
{"start_time": int(current_gap_start), "end_time": int(before)}
|
||||
)
|
||||
|
||||
return JSONResponse(content=no_recording_segments)
|
||||
|
||||
@@ -489,7 +495,7 @@ async def no_recordings(
|
||||
Recordings can be filtered by cameras and kept based on motion, objects, or audio attributes.
|
||||
""",
|
||||
)
|
||||
def delete_recordings(
|
||||
async def delete_recordings(
|
||||
start: float = PathParam(..., description="Start timestamp (unix)"),
|
||||
end: float = PathParam(..., description="End timestamp (unix)"),
|
||||
params: RecordingsDeleteQueryParams = Depends(),
|
||||
|
||||
@@ -581,7 +581,6 @@ 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"
|
||||
@@ -618,14 +617,7 @@ class WebPushClient(Communicator):
|
||||
else:
|
||||
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
|
||||
|
||||
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)}"
|
||||
|
||||
title = f"{titlecase(', '.join(sorted_objects).replace('_', ' '))}{' was' if state == 'end' else ''} detected in {', '.join(formatted_zone_names)}"
|
||||
message = f"Detected on {camera_name}"
|
||||
|
||||
if ended:
|
||||
@@ -685,7 +677,7 @@ class WebPushClient(Communicator):
|
||||
|
||||
title = f"{name.replace('_', ' ')} triggered on {camera_name}"
|
||||
message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}"
|
||||
image = f"api/events/{event_id}/thumbnail.webp"
|
||||
image = f"clips/triggers/{camera}/{event_id}.webp"
|
||||
|
||||
direct_url = f"/explore?event_id={event_id}"
|
||||
ttl = 0
|
||||
|
||||
+7
-12
@@ -40,6 +40,7 @@ from frigate.const import (
|
||||
)
|
||||
from frigate.models import User
|
||||
from frigate.output.ws_auth import ws_has_camera_access
|
||||
from frigate.util.builtin import scope_stats_for_non_admin
|
||||
from frigate.util.origin import origin_allowed
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -210,7 +211,7 @@ _WS_RESHAPE_JOB_STATE_TOPICS = frozenset(
|
||||
|
||||
# Topics whose payload mixes global aggregates with a ``cameras`` sub-dict
|
||||
# keyed by camera name. Aggregates and detector data stay; per-camera entries
|
||||
# are filtered.
|
||||
# are filtered and process cmdlines are stripped for non-admins.
|
||||
_WS_RESHAPE_STATS_TOPICS = frozenset(
|
||||
{
|
||||
"stats",
|
||||
@@ -455,20 +456,14 @@ def _materialize_for_ws(
|
||||
return _wrap_envelope(topic, filtered_jobs)
|
||||
|
||||
if kind == "reshape_stats":
|
||||
if _ws_is_unrestricted(ws, config):
|
||||
if "admin" in _ws_valid_roles(ws, config):
|
||||
return full_message
|
||||
if not isinstance(parsed_payload, dict):
|
||||
return None
|
||||
allowed = _ws_allowed_cameras(ws, config)
|
||||
cameras_block = parsed_payload.get("cameras")
|
||||
if isinstance(cameras_block, dict):
|
||||
filtered_cameras = {
|
||||
name: data for name, data in cameras_block.items() if name in allowed
|
||||
}
|
||||
reshaped = dict(parsed_payload)
|
||||
reshaped["cameras"] = filtered_cameras
|
||||
return _wrap_envelope(topic, reshaped)
|
||||
return full_message
|
||||
return _wrap_envelope(
|
||||
topic,
|
||||
scope_stats_for_non_admin(parsed_payload, _ws_allowed_cameras(ws, config)),
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@@ -6,10 +6,8 @@ import threading
|
||||
import time
|
||||
from collections.abc import Callable, Generator, Iterable
|
||||
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
||||
from contextlib import closing
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
from itertools import islice
|
||||
from typing import Any
|
||||
|
||||
import cv2
|
||||
@@ -613,49 +611,24 @@ class MotionSearchRunner(threading.Thread):
|
||||
|
||||
def _detect_with_progress(
|
||||
self,
|
||||
frames: Iterable[np.ndarray],
|
||||
indexed_frames: list[tuple[int, np.ndarray]],
|
||||
timestamp_fn: Callable[[int], float],
|
||||
) -> tuple[list[MotionSearchResult], int]:
|
||||
"""Run detection while firing throttled progress as frames are scanned.
|
||||
|
||||
Returns ``(results, frame_count)``.
|
||||
"""
|
||||
frame_count = 0
|
||||
) -> list[MotionSearchResult]:
|
||||
"""Run detection while firing throttled progress as frames are scanned."""
|
||||
|
||||
def _gen() -> Generator[tuple[int, np.ndarray], None, None]:
|
||||
nonlocal frame_count
|
||||
for i, frame in enumerate(frames):
|
||||
frame_count = i + 1
|
||||
for i, frame in indexed_frames:
|
||||
if not self._should_stop():
|
||||
self._emit_progress(timestamp_fn(i))
|
||||
yield i, frame
|
||||
|
||||
results = detect_motion_scaled(
|
||||
return detect_motion_scaled(
|
||||
_gen(),
|
||||
self.scaled_mask,
|
||||
self.job.threshold,
|
||||
self.job.min_area,
|
||||
timestamp_fn,
|
||||
)
|
||||
return results, frame_count
|
||||
|
||||
def _decode_vod(
|
||||
self, vod_url: str, keyframes: bool
|
||||
) -> Generator[np.ndarray, None, None]:
|
||||
return iter_vod_frames(
|
||||
self.ffmpeg_path,
|
||||
vod_url,
|
||||
self.scaled[0],
|
||||
self.scaled[1],
|
||||
self.channels,
|
||||
self.decode_args,
|
||||
self.crop,
|
||||
self.scaled,
|
||||
True,
|
||||
self._should_stop,
|
||||
skip_nonkey=keyframes,
|
||||
fps_rate=None if keyframes else self.fps_rate,
|
||||
)
|
||||
|
||||
def _process_run(
|
||||
self, run: list[Recordings]
|
||||
@@ -666,8 +639,7 @@ class MotionSearchRunner(threading.Thread):
|
||||
are all decoded anyway) paired with its probed PTS; if the decoded and
|
||||
probed counts disagree (the decoder ignored ``-skip_frame nokey`` or the
|
||||
stream is corrupt) this run re-runs in the fixed-cadence fallback.
|
||||
Frames stream through detection, so a run never holds more than the
|
||||
current and previous frame. Returns ``(results, frame_count)``.
|
||||
Returns ``(results, frame_count)``.
|
||||
"""
|
||||
run_start: float = run[0].start_time # type: ignore[assignment]
|
||||
run_end: float = run[-1].end_time # type: ignore[assignment]
|
||||
@@ -678,21 +650,35 @@ class MotionSearchRunner(threading.Thread):
|
||||
kf_pts = probe_vod_keyframe_pts(
|
||||
self.ffprobe_path, vod_url, self._should_stop
|
||||
)
|
||||
|
||||
if kf_pts:
|
||||
frames = list(
|
||||
iter_vod_frames(
|
||||
self.ffmpeg_path,
|
||||
vod_url,
|
||||
self.scaled[0],
|
||||
self.scaled[1],
|
||||
self.channels,
|
||||
self.decode_args,
|
||||
self.crop,
|
||||
self.scaled,
|
||||
True,
|
||||
self._should_stop,
|
||||
skip_nonkey=True,
|
||||
fps_rate=None,
|
||||
)
|
||||
)
|
||||
if kf_pts and len(frames) == len(kf_pts):
|
||||
abs_times = [stream_time_to_absolute(time_map, p) for p in kf_pts]
|
||||
indexed = list(enumerate(frames))
|
||||
|
||||
with closing(self._decode_vod(vod_url, keyframes=True)) as frames:
|
||||
results, frame_count = self._detect_with_progress(
|
||||
islice(frames, len(abs_times)), abs_times.__getitem__
|
||||
)
|
||||
extra_frames = next(frames, None) is not None
|
||||
def _ts_kf(i: int) -> float:
|
||||
return abs_times[i]
|
||||
|
||||
if frame_count == len(abs_times) and not extra_frames:
|
||||
return results, frame_count
|
||||
results = self._detect_with_progress(indexed, _ts_kf)
|
||||
return results, len(frames)
|
||||
|
||||
logger.debug(
|
||||
"Keyframe decode did not match %d probed keyframes, using cadence",
|
||||
"Keyframe count mismatch (%d decoded vs %d probed), using cadence",
|
||||
len(frames),
|
||||
len(kf_pts),
|
||||
)
|
||||
|
||||
@@ -702,12 +688,29 @@ class MotionSearchRunner(threading.Thread):
|
||||
self, vod_url: str, time_map: list[tuple[float, float, float]]
|
||||
) -> tuple[list[MotionSearchResult], int]:
|
||||
"""Fixed-cadence fallback: fps-filtered VOD decode, evenly spaced times."""
|
||||
frames = list(
|
||||
iter_vod_frames(
|
||||
self.ffmpeg_path,
|
||||
vod_url,
|
||||
self.scaled[0],
|
||||
self.scaled[1],
|
||||
self.channels,
|
||||
self.decode_args,
|
||||
self.crop,
|
||||
self.scaled,
|
||||
True,
|
||||
self._should_stop,
|
||||
skip_nonkey=False,
|
||||
fps_rate=self.fps_rate,
|
||||
)
|
||||
)
|
||||
indexed = list(enumerate(frames))
|
||||
|
||||
def _ts_fps(i: int) -> float:
|
||||
return stream_time_to_absolute(time_map, i / self.fps_rate)
|
||||
|
||||
with closing(self._decode_vod(vod_url, keyframes=False)) as frames:
|
||||
return self._detect_with_progress(frames, _ts_fps)
|
||||
results = self._detect_with_progress(indexed, _ts_fps)
|
||||
return results, len(frames)
|
||||
|
||||
def _merge_run(
|
||||
self,
|
||||
|
||||
@@ -379,7 +379,7 @@ def move_preview_frames(loc: str) -> None:
|
||||
src,
|
||||
dst,
|
||||
)
|
||||
except OSError:
|
||||
except shutil.Error:
|
||||
logger.error(
|
||||
"Failed to move preview restart cache from %s to %s",
|
||||
src,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
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
|
||||
@@ -31,6 +31,23 @@ class TestHttpApp(BaseTestHttp):
|
||||
response_json = response.json()
|
||||
assert response_json == self.test_stats
|
||||
|
||||
def test_stats_endpoint_strips_cmdline_for_viewers(self):
|
||||
stats = Mock(spec=StatsEmitter)
|
||||
stats.get_latest_stats.return_value = {
|
||||
**self.test_stats,
|
||||
"cpu_usages": {"52": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
|
||||
"bandwidth_usages": {"52": {"bandwidth": 1.0}},
|
||||
}
|
||||
app = super().create_app(stats)
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.get(
|
||||
"/stats",
|
||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
||||
)
|
||||
assert response.json()["cpu_usages"] == {"52": {"cpu": "1.0"}}
|
||||
assert "bandwidth_usages" not in response.json()
|
||||
|
||||
def test_recordings_storage_requires_admin(self):
|
||||
stats = Mock(spec=StatsEmitter)
|
||||
stats.get_latest_stats.return_value = self.test_stats
|
||||
@@ -99,32 +116,6 @@ 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
|
||||
@@ -181,6 +172,10 @@ class TestHttpApp(BaseTestHttp):
|
||||
|
||||
def test_config_response_hides_notification_email_from_viewers(self):
|
||||
self.minimal_config["notifications"] = {"email": "{FRIGATE_TEST_EMAIL}"}
|
||||
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
|
||||
self.minimal_config["cameras"]["front_door"]["profiles"] = {
|
||||
"away": {"notifications": {"email": "{FRIGATE_TEST_EMAIL}"}}
|
||||
}
|
||||
|
||||
with patch.dict(FRIGATE_ENV_VARS, {"FRIGATE_TEST_EMAIL": "me@example.com"}):
|
||||
app = super().create_app()
|
||||
@@ -199,10 +194,165 @@ class TestHttpApp(BaseTestHttp):
|
||||
config["cameras"]["front_door"]["notifications"]["email"]
|
||||
== REDACTED_CREDENTIAL_SENTINEL
|
||||
)
|
||||
assert (
|
||||
config["cameras"]["front_door"]["profiles"]["away"]["notifications"][
|
||||
"email"
|
||||
]
|
||||
== REDACTED_CREDENTIAL_SENTINEL
|
||||
)
|
||||
|
||||
response = client.get("/config")
|
||||
assert response.json()["notifications"]["email"] == "me@example.com"
|
||||
|
||||
def test_config_response_limits_urls_and_go2rtc_for_viewers(self):
|
||||
secret_path = "rtsp://10.0.0.1:554/user=admin_password=hunter2_channel=1"
|
||||
self.minimal_config["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"] = (
|
||||
secret_path
|
||||
)
|
||||
auth_header = "-headers 'Authorization: Basic c2VjcmV0'"
|
||||
args = {
|
||||
"global_args": auth_header,
|
||||
"input_args": auth_header,
|
||||
"output_args": {"detect": auth_header},
|
||||
}
|
||||
self.minimal_config["ffmpeg"] = dict(args)
|
||||
front_door = self.minimal_config["cameras"]["front_door"]
|
||||
front_door["ffmpeg"].update(args)
|
||||
front_door["ffmpeg"]["inputs"][0].update(
|
||||
global_args=auth_header, input_args=auth_header
|
||||
)
|
||||
front_door["webui_url"] = "http://admin:hunter2@10.0.0.1/"
|
||||
self.minimal_config["go2rtc"] = {
|
||||
"streams": {"front_door": [secret_path, "ffmpeg:front_door#audio=opus"]},
|
||||
"webrtc": {"candidates": ["10.0.0.2:8555"]},
|
||||
"webtorrent": {"shares": {"share": {"src": "front_door", "pwd": "x"}}},
|
||||
}
|
||||
app = super().create_app()
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.get(
|
||||
"/config",
|
||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = response.json()
|
||||
camera = config["cameras"]["front_door"]
|
||||
assert camera["ffmpeg"]["inputs"][0]["path"] == ""
|
||||
assert camera["ffmpeg_cmds"] == []
|
||||
assert "webui_url" not in camera
|
||||
assert "hunter2" not in response.text
|
||||
assert "c2VjcmV0" not in response.text
|
||||
assert config["go2rtc"] == {
|
||||
"streams": {"front_door": []},
|
||||
"webrtc": {"candidates": ["10.0.0.2:8555"]},
|
||||
}
|
||||
|
||||
config = client.get("/config").json()
|
||||
camera = config["cameras"]["front_door"]
|
||||
assert camera["ffmpeg"]["inputs"][0]["path"] == secret_path
|
||||
assert camera["ffmpeg"]["inputs"][0]["input_args"] == auth_header
|
||||
assert camera["ffmpeg"]["input_args"] == auth_header
|
||||
assert camera["ffmpeg_cmds"]
|
||||
assert config["go2rtc"]["streams"]["front_door"][0] == secret_path
|
||||
assert "webtorrent" in config["go2rtc"]
|
||||
|
||||
def test_config_response_hides_genai_endpoint_from_viewers(self):
|
||||
self.minimal_config["genai"] = {
|
||||
"local": {
|
||||
"provider": "ollama",
|
||||
"model": "llava",
|
||||
"base_url": "http://user:pass@ollama:11434",
|
||||
"provider_options": {"keep_alive": -1},
|
||||
}
|
||||
}
|
||||
app = super().create_app()
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
genai = client.get(
|
||||
"/config",
|
||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
||||
).json()["genai"]["local"]
|
||||
assert "base_url" not in genai
|
||||
assert "provider_options" not in genai
|
||||
assert genai["provider"] == "ollama"
|
||||
|
||||
genai = client.get("/config").json()["genai"]["local"]
|
||||
assert genai["base_url"] == "http://user:pass@ollama:11434"
|
||||
|
||||
def test_metrics_requires_admin(self):
|
||||
stats = Mock(spec=StatsEmitter)
|
||||
stats.get_latest_stats.return_value = self.test_stats
|
||||
app = super().create_app(stats)
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.get(
|
||||
"/metrics",
|
||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
assert client.get("/metrics").status_code == 200
|
||||
|
||||
def test_config_response_allows_null_profile_notifications(self):
|
||||
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
|
||||
self.minimal_config["cameras"]["front_door"]["profiles"] = {
|
||||
"away": {"notifications": None}
|
||||
}
|
||||
app = super().create_app()
|
||||
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.get(
|
||||
"/config",
|
||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_go2rtc_stream_producer_sources_hidden_from_viewers(self):
|
||||
secret_url = "ffmpeg:rtsp://admin:hunter2@10.0.0.1:554/live"
|
||||
stream = {
|
||||
"producers": [
|
||||
{
|
||||
"url": secret_url,
|
||||
"source": "ffmpeg -i rtsp://admin:hunter2@10.0.0.1:554/live",
|
||||
"medias": ["video, recvonly, H264"],
|
||||
}
|
||||
],
|
||||
"consumers": [{"url": "rtmp://a.rtmp.youtube.com/live2/hunter2"}],
|
||||
}
|
||||
app = super().create_app()
|
||||
viewer = {"remote-user": "viewer", "remote-role": "viewer"}
|
||||
|
||||
with (
|
||||
patch("frigate.api.camera.requests.get") as get,
|
||||
AuthTestClient(app) as client,
|
||||
):
|
||||
get.return_value.json.side_effect = lambda: copy.deepcopy(stream)
|
||||
|
||||
viewer_stream = {"producers": [{"medias": ["video, recvonly, H264"]}]}
|
||||
|
||||
response = client.get("/go2rtc/streams/front_door", headers=viewer)
|
||||
assert response.json() == viewer_stream
|
||||
|
||||
producer = client.get("/go2rtc/streams/front_door").json()["producers"][0]
|
||||
assert producer["medias"] == ["video, recvonly, H264"]
|
||||
assert "hunter2" not in producer["url"]
|
||||
|
||||
get.return_value.json.side_effect = lambda: {
|
||||
"front_door": copy.deepcopy(stream)
|
||||
}
|
||||
response = client.get("/go2rtc/streams", headers=viewer)
|
||||
assert response.json() == {"front_door": viewer_stream}
|
||||
|
||||
# unconnected streams have url-only producers and null consumers
|
||||
get.return_value.json.side_effect = lambda: {
|
||||
"front_door": {"producers": [{"url": secret_url}], "consumers": None}
|
||||
}
|
||||
response = client.get("/go2rtc/streams")
|
||||
assert response.status_code == 200
|
||||
assert "hunter2" not in response.text
|
||||
response = client.get("/go2rtc/streams", headers=viewer)
|
||||
assert response.json() == {"front_door": {"producers": [{"medias": None}]}}
|
||||
|
||||
def test_config_response_keeps_plus_model_reference(self):
|
||||
model_id = "test_plus_reference"
|
||||
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
|
||||
|
||||
@@ -4,11 +4,9 @@ import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import patch
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from fastapi import Request
|
||||
|
||||
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user
|
||||
@@ -590,47 +588,6 @@ class TestHttpMedia(BaseTestHttp):
|
||||
response = client.get("/recordings/unavailable", params={"scale": 0})
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_recordings_unavailable_large_span(self):
|
||||
"""A wide span at a fine scale returns its gaps without stepping per bucket."""
|
||||
with AuthTestClient(self.app) as client:
|
||||
self._insert_recording("only", 1000, 1100)
|
||||
|
||||
response = client.get(
|
||||
"/recordings/unavailable",
|
||||
params={"after": 1, "before": 10**12, "scale": 1},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == [
|
||||
{"start_time": 1, "end_time": 1000},
|
||||
{"start_time": 1100, "end_time": 10**12},
|
||||
]
|
||||
|
||||
for param in ("before", "after"):
|
||||
for bound in ("inf", "-inf", "nan"):
|
||||
response = client.get(
|
||||
"/recordings/unavailable", params={param: bound}
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
def test_latest_frame_height_capped_at_source(self):
|
||||
"""A requested height above the frame height returns the frame unscaled."""
|
||||
frame = np.zeros((90, 160, 3), np.uint8)
|
||||
processor = MagicMock()
|
||||
processor.get_current_frame.return_value = frame
|
||||
processor.get_current_frame_time.return_value = datetime.now().timestamp()
|
||||
self.app.detected_frames_processor = processor
|
||||
|
||||
with AuthTestClient(self.app) as client:
|
||||
for height, expected in ((45, (45, 80)), (5000, (90, 160))):
|
||||
response = client.get(
|
||||
"/front_door/latest.jpg", params={"height": height}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
image = cv2.imdecode(
|
||||
np.frombuffer(response.content, np.uint8), cv2.IMREAD_COLOR
|
||||
)
|
||||
assert image.shape[:2] == expected
|
||||
|
||||
def test_recordings_summary_day_attribution_by_start_time(self):
|
||||
"""
|
||||
A recording spanning midnight marks only its start day.
|
||||
|
||||
@@ -122,11 +122,6 @@ class TestResolveMediaUri(unittest.TestCase):
|
||||
MediaAuthResolution.CAMERA,
|
||||
camera="back_door",
|
||||
)
|
||||
self._assert(
|
||||
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4",
|
||||
MediaAuthResolution.CAMERA,
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
def test_clip_flat_filename_resolves_camera(self):
|
||||
self._assert(
|
||||
@@ -182,14 +177,6 @@ class TestResolveMediaUri(unittest.TestCase):
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
def test_clip_triggers(self):
|
||||
self._assert("/clips/triggers/", MediaAuthResolution.LISTING_MULTI_CAMERA)
|
||||
self._assert(
|
||||
"/clips/triggers/back_door/abc.webp",
|
||||
MediaAuthResolution.CAMERA,
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
def test_clip_review_thumbs(self):
|
||||
# Format: /clips/review/thumb-{camera}-{review_id}.webp (frigate/review/maintainer.py).
|
||||
self._assert(
|
||||
@@ -353,14 +340,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
|
||||
self.assertIsNone(
|
||||
self._deny("/clips/thumbs/front_door/abc.webp", "limited_user")
|
||||
)
|
||||
self.assertIsNone(
|
||||
self._deny(
|
||||
"/recordings/2026-05-11/14/front_door@sub/00.00.mp4", "limited_user"
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
self._deny("/clips/triggers/front_door/abc.webp", "limited_user")
|
||||
)
|
||||
|
||||
def test_restricted_role_blocked_other_camera(self):
|
||||
self.assertEqual(self._deny("/clips/back_door-1.jpg", "limited_user"), 403)
|
||||
@@ -371,15 +350,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
|
||||
self.assertEqual(
|
||||
self._deny("/clips/thumbs/back_door/abc.webp", "limited_user"), 403
|
||||
)
|
||||
self.assertEqual(
|
||||
self._deny(
|
||||
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4", "limited_user"
|
||||
),
|
||||
403,
|
||||
)
|
||||
self.assertEqual(
|
||||
self._deny("/clips/triggers/back_door/abc.webp", "limited_user"), 403
|
||||
)
|
||||
|
||||
def test_restricted_role_blocked_admin_only(self):
|
||||
self.assertEqual(self._deny("/clips/faces/train/foo.webp", "limited_user"), 403)
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
"""Tests for media sync orphan cleanup."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.models import Export, ExportCase
|
||||
from frigate.util.media import sync_exports
|
||||
|
||||
|
||||
class TestSyncExports(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.db = SqliteDatabase(":memory:")
|
||||
self.enterContext(self.db.bind_ctx([Export, ExportCase]))
|
||||
self.db.create_tables([Export, ExportCase])
|
||||
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.clips_dir = os.path.join(self.tmp.name, "clips")
|
||||
self.export_dir = os.path.join(self.tmp.name, "exports")
|
||||
self.thumb_dir = os.path.join(self.clips_dir, "export")
|
||||
os.makedirs(self.thumb_dir)
|
||||
os.makedirs(self.export_dir)
|
||||
|
||||
patcher_clips = patch("frigate.util.media.CLIPS_DIR", self.clips_dir)
|
||||
patcher_exports = patch("frigate.util.media.EXPORT_DIR", self.export_dir)
|
||||
patcher_clips.start()
|
||||
patcher_exports.start()
|
||||
self.addCleanup(patcher_clips.stop)
|
||||
self.addCleanup(patcher_exports.stop)
|
||||
|
||||
def tearDown(self):
|
||||
self.db.close()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def _touch(self, path: str) -> str:
|
||||
open(path, "wb").close()
|
||||
return path
|
||||
|
||||
def test_orphaned_webp_and_jpg_thumbnails_are_removed(self):
|
||||
for i, ext in enumerate(("webp", "jpg")):
|
||||
Export.insert(
|
||||
id=f"front_{i}",
|
||||
camera="front",
|
||||
name=f"export {i}",
|
||||
date=0,
|
||||
video_path=self._touch(os.path.join(self.export_dir, f"{i}.mp4")),
|
||||
thumb_path=self._touch(os.path.join(self.thumb_dir, f"{i}.{ext}")),
|
||||
in_progress=False,
|
||||
).execute()
|
||||
|
||||
orphan_webp = self._touch(os.path.join(self.thumb_dir, "gone.webp"))
|
||||
orphan_jpg = self._touch(os.path.join(self.thumb_dir, "gone.jpg"))
|
||||
|
||||
result = sync_exports()
|
||||
|
||||
self.assertEqual(sorted(result.orphan_paths), sorted([orphan_jpg, orphan_webp]))
|
||||
self.assertEqual(result.orphans_deleted, 2)
|
||||
self.assertEqual(sorted(os.listdir(self.thumb_dir)), ["0.webp", "1.jpg"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.util.object_names import get_categorized_object_names
|
||||
|
||||
|
||||
class TestCategorizedObjectNames(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.config = FrigateConfig(
|
||||
**{
|
||||
"mqtt": {"host": "mqtt"},
|
||||
"cameras": {
|
||||
"front_door": {
|
||||
"ffmpeg": {
|
||||
"inputs": [
|
||||
{
|
||||
"path": "rtsp://10.0.0.1:554/video",
|
||||
"roles": ["detect"],
|
||||
}
|
||||
]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
"objects": {"track": ["person"]},
|
||||
},
|
||||
"yard": {
|
||||
"ffmpeg": {
|
||||
"inputs": [
|
||||
{
|
||||
"path": "rtsp://10.0.0.2:554/video",
|
||||
"roles": ["detect"],
|
||||
}
|
||||
]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
"objects": {"track": ["person", "dog"]},
|
||||
},
|
||||
},
|
||||
"classification": {
|
||||
"custom": {
|
||||
"pets": {
|
||||
"object_config": {
|
||||
"objects": ["dog"],
|
||||
"classification_type": "sub_label",
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
@patch(
|
||||
"frigate.util.object_names._get_classification_categories",
|
||||
return_value={"rex"},
|
||||
)
|
||||
def test_classification_categories_limited_to_tracked_objects(self, _categories):
|
||||
names = get_categorized_object_names(self.config, ["front_door"])
|
||||
self.assertNotIn("dog", names)
|
||||
|
||||
self.assertNotIn("dog", get_categorized_object_names(self.config, []))
|
||||
|
||||
names = get_categorized_object_names(self.config, ["yard"])
|
||||
self.assertEqual(names["dog"], ["rex"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -8,7 +8,6 @@ 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
|
||||
@@ -503,16 +502,6 @@ 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."""
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import unittest
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from frigate.util.image import get_snapshot_bytes
|
||||
|
||||
|
||||
class TestSnapshotBytes(unittest.TestCase):
|
||||
def snapshot_shape(self, height: int, crop: bool = False) -> tuple[int, int]:
|
||||
jpg, _ = get_snapshot_bytes(
|
||||
np.zeros((90, 160, 3), np.uint8),
|
||||
0.0,
|
||||
"jpg",
|
||||
crop=crop,
|
||||
height=height,
|
||||
label="person",
|
||||
box=(70, 35, 90, 55),
|
||||
score=None,
|
||||
area=None,
|
||||
attributes=None,
|
||||
color=(255, 255, 255),
|
||||
)
|
||||
image = cv2.imdecode(np.frombuffer(jpg, np.uint8), cv2.IMREAD_COLOR)
|
||||
return image.shape[:2]
|
||||
|
||||
def test_height_capped_at_frame_height(self):
|
||||
self.assertEqual(self.snapshot_shape(45), (45, 80))
|
||||
self.assertEqual(self.snapshot_shape(5000), (90, 160))
|
||||
|
||||
def test_crop_can_scale_up_to_frame_height(self):
|
||||
self.assertEqual(self.snapshot_shape(5000, crop=True)[0], 90)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,42 +0,0 @@
|
||||
"""Tests for trigger push notifications."""
|
||||
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from frigate.comms.webpush import WebPushClient
|
||||
|
||||
|
||||
class TestTriggerNotification(unittest.TestCase):
|
||||
def test_image_is_the_triggering_event_thumbnail(self):
|
||||
client = WebPushClient.__new__(WebPushClient)
|
||||
client.config = SimpleNamespace(
|
||||
notifications=SimpleNamespace(email="admin@example.com"),
|
||||
cameras={"front_door": SimpleNamespace(friendly_name=None)},
|
||||
)
|
||||
client.web_pushers = {"admin": []}
|
||||
client.user_cameras = {"admin": {"front_door"}}
|
||||
client.last_camera_notification_time = {}
|
||||
client._within_cooldown = MagicMock(return_value=False)
|
||||
client.check_registrations = MagicMock()
|
||||
client.cleanup_registrations = MagicMock()
|
||||
client.send_push_notification = MagicMock()
|
||||
|
||||
client.send_trigger(
|
||||
{
|
||||
"camera": "front_door",
|
||||
"event_id": "1700000000.0-abc123",
|
||||
"name": "red_car",
|
||||
"type": "thumbnail",
|
||||
"score": 0.9,
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
client.send_push_notification.call_args.kwargs["image"],
|
||||
"api/events/1700000000.0-abc123/thumbnail.webp",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -517,6 +517,8 @@ class TestMaterializeForWs(unittest.TestCase):
|
||||
"garage": {"camera_fps": 5.0, "pid": 1236},
|
||||
},
|
||||
"detectors": {"cpu": {"detection_start": 0.0, "inference_speed": 10}},
|
||||
"cpu_usages": {"1234": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
|
||||
"bandwidth_usages": {"1234": {"bandwidth": 1.0}},
|
||||
"service": {"uptime": 12345, "version": "0.16.0"},
|
||||
"camera_fps": 15.0,
|
||||
"detection_fps": 6.0,
|
||||
@@ -540,6 +542,17 @@ class TestMaterializeForWs(unittest.TestCase):
|
||||
self.assertIn("detectors", inner)
|
||||
self.assertIn("service", inner)
|
||||
|
||||
def test_stats_non_admin_gets_no_cmdline(self):
|
||||
for role in ("viewer", "house_only"):
|
||||
message = self._materialize(_ws(role), "stats", self._stats_payload())
|
||||
inner = json.loads(json.loads(message)["payload"]) # type: ignore[arg-type]
|
||||
self.assertEqual(inner["cpu_usages"], {"1234": {"cpu": "1.0"}})
|
||||
self.assertNotIn("bandwidth_usages", inner)
|
||||
|
||||
message = self._materialize(_ws("viewer"), "stats", self._stats_payload())
|
||||
inner = json.loads(json.loads(message)["payload"]) # type: ignore[arg-type]
|
||||
self.assertIn("garage", inner["cameras"])
|
||||
|
||||
def test_stats_restricted_with_no_allowed_cameras_still_sends_aggregates(self):
|
||||
"""A restricted role whose allow-list contains only nonexistent cameras
|
||||
still gets the global aggregates and service block."""
|
||||
|
||||
@@ -131,6 +131,34 @@ def clean_camera_user_pass(line: str) -> str:
|
||||
return re.sub(REGEX_CREDENTIAL_QUERY_PARAM, r"\1*", line)
|
||||
|
||||
|
||||
def scope_stats_for_non_admin(
|
||||
stats: dict[str, Any], allowed_cameras: set[str]
|
||||
) -> dict[str, Any]:
|
||||
"""Return a copy of stats limited to allowed_cameras, without process cmdlines.
|
||||
|
||||
cmdline can leak camera URLs and paths. cpu and mem stay so client-side
|
||||
problem heuristics still work. bandwidth_usages is keyed by pid and can't
|
||||
be scoped to cameras.
|
||||
"""
|
||||
scoped = {**stats}
|
||||
scoped.pop("bandwidth_usages", None)
|
||||
|
||||
if stats.get("cameras") is not None:
|
||||
scoped["cameras"] = {
|
||||
name: data
|
||||
for name, data in stats["cameras"].items()
|
||||
if name in allowed_cameras
|
||||
}
|
||||
|
||||
if stats.get("cpu_usages") is not None:
|
||||
scoped["cpu_usages"] = {
|
||||
pid: {k: v for k, v in usage.items() if k != "cmdline"}
|
||||
for pid, usage in stats["cpu_usages"].items()
|
||||
}
|
||||
|
||||
return scoped
|
||||
|
||||
|
||||
def _mask_userinfo(match: re.Match[str]) -> str:
|
||||
# A credential key in the userinfo means a query password holds "@" or a
|
||||
# password holds a query key. Neither split is safe, so mask the whole URL.
|
||||
|
||||
@@ -1191,11 +1191,7 @@ 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 (
|
||||
FilterConfig,
|
||||
RuntimeFilterConfig,
|
||||
RuntimeMotionConfig,
|
||||
)
|
||||
from frigate.config.config import RuntimeFilterConfig, RuntimeMotionConfig
|
||||
|
||||
current = getattr(camera_config, section, None)
|
||||
if current is None:
|
||||
@@ -1228,9 +1224,6 @@ 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)
|
||||
|
||||
@@ -458,7 +458,6 @@ def get_snapshot_bytes(
|
||||
best_frame = best_frame[region[1] : region[3], region[0] : region[2]]
|
||||
|
||||
if height:
|
||||
height = min(height, frame.shape[0])
|
||||
width = int(height * best_frame.shape[1] / best_frame.shape[0])
|
||||
best_frame = cv2.resize(
|
||||
best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA
|
||||
@@ -1276,7 +1275,7 @@ def run_ffmpeg_snapshot(
|
||||
|
||||
if height is not None:
|
||||
ffmpeg_cmd.insert(-3, "-vf")
|
||||
ffmpeg_cmd.insert(-3, f"scale=-1:'min({height},ih)'")
|
||||
ffmpeg_cmd.insert(-3, f"scale=-1:{height}")
|
||||
|
||||
try:
|
||||
process = sp.run(
|
||||
@@ -1299,17 +1298,11 @@ def get_image_from_recording(
|
||||
relative_frame_time: float,
|
||||
codec: str,
|
||||
height: int | None = None,
|
||||
timeout: int = 30,
|
||||
) -> Any | None:
|
||||
"""retrieve a frame from given time in recording file."""
|
||||
|
||||
image_data, _ = run_ffmpeg_snapshot(
|
||||
ffmpeg,
|
||||
file_path,
|
||||
codec,
|
||||
seek_time=relative_frame_time,
|
||||
height=height,
|
||||
timeout=timeout,
|
||||
ffmpeg, file_path, codec, seek_time=relative_frame_time, height=height
|
||||
)
|
||||
|
||||
return image_data
|
||||
|
||||
@@ -639,7 +639,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
|
||||
"""Sync export files - delete files not referenced by any export record.
|
||||
|
||||
Export videos are stored at: EXPORT_DIR/*.mp4
|
||||
Export thumbnails are stored at: CLIPS_DIR/export/*.webp (legacy *.jpg)
|
||||
Export thumbnails are stored at: CLIPS_DIR/export/*.jpg
|
||||
The paths are stored in Export.video_path and Export.thumb_path
|
||||
"""
|
||||
result = SyncResult(media_type="exports")
|
||||
@@ -667,7 +667,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
|
||||
thumb_files: list[str] = []
|
||||
if os.path.isdir(export_thumb_dir):
|
||||
for file in os.listdir(export_thumb_dir):
|
||||
if file.endswith((".webp", ".jpg")):
|
||||
if file.endswith(".jpg"):
|
||||
file_path = os.path.join(export_thumb_dir, file)
|
||||
thumb_files.append(file_path)
|
||||
|
||||
|
||||
@@ -91,7 +91,8 @@ def get_categorized_object_names(
|
||||
continue
|
||||
|
||||
for label in model_config.object_config.objects:
|
||||
names.setdefault(label, set()).update(categories)
|
||||
if label in tracked_objects:
|
||||
names.setdefault(label, set()).update(categories)
|
||||
|
||||
return {
|
||||
label: sorted(label_names)
|
||||
|
||||
+1
-20
@@ -5,30 +5,11 @@ export type VideoResolutionType = {
|
||||
};
|
||||
|
||||
type LiveProducerMetadata = {
|
||||
type: string;
|
||||
url: string;
|
||||
remote_addr: string;
|
||||
user_agent: string;
|
||||
sdp: string;
|
||||
medias?: string[];
|
||||
receivers?: string[];
|
||||
recv: number;
|
||||
};
|
||||
|
||||
type LiveConsumerMetadata = {
|
||||
type: string;
|
||||
url: string;
|
||||
remote_addr: string;
|
||||
user_agent: string;
|
||||
sdp: string;
|
||||
medias?: string[];
|
||||
senders?: string[];
|
||||
send: number;
|
||||
medias?: string[] | null;
|
||||
};
|
||||
|
||||
export type LiveStreamMetadata = {
|
||||
producers: LiveProducerMetadata[];
|
||||
consumers: LiveConsumerMetadata[];
|
||||
};
|
||||
|
||||
// mse-codec is go2rtc's proof that it has no codec this browser plays;
|
||||
|
||||
@@ -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">
|
||||
<a
|
||||
href={config?.cameras[cameraConfig.name]?.webui_url ?? ""}
|
||||
<Link
|
||||
to={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" />
|
||||
</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user