Compare commits

..
Author SHA1 Message Date
Nicolas Mowen 130815ac70 Support HEIC images for Face Recognition 2026-11-19 08:04:18 -07:00
54 changed files with 729 additions and 2099 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
ruff == 0.17.5
ruff == 0.17.4
# types
types-peewee == 4.0.*
+5 -5
View File
@@ -4,14 +4,14 @@ click == 8.5.*
aiohttp == 3.14.*
starlette == 1.10.*
starlette-context == 0.5.*
fastapi[standard-no-fastapi-cloud-cli] == 0.165.*
fastapi[standard-no-fastapi-cloud-cli] == 0.162.*
uvicorn == 0.54.*
slowapi == 0.1.*
joserfc == 1.8.*
cryptography == 50.0.*
pathvalidate == 3.3.*
markupsafe == 3.0.*
python-multipart == 0.0.34
python-multipart == 0.0.33
# Classification Model Training
tensorflow == 2.19.* ; platform_machine == 'aarch64'
tensorflow-cpu == 2.21.* ; platform_machine == 'x86_64'
@@ -43,13 +43,13 @@ opencv-contrib-python == 4.11.0.*
scipy == 1.17.*
# OpenVino & ONNX
openvino == 2026.4.*
onnxruntime == 1.32.*
onnxruntime == 1.31.*
# Embeddings
transformers == 5.22.*
# Generative AI
google-genai == 3.6.*
google-genai == 3.2.*
ollama == 0.6.*
openai == 3.55.*
openai == 3.49.*
# push notifications
py-vapid == 1.9.6
pywebpush == 2.5.*
@@ -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/;
+6 -16
View File
@@ -40,7 +40,6 @@ from frigate.api.defs.request.app_body import (
MediaSyncBody,
)
from frigate.api.defs.tags import Tags
from frigate.api.plus_util import plus_rate_limited_response
from frigate.config import FrigateConfig, GenAIConfig, GenAIProviderEnum
from frigate.config.camera.updater import (
CameraConfigUpdateEnum,
@@ -55,7 +54,7 @@ from frigate.jobs.media_sync import (
start_media_sync_job,
)
from frigate.models import Event, Timeline
from frigate.plus import PlusKeyStatus, PlusRateLimitError, load_plus_model_info
from frigate.plus import PlusKeyStatus, load_plus_model_info
from frigate.stats.prometheus import get_metrics, update_metrics
from frigate.types import JobStatusTypesEnum
from frigate.util.builtin import (
@@ -1655,10 +1654,7 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
status_code=400,
)
try:
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
if not models["list"]:
return JSONResponse(
@@ -1698,17 +1694,11 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
async def validate_plus_key(request: Request):
"""Validate the configured Frigate+ API key with the Frigate+ server."""
plus_api = request.app.frigate_config.plus_api
status = await plus_api.validate_key()
content: dict[str, Any] = {
"success": status == PlusKeyStatus.valid,
"status": status.value,
}
status = await request.app.frigate_config.plus_api.validate_key()
if status == PlusKeyStatus.rate_limited:
content["retry_after"] = plus_api.rate_limit_remaining()
return JSONResponse(content=content)
return JSONResponse(
content={"success": status == PlusKeyStatus.valid, "status": status.value}
)
@router.get(
@@ -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)
-8
View File
@@ -53,13 +53,11 @@ from frigate.api.defs.response.event_response import (
)
from frigate.api.defs.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags
from frigate.api.plus_util import plus_rate_limited_response
from frigate.comms.event_metadata_updater import EventMetadataTypeEnum
from frigate.config.classification import ObjectClassificationType
from frigate.const import CLIPS_DIR
from frigate.embeddings import EmbeddingsContext
from frigate.models import Event, ReviewSegment, Timeline, Trigger
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObject
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
from frigate.util.path import get_trigger_thumbnail_path, safe_join
@@ -1141,8 +1139,6 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
plus_id = await asyncio.to_thread(
request.app.frigate_config.plus_api.upload_image, image, event.camera
)
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except Exception as ex:
logger.exception(ex)
return JSONResponse(
@@ -1164,8 +1160,6 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
box,
event.label,
)
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError:
message = "Error uploading annotation, unsupported label provided."
logger.error(message)
@@ -1262,8 +1256,6 @@ async def false_positive(request: Request, event_id: str):
event.model_type,
event.detector_type,
)
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError:
message = "Error uploading false positive, unsupported label provided."
logger.error(message)
+8 -16
View File
@@ -36,7 +36,6 @@ from frigate.api.defs.query.media_query_parameters import (
MediaMjpegFeedQueryParams,
)
from frigate.api.defs.tags import Tags
from frigate.api.plus_util import plus_rate_limited_response
from frigate.camera.state import CameraState
from frigate.config import FrigateConfig
from frigate.config.camera.snapshots import SnapshotsConfig
@@ -49,7 +48,6 @@ from frigate.const import (
)
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
from frigate.output.preview import get_most_recent_preview_frame
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.file import (
@@ -168,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 (
@@ -283,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:
@@ -325,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)
@@ -478,12 +473,9 @@ async def submit_recording_snapshot_to_plus(
)
nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
try:
await asyncio.to_thread(
request.app.frigate_config.plus_api.upload_image, nd, camera_name
)
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
await asyncio.to_thread(
request.app.frigate_config.plus_api.upload_image, nd, camera_name
)
return JSONResponse(
content={
+6 -16
View File
@@ -17,10 +17,10 @@ import re
from enum import Enum
from urllib.parse import unquote
from peewee import DoesNotExist, Field
from peewee import DoesNotExist
from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR, EXPORT_DIR
from frigate.const import EXPORT_DIR
from frigate.models import Export, User
logger = logging.getLogger(__name__)
@@ -151,7 +151,6 @@ def _resolve_clip(
# /clips/thumbs/{cam}/... → camera
# /clips/previews/{cam}/... → camera
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
# /clips/export/{export_id}.{ext} → camera (DB lookup)
# /clips/faces/... → admin-only
# /clips/genai-requests/... → admin-only
# /clips/preview_restart_cache/... → admin-only
@@ -176,11 +175,6 @@ def _resolve_clip(
return MediaAuthResolution.CAMERA, camera
return MediaAuthResolution.UNRESOLVED_MEDIA, None
if second == "export" and len(parts) == 3:
return _export_camera(
Export.thumb_path, os.path.join(CLIPS_DIR, "export", parts[2])
)
if second in ("faces", "genai-requests", "preview_restart_cache"):
return MediaAuthResolution.ADMIN_ONLY, None
@@ -240,19 +234,15 @@ def _resolve_export(
if len(parts) != 2:
return MediaAuthResolution.UNRESOLVED_MEDIA, None
return _export_camera(Export.video_path, os.path.join(EXPORT_DIR, parts[1]))
def _export_camera(
field: Field, full_path: str
) -> tuple[MediaAuthResolution, str | None]:
filename = parts[1]
full_path = os.path.join(EXPORT_DIR, filename)
try:
export = Export.get(field == full_path)
export = Export.get(Export.video_path == full_path)
return MediaAuthResolution.CAMERA, export.camera
except DoesNotExist:
return MediaAuthResolution.UNRESOLVED_MEDIA, None
except Exception as e:
logger.warning("Export DB lookup failed for %s: %s", full_path, e)
logger.warning("Export DB lookup failed for %s: %s", filename, e)
return MediaAuthResolution.UNRESOLVED_MEDIA, None
-31
View File
@@ -1,31 +0,0 @@
"""Shared responses for endpoints that call Frigate+."""
from fastapi.responses import JSONResponse
from frigate.plus import PlusRateLimitError
def plus_rate_limited_response(err: PlusRateLimitError) -> JSONResponse:
"""Tell the client Frigate+ is rate limiting requests and how long to wait.
Args:
err: The rate limit raised by the Frigate+ client
Returns:
A 429 response with the wait in retry_after (and the Retry-After
header) when Frigate+ provided one
"""
headers = None
if err.retry_after is not None:
headers = {"Retry-After": str(err.retry_after)}
return JSONResponse(
content={
"success": False,
"message": "Frigate+ is rate limiting requests, try again later",
"retry_after": err.retry_after,
},
status_code=429,
headers=headers,
)
+35 -29
View File
@@ -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(),
+1 -9
View File
@@ -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:
+1 -23
View File
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
from pydantic.fields import PrivateAttr
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
from frigate.plus import PlusApi, PlusRateLimitError, load_plus_model_info
from frigate.plus import PlusApi, load_plus_model_info
from frigate.util.builtin import generate_color_palette, load_labels
logger = logging.getLogger(__name__)
@@ -52,16 +52,6 @@ DEFAULT_SCENE = "default"
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$"
def _rate_limited_message(model_id: str, err: PlusRateLimitError) -> str:
"""Explain a rate limited Frigate+ model download, with the wait if known."""
message = f"Frigate+ is rate limiting requests, unable to download model {model_id}"
if err.retry_after is not None:
return f"{message}. Try again in {err.retry_after} seconds"
return f"{message}. Try again later"
class ModelConfig(BaseModel):
scene: str = Field(
default=DEFAULT_SCENE,
@@ -203,16 +193,6 @@ class ModelConfig(BaseModel):
raise ValueError(
f"Unable to connect to Frigate+ to download model {model_id}"
) from e
except PlusRateLimitError as e:
raise ValueError(_rate_limited_message(model_id, e)) from e
# an error body written here would be mistaken for the model on
# every later start, since only the file's existence is checked
if not r.ok:
raise ValueError(
f"Unable to download model {model_id} from Frigate+ "
f"(HTTP {r.status_code})"
)
with open(self.path, "wb") as f:
f.write(r.content)
@@ -225,8 +205,6 @@ class ModelConfig(BaseModel):
raise ValueError(
f"Unable to connect to Frigate+ to download model info for {model_id}"
) from e
except PlusRateLimitError as e:
raise ValueError(_rate_limited_message(model_id, e)) from e
with open(model_info_path, "w") as f:
json.dump(model_info, f)
-1
View File
@@ -42,7 +42,6 @@ def should_update_db(prev_event: dict[str, Any], current_event: dict[str, Any])
or prev_event["recognized_license_plate"]
!= current_event["recognized_license_plate"]
or prev_event["path_data"] != current_event["path_data"]
or prev_event["max_severity"] != current_event["max_severity"]
):
return True
return False
+7 -26
View File
@@ -187,35 +187,16 @@ def build_review_description_response_format(concerns: list[str]) -> dict[str, A
Strips the `time` field (populated server-side) and drops
`other_concerns` when no concerns are configured.
Every remaining property must be listed in `required` because strict
providers (OpenAI) reject a schema with any optional property.
"""
schema = ReviewMetadata.model_json_schema()
properties = schema.setdefault("properties", {})
required = schema.setdefault("required", [])
properties.pop("time", None)
schema.get("properties", {}).pop("time", None)
if "time" in required:
required.remove("time")
if concerns:
# The model field is nullable with a default so stored metadata
# without concerns still parses. For generation, require a plain list
# instead; the model returns an empty list when no concern applies.
properties["other_concerns"] = {
"type": "array",
"items": {"type": "string"},
"description": properties["other_concerns"]["description"],
}
if "other_concerns" not in required:
required.append("other_concerns")
else:
properties.pop("other_concerns", None)
if "other_concerns" in required:
required.remove("other_concerns")
if "time" in schema.get("required", []):
schema["required"].remove("time")
if not concerns:
schema.get("properties", {}).pop("other_concerns", None)
if "other_concerns" in schema.get("required", []):
schema["required"].remove("other_concerns")
return {
"type": "json_schema",
+49 -46
View File
@@ -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,
+1 -1
View File
@@ -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,
+14 -121
View File
@@ -1,11 +1,8 @@
import datetime
import email.utils
import json
import logging
import math
import os
import re
import time
from enum import Enum
from pathlib import Path
from typing import Any, TypeGuard
@@ -31,7 +28,6 @@ class PlusKeyStatus(str, Enum):
valid = "valid"
invalid = "invalid"
unreachable = "unreachable"
rate_limited = "rate_limited"
not_set = "not_set"
@@ -74,51 +70,6 @@ def load_plus_model_info(model_id: str) -> dict[str, Any] | None:
return add_hailo_alias(model_info)
class PlusRateLimitError(Exception):
"""Frigate+ rejected a request because too many requests were made."""
def __init__(self, retry_after: int | None) -> None:
self.retry_after = retry_after
super().__init__(
f"Rate limited by Frigate+, retry in {retry_after} seconds"
if retry_after is not None
else "Rate limited by Frigate+"
)
def parse_retry_after(value: str | None) -> int | None:
"""Read the number of seconds to wait from a Retry-After header.
The header (RFC 9110 section 10.2.3) is either a number of seconds or an
HTTP date to retry after.
Args:
value: The raw header value
Returns:
Whole seconds to wait, or None when the header is missing or invalid
"""
if not value:
return None
value = value.strip()
if value.isdigit():
return int(value)
try:
retry_at = email.utils.parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
# HTTP dates are always GMT, but "-0000" parses as a naive datetime
if retry_at.tzinfo is None:
retry_at = retry_at.replace(tzinfo=datetime.UTC)
remaining = (retry_at - datetime.datetime.now(datetime.UTC)).total_seconds()
return max(0, math.ceil(remaining))
def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
if image.shape[1] >= image.shape[0]:
width = min(max_dim, image.shape[1])
@@ -177,54 +128,14 @@ class PlusApi:
self._is_active: bool = self.key is not None
self._token_data: dict = {}
# when Frigate+ last asked us to back off, requests are refused locally
# until this time instead of being sent to the server again
self._rate_limited_until: float | None = None
# Retry connection failures so a network that comes up late at startup
# doesn't fail the Frigate+ model download. Retry-After is not honored
# here, since urllib3 would block the calling thread for as long as the
# server asks; a 429 is raised to the caller as PlusRateLimitError.
# doesn't fail the Frigate+ model download
self._session = requests.Session()
self._session.mount(
self.host,
HTTPAdapter(
max_retries=Retry(
connect=5, backoff_factor=1, respect_retry_after_header=False
)
),
self.host, HTTPAdapter(max_retries=Retry(connect=5, backoff_factor=1))
)
def rate_limit_remaining(self) -> int | None:
"""Seconds until Frigate+ accepts requests again, or None if not limited."""
if self._rate_limited_until is None:
return None
remaining = math.ceil(self._rate_limited_until - time.time())
return remaining if remaining > 0 else None
def _note_rate_limit(self, retry_after: int | None) -> None:
"""Remember how long Frigate+ asked us to wait."""
logger.warning(
"Frigate+ rate limit reached, retry after %s seconds",
retry_after if retry_after is not None else "unknown",
)
if retry_after is not None:
self._rate_limited_until = time.time() + retry_after
def _raise_if_rate_limited(self) -> None:
remaining = self.rate_limit_remaining()
if remaining is not None:
raise PlusRateLimitError(remaining)
def _check_rate_limit(self, r: Response) -> None:
if r.status_code == 429:
retry_after = parse_retry_after(r.headers.get("Retry-After"))
self._note_rate_limit(retry_after)
raise PlusRateLimitError(retry_after)
def _refresh_token_if_needed(self) -> None:
if (
self._token_data.get("expires") is None
@@ -234,12 +145,10 @@ class PlusApi:
raise Exception(
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key"
)
self._raise_if_rate_limited()
parts = self.key.split(":")
r = self._session.get(
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
)
self._check_rate_limit(r)
if not r.ok:
raise Exception(f"Unable to refresh API token: {r.text}")
self._token_data = r.json()
@@ -248,30 +157,24 @@ class PlusApi:
self._refresh_token_if_needed()
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
def _request(self, method: str, path: str, data: dict | None = None) -> Response:
"""Make an authenticated Frigate+ request.
def _get(self, path: str) -> Response:
return self._session.get(
f"{self.host}/v1/{path}", headers=self._get_authorization_header()
)
Raises:
PlusRateLimitError: Frigate+ is rate limiting requests
"""
self._raise_if_rate_limited()
r = self._session.request(
method,
def _post(self, path: str, data: dict) -> Response:
return self._session.post(
f"{self.host}/v1/{path}",
headers=self._get_authorization_header(),
json=data,
)
self._check_rate_limit(r)
return r
def _get(self, path: str) -> Response:
return self._request("GET", path)
def _post(self, path: str, data: dict) -> Response:
return self._request("POST", path, data)
def _put(self, path: str, data: dict) -> Response:
return self._request("PUT", path, data)
return self._session.put(
f"{self.host}/v1/{path}",
headers=self._get_authorization_header(),
json=data,
)
def is_active(self) -> bool:
return self._is_active
@@ -284,16 +187,11 @@ class PlusApi:
result reflects the key's current state rather than a cached token.
Returns:
The key's status as reported by the Frigate+ server. When it is
rate_limited, rate_limit_remaining() gives the wait if known.
The key's status as reported by the Frigate+ server
"""
if self.key is None:
return PlusKeyStatus.not_set
# asking again before the wait is over would only be refused again
if self.rate_limit_remaining() is not None:
return PlusKeyStatus.rate_limited
key_id, _, secret = self.key.partition(":")
# Use a single request with a timeout instead of the retrying session,
@@ -309,7 +207,6 @@ class PlusApi:
auth=aiohttp.BasicAuth(key_id, secret),
) as r:
status = r.status
retry_after = parse_retry_after(r.headers.get("Retry-After"))
token_data = await r.json(content_type=None) if r.ok else None
except (aiohttp.ClientError, TimeoutError) as err:
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
@@ -321,10 +218,6 @@ class PlusApi:
if status in (401, 403):
return PlusKeyStatus.invalid
if status == 429:
self._note_rate_limit(retry_after)
return PlusKeyStatus.rate_limited
if status >= 400:
logger.warning(
"Unexpected response validating Frigate+ API key: %s", status
+48 -13
View File
@@ -30,7 +30,6 @@ from frigate.const import (
UPSERT_REVIEW_SEGMENT,
)
from frigate.models import ReviewSegment
from frigate.review.severity import get_review_severity
from frigate.review.types import SeverityEnum
from frigate.track.object_processing import ManualEventState
from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop
@@ -218,21 +217,57 @@ class ActiveObjects:
}
for o in all_objects:
severity = get_review_severity(
camera_config,
label=o["label"],
current_zones=o["current_zones"],
false_positive=o["false_positive"],
detected=o["frame_time"] == frame_time,
position_changes=o["position_changes"],
motionless_count=o["motionless_count"],
pending_loitering=o["pending_loitering"],
)
if (
o["motionless_count"] >= camera_config.detect.stationary.threshold
and not o["pending_loitering"]
):
# no stationary objects unless loitering
continue
if severity == SeverityEnum.alert:
if o["position_changes"] == 0:
# object must have moved at least once
continue
if o["frame_time"] != frame_time:
# object must be detected in this frame
continue
if o["false_positive"]:
# object must not be a false positive
continue
if (
o["label"] in camera_config.review.alerts.labels
and (
not camera_config.review.alerts.required_zones
or (
len(o["current_zones"]) > 0
and set(o["current_zones"])
& set(camera_config.review.alerts.required_zones)
)
)
and camera_config.review.alerts.enabled
):
self.categorized_objects["alerts"].append(o)
elif severity == SeverityEnum.detection:
continue
if (
(
camera_config.review.detections.labels is None
or o["label"] in camera_config.review.detections.labels
)
and (
not camera_config.review.detections.required_zones
or (
len(o["current_zones"]) > 0
and set(o["current_zones"])
& set(camera_config.review.detections.required_zones)
)
)
and camera_config.review.detections.enabled
):
self.categorized_objects["detections"].append(o)
continue
def has_active_objects(self) -> bool:
return (
-80
View File
@@ -1,80 +0,0 @@
"""Rules for which review severity a tracked object qualifies for."""
from typing import cast
from frigate.config import CameraConfig
from frigate.review.types import SeverityEnum
def get_review_severity(
camera_config: CameraConfig,
*,
label: str,
current_zones: list[str],
false_positive: bool,
detected: bool,
position_changes: int,
motionless_count: int,
pending_loitering: bool,
) -> SeverityEnum | None:
"""Get the review severity a tracked object qualifies for on the current frame.
Review segments and a tracked object's max_severity both use this, so an
object is only reported as an alert or detection when it could actually
create or extend a review segment of that severity.
Args:
camera_config: Config for the camera the object is on
label: The object's label
current_zones: Zones the object is in on the current frame
false_positive: Whether the object is still considered a false positive
detected: Whether the object was detected on the current frame
position_changes: Number of times the object has changed position
motionless_count: Number of frames the object has not moved
pending_loitering: Whether the object is in a loitering zone but has
not met the loitering time yet
Returns:
The severity the object qualifies for, or None if it does not qualify
"""
# always populated from detect fps when the config is loaded
stationary_threshold = cast(int, camera_config.detect.stationary.threshold)
# stationary objects don't count unless they are loitering
if motionless_count >= stationary_threshold and not pending_loitering:
return None
# object must have moved at least once
if position_changes == 0:
return None
if not detected or false_positive:
return None
review_config = camera_config.review
zones = set(current_zones)
if (
review_config.alerts.enabled
and label in review_config.alerts.labels
and (
not review_config.alerts.required_zones
or zones & set(review_config.alerts.required_zones)
)
):
return SeverityEnum.alert
if (
review_config.detections.enabled
and (
review_config.detections.labels is None
or label in review_config.detections.labels
)
and (
not review_config.detections.required_zones
or zones & set(review_config.detections.required_zones)
)
):
return SeverityEnum.detection
return None
-27
View File
@@ -4,7 +4,6 @@ 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
@@ -99,32 +98,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
+1 -64
View File
@@ -4,17 +4,14 @@ 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
from frigate.const import MAX_SEGMENT_DURATION
from frigate.models import Event, Recordings
from frigate.plus import PlusRateLimitError
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -591,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.
@@ -2145,22 +2101,3 @@ class TestHttpMedia(BaseTestHttp):
self.assertEqual(response.status_code, 200)
upload.assert_called_once_with("frame", "front_door")
def test_plus_snapshot_rate_limited(self):
self._insert_recording("snapshot", 1000, 1010)
with (
AuthTestClient(self.app) as client,
patch("frigate.api.media.get_image_from_recording", return_value=b"png"),
patch("frigate.api.media.cv2.imdecode", return_value="frame"),
patch.object(
self.app.frigate_config.plus_api,
"upload_image",
side_effect=PlusRateLimitError(60),
),
):
response = client.post("/front_door/plus/1005")
self.assertEqual(response.status_code, 429)
self.assertEqual(response.json()["retry_after"], 60)
self.assertEqual(response.headers["Retry-After"], "60")
+4 -85
View File
@@ -3,10 +3,8 @@
import unittest
from unittest.mock import patch
import numpy as np
from frigate.models import Event
from frigate.plus import PlusKeyStatus, PlusRateLimitError
from frigate.plus import PlusKeyStatus
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -14,13 +12,11 @@ class TestHttpPlusValidate(BaseTestHttp):
def setUp(self):
super().setUp([Event])
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict:
def _validate(self, status: PlusKeyStatus) -> dict:
app = self.create_app()
plus_api = app.frigate_config.plus_api
with (
patch.object(plus_api, "validate_key", return_value=status),
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
with patch.object(
app.frigate_config.plus_api, "validate_key", return_value=status
):
with AuthTestClient(app) as client:
response = client.post("/plus/validate")
@@ -39,12 +35,6 @@ class TestHttpPlusValidate(BaseTestHttp):
{"success": False, "status": "invalid"},
)
def test_a_rate_limited_key_includes_the_wait(self):
self.assertEqual(
self._validate(PlusKeyStatus.rate_limited, 90),
{"success": False, "status": "rate_limited", "retry_after": 90},
)
def test_viewers_cannot_validate(self):
app = self.create_app()
@@ -57,76 +47,5 @@ class TestHttpPlusValidate(BaseTestHttp):
self.assertEqual(response.status_code, 403)
class TestHttpPlusRateLimit(BaseTestHttp):
"""A Frigate+ rate limit reaches the client as a 429 with the wait."""
def setUp(self):
super().setUp([Event])
self.app = self.create_app()
self.plus_api = self.app.frigate_config.plus_api
patcher = patch.object(self.plus_api, "is_active", return_value=True)
patcher.start()
self.addCleanup(patcher.stop)
def _assert_rate_limited(self, response, retry_after: int | None) -> None:
self.assertEqual(response.status_code, 429)
self.assertEqual(response.json()["retry_after"], retry_after)
self.assertFalse(response.json()["success"])
self.assertEqual(
response.headers.get("Retry-After"),
None if retry_after is None else str(retry_after),
)
def test_listing_models(self):
for retry_after in (30, None):
with (
self.subTest(retry_after=retry_after),
patch.object(
self.plus_api,
"get_models",
side_effect=PlusRateLimitError(retry_after),
),
AuthTestClient(self.app) as client,
):
self._assert_rate_limited(client.get("/plus/models"), retry_after)
def test_submitting_an_event(self):
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
with (
patch(
"frigate.api.event.load_event_snapshot_image",
return_value=(np.ones((10, 10, 3), np.uint8), True),
),
patch.object(
self.plus_api, "upload_image", side_effect=PlusRateLimitError(30)
),
AuthTestClient(self.app) as client,
):
response = client.post("/events/event/plus", json={})
self._assert_rate_limited(response, 30)
self.assertIsNone(Event.get(Event.id == "event").plus_id)
def test_submitting_a_false_positive(self):
self.insert_mock_event(
"event", data={"box": [0, 0, 1, 1], "region": [0, 0, 1, 1], "score": 0.9}
)
Event.update(plus_id="plus").where(Event.id == "event").execute()
with (
patch.object(
self.plus_api,
"add_false_positive",
side_effect=PlusRateLimitError(45),
),
AuthTestClient(self.app) as client,
):
response = client.put("/events/event/false_positive")
self._assert_rate_limited(response, 45)
self.assertFalse(Event.get(Event.id == "event").false_positive)
if __name__ == "__main__":
unittest.main(verbosity=2)
+1 -47
View File
@@ -3,7 +3,7 @@ import os
import tempfile
import unittest
from copy import deepcopy
from unittest.mock import MagicMock, patch
from unittest.mock import patch
import numpy as np
import requests
@@ -14,7 +14,6 @@ from frigate.config import BirdseyeModeEnum, FrigateConfig, RetainModeEnum
from frigate.const import MODEL_CACHE_DIR
from frigate.detectors import DetectorTypeEnum
from frigate.detectors.device import build_detector_config, runner_names
from frigate.plus import PlusRateLimitError
from frigate.util.builtin import deep_merge
from frigate.util.config import resolve_ffmpeg_path
@@ -1638,51 +1637,6 @@ class TestConfig(unittest.TestCase):
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
FrigateConfig(**config)
def _plus_model_config(self, model_id: str) -> dict:
return {
"mqtt": {"host": "mqtt"},
"models": [{"path": f"plus://{model_id}", "devices": ["cpu"]}],
"cameras": {
"back": {
"ffmpeg": {
"inputs": [
{
"path": "rtsp://10.0.0.1:554/video",
"roles": ["detect"],
},
]
},
}
},
}
@patch("frigate.detectors.detector_config.requests.get")
@patch(
"frigate.plus.PlusApi.get_model_download_url",
return_value="https://download.invalid/model",
)
def test_plus_model_error_response_is_not_saved(self, _, download):
model_id = "error_response_model"
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
download.return_value = MagicMock(ok=False, status_code=429, content=b"busy")
with self.assertRaisesRegex(ValidationError, r"HTTP 429"):
FrigateConfig(**self._plus_model_config(model_id))
self.assertFalse(os.path.exists(model_path))
def test_plus_rate_limit_is_validation_error(self):
for retry_after, message in ((45, "Try again in 45 seconds"), (None, "later")):
with (
self.subTest(retry_after=retry_after),
patch(
"frigate.plus.PlusApi.get_model_download_url",
side_effect=PlusRateLimitError(retry_after),
),
self.assertRaisesRegex(ValidationError, f"rate limiting.*{message}"),
):
FrigateConfig(**self._plus_model_config("rate_limited_model"))
def test_fails_on_invalid_role(self):
config = {
"mqtt": {"host": "mqtt"},
@@ -1,42 +0,0 @@
"""When tracked object updates are written to the database."""
import unittest
from typing import Any
from frigate.events.maintainer import should_update_db
def _event(**overrides: Any) -> dict[str, Any]:
return {
"end_time": None,
"has_clip": False,
"has_snapshot": True,
"top_score": 0.8,
"entered_zones": ["porch"],
"average_estimated_speed": 0,
"velocity_angle": 0,
"recognized_license_plate": None,
"path_data": [],
"max_severity": None,
**overrides,
}
class TestShouldUpdateDb(unittest.TestCase):
def test_unchanged_saved_event_is_not_updated(self):
self.assertFalse(should_update_db(_event(), _event()))
def test_max_severity_change_updates_saved_event(self):
self.assertTrue(should_update_db(_event(), _event(max_severity="alert")))
def test_max_severity_change_ignored_when_not_saved(self):
self.assertFalse(
should_update_db(
_event(has_snapshot=False),
_event(has_snapshot=False, max_severity="alert"),
)
)
if __name__ == "__main__":
unittest.main()
-36
View File
@@ -7,47 +7,11 @@ from frigate.genai.prompts import (
REVIEW_DESCRIPTION_FIELD_GUIDELINES,
REVIEW_RESPONSE_STYLES,
build_review_description_prompt,
build_review_description_response_format,
build_review_summary_prompt,
get_review_field_guidelines,
)
class TestReviewDescriptionResponseFormat(unittest.TestCase):
def _schema(self, concerns: list[str]) -> dict:
response_format = build_review_description_response_format(concerns)
self.assertTrue(response_format["json_schema"]["strict"])
return response_format["json_schema"]["schema"]
def test_every_property_is_required_for_strict_mode(self):
for concerns in ([], ["a person loitering near the gate"]):
with self.subTest(concerns=concerns):
schema = self._schema(concerns)
self.assertEqual(set(schema["properties"]), set(schema["required"]))
def test_time_is_never_requested(self):
schema = self._schema(["a person loitering near the gate"])
self.assertNotIn("time", schema["properties"])
self.assertNotIn("time", schema["required"])
def test_concerns_omitted_when_not_configured(self):
schema = self._schema([])
self.assertNotIn("other_concerns", schema["properties"])
self.assertNotIn("other_concerns", schema["required"])
def test_concerns_requested_as_plain_list_when_configured(self):
schema = self._schema(["a person loitering near the gate"])
concerns = schema["properties"]["other_concerns"]
self.assertEqual(concerns["type"], "array")
self.assertEqual(concerns["items"], {"type": "string"})
self.assertNotIn("anyOf", concerns)
self.assertNotIn("default", concerns)
def test_schema_is_not_shared_between_calls(self):
self._schema(["a person loitering near the gate"])
self.assertNotIn("other_concerns", self._schema([])["properties"])
class TestReviewResponseStyle(unittest.TestCase):
def _build_prompt(self, response_style: str = "default") -> str:
review_data = {
+2 -30
View File
@@ -20,7 +20,7 @@ from frigate.api.media_auth import (
resolve_media_uri,
)
from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR, EXPORT_DIR
from frigate.const import EXPORT_DIR
from frigate.models import Event, Export, Recordings, ReviewSegment
from frigate.test.const import TEST_DB, TEST_DB_CLEANUPS, TEST_DB_PRAGMAS
@@ -247,7 +247,7 @@ class TestExportResolution(unittest.TestCase):
name=f"export-{export_id}",
date=int(datetime.datetime.now().timestamp()),
video_path=os.path.join(EXPORT_DIR, filename),
thumb_path=os.path.join(CLIPS_DIR, "export", f"{export_id}.webp"),
thumb_path=os.path.join(EXPORT_DIR, f"{filename}.jpg"),
in_progress=False,
).execute()
@@ -280,34 +280,6 @@ class TestExportResolution(unittest.TestCase):
resolution, _ = resolve_media_uri("/exports/clip.mp4", self.config)
self.assertEqual(resolution, MediaAuthResolution.UNRESOLVED_MEDIA)
def test_export_thumbnail_resolves_camera(self):
self._insert_export("back_door_abc123", "back_door", "back_door_clip.mp4")
resolution, camera = resolve_media_uri(
"/clips/export/back_door_abc123.webp", self.config
)
self.assertEqual(resolution, MediaAuthResolution.CAMERA)
self.assertEqual(camera, "back_door")
def test_unknown_export_thumbnail_is_unresolved(self):
resolution, _ = resolve_media_uri("/clips/export/missing.webp", self.config)
self.assertEqual(resolution, MediaAuthResolution.UNRESOLVED_MEDIA)
def test_export_thumbnail_gated_by_camera_access(self):
self._insert_export("back_door_abc123", "back_door", "back_door_clip.mp4")
self._insert_export("front_door_def456", "front_door", "front_door_clip.mp4")
url = "/clips/export/{}.webp"
self.assertIsNone(
deny_response_for_media_uri(
url.format("front_door_def456"), "limited_user", self.config
)
)
self.assertEqual(
deny_response_for_media_uri(
url.format("back_door_abc123"), "limited_user", self.config
),
403,
)
class TestDenyResponseForMediaUri(unittest.TestCase):
"""End-to-end decision check used by /auth."""
+4 -178
View File
@@ -1,14 +1,9 @@
"""Tests for Frigate+ model metadata."""
import asyncio
import datetime
import email.utils
import http.server
import json
import os
import tempfile
import threading
import time
import unittest
from unittest.mock import MagicMock, patch
@@ -16,16 +11,7 @@ import aiohttp
from aiohttp import web
from aiohttp.test_utils import TestServer
from frigate.const import PLUS_ENV_VAR
from frigate.plus import (
PlusApi,
PlusKeyStatus,
PlusRateLimitError,
load_plus_model_info,
parse_retry_after,
)
TEST_PLUS_KEY = f"{'a' * 8}-{'b' * 4}-{'c' * 4}-{'d' * 4}-{'e' * 12}:{'f' * 40}"
from frigate.plus import PlusApi, PlusKeyStatus, load_plus_model_info
class TestHailoAlias(unittest.TestCase):
@@ -113,26 +99,18 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
api.host = host
api.key = key
api._token_data = dict(self.CACHED_TOKEN)
api._rate_limited_until = None
return api
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
api = self._api(await self._serve(handler))
return await api.validate_key(), api
def _replies(
self,
status: int = 200,
body: object = None,
text: str | None = None,
headers: dict[str, str] | None = None,
):
def _replies(self, status: int = 200, body: object = None, text: str | None = None):
async def handler(request: web.Request) -> web.Response:
self.auth = request.headers.get("Authorization")
self.requests_seen = getattr(self, "requests_seen", 0) + 1
if text is not None:
return web.Response(status=status, text=text, headers=headers)
return web.json_response(body, status=status, headers=headers)
return web.Response(status=status, text=text)
return web.json_response(body, status=status)
return handler
@@ -156,25 +134,6 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
self.assertEqual(status, PlusKeyStatus.unreachable)
async def test_a_rate_limited_key_is_not_reported_as_invalid(self):
api = self._api(
await self._serve(self._replies(429, {}, headers={"Retry-After": "120"}))
)
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
self.assertAlmostEqual(api.rate_limit_remaining(), 120, delta=1)
self.assertEqual(api._token_data, self.CACHED_TOKEN)
# validating again during the wait doesn't ask the server
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
self.assertEqual(self.requests_seen, 1)
async def test_a_rate_limit_without_retry_after(self):
status, api = await self._validate(self._replies(429, {}))
self.assertEqual(status, PlusKeyStatus.rate_limited)
self.assertIsNone(api.rate_limit_remaining())
async def test_unusable_replies_keep_the_cached_token(self):
# a successful reply without a usable token must not replace one that
# later Frigate+ requests depend on
@@ -253,138 +212,5 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
self.assertEqual(requests_seen, [])
class TestParseRetryAfter(unittest.TestCase):
def test_delay_seconds(self):
self.assertEqual(parse_retry_after("120"), 120)
self.assertEqual(parse_retry_after(" 0 "), 0)
def test_an_http_date(self):
retry_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=90)
header = email.utils.format_datetime(retry_at, usegmt=True)
self.assertAlmostEqual(parse_retry_after(header), 90, delta=2)
def test_a_date_in_the_past_is_no_wait(self):
self.assertEqual(parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"), 0)
def test_missing_or_invalid_values(self):
for value in (None, "", "soon", "-5", "1.5"):
with self.subTest(value=value):
self.assertIsNone(parse_retry_after(value))
class TestRateLimit(unittest.TestCase):
"""A 429 from Frigate+ is raised at once instead of blocking on Retry-After."""
def setUp(self):
self.hits: list[str] = []
self.status = 429
self.headers: dict[str, str] = {"Retry-After": "30"}
test = self
class Handler(http.server.BaseHTTPRequestHandler):
def _reply(self):
test.hits.append(f"{self.command} {self.path}")
length = int(self.headers.get("Content-Length") or 0)
self.rfile.read(length)
if self.path == "/v1/auth/token":
status, body = (
200,
json.dumps({"accessToken": "t", "expires": time.time() + 3600}),
)
headers = {}
else:
status, body, headers = test.status, "{}", test.headers
self.send_response(status)
for name, value in headers.items():
self.send_header(name, value)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body.encode())
do_GET = do_PUT = do_POST = _reply
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
host = f"http://127.0.0.1:{server.server_port}"
with (
patch("frigate.plus.PLUS_API_HOST", host),
patch.dict(os.environ, {PLUS_ENV_VAR: TEST_PLUS_KEY}),
):
self.api = PlusApi()
def _api_hits(self) -> list[str]:
return [hit for hit in self.hits if hit != "GET /v1/auth/token"]
def test_a_429_is_raised_without_retrying(self):
for call in (
lambda: self.api.get_models(),
lambda: self.api.add_annotation("img", [0, 0, 1, 1], "person"),
lambda: self.api._post("image/create", {}),
):
with self.subTest(call=call):
self.hits.clear()
self.api._rate_limited_until = None
start = time.monotonic()
with self.assertRaises(PlusRateLimitError) as ctx:
call()
self.assertEqual(ctx.exception.retry_after, 30)
self.assertEqual(len(self._api_hits()), 1)
self.assertLess(time.monotonic() - start, 5)
def test_requests_are_refused_locally_until_retry_after_passes(self):
with self.assertRaises(PlusRateLimitError):
self.api.get_models()
self.assertAlmostEqual(self.api.rate_limit_remaining(), 30, delta=1)
self.hits.clear()
with self.assertRaises(PlusRateLimitError) as ctx:
self.api.get_model_info("abc")
self.assertAlmostEqual(ctx.exception.retry_after, 30, delta=1)
self.assertEqual(self.hits, [])
# once the wait has passed, requests go to the server again
self.api._rate_limited_until = time.time() - 1
self.status = 200
self.assertEqual(self.api.get_model_info("abc"), {})
self.assertIsNone(self.api.rate_limit_remaining())
def test_a_429_without_retry_after_is_not_remembered(self):
self.headers = {}
with self.assertRaises(PlusRateLimitError) as ctx:
self.api.get_models()
self.assertIsNone(ctx.exception.retry_after)
self.assertIsNone(self.api.rate_limit_remaining())
def test_a_rate_limited_token_refresh(self):
self.api._token_data = {}
with patch.object(
self.api._session,
"get",
return_value=MagicMock(status_code=429, headers={"Retry-After": "60"}),
):
with self.assertRaises(PlusRateLimitError) as ctx:
self.api.get_models()
self.assertEqual(ctx.exception.retry_after, 60)
self.assertAlmostEqual(self.api.rate_limit_remaining(), 60, delta=1)
if __name__ == "__main__":
unittest.main(verbosity=2)
-11
View File
@@ -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."""
-253
View File
@@ -1,253 +0,0 @@
"""Review severity rules shared by review segments and tracked objects."""
import unittest
from typing import Any
from frigate.config import FrigateConfig
from frigate.review.maintainer import ActiveObjects
from frigate.review.severity import get_review_severity
from frigate.review.types import SeverityEnum
from frigate.track.tracked_object import TrackedObject
CAMERA = "cam"
FPS = 5
ZONE = "porch"
INSIDE_X = 480
OUTSIDE_X = 160
def _config(alerts_enabled: bool = True) -> FrigateConfig:
return FrigateConfig(
**{
"mqtt": {"enabled": False},
"cameras": {
CAMERA: {
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
]
},
"detect": {"width": 640, "height": 480, "fps": FPS},
"objects": {"track": ["person"]},
"zones": {ZONE: {"coordinates": "0.5,0,1,0,1,1,0.5,1"}},
"review": {
"alerts": {
"enabled": alerts_enabled,
"required_zones": [ZONE],
}
},
}
},
}
)
class TestGetReviewSeverity(unittest.TestCase):
def setUp(self):
self.camera_config = _config().cameras[CAMERA]
self.stationary_threshold = self.camera_config.detect.stationary.threshold
def _severity(self, camera_config=None, **overrides: Any) -> SeverityEnum | None:
kwargs = {
"label": "person",
"current_zones": [ZONE],
"false_positive": False,
"detected": True,
"position_changes": 1,
"motionless_count": 0,
"pending_loitering": False,
**overrides,
}
return get_review_severity(camera_config or self.camera_config, **kwargs)
def test_alert_in_required_zone(self):
self.assertEqual(self._severity(), SeverityEnum.alert)
def test_detection_outside_alert_required_zone(self):
self.assertEqual(self._severity(current_zones=[]), SeverityEnum.detection)
def test_detection_when_alerts_disabled(self):
camera_config = _config(alerts_enabled=False).cameras[CAMERA]
self.assertEqual(
self._severity(camera_config=camera_config), SeverityEnum.detection
)
def test_stationary_object_does_not_qualify(self):
self.assertIsNone(self._severity(motionless_count=self.stationary_threshold))
def test_stationary_loitering_object_qualifies(self):
self.assertEqual(
self._severity(
motionless_count=self.stationary_threshold, pending_loitering=True
),
SeverityEnum.alert,
)
def test_object_that_never_moved_does_not_qualify(self):
self.assertIsNone(self._severity(position_changes=0))
def test_undetected_object_does_not_qualify(self):
self.assertIsNone(self._severity(detected=False))
def test_false_positive_does_not_qualify(self):
self.assertIsNone(self._severity(false_positive=True))
class TestTrackedObjectMaxSeverity(unittest.TestCase):
"""max_severity must match what review segments would have been created."""
def setUp(self):
config = _config()
self.camera_config = config.cameras[CAMERA]
self.stationary_threshold = self.camera_config.detect.stationary.threshold
self.frame = 0
self.position_changes = 0
self.motionless_count = 0
self.last_detection = self._obj_data(OUTSIDE_X, 0.6, 1000.0)
self.obj = TrackedObject(
config.model_for_camera(CAMERA),
self.camera_config,
config.ui,
{},
{**self.last_detection, "score_history": [0.6]},
)
def _obj_data(self, x: int, score: float, frame_time: float) -> dict[str, Any]:
return {
"id": "1000.0-abcdef",
"label": "person",
"frame_time": frame_time,
"start_time": 1000.0,
"score": score,
"box": (x - 40, 200, x + 40, 360),
"area": 12800,
"ratio": 0.5,
"region": (0, 0, 640, 480),
"centroid": (x, 280),
"position_changes": self.position_changes,
"motionless_count": self.motionless_count,
"attributes": [],
"sub_label": None,
}
def _step(
self, x: int, score: float, moved: bool, detected: bool = True
) -> SeverityEnum | None:
"""Advance one frame and return the severity review segments would see."""
self.frame += 1
frame_time = 1000.0 + self.frame / FPS
if detected:
# mirror the tracker, which counts the first move and any move
# after the object was stationary as a position change
if moved:
if (
self.position_changes == 0
or self.motionless_count >= self.stationary_threshold
):
self.position_changes += 1
self.motionless_count = 0
else:
self.motionless_count += 1
self.last_detection = self._obj_data(x, score, frame_time)
_, self.last_significant, _, _ = self.obj.update(
frame_time, dict(self.last_detection), False
)
activity = ActiveObjects(frame_time, self.camera_config, [self.obj.to_dict()])
if activity.has_activity_category(SeverityEnum.alert):
return SeverityEnum.alert
if activity.has_activity_category(SeverityEnum.detection):
return SeverityEnum.detection
return None
def test_object_confirmed_while_stationary_in_zone_has_no_severity(self):
"""An object that only becomes a true positive after it stopped moving
never creates a review, so it must not be reported as an alert even
though it entered a required zone."""
review_severities = []
# walks into the zone with a low score, so it is a false positive
for i in range(10):
review_severities.append(self._step(OUTSIDE_X + i * 40, 0.6, moved=True))
# sits still until it is stationary
for _ in range(self.stationary_threshold):
review_severities.append(self._step(INSIDE_X, 0.6, moved=False))
# a re-detection while still stationary confirms it as a true positive
for _ in range(10):
review_severities.append(self._step(INSIDE_X, 0.9, moved=False))
# leaves and is no longer detected
for _ in range(10):
review_severities.append(self._step(INSIDE_X, 0.9, False, detected=False))
self.assertFalse(self.obj.false_positive)
self.assertEqual(self.obj.obj_data["position_changes"], 1)
self.assertEqual(self.obj.entered_zones, [ZONE])
self.assertEqual(set(review_severities), {None})
self.assertIsNone(self.obj.max_severity)
self.assertIsNone(self.obj.to_dict()["max_severity"])
def test_severity_change_is_significant(self):
"""Confirming an object already moving in the zone changes nothing else
that is watched, but the new severity still has to be published."""
for i in range(10):
self._step(OUTSIDE_X + i * 40, 0.6, moved=True)
self.assertEqual(self.obj.current_zones, [ZONE])
self.assertIsNone(self.obj.max_severity)
for i in range(10):
self._step(INSIDE_X + (i % 2) * 10, 0.9, moved=True)
if self.obj.max_severity is not None:
break
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
self.assertTrue(self.last_significant)
self._step(INSIDE_X, 0.9, moved=True)
self.assertFalse(self.last_significant)
def test_alert_is_kept_after_object_stops_qualifying(self):
for i in range(10):
self._step(OUTSIDE_X + i * 40, 0.9, moved=True)
self.assertEqual(self.obj.current_zones, [ZONE])
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
for _ in range(self.stationary_threshold + 5):
self._step(INSIDE_X, 0.9, moved=False)
self.assertTrue(self.obj.is_stationary())
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
def test_detection_upgrades_to_alert_and_is_not_downgraded(self):
review_severities = []
for _ in range(8):
review_severities.append(self._step(OUTSIDE_X, 0.9, moved=True))
self.assertEqual(self.obj.max_severity, SeverityEnum.detection)
for _ in range(5):
review_severities.append(self._step(INSIDE_X, 0.9, moved=True))
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
for _ in range(5):
review_severities.append(self._step(OUTSIDE_X, 0.9, moved=True))
self.assertEqual(review_severities[-1], SeverityEnum.detection)
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
self.assertIn(SeverityEnum.alert, review_severities)
if __name__ == "__main__":
unittest.main()
+40 -18
View File
@@ -511,33 +511,55 @@ class TestHttp(unittest.TestCase):
Recordings.get(Recordings.id == rec_d3_id)
def test_storage_cleanup_keeps_retained(self):
"""Ensure cleanup steps over retained segments to reach newer ones."""
"""Ensure that all recordings are cleaned up when necessary."""
config = FrigateConfig(**self.minimal_config)
storage = StorageMaintainer(config, MagicMock())
seg_len = 600
base = datetime.datetime.now().timestamp() - 7200
_insert_mock_event("123456.keep", base, base + 2.5 * seg_len, True)
id = "123456.keep"
time_keep = datetime.datetime.now().timestamp()
_insert_mock_event(
id,
time_keep,
time_keep + 30,
True,
)
rec_k_id = "1234567.keep"
rec_k2_id = "1234568.keep"
rec_k3_id = "1234569.keep"
_insert_mock_recording(
rec_k_id,
os.path.join(self.test_dir, f"{rec_k_id}.tmp"),
time_keep,
time_keep + 10,
)
_insert_mock_recording(
rec_k2_id,
os.path.join(self.test_dir, f"{rec_k2_id}.tmp"),
time_keep + 10,
time_keep + 20,
)
_insert_mock_recording(
rec_k3_id,
os.path.join(self.test_dir, f"{rec_k3_id}.tmp"),
time_keep + 20,
time_keep + 30,
)
paths = {}
for i in range(10):
rec_id = f"segment-{i}"
paths[rec_id] = os.path.join(self.test_dir, f"{rec_id}.tmp")
time_delete = datetime.datetime.now().timestamp() - 7200
for i in range(0, 59):
id = f"{123456 + i}.delete"
_insert_mock_recording(
rec_id, paths[rec_id], base + i * seg_len, base + (i + 1) * seg_len
id,
os.path.join(self.test_dir, f"{id}.tmp"),
time_delete,
time_delete + 600,
)
# Hourly bandwidth is 48 MB, so cleanup needs all 56 MB of unretained
# segments and must pass the older retained ones to get there.
storage.calculate_camera_bandwidth()
storage.reduce_storage_consumption()
retained = {"segment-0", "segment-1", "segment-2"}
remaining = {r.id for r in Recordings.select(Recordings.id)}
on_disk = {rec_id for rec_id, path in paths.items() if os.path.exists(path)}
self.assertEqual(remaining, retained)
self.assertEqual(on_disk, retained)
self.assertFalse(storage.retention_unmet)
assert Recordings.get(Recordings.id == rec_k_id)
assert Recordings.get(Recordings.id == rec_k2_id)
assert Recordings.get(Recordings.id == rec_k3_id)
def test_unmet_retention_sets_the_live_flag(self):
config = FrigateConfig(**self.minimal_config)
-36
View File
@@ -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()
+30 -25
View File
@@ -17,7 +17,6 @@ from frigate.config import (
)
from frigate.const import CLIPS_DIR, REPLAY_CAMERA_PREFIX, THUMB_DIR
from frigate.detectors.detector_config import ModelConfig
from frigate.review.severity import get_review_severity
from frigate.review.types import SeverityEnum
from frigate.util.builtin import sanitize_float
from frigate.util.image import (
@@ -70,8 +69,6 @@ class TrackedObject:
self.new_zone_entered: bool = False
self.attributes: dict[str, float] = defaultdict(float)
self.false_positive = True
# highest review severity the object qualified for on any frame
self.max_severity: SeverityEnum | None = None
self.has_clip = False
self.has_snapshot = False
self.top_score = self.computed_score = 0.0
@@ -88,6 +85,36 @@ class TrackedObject:
self.path_data: list[tuple[Any, float]] = []
self.previous = self.to_dict()
@property
def max_severity(self) -> str | None:
review_config = self.camera_config.review
if (
self.camera_config.review.alerts.enabled
and self.obj_data["label"] in review_config.alerts.labels
and (
not review_config.alerts.required_zones
or set(self.entered_zones) & set(review_config.alerts.required_zones)
)
):
return SeverityEnum.alert
if (
self.camera_config.review.detections.enabled
and (
not review_config.detections.labels
or self.obj_data["label"] in review_config.detections.labels
)
and (
not review_config.detections.required_zones
or set(self.entered_zones)
& set(review_config.detections.required_zones)
)
):
return SeverityEnum.detection
return None
def _is_false_positive(self) -> bool:
# once a true positive, always a true positive
if not self.false_positive:
@@ -359,28 +386,6 @@ class TrackedObject:
self.obj_data.update(obj_data)
self.current_zones = current_zones
# use the same per-frame rules as review segments, so max_severity is
# never alert or detection unless the object could create that review
severity = get_review_severity(
self.camera_config,
label=self.obj_data["label"],
current_zones=current_zones,
false_positive=self.false_positive,
detected=detected,
position_changes=self.obj_data["position_changes"],
motionless_count=self.obj_data["motionless_count"],
pending_loitering=self.pending_loitering,
)
if severity != self.max_severity and (
severity == SeverityEnum.alert
or (severity == SeverityEnum.detection and self.max_severity is None)
):
self.max_severity = severity
# max_severity is saved with the event, so publish the change
significant_change = True
logger.debug(
f"{self.camera_config.name}: Updating {obj_data['id']}: thumb update? {thumb_update}, significant change? {significant_change}, path update? {path_update}, autotracker update? {autotracker_update} "
)
+1 -8
View File
@@ -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)
+2 -9
View File
@@ -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
-33
View File
@@ -342,37 +342,4 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
dialog.getByRole("button", { name: "Yes", exact: true }),
).toBeVisible();
});
test("a rate limited submission says how long to wait", async ({
frigateApp,
}) => {
await frigateApp.installDefaults({ config: { plus: { enabled: true } } });
const page = frigateApp.page;
await page.route("**/api/events/*/plus", (route) =>
route.fulfill({
status: 429,
headers: { "Retry-After": "90" },
json: { success: false, retry_after: 90 },
}),
);
await frigateApp.goto("/explore?labels=person");
const firstResult = page.locator("[data-start]").first();
await expect(firstResult).toBeVisible({ timeout: 10_000 });
await firstResult.click();
const dialog = page.getByRole("dialog");
await dialog.getByRole("button", { name: "Yes", exact: true }).click();
await expect(
page.getByText(
"Frigate+ is rate limiting requests. Try again in 1 minute, 30 seconds.",
),
).toBeVisible();
// the object can be submitted again once the wait is over
await expect(
dialog.getByRole("button", { name: "Yes", exact: true }),
).toBeVisible();
});
});
@@ -459,36 +459,6 @@ test.describe("Detection models settings @high", () => {
);
});
test("a Frigate+ rate limit says how long to wait", async ({
frigateApp,
}) => {
await installRoutes(
frigateApp.page,
[
{
scene: "default",
devices: ["openvino:GPU.0"],
path: "plus://abc123",
plus: PLUS_MODEL,
},
],
true,
);
// registered last, so it takes precedence over the models route above
await frigateApp.page.route("**/api/plus/models", (route) =>
route.fulfill({
status: 429,
headers: { "Retry-After": "120" },
json: { success: false, retry_after: 120 },
}),
);
await openPage(frigateApp);
await expect(frigateApp.page.locator("#pageRoot")).toContainText(
"Frigate+ is rate limiting requests. Try again in 2 minutes.",
);
});
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
frigateApp,
}) => {
+171 -233
View File
@@ -10,7 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@cycjimmy/jsmpeg-player": "^7.0.0",
"@hookform/resolvers": "^7.0.7",
"@hookform/resolvers": "^7.0.6",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-aspect-ratio": "^1.2.0",
"@radix-ui/react-checkbox": "^1.4.1",
@@ -37,7 +37,7 @@
"@rjsf/shadcn": "^6.11.1",
"@rjsf/utils": "^6.10.1",
"@rjsf/validator-ajv8": "^6.11.1",
"apexcharts": "^8.9.1",
"apexcharts": "^8.8.1",
"axios": "^1.21.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -45,50 +45,50 @@
"copy-to-clipboard": "^4.0.2",
"date-fns": "^4.4.0",
"date-fns-tz": "^3.2.0",
"framer-motion": "^14.14.0",
"framer-motion": "^14.12.0",
"heic-to": "^1.6.7",
"hls.js": "^1.7.4",
"i18next": "^27.2.2",
"i18next-http-backend": "^4.1.0",
"i18next": "^27.1.1",
"i18next-http-backend": "^4.0.10",
"idb-keyval": "^6.3.0",
"js-yaml": "^5.5.0",
"konva": "^10.9.1",
"lodash": "^4.18.1",
"lucide-react": "^1.76.0",
"lucide-react": "^1.72.0",
"monaco-yaml": "^5.5.1",
"next-themes": "^0.4.6",
"nosleep.js": "^0.12.0",
"react": "^19.3.1",
"react-apexcharts": "^2.2.1",
"react-apexcharts": "^2.2.0",
"react-day-picker": "^10.0.2",
"react-device-detect": "^2.2.3",
"react-dom": "^19.3.1",
"react-dropzone": "^20.2.1",
"react-dropzone": "^20.2.0",
"react-grid-layout": "^2.3.0",
"react-hook-form": "^7.92.0",
"react-i18next": "^18.0.3",
"react-i18next": "^18.0.1",
"react-icons": "^5.7.0",
"react-konva": "^19.3.2",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.18.6",
"react-router-dom": "^7.18.5",
"react-swipeable": "^7.0.2",
"react-zoom-pan-pinch": "3.4.4",
"remark-gfm": "^4.0.0",
"scroll-into-view-if-needed": "^3.2.1",
"scroll-into-view-if-needed": "^3.2.0",
"sonner": "^2.0.8",
"swr": "^2.5.1",
"tailwind-merge": "^2.6.2",
"tailwind-merge": "^2.6.1",
"tailwind-scrollbar": "^3.1.0",
"tailwindcss-animate": "^1.0.7",
"use-long-press": "^3.3.0",
"vaul": "^1.1.2",
"virtua": "^0.55.0",
"virtua": "^0.54.2",
"vite-plugin-monaco-editor": "^1.1.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.65.1",
"@playwright/test": "^1.65.0",
"@types/js-yaml": "^4.0.9",
"@types/lodash": "^4.17.27",
"@types/node": "^26.6.6",
@@ -97,21 +97,21 @@
"@vitejs/plugin-react": "^6.3.0",
"autoprefixer": "^10.6.2",
"esbuild": "^0.28.2",
"eslint": "^10.15.0",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.7",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.8",
"eslint-plugin-react-refresh": "^0.5.7",
"globals": "^17.14.0",
"i18next-cli": "^1.5.11",
"monaco-editor": "^0.53.0",
"patch-package": "^8.0.1",
"postcss": "^8.5.33",
"postcss": "^8.5.32",
"prettier": "^3.10.1",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^3.4.19",
"typescript": "^6.0.3",
"typescript-eslint": "^8.73.0",
"typescript-eslint": "^8.72.2",
"vite": "^8.3.8"
}
},
@@ -971,37 +971,20 @@
}
},
"node_modules/@eslint/config-array": {
"version": "0.23.6",
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz",
"integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==",
"version": "0.23.5",
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
"integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/object-schema": "^3.0.5",
"debug": "^4.3.1",
"minimatch": "^11.0.5"
"minimatch": "^10.2.4"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
"node_modules/@eslint/config-array/node_modules/minimatch": {
"version": "11.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/nonrecursive-glob-match": "^1.1.0",
"brace-expansion": "^5.0.12"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@eslint/config-helpers": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
@@ -1112,9 +1095,9 @@
"license": "MIT"
},
"node_modules/@hookform/resolvers": {
"version": "7.0.7",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.7.tgz",
"integrity": "sha512-sxiEGu5dhg6gMEsGznEQ/++634YiRLmxclw+/B1+yNN9uuhKIfNCRTE4xwqkRcKNqBPwtmDXg5oDhLw3i/wklw==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.6.tgz",
"integrity": "sha512-LSTMwW4tmRWtM7pS5HkSqahi71USbhrmjc9pNHNa7UyYTbKIK/e0G1EAw6xsEnp9GahTjXhunxRJp0Bd8E6NZA==",
"license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
@@ -1642,13 +1625,6 @@
"node": ">=18"
}
},
"node_modules/@isaacs/nonrecursive-glob-match": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
"dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1796,13 +1772,13 @@
}
},
"node_modules/@playwright/test": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz",
"integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
"version": "1.65.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.0.tgz",
"integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.65.1"
"playwright": "1.65.0"
},
"bin": {
"playwright": "cli.js"
@@ -3769,17 +3745,17 @@
"license": "MIT"
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.73.0.tgz",
"integrity": "sha512-UkygMFer53Yzn29MCYFTHf34hGXf5KJhiDWfIm1tXtXRrym1CS6l5H9Y3yCtPWChpC0/f93H88gdj8tN0dd4kw==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz",
"integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.12.2",
"@typescript-eslint/scope-manager": "8.73.0",
"@typescript-eslint/type-utils": "8.73.0",
"@typescript-eslint/utils": "8.73.0",
"@typescript-eslint/visitor-keys": "8.73.0",
"@typescript-eslint/scope-manager": "8.72.2",
"@typescript-eslint/type-utils": "8.72.2",
"@typescript-eslint/utils": "8.72.2",
"@typescript-eslint/visitor-keys": "8.72.2",
"ignore": "^7.0.5",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0"
@@ -3792,15 +3768,15 @@
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript-eslint/parser": "^8.73.0",
"@typescript-eslint/parser": "^8.72.2",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0"
}
},
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
"version": "7.0.16",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz",
"integrity": "sha512-52N+Y4HRMOJmbLmr+DqO4iSRyyB7N52gm7PWCT6h0p978+oKbqHCB7gIJIwZvBUsjlSdWbrBFqUSmIFNZMpn0A==",
"version": "7.0.14",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz",
"integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==",
"dev": true,
"license": "MIT",
"engines": {
@@ -3808,16 +3784,16 @@
}
},
"node_modules/@typescript-eslint/parser": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz",
"integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz",
"integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/scope-manager": "8.73.0",
"@typescript-eslint/types": "8.73.0",
"@typescript-eslint/typescript-estree": "8.73.0",
"@typescript-eslint/visitor-keys": "8.73.0",
"@typescript-eslint/scope-manager": "8.72.2",
"@typescript-eslint/types": "8.72.2",
"@typescript-eslint/typescript-estree": "8.72.2",
"@typescript-eslint/visitor-keys": "8.72.2",
"debug": "^4.4.3"
},
"engines": {
@@ -3833,14 +3809,14 @@
}
},
"node_modules/@typescript-eslint/project-service": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz",
"integrity": "sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz",
"integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/tsconfig-utils": "^8.73.0",
"@typescript-eslint/types": "^8.73.0",
"@typescript-eslint/tsconfig-utils": "^8.72.2",
"@typescript-eslint/types": "^8.72.2",
"debug": "^4.4.3"
},
"engines": {
@@ -3855,14 +3831,14 @@
}
},
"node_modules/@typescript-eslint/scope-manager": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz",
"integrity": "sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz",
"integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.73.0",
"@typescript-eslint/visitor-keys": "8.73.0"
"@typescript-eslint/types": "8.72.2",
"@typescript-eslint/visitor-keys": "8.72.2"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -3873,9 +3849,9 @@
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz",
"integrity": "sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz",
"integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==",
"dev": true,
"license": "MIT",
"engines": {
@@ -3890,15 +3866,15 @@
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.73.0.tgz",
"integrity": "sha512-MOC9i4xy1F7KcDde7Ip8jf1SrRiALb2Km4UWxGNjUE2YlhjIEo1ayE27GHIwIQyfWuHTmEonQT14uyurlyC6aA==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz",
"integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.73.0",
"@typescript-eslint/typescript-estree": "8.73.0",
"@typescript-eslint/utils": "8.73.0",
"@typescript-eslint/types": "8.72.2",
"@typescript-eslint/typescript-estree": "8.72.2",
"@typescript-eslint/utils": "8.72.2",
"debug": "^4.4.3",
"ts-api-utils": "^2.5.0"
},
@@ -3915,9 +3891,9 @@
}
},
"node_modules/@typescript-eslint/types": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz",
"integrity": "sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz",
"integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==",
"dev": true,
"license": "MIT",
"engines": {
@@ -3929,18 +3905,18 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz",
"integrity": "sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz",
"integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/project-service": "8.73.0",
"@typescript-eslint/tsconfig-utils": "8.73.0",
"@typescript-eslint/types": "8.73.0",
"@typescript-eslint/visitor-keys": "8.73.0",
"@typescript-eslint/project-service": "8.72.2",
"@typescript-eslint/tsconfig-utils": "8.72.2",
"@typescript-eslint/types": "8.72.2",
"@typescript-eslint/visitor-keys": "8.72.2",
"debug": "^4.4.3",
"minimatch": "^11.0.1",
"minimatch": "^10.2.2",
"semver": "^7.7.3",
"tinyglobby": "^0.2.15",
"ts-api-utils": "^2.5.0"
@@ -3953,43 +3929,20 @@
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev",
"typescript": ">=4.8.4 <6.1.0"
},
"peerDependenciesMeta": {
"@typescript/native": {
"optional": true
}
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
"version": "11.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/nonrecursive-glob-match": "^1.1.0",
"brace-expansion": "^5.0.12"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@typescript-eslint/utils": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.73.0.tgz",
"integrity": "sha512-j2SVJJvVkXdUL0WcEzo4vEH1mO1vIi8KlVukcYA2MgMZvYN2LlZR4PmsW+GTSxSW24j6Q/EP7+MOifLtg5hmsA==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz",
"integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.9.1",
"@typescript-eslint/scope-manager": "8.73.0",
"@typescript-eslint/types": "8.73.0",
"@typescript-eslint/typescript-estree": "8.73.0"
"@typescript-eslint/scope-manager": "8.72.2",
"@typescript-eslint/types": "8.72.2",
"@typescript-eslint/typescript-estree": "8.72.2"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -4004,13 +3957,13 @@
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz",
"integrity": "sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz",
"integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/types": "8.73.0",
"@typescript-eslint/types": "8.72.2",
"eslint-visitor-keys": "^5.0.0"
},
"engines": {
@@ -4192,18 +4145,18 @@
}
},
"node_modules/apex-commons": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/apex-commons/-/apex-commons-0.11.0.tgz",
"integrity": "sha512-r0t1hq4eNzjqRHlf0qG9jiwhd3g/68A9QvgVyjres4oif72NWA1pcvFizpx7gjc/SPECALq0KkL5f12ODIDBPA==",
"version": "0.10.0",
"resolved": "https://registry.npmjs.org/apex-commons/-/apex-commons-0.10.0.tgz",
"integrity": "sha512-mBXqK6wykMnWV4TzT9636k4aaeEvE8PmBIfa2bHx91eQoit8RjJrOlBpGxNGz1Bmt6gq2U3CoqPAUZftBbYdLQ==",
"license": "SEE LICENSE IN LICENSE.md"
},
"node_modules/apexcharts": {
"version": "8.9.1",
"resolved": "https://registry.npmjs.org/apexcharts/-/apexcharts-8.9.1.tgz",
"integrity": "sha512-0SsOUfiEsJblL9tB8IoHfpSMq1cxBnA3v8TNDPA9zfe7gDUVXEfNQte1kdVztsWVQuNPIoZZ3/591LkEwgxuLA==",
"version": "8.8.1",
"resolved": "https://registry.npmjs.org/apexcharts/-/apexcharts-8.8.1.tgz",
"integrity": "sha512-Aeha39Wdrg4pTdJTpM+QsQemLoCRpwC5tEgwHYzbvtRxo4E9EmQ6zdTZbhcYia24HyPhqx3IATd1evgS0lRtzw==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
"apex-commons": "^0.11.0"
"apex-commons": "^0.10.0"
},
"engines": {
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
@@ -4775,10 +4728,9 @@
}
},
"node_modules/compute-scroll-into-view": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.2.2.tgz",
"integrity": "sha512-X+jf3y2j3TbtxA3fq3/kBNiSnD1QlIChiIQdAc2Yo1LtOc0yjO1TzgxWJf8PwtKPGgSvSfWUlVvrb7vGx1eYWA==",
"license": "MIT"
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.0.tgz",
"integrity": "sha512-rj8l8pD4bJ1nx+dAkMhV1xB5RuZEyVysfxJqB1pRchh1KVvwOv9b7CGB8ZfjTImVv2oF+sYMUkMZq6Na5Ftmbg=="
},
"node_modules/convert-source-map": {
"version": "2.0.0",
@@ -5104,9 +5056,9 @@
}
},
"node_modules/eslint": {
"version": "10.15.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz",
"integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==",
"version": "10.14.0",
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.14.0.tgz",
"integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==",
"dev": true,
"license": "MIT",
"workspaces": [
@@ -5115,7 +5067,7 @@
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.2",
"@eslint/config-array": "^0.23.6",
"@eslint/config-array": "^0.23.5",
"@eslint/config-helpers": "^0.7.0",
"@eslint/core": "^1.2.1",
"@eslint/plugin-kit": "^0.7.3",
@@ -5140,7 +5092,7 @@
"imurmurhash": "^0.1.4",
"is-glob": "^4.0.0",
"json-stable-stringify-without-jsonify": "^1.0.1",
"minimatch": "^11.0.5",
"minimatch": "^10.2.6",
"natural-compare": "^1.4.0",
"optionator": "^0.9.3"
},
@@ -5243,9 +5195,9 @@
}
},
"node_modules/eslint-plugin-react-refresh": {
"version": "0.5.8",
"resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.8.tgz",
"integrity": "sha512-VYgz1iCC5LxeAd6YRz5ATfg8WKrNb1ulHMpCe4pQpn3CS9DiYpZi5wcag73O8iChLhrl/CmlGMmzA6eXZ2cX4Q==",
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.7.tgz",
"integrity": "sha512-XhJSzLljuYD4UjNuFGJu2v7aD3sqNVK12w5/DCUfrNfHWegZo2+TsavNx8MuxMwEquuFAzNbNfXKU0WoZ+YUIg==",
"dev": true,
"license": "MIT",
"peerDependencies": {
@@ -5308,23 +5260,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/eslint/node_modules/minimatch": {
"version": "11.0.9",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"@isaacs/nonrecursive-glob-match": "^1.1.0",
"brace-expansion": "^5.0.12"
},
"engines": {
"node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/espree": {
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz",
@@ -5598,9 +5533,9 @@
}
},
"node_modules/file-selector": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/file-selector/-/file-selector-5.0.3.tgz",
"integrity": "sha512-d15nlW+KKq82TlItRvCHtJ8NXCX0nwz2SEUR1MOT8W50c5q2se551ZFdhITFrWohl/5wbRPfMMF9jq4Oj1xRGQ==",
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/file-selector/-/file-selector-5.0.1.tgz",
"integrity": "sha512-v0g/PTeuQgvKCBrVRsfVudvwXlRHSWHEQkVgKawgCGHkEpKA1clp3Om5jvEVhz8G9W/mOYjJH9FhkH4C888PgQ==",
"license": "MIT",
"engines": {
"node": ">= 22"
@@ -5731,12 +5666,12 @@
}
},
"node_modules/framer-motion": {
"version": "14.14.0",
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.14.0.tgz",
"integrity": "sha512-fidRX0VzkZdA9OovFiBSzJtt9/jLcJpna78Z+KCqQQZIWoIpN3tOhEXAhhAw/FObUUh+o3Y18yx1F4BP0mVJ8Q==",
"version": "14.12.0",
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.12.0.tgz",
"integrity": "sha512-4m+10xYan0ic8nFI8zyB5hJkW5F8F4Rer617UecOs8esw0he9unDgXaEZ0rUX7oztz1w4iuvyPWhk4jltMX5iw==",
"license": "MIT",
"dependencies": {
"motion-dom": "14.14.0",
"motion-dom": "14.12.0",
"motion-utils": "14.7.0",
"tslib": "^2.4.0"
},
@@ -6150,9 +6085,9 @@
}
},
"node_modules/i18next": {
"version": "27.2.2",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-27.2.2.tgz",
"integrity": "sha512-1/AJgz/bpE/YL6tqekQlZAzDhkmrUBbgU8+Xon/Lwv6c5WdYuyFZ9mb86OVfR2C2XujUDT7Rz23Ydaq4l981lA==",
"version": "27.1.1",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-27.1.1.tgz",
"integrity": "sha512-Qq3aJizS3RXQ30crhx9BKQLrHoa6GKpgrOJjVZ9vgj3EBxAddrmVfDNUrAMxSUimw5Jc+ld4SSZUAzf1q4nGyQ==",
"funding": [
{
"type": "individual",
@@ -6268,9 +6203,9 @@
}
},
"node_modules/i18next-http-backend": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.1.0.tgz",
"integrity": "sha512-OY3KA8s6WUfUCviw+6VA79148bYaws+FEOZD6MNeZ8Tw1ocfu1j1Qp3ROYNMikzNv1gyTBgzHbWMP/rfZDSp1g==",
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.0.10.tgz",
"integrity": "sha512-CfdQuwIVijbrS/fmiTAQYcYyje4nMbH9aIjKYhhm5bgVmWKWLOM1F7qrA1o63Jl1JxQcRjdtWhKlvDzyqV9aPg==",
"license": "MIT",
"engines": {
"node": ">=18"
@@ -7140,9 +7075,9 @@
}
},
"node_modules/lucide-react": {
"version": "1.76.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.76.0.tgz",
"integrity": "sha512-wRVHt2Xf64GXndB4rQOY9+3Wy9oJ59HDMYv6vwhT0hpSwUxQhG/RM9YijnOmvmIQ+VI/n+1V/FKd6gP4XL2aBQ==",
"version": "1.72.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.72.0.tgz",
"integrity": "sha512-fbF5i1GU8GODETa3Q7rXqrJrcx3iPYrQtxthom103zGx+Z0BGwKYAW9s+9435ohYJ7hQm0av0PoZcqI1CRwNrg==",
"license": "ISC",
"peerDependencies": {
"@types/react": "*",
@@ -8217,9 +8152,9 @@
}
},
"node_modules/motion-dom": {
"version": "14.14.0",
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.14.0.tgz",
"integrity": "sha512-IAxcKhYkuQA2W0Tlx1AvVgImfqEoF3/t3IovbPQJlYkefmGsmrXjn967lMII5VmFmLpQEab4+ZkHo/ijJ4Esig==",
"version": "14.12.0",
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.12.0.tgz",
"integrity": "sha512-YnAY17g8mXRVoXGZbH+v/O2SkNBJqz2TMuqL9yek9Omfhsdjw7gJwNgI5nsGZFpbbm3vINyOo+VtGPryIslatw==",
"license": "MIT",
"dependencies": {
"motion-utils": "14.7.0"
@@ -8681,13 +8616,13 @@
}
},
"node_modules/playwright": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
"version": "1.65.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz",
"integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.65.1"
"playwright-core": "1.65.0"
},
"bin": {
"playwright": "cli.js"
@@ -8697,9 +8632,9 @@
}
},
"node_modules/playwright-core": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
"version": "1.65.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz",
"integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -8710,9 +8645,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.33",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
"integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
"version": "8.5.32",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
"integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
"funding": [
{
"type": "opencollective",
@@ -9082,9 +9017,9 @@
}
},
"node_modules/react-apexcharts": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/react-apexcharts/-/react-apexcharts-2.2.1.tgz",
"integrity": "sha512-cRx+RpRk6WG0SZelOvqDOqbJOWoUSHWAreAkgpNJwsG9axV+uEtTh8zOATW2uK0IjfmFZA8KenSIipslbras4g==",
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/react-apexcharts/-/react-apexcharts-2.2.0.tgz",
"integrity": "sha512-MEiH/T65ooUNf8V7Cq7fCu1femP3+lN9Svzsv+jNNS6AcRSciyA1LLvc1VETWqAiqMxQyX8NYEhZxOYnMf262g==",
"license": "SEE LICENSE IN LICENSE.md",
"dependencies": {
"prop-types": "^15.8.1"
@@ -9159,13 +9094,13 @@
}
},
"node_modules/react-dropzone": {
"version": "20.2.1",
"resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-20.2.1.tgz",
"integrity": "sha512-8ldzI42a+iz6jlC5t0HoOO5ce65dU8ZGo8ZpesL2E57JByC8LBUieMrkGj97YYfgMaYKwkhpkfYxKOCKAekywA==",
"version": "20.2.0",
"resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-20.2.0.tgz",
"integrity": "sha512-FRlcSp6UFT9Etg57U4+g6O6qF/jH7sUh2Hz67lQlrZJa/3FjfAFvw7DwDSItiG2vBUXTdh2wroEwXPPg7o/jkg==",
"license": "MIT",
"dependencies": {
"attr-accept": "^4.0.1",
"file-selector": "^5.0.2"
"file-selector": "^5.0.1"
},
"engines": {
"node": ">= 22"
@@ -9221,9 +9156,9 @@
}
},
"node_modules/react-i18next": {
"version": "18.0.3",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-18.0.3.tgz",
"integrity": "sha512-S84rtVuaKuiRtoCOspbGEaDlFjka+KvK/A5YCOr4LQ41XF3iJOrJ5rqQTD/jJHFVUf6X1i4ZMN5PGGgpz8NN6g==",
"version": "18.0.1",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-18.0.1.tgz",
"integrity": "sha512-kPWXI0E/lrPj3+/umcKNzYZVnWmEedLiamMzDIHfbs+5ANf6yzvlZsjKou8f7kaGkfMMDLIZBejV+4aSN1CyBw==",
"license": "MIT",
"dependencies": {
"html-parse-stringify": "^4.0.1"
@@ -9396,9 +9331,9 @@
}
},
"node_modules/react-router": {
"version": "7.18.6",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.6.tgz",
"integrity": "sha512-SP8KqKfRLlJzqzPseC+r6yYFsqPEavtQCC4BKV810tBGijjESLtwVPam+gPOO+wYeXrYN/TNy2CAykQVcNg4iQ==",
"version": "7.18.5",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.5.tgz",
"integrity": "sha512-dTgvcXDOrLPrlLHrcZAqWveiK1hMSqN+rGAJzegP8HtmNkfRxOoshGWBNX3ZJ0cZjOHkRdlUJtaIhZMLLyGyPw==",
"license": "MIT",
"dependencies": {
"cookie": "^1.0.1",
@@ -9418,12 +9353,12 @@
}
},
"node_modules/react-router-dom": {
"version": "7.18.6",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.6.tgz",
"integrity": "sha512-a8JzFsKEY3EY9QL7t4T1b1OhuY0ngEfwMzXQNgBO/2cuIW9028JbVq3uk2rKnjLredzcIoDKLzUkguIq6fnkFA==",
"version": "7.18.5",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.5.tgz",
"integrity": "sha512-9HcfDMU6JJ/fp6gJZYGwNE6RknVGS4kBjH1HkNw959mCJi70TVwdipQWv2FEol9uGpi+SZTFtVpJPtEQfayeOw==",
"license": "MIT",
"dependencies": {
"react-router": "7.18.6"
"react-router": "7.18.5"
},
"engines": {
"node": ">=20.0.0"
@@ -9727,12 +9662,15 @@
"license": "MIT"
},
"node_modules/scroll-into-view-if-needed": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.2.1.tgz",
"integrity": "sha512-dgeJvJhSV9MY6hyhtsivbSxHoZVm+lumsWTObtUdAchJflwOGmKKHNkEpU8pVYMomZ8h/yrfzVQkcPlObQNDWQ==",
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.2.0.tgz",
"integrity": "sha512-mnlrulRcw9gQR/HI0SlT56kmyCS/Z1tH/By43m8v8kHBjD8XecscweRcjKAk3kt4WLeyJQaSSQ8efy5f+r/dqA==",
"license": "MIT",
"dependencies": {
"compute-scroll-into-view": "^3.2.2"
"compute-scroll-into-view": "^3.0.2"
},
"engines": {
"node": ">=26"
}
},
"node_modules/semver": {
@@ -10000,9 +9938,9 @@
}
},
"node_modules/tailwind-merge": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.2.tgz",
"integrity": "sha512-o2TX9QB8K2cfaJYgMwv96uAUQK5SqpRJHD2vGDK5nyF/tk9PQTZFpwgsDsySQjlIbYdZ6ZDkk5W+bSuWSe92AA==",
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz",
"integrity": "sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==",
"license": "MIT",
"funding": {
"type": "github",
@@ -10225,16 +10163,16 @@
}
},
"node_modules/typescript-eslint": {
"version": "8.73.0",
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.73.0.tgz",
"integrity": "sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg==",
"version": "8.72.2",
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.2.tgz",
"integrity": "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@typescript-eslint/eslint-plugin": "8.73.0",
"@typescript-eslint/parser": "8.73.0",
"@typescript-eslint/typescript-estree": "8.73.0",
"@typescript-eslint/utils": "8.73.0"
"@typescript-eslint/eslint-plugin": "8.72.2",
"@typescript-eslint/parser": "8.72.2",
"@typescript-eslint/typescript-estree": "8.72.2",
"@typescript-eslint/utils": "8.72.2"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -10527,9 +10465,9 @@
}
},
"node_modules/virtua": {
"version": "0.55.0",
"resolved": "https://registry.npmjs.org/virtua/-/virtua-0.55.0.tgz",
"integrity": "sha512-w79kvcw7PwXFmo+MSENbgy3XL61OfStJm7FPtJwZey1EsK0F0gDXmgGHvblS/iebDcg+K5J1ddlUGJ5dXGo4lA==",
"version": "0.54.2",
"resolved": "https://registry.npmjs.org/virtua/-/virtua-0.54.2.tgz",
"integrity": "sha512-lYCAxyXCGkhXVvuKv8a+LklZquy0E9dIObYcOUyo6nP4VSvLeiIsiz94mA3ZKYuM5egkke5RIi2nXi5OIATc7A==",
"license": "MIT",
"peerDependencies": {
"@angular/common": ">=20.0.0",
+18 -18
View File
@@ -22,7 +22,7 @@
},
"dependencies": {
"@cycjimmy/jsmpeg-player": "^7.0.0",
"@hookform/resolvers": "^7.0.7",
"@hookform/resolvers": "^7.0.6",
"@radix-ui/react-alert-dialog": "^1.2.1",
"@radix-ui/react-aspect-ratio": "^1.2.0",
"@radix-ui/react-checkbox": "^1.4.1",
@@ -49,7 +49,7 @@
"@rjsf/shadcn": "^6.11.1",
"@rjsf/utils": "^6.10.1",
"@rjsf/validator-ajv8": "^6.11.1",
"apexcharts": "^8.9.1",
"apexcharts": "^8.8.1",
"axios": "^1.21.1",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -57,50 +57,50 @@
"copy-to-clipboard": "^4.0.2",
"date-fns": "^4.4.0",
"date-fns-tz": "^3.2.0",
"framer-motion": "^14.14.0",
"framer-motion": "^14.12.0",
"heic-to": "^1.6.7",
"hls.js": "^1.7.4",
"i18next": "^27.2.2",
"i18next-http-backend": "^4.1.0",
"i18next": "^27.1.1",
"i18next-http-backend": "^4.0.10",
"idb-keyval": "^6.3.0",
"js-yaml": "^5.5.0",
"konva": "^10.9.1",
"lodash": "^4.18.1",
"lucide-react": "^1.76.0",
"lucide-react": "^1.72.0",
"monaco-yaml": "^5.5.1",
"next-themes": "^0.4.6",
"nosleep.js": "^0.12.0",
"react": "^19.3.1",
"react-apexcharts": "^2.2.1",
"react-apexcharts": "^2.2.0",
"react-day-picker": "^10.0.2",
"react-device-detect": "^2.2.3",
"react-dom": "^19.3.1",
"react-dropzone": "^20.2.1",
"react-dropzone": "^20.2.0",
"react-grid-layout": "^2.3.0",
"react-hook-form": "^7.92.0",
"react-i18next": "^18.0.3",
"react-i18next": "^18.0.1",
"react-icons": "^5.7.0",
"react-konva": "^19.3.2",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.18.6",
"react-router-dom": "^7.18.5",
"react-swipeable": "^7.0.2",
"react-zoom-pan-pinch": "3.4.4",
"remark-gfm": "^4.0.0",
"scroll-into-view-if-needed": "^3.2.1",
"scroll-into-view-if-needed": "^3.2.0",
"sonner": "^2.0.8",
"swr": "^2.5.1",
"tailwind-merge": "^2.6.2",
"tailwind-merge": "^2.6.1",
"tailwind-scrollbar": "^3.1.0",
"tailwindcss-animate": "^1.0.7",
"use-long-press": "^3.3.0",
"vaul": "^1.1.2",
"virtua": "^0.55.0",
"virtua": "^0.54.2",
"vite-plugin-monaco-editor": "^1.1.0",
"zod": "^4.6.7"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.65.1",
"@playwright/test": "^1.65.0",
"@types/js-yaml": "^4.0.9",
"@types/lodash": "^4.17.27",
"@types/node": "^26.6.6",
@@ -109,21 +109,21 @@
"@vitejs/plugin-react": "^6.3.0",
"autoprefixer": "^10.6.2",
"esbuild": "^0.28.2",
"eslint": "^10.15.0",
"eslint": "^10.14.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.7",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.8",
"eslint-plugin-react-refresh": "^0.5.7",
"globals": "^17.14.0",
"i18next-cli": "^1.5.11",
"monaco-editor": "^0.53.0",
"patch-package": "^8.0.1",
"postcss": "^8.5.33",
"postcss": "^8.5.32",
"prettier": "^3.10.1",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^3.4.19",
"typescript": "^6.0.3",
"typescript-eslint": "^8.73.0",
"typescript-eslint": "^8.72.2",
"vite": "^8.3.8"
},
"overrides": {
-4
View File
@@ -327,10 +327,6 @@
"copyDetails": "Copy details",
"copyFailed": "Could not copy details to clipboard"
},
"plusRateLimited": {
"retryIn": "Frigate+ is rate limiting requests. Try again in {{duration}}.",
"retryLater": "Frigate+ is rate limiting requests. Try again later."
},
"selectItem": "Select {{item}}",
"readTheDocumentation": "Read the documentation",
"information": {
@@ -14,7 +14,6 @@ import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { FrigateConfig } from "@/types/frigateConfig";
import { describeSupportedDetectors } from "@/utils/plusModels";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
export type FrigatePlusModel = {
id: string;
@@ -66,26 +65,20 @@ export function ModelSourcePicker({
// metadata of whatever model was saved before it
const selectedId = plusModelId(path) ?? plus?.id;
const { getRateLimitMessage } = usePlusRateLimit();
const {
data: availableModels,
error: modelsError,
isLoading,
} = useSWR<Record<string, FrigatePlusModel>>(
plusEnabled ? "/plus/models" : null,
{
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data.reduce(
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
obj[model.id] = model;
return obj;
},
{},
);
},
const { data: availableModels, isLoading } = useSWR<
Record<string, FrigatePlusModel>
>(plusEnabled ? "/plus/models" : null, {
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data.reduce(
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
obj[model.id] = model;
return obj;
},
{},
);
},
);
});
const [showIncompatible, setShowIncompatible] = useState(false);
const showIncompatibleId = useId();
@@ -108,7 +101,6 @@ export function ModelSourcePicker({
const isCompatible = (model: FrigatePlusModel) =>
!detector || model.supportedDetectors.includes(detector);
const rateLimitMessage = getRateLimitMessage(modelsError);
const allEntries = Object.entries(availableModels ?? {});
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
@@ -171,8 +163,7 @@ export function ModelSourcePicker({
<SelectGroup>
{entries.length === 0 ? (
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
{rateLimitMessage ??
t("frigatePlus.modelInfo.noModelsAvailable")}
{t("frigatePlus.modelInfo.noModelsAvailable")}
</div>
) : (
entries.map(([id, model]) => (
@@ -193,9 +184,6 @@ export function ModelSourcePicker({
</SelectGroup>
</SelectContent>
</Select>
{rateLimitMessage && (
<p className="text-xs text-danger">{rateLimitMessage}</p>
)}
<p className="text-xs text-muted-foreground">
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
</p>
@@ -87,7 +87,6 @@ import TextEntryDialog from "@/components/overlay/dialog/TextEntryDialog";
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
import { Trans, useTranslation } from "react-i18next";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import { getTranslatedLabel } from "@/utils/i18n";
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
import { DialogPortal } from "@radix-ui/react-dialog";
@@ -700,7 +699,6 @@ function ObjectDetailsTab({
"views/faceLibrary",
"components/dialog",
]);
const { getRateLimitMessage } = usePlusRateLimit();
const apiHost = useApiHost();
const hasCustomClassificationModels = useMemo(
@@ -1288,7 +1286,7 @@ function ObjectDetailsTab({
revalidate: false,
},
);
} catch (error) {
} catch {
if (displayedIdRef.current === eventId) {
setState("reviewing");
}
@@ -1296,13 +1294,12 @@ function ObjectDetailsTab({
// the toast is not object specific, so it is always shown to avoid
// silently dropping a failed submission
toast.error(
getRateLimitMessage(error) ??
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
{ position: "top-center" },
);
}
},
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage],
[search, mutate, mapSearchResults, isEventsKey, t],
);
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
@@ -54,7 +54,6 @@ import { useApiHost } from "@/api";
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
import ObjectTrackOverlay from "../ObjectTrackOverlay";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import { VideoResolutionType } from "@/types/live";
import { VodManifest } from "@/types/playback";
@@ -935,7 +934,6 @@ function LifecycleIconRow({
annotationOffset,
}: LifecycleIconRowProps) {
const { t } = useTranslation(["views/explore", "components/player"]);
const { getRateLimitMessage } = usePlusRateLimit();
const { data: config } = useSWR<FrigateConfig>("config");
const [isOpen, setIsOpen] = useState(false);
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
@@ -1253,12 +1251,11 @@ function LifecycleIconRow({
position: "top-center",
},
);
} catch (error) {
} catch {
toast.error(
getRateLimitMessage(error) ??
t("toast.error.submitFrigatePlusFailed", {
ns: "components/player",
}),
t("toast.error.submitFrigatePlusFailed", {
ns: "components/player",
}),
{
position: "top-center",
},
@@ -22,7 +22,6 @@ import { baseUrl } from "@/api/baseUrl";
import { getTranslatedLabel } from "@/utils/i18n";
import useImageLoaded from "@/hooks/use-image-loaded";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
export type FrigatePlusDialogProps = {
upload?: Event;
@@ -38,7 +37,6 @@ export function FrigatePlusDialog({
onEventUploaded,
}: FrigatePlusDialogProps) {
const { t, i18n } = useTranslation(["components/dialog"]);
const { getRateLimitMessage } = usePlusRateLimit();
type SubmissionState = "reviewing" | "uploading" | "submitted";
const [state, setState] = useState<SubmissionState>(
@@ -65,15 +63,14 @@ export function FrigatePlusDialog({
setState("submitted");
onEventUploaded();
} catch (error) {
} catch {
setState("reviewing");
toast.error(
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"),
{ position: "top-center" },
);
toast.error(t("explore.plus.review.toast.error"), {
position: "top-center",
});
}
},
[upload, onEventUploaded, t, getRateLimitMessage],
[upload, onEventUploaded, t],
);
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
+9 -19
View File
@@ -22,7 +22,6 @@ import { ASPECT_VERTICAL_LAYOUT, RecordingPlayerError } from "@/types/record";
import { useTranslation } from "react-i18next";
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
// Android native hls does not seek correctly
const USE_NATIVE_HLS = false;
@@ -110,7 +109,6 @@ export default function HlsVideoPlayer({
transformedOverlay,
}: HlsVideoPlayerProps) {
const { t } = useTranslation("components/player");
const { getRateLimitMessage } = usePlusRateLimit();
const { data: config } = useSWR<FrigateConfig>("config");
const isAdmin = useIsAdmin();
@@ -527,26 +525,18 @@ export default function HlsVideoPlayer({
onUploadFrame={async () => {
const frameTime = getVideoTime();
if (!frameTime || !onUploadFrame) {
return;
}
try {
if (frameTime && onUploadFrame) {
const resp = await onUploadFrame(frameTime);
if (resp?.status !== 200) {
throw new Error();
if (resp && resp.status == 200) {
toast.success(t("toast.success.submittedFrigatePlus"), {
position: "top-center",
});
} else {
toast.success(t("toast.error.submitFrigatePlusFailed"), {
position: "top-center",
});
}
toast.success(t("toast.success.submittedFrigatePlus"), {
position: "top-center",
});
} catch (error) {
toast.error(
getRateLimitMessage(error) ??
t("toast.error.submitFrigatePlusFailed"),
{ position: "top-center" },
);
}
}}
onSnapshot={onSnapshot ? handleSnapshot : undefined}
+8 -13
View File
@@ -10,7 +10,6 @@ import {
SelectValue,
} from "@/components/ui/select";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import type { FrigateConfig } from "@/types/frigateConfig";
import type { DetectionHardware } from "@/types/hardware";
import { recommendedDetectorCount } from "@/utils/detectionHardware";
@@ -80,16 +79,15 @@ export default function SetupDetector({
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
const { getRateLimitMessage } = usePlusRateLimit();
const { data: plusModels, error: plusModelsError } = useSWR<
FrigatePlusModel[]
>(plusEnabled && needsModel ? "/plus/models" : null, {
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data;
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
plusEnabled && needsModel ? "/plus/models" : null,
{
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data;
},
},
});
const plusRateLimitMessage = getRateLimitMessage(plusModelsError);
);
const [plusModelId, setPlusModelId] = useState("");
const compatiblePlusModels = useMemo(
@@ -219,9 +217,6 @@ export default function SetupDetector({
<p>
{t("setupWizard.detector.modelRequired", { name: selected.name })}
</p>
{plusEnabled && plusRateLimitMessage && (
<p className="text-danger">{plusRateLimitMessage}</p>
)}
{plusEnabled ? (
<Select value={plusModelId} onValueChange={setPlusModelId}>
<SelectTrigger className="max-w-xs">
@@ -28,7 +28,7 @@ export function SummarySegment({
<div className="absolute inset-0 flex h-full cursor-pointer justify-end">
<div
className={cn(
"w-full",
"w-[10px]",
severityColors[severity],
height < 0.5 && "min-h-[0.5px]",
)}
+157 -211
View File
@@ -8,26 +8,18 @@ import React, {
import { SummarySegment } from "./SummarySegment";
import {
ConsolidatedSegmentData,
MotionData,
ReviewSegment,
ReviewSeverity,
} from "@/types/review";
import { useTimelineUtils } from "@/hooks/use-timeline-utils";
import { cn } from "@/lib/utils";
import { isMobile } from "react-device-detect";
const MIN_BOX_HEIGHT = isMobile ? 20 : 12;
const DRAG_THRESHOLD = 4;
export type SummaryTimelineProps = {
reviewTimelineRef: React.RefObject<HTMLDivElement | null>;
timelineStart: number;
timelineEnd: number;
segmentDuration: number;
events?: ReviewSegment[];
severityType?: ReviewSeverity;
motionData?: MotionData[];
motionScale?: number;
events: ReviewSegment[];
severityType: ReviewSeverity;
};
export function SummaryTimeline({
@@ -35,22 +27,16 @@ export function SummaryTimeline({
timelineStart,
timelineEnd,
segmentDuration,
events = [],
events,
severityType,
motionData,
motionScale,
}: SummaryTimelineProps) {
const summaryTimelineRef = useRef<HTMLDivElement>(null);
const visibleSectionRef = useRef<HTMLDivElement>(null);
const motionCanvasRef = useRef<HTMLCanvasElement>(null);
const [isDragging, setIsDragging] = useState(false);
const dragRef = useRef<{
startY: number;
startScrollTop: number;
insideBox: boolean;
moved: boolean;
} | null>(null);
const [scrollStartPosition, setScrollStartPosition] = useState<number>(0);
const [initialReviewTimelineScrollTop, setInitialReviewTimelineScrollTop] =
useState<number>(0);
const observer = useRef<ResizeObserver | null>(null);
@@ -143,79 +129,6 @@ export function SummaryTimeline({
segmentDuration,
]);
// Each motion sample covers motionScale seconds with a 0-100 value, and
// bins without motion are absent. Opacity is the bucket's mean value.
const drawMotion = useCallback(() => {
const canvas = motionCanvasRef.current;
const ctx = canvas?.getContext("2d");
if (!canvas || !ctx || !motionData || !motionScale) {
return;
}
const { clientWidth: width, clientHeight: height } = canvas;
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const duration = timelineStart - timelineEnd;
if (duration <= 0 || height <= 0) {
return;
}
const rows = Math.max(
1,
Math.min(Math.floor(height), Math.ceil(duration / motionScale)),
);
const rowHeight = height / rows;
const rowSeconds = duration / rows;
const sums = new Array<number>(rows).fill(0);
motionData.forEach((item) => {
const row = Math.floor(
((timelineStart - item.start_time) / duration) * rows,
);
if (row >= 0 && row < rows) {
sums[row] += item.motion ?? 0;
}
});
const color = getComputedStyle(document.documentElement)
.getPropertyValue("--severity_significant_motion")
.trim();
const samplesPerRow = rowSeconds / motionScale;
sums.forEach((sum, row) => {
if (sum == 0) {
return;
}
const intensity = Math.min(1, sum / (100 * samplesPerRow));
ctx.fillStyle = `hsl(${color} / ${intensity})`;
ctx.fillRect(0, row * rowHeight, width, Math.ceil(rowHeight));
});
}, [motionData, motionScale, timelineStart, timelineEnd]);
useEffect(() => {
const canvas = motionCanvasRef.current;
if (!canvas) {
return;
}
drawMotion();
const resizeObserver = new ResizeObserver(drawMotion);
resizeObserver.observe(canvas);
return () => resizeObserver.disconnect();
}, [drawMotion]);
const setVisibleSectionStyles = useCallback(() => {
if (
reviewTimelineRef.current &&
@@ -231,22 +144,13 @@ export function SummaryTimeline({
} = content;
const { clientHeight: summaryTimelineVisibleHeight } = summary;
// The box keeps a minimum height so it stays visible when zoomed in,
// centered on the true visible range.
const trueHeight =
summaryTimelineVisibleHeight *
(reviewTimelineVisibleHeight / reviewTimelineFullHeight);
const trueTop =
summaryTimelineVisibleHeight * (scrolled / reviewTimelineFullHeight);
const height = Math.max(trueHeight, MIN_BOX_HEIGHT);
const top = Math.min(
Math.max(trueTop - (height - trueHeight) / 2, 0),
summaryTimelineVisibleHeight - height,
);
visibleSectionRef.current.style.top = `${top}px`;
visibleSectionRef.current.style.height = `${height}px`;
visibleSectionRef.current.style.top = `${
summaryTimelineVisibleHeight * (scrolled / reviewTimelineFullHeight)
}px`;
visibleSectionRef.current.style.height = `${
reviewTimelineVisibleHeight *
(reviewTimelineVisibleHeight / reviewTimelineFullHeight)
}px`;
}
}, [reviewTimelineRef, summaryTimelineRef, visibleSectionRef]);
@@ -280,137 +184,178 @@ export function SummaryTimeline({
segmentDuration,
]);
const scrollTopForPosition = useCallback(
(clientY: number) => {
const timeline = reviewTimelineRef.current;
const summary = summaryTimelineRef.current;
if (!timeline || !summary) {
return 0;
const timelineClick = useCallback(
(
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>,
) => {
// prevent default only for mouse events
// to avoid chrome/android issues
if (e.nativeEvent instanceof MouseEvent) {
e.preventDefault();
}
e.stopPropagation();
const rect = summary.getBoundingClientRect();
const ratio = (clientY - rect.top) / rect.height;
return ratio * timeline.scrollHeight - timeline.clientHeight / 2;
},
[reviewTimelineRef],
);
let clientY;
if ("TouchEvent" in window && e.nativeEvent instanceof TouchEvent) {
clientY = e.nativeEvent.touches[0].clientY;
} else if (e.nativeEvent instanceof MouseEvent) {
clientY = e.nativeEvent.clientY;
}
if (
clientY &&
reviewTimelineRef.current &&
summaryTimelineRef.current &&
visibleSectionRef.current
) {
const { clientHeight: summaryTimelineVisibleHeight } =
summaryTimelineRef.current;
const scrollTimelineTo = useCallback(
(top: number, behavior: ScrollBehavior = "auto") => {
const timeline = reviewTimelineRef.current;
const rect = summaryTimelineRef.current.getBoundingClientRect();
const summaryTimelineTop = rect.top;
if (timeline) {
const maxScrollTop = timeline.scrollHeight - timeline.clientHeight;
timeline.scrollTo({
top: Math.min(Math.max(top, 0), maxScrollTop),
behavior,
const { scrollHeight: reviewTimelineHeight } =
reviewTimelineRef.current;
const { clientHeight: visibleSectionHeight } =
visibleSectionRef.current;
const visibleSectionOffset = -(visibleSectionHeight / 2);
const clickPercentage =
(clientY - summaryTimelineTop + visibleSectionOffset) /
summaryTimelineVisibleHeight;
reviewTimelineRef.current.scrollTo({
top: Math.floor(reviewTimelineHeight * clickPercentage),
behavior: "smooth",
});
}
},
[reviewTimelineRef],
[reviewTimelineRef, summaryTimelineRef, visibleSectionRef],
);
// A press outside the box jumps there on release, or snaps the box under
// the pointer once it moves and then drags it.
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (
e.button != 0 ||
!reviewTimelineRef.current ||
!visibleSectionRef.current
) {
return;
const handleMouseDown = useCallback(
(
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>,
) => {
// prevent default only for mouse events
// to avoid chrome/android issues
if (e.nativeEvent instanceof MouseEvent) {
e.preventDefault();
}
e.stopPropagation();
setIsDragging(true);
let clientY;
if ("TouchEvent" in window && e.nativeEvent instanceof TouchEvent) {
clientY = e.nativeEvent.touches[0].clientY;
} else if (e.nativeEvent instanceof MouseEvent) {
clientY = e.nativeEvent.clientY;
}
if (clientY && summaryTimelineRef.current && reviewTimelineRef.current) {
setScrollStartPosition(clientY);
setInitialReviewTimelineScrollTop(reviewTimelineRef.current.scrollTop);
}
},
[setIsDragging, summaryTimelineRef, reviewTimelineRef],
);
const handleMouseUp = useCallback(
(e: MouseEvent | TouchEvent) => {
e.preventDefault();
e.stopPropagation();
e.currentTarget.setPointerCapture(e.pointerId);
const box = visibleSectionRef.current.getBoundingClientRect();
dragRef.current = {
startY: e.clientY,
startScrollTop: reviewTimelineRef.current.scrollTop,
insideBox: e.clientY >= box.top && e.clientY <= box.bottom,
moved: false,
};
if (isDragging) {
setIsDragging(false);
}
},
[reviewTimelineRef],
[isDragging, setIsDragging],
);
const handlePointerMove = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
const timeline = reviewTimelineRef.current;
const summary = summaryTimelineRef.current;
if (!drag || !timeline || !summary) {
return;
}
const deltaY = e.clientY - drag.startY;
if (!drag.moved) {
if (Math.abs(deltaY) < DRAG_THRESHOLD) {
return;
const handleMouseMove = useCallback(
(e: MouseEvent | TouchEvent) => {
if (
summaryTimelineRef.current &&
reviewTimelineRef.current &&
visibleSectionRef.current
) {
// prevent default only for mouse events
// to avoid chrome/android issues
if (e instanceof MouseEvent) {
e.preventDefault();
}
e.stopPropagation();
let clientY;
if ("TouchEvent" in window && e instanceof TouchEvent) {
clientY = e.touches[0].clientY;
} else if (e instanceof MouseEvent) {
clientY = e.clientY;
}
if (isDragging && clientY) {
const { clientHeight: summaryTimelineVisibleHeight } =
summaryTimelineRef.current;
drag.moved = true;
setIsDragging(true);
const {
scrollHeight: reviewTimelineHeight,
clientHeight: reviewTimelineVisibleHeight,
} = reviewTimelineRef.current;
if (!drag.insideBox) {
drag.startScrollTop = scrollTopForPosition(drag.startY);
const { clientHeight: visibleSectionHeight } =
visibleSectionRef.current;
const deltaY =
(clientY - scrollStartPosition) *
(summaryTimelineVisibleHeight / visibleSectionHeight);
const newScrollTop = Math.min(
initialReviewTimelineScrollTop + deltaY,
reviewTimelineHeight - reviewTimelineVisibleHeight,
);
reviewTimelineRef.current.scrollTop = newScrollTop;
}
}
scrollTimelineTo(
drag.startScrollTop +
deltaY * (timeline.scrollHeight / summary.clientHeight),
);
},
[reviewTimelineRef, scrollTopForPosition, scrollTimelineTo],
[
initialReviewTimelineScrollTop,
isDragging,
reviewTimelineRef,
scrollStartPosition,
],
);
const handlePointerUp = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
const drag = dragRef.current;
dragRef.current = null;
setIsDragging(false);
const documentRef = useRef<Document | null>(document);
useEffect(() => {
const documentInstance = documentRef.current;
if (drag && !drag.moved && !drag.insideBox) {
scrollTimelineTo(scrollTopForPosition(e.clientY), "smooth");
}
},
[scrollTopForPosition, scrollTimelineTo],
);
const handlePointerCancel = useCallback(() => {
dragRef.current = null;
setIsDragging(false);
}, []);
if (isDragging) {
documentInstance?.addEventListener("mousemove", handleMouseMove);
documentInstance?.addEventListener("touchmove", handleMouseMove);
documentInstance?.addEventListener("mouseup", handleMouseUp);
documentInstance?.addEventListener("touchend", handleMouseUp);
} else {
documentInstance?.removeEventListener("mousemove", handleMouseMove);
documentInstance?.removeEventListener("touchmove", handleMouseMove);
documentInstance?.removeEventListener("mouseup", handleMouseUp);
documentInstance?.removeEventListener("touchend", handleMouseUp);
}
return () => {
documentInstance?.removeEventListener("mousemove", handleMouseMove);
documentInstance?.removeEventListener("touchmove", handleMouseMove);
documentInstance?.removeEventListener("mouseup", handleMouseUp);
documentInstance?.removeEventListener("touchend", handleMouseUp);
};
}, [handleMouseMove, handleMouseUp, isDragging]);
return (
<div
className={cn(
"no-scrollbar relative h-full touch-none select-none overflow-hidden border-l-[1px] border-neutral-700 bg-secondary",
isDragging ? "cursor-grabbing" : "cursor-pointer",
)}
className={`no-scrollbar relative h-full select-none overflow-hidden border-l-[1px] border-neutral-700 bg-secondary`}
role="scrollbar"
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel}
>
{motionData && (
<canvas
ref={motionCanvasRef}
className="pointer-events-none absolute inset-0 size-full"
/>
)}
<div
ref={summaryTimelineRef}
className="relative z-10 flex h-full flex-col-reverse"
onClick={timelineClick}
onTouchEnd={timelineClick}
>
{consolidatedSegments.map((segment, index) => (
<SummarySegment
@@ -422,10 +367,11 @@ export function SummaryTimeline({
</div>
<div
ref={visibleSectionRef}
className={cn(
"absolute z-20 w-full border-y border-primary/60 bg-primary/30 shadow-[0_0_0_1px_hsl(var(--background))]",
!isDragging && "cursor-grab",
)}
onMouseDown={handleMouseDown}
onTouchStart={handleMouseDown}
className={`absolute z-20 w-full touch-none bg-primary/30 ${
isDragging ? "cursor-grabbing" : "cursor-grab"
}`}
></div>
</div>
);
-49
View File
@@ -1,49 +0,0 @@
import axios from "axios";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useDateLocale } from "@/hooks/use-date-locale";
import { formatSecondsToDuration } from "@/utils/dateUtil";
/**
* The wait Frigate+ asked for when a request failed because of its rate limit.
*
* @returns the seconds to wait, null when rate limited without a known wait,
* or undefined when the error is not a rate limit
*/
export function getPlusRetryAfter(error: unknown): number | null | undefined {
if (!axios.isAxiosError(error) || error.response?.status !== 429) {
return undefined;
}
const retryAfter = error.response.data?.retry_after;
return typeof retryAfter === "number" ? retryAfter : null;
}
/** Messages telling the user Frigate+ is rate limiting requests. */
export function usePlusRateLimit() {
const { t } = useTranslation(["common"]);
const dateLocale = useDateLocale();
const formatRateLimit = useCallback(
(retryAfter: number | null | undefined) =>
retryAfter && retryAfter > 0
? t("plusRateLimited.retryIn", {
ns: "common",
duration: formatSecondsToDuration(retryAfter, dateLocale),
})
: t("plusRateLimited.retryLater", { ns: "common" }),
[t, dateLocale],
);
// undefined when the error is not a rate limit, so callers can fall back
// to their own error message
const getRateLimitMessage = useCallback(
(error: unknown) => {
const retryAfter = getPlusRetryAfter(error);
return retryAfter === undefined ? undefined : formatRateLimit(retryAfter);
},
[formatRateLimit],
);
return { formatRateLimit, getRateLimitMessage };
}
+1 -2
View File
@@ -2,7 +2,6 @@ import i18n, { t } from "i18next";
import { initReactI18next } from "react-i18next";
import HttpBackend from "i18next-http-backend";
import { EventType } from "@/types/search";
import { baseUrl } from "@/api/baseUrl";
export const getTranslatedLabel = (
label: string,
@@ -34,7 +33,7 @@ i18n
fallbackLng: "en", // use en if detected lng is not available
backend: {
loadPath: `${baseUrl}locales/{{lng}}/{{ns}}.json?v=${import.meta.env.VITE_GIT_COMMIT_HASH || "unknown"}`,
loadPath: `locales/{{lng}}/{{ns}}.json?v=${import.meta.env.VITE_GIT_COMMIT_HASH || "unknown"}`,
},
ns: [
+29 -54
View File
@@ -923,7 +923,7 @@ function DetectionReview({
)}
</div>
</div>
<div className="flex w-[73px] flex-row md:w-[110px]">
<div className="flex w-[65px] flex-row md:w-[110px]">
<div className="no-scrollbar relative w-[55px] md:w-[100px]">
{loading ? (
<Skeleton className="size-full" />
@@ -951,7 +951,7 @@ function DetectionReview({
/>
)}
</div>
<div className="w-[18px] md:w-[10px]">
<div className="w-[10px]">
{loading ? (
<Skeleton className="w-full" />
) : (
@@ -1013,7 +1013,6 @@ function MotionReview({
const segmentDuration = 30;
const { data: config } = useSWR<FrigateConfig>("config");
const allowedCameras = useAllowedCameras();
const motionTimelineRef = useRef<HTMLDivElement>(null);
const reviewCameras = useMemo(() => {
if (!config) {
@@ -1701,58 +1700,34 @@ function MotionReview({
</div>
</div>
{!selectedMotionPreviewCamera && (
<div
className={cn(
"flex flex-row",
motionOnly ? "w-[55px] md:w-[100px]" : "w-[73px] md:w-[110px]",
)}
>
<div className="no-scrollbar w-[55px] overflow-y-auto md:w-[100px]">
{motionData ? (
<MotionReviewTimeline
timelineRef={motionTimelineRef}
segmentDuration={segmentDuration}
timestampSpread={15}
timelineStart={timeRangeSegments.end}
timelineEnd={timeRangeSegments.start}
motionOnly={motionOnly}
showHandlebar
handlebarTime={currentTime}
setHandlebarTime={setCurrentTime}
events={reviewItems?.all ?? []}
motion_events={motionData ?? []}
contentRef={contentRef}
onHandlebarDraggingChange={(scrubbing) => {
if (playing && scrubbing) {
setPlaying(false);
}
<div className="no-scrollbar w-[55px] overflow-y-auto md:w-[100px]">
{motionData ? (
<MotionReviewTimeline
segmentDuration={segmentDuration}
timestampSpread={15}
timelineStart={timeRangeSegments.end}
timelineEnd={timeRangeSegments.start}
motionOnly={motionOnly}
showHandlebar
handlebarTime={currentTime}
setHandlebarTime={setCurrentTime}
events={reviewItems?.all ?? []}
motion_events={motionData ?? []}
contentRef={contentRef}
onHandlebarDraggingChange={(scrubbing) => {
if (playing && scrubbing) {
setPlaying(false);
}
setScrubbing(scrubbing);
}}
dense={isMobileOnly}
isZooming={false}
zoomDirection={null}
alwaysShowMotionLine={true}
/>
) : (
<Skeleton className="size-full" />
)}
</div>
{!motionOnly && (
<div className="w-[18px] md:w-[10px]">
{motionData ? (
<SummaryTimeline
reviewTimelineRef={motionTimelineRef}
timelineStart={timeRangeSegments.end}
timelineEnd={timeRangeSegments.start}
segmentDuration={segmentDuration}
motionData={motionData}
motionScale={segmentDuration / 2}
/>
) : (
<Skeleton className="w-full" />
)}
</div>
setScrubbing(scrubbing);
}}
dense={isMobileOnly}
isZooming={false}
zoomDirection={null}
alwaysShowMotionLine={true}
/>
) : (
<Skeleton className="size-full" />
)}
</div>
)}
+28 -48
View File
@@ -70,7 +70,6 @@ import { cn } from "@/lib/utils";
import { useFullscreen } from "@/hooks/use-fullscreen";
import { useTimezone } from "@/hooks/use-date-utils";
import { useTimelineZoom } from "@/hooks/use-timeline-zoom";
import SummaryTimeline from "@/components/timeline/SummaryTimeline";
import { useTranslation } from "react-i18next";
import { useTimelineUtils } from "@/hooks/use-timeline-utils";
import {
@@ -1318,14 +1317,14 @@ function Timeline({
isDesktop
? cn(
timelineType == "timeline"
? "w-[110px] flex-shrink-0"
? "w-[100px] flex-shrink-0"
: timelineType == "detail"
? "min-w-[20rem] max-w-[30%] flex-shrink-0 flex-grow-0 basis-[30rem] md:min-w-[20rem] md:max-w-[25%] lg:min-w-[30rem] lg:max-w-[33%]"
: "w-80 flex-shrink-0",
)
: cn(
timelineType == "timeline"
? "portrait:flex-grow landscape:w-[128px] landscape:flex-shrink-0"
? "portrait:flex-grow landscape:w-[100px] landscape:flex-shrink-0"
: timelineType == "detail"
? "portrait:flex-grow landscape:w-[19rem] landscape:flex-shrink-0"
: "portrait:flex-grow landscape:w-[19rem] landscape:flex-shrink-0",
@@ -1346,51 +1345,32 @@ function Timeline({
)}
{timelineType == "timeline" ? (
!isLoading ? (
<div className="flex size-full flex-row">
<div className="relative h-full min-w-0 flex-1">
<MotionReviewTimeline
timelineRef={selectedTimelineRef}
segmentDuration={zoomSettings.segmentDuration}
timestampSpread={zoomSettings.timestampSpread}
timelineStart={timeRange.before}
timelineEnd={timeRange.after}
showHandlebar={exportRange == undefined}
showExportHandles={exportRange != undefined}
exportStartTime={exportRange?.after}
exportEndTime={exportRange?.before}
setExportStartTime={setExportStartTime}
setExportEndTime={setExportEndTime}
handlebarTime={currentTime}
setHandlebarTime={setCurrentTime}
events={mainCameraReviewItems}
motion_events={motionData ?? []}
noRecordingRanges={noRecordings ?? []}
subOnlyRanges={subOnlyRanges}
contentRef={contentRef}
onHandlebarDraggingChange={setScrubbing}
isZooming={isZooming}
zoomDirection={zoomDirection}
onZoomChange={handleZoomChange}
possibleZoomLevels={possibleZoomLevels}
currentZoomLevel={currentZoomLevel}
/>
</div>
<div
className={cn(
"flex-shrink-0",
isDesktop ? "w-[10px]" : "w-[28px]",
)}
>
<SummaryTimeline
reviewTimelineRef={selectedTimelineRef}
timelineStart={timeRange.before}
timelineEnd={timeRange.after}
segmentDuration={zoomSettings.segmentDuration}
motionData={motionData}
motionScale={Math.round(zoomSettings.segmentDuration / 2)}
/>
</div>
</div>
<MotionReviewTimeline
timelineRef={selectedTimelineRef}
segmentDuration={zoomSettings.segmentDuration}
timestampSpread={zoomSettings.timestampSpread}
timelineStart={timeRange.before}
timelineEnd={timeRange.after}
showHandlebar={exportRange == undefined}
showExportHandles={exportRange != undefined}
exportStartTime={exportRange?.after}
exportEndTime={exportRange?.before}
setExportStartTime={setExportStartTime}
setExportEndTime={setExportEndTime}
handlebarTime={currentTime}
setHandlebarTime={setCurrentTime}
events={mainCameraReviewItems}
motion_events={motionData ?? []}
noRecordingRanges={noRecordings ?? []}
subOnlyRanges={subOnlyRanges}
contentRef={contentRef}
onHandlebarDraggingChange={setScrubbing}
isZooming={isZooming}
zoomDirection={zoomDirection}
onZoomChange={handleZoomChange}
possibleZoomLevels={possibleZoomLevels}
currentZoomLevel={currentZoomLevel}
/>
) : (
<Skeleton className="size-full" />
)
@@ -20,17 +20,10 @@ import { isReplayCamera } from "@/utils/cameraUtil";
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
import { getPrimaryModel } from "@/utils/modelUtil";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
type PlusKeyStatus =
"valid" | "invalid" | "unreachable" | "rate_limited" | "not_set";
type PlusKeyStatus = "valid" | "invalid" | "unreachable" | "not_set";
type PlusValidateResponse = {
success: boolean;
status: PlusKeyStatus;
// seconds until Frigate+ accepts requests again, when rate limited
retry_after?: number | null;
};
type PlusValidateResponse = { success: boolean; status: PlusKeyStatus };
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
const { t } = useTranslation("views/settings");
@@ -41,8 +34,6 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
const [isValidating, setIsValidating] = useState(false);
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
const [retryAfter, setRetryAfter] = useState<number | null>(null);
const { formatRateLimit } = usePlusRateLimit();
const validateKey = useCallback(async () => {
setIsValidating(true);
@@ -50,7 +41,6 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
try {
const response = await axios.post<PlusValidateResponse>("plus/validate");
setKeyStatus(response.data.status);
setRetryAfter(response.data.retry_after ?? null);
} catch {
setKeyStatus("unreachable");
} finally {
@@ -134,8 +124,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
<div className="flex items-center gap-2">
{keyStatus === "valid" ? (
<CheckCircle2 className="size-5 shrink-0 text-green-500" />
) : keyStatus === "unreachable" ||
keyStatus === "rate_limited" ? (
) : keyStatus === "unreachable" ? (
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
) : (
<XCircle className="size-5 shrink-0 text-red-500" />
@@ -145,9 +134,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
? t("frigatePlus.apiKey.serverValid")
: keyStatus === "unreachable"
? t("frigatePlus.apiKey.serverUnreachable")
: keyStatus === "rate_limited"
? formatRateLimit(retryAfter)
: t("frigatePlus.apiKey.serverInvalid")}
: t("frigatePlus.apiKey.serverInvalid")}
</span>
</div>
)}
@@ -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>
)}