Compare commits

..
Author SHA1 Message Date
Josh Hawkins d7977e63fb fix test 2026-11-24 08:16:55 -06:00
Josh Hawkins 5917130b7e scope review lookup by event id to allowed cameras
The review lookup by event id matched the id with GLOB, so wildcard characters in the id matched other ids, and the camera check ran on whichever row matched first, returning a 403 that named a camera the user can't access. The id now matches literally and the query only searches the user's allowed cameras, so a review item on another camera returns the same 404 as a missing one.
2026-11-24 08:08:05 -06:00
Josh Hawkins 478633b322 admin-only frigate+ frame upload
the UI already hides this so this is just to fix the endpoint
2026-11-24 08:05:58 -06:00
Josh Hawkins 0d047d79c2 deny admin-only media to viewer
The media auth check allowed any role without a camera list before it looked at admin-only paths, so viewer could list and download the face library, classification train and dataset images, and GenAI request frames from /clips/ even though the matching API routes and UI pages are admin-only. Admin-only paths are now denied to every non-admin role before that check.
2026-11-24 08:01:41 -06:00
49 changed files with 487 additions and 1129 deletions
+87 -8
View File
@@ -2311,8 +2311,8 @@ paths:
$ref: '#/components/schemas/HTTPValidationError' $ref: '#/components/schemas/HTTPValidationError'
security: security:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: camera x-required-role: any
description: '**Access:** Authenticated user with access to the referenced camera.' description: '**Access:** Any authenticated user.'
/review/{review_id}: /review/{review_id}:
get: get:
tags: tags:
@@ -4608,6 +4608,14 @@ paths:
- type: 'null' - type: 'null'
default: 1 default: 1
title: Include Thumbnails title: Include Thumbnails
- name: favorites
in: query
required: false
schema:
anyOf:
- type: integer
- type: 'null'
title: Favorites
- name: min_score - name: min_score
in: query in: query
required: false required: false
@@ -5138,6 +5146,75 @@ paths:
security: security:
- frigateAdminAuth: [] - frigateAdminAuth: []
x-required-role: admin x-required-role: admin
/events/{event_id}/retain:
post:
tags:
- Events
summary: Set event retain indefinitely.
description: |-
**Access:** Admin role required.
Sets an event to retain indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
operationId: set_retain_events__event_id__retain_post
parameters:
- name: event_id
in: path
required: true
schema:
type: string
title: Event Id
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/GenericResponse'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
delete:
tags:
- Events
summary: Stop event from being retained indefinitely
description: |-
**Access:** Admin role required.
Stops an event from being retained indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
operationId: delete_retain_events__event_id__retain_delete
parameters:
- name: event_id
in: path
required: true
schema:
type: string
title: Event Id
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/GenericResponse'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
/events/{event_id}/plus: /events/{event_id}/plus:
post: post:
tags: tags:
@@ -6075,9 +6152,7 @@ paths:
in: path in: path
required: true required: true
schema: schema:
anyOf: type: string
- type: string
- type: 'null'
title: Camera Name title: Camera Name
- name: frame_time - name: frame_time
in: path in: path
@@ -6098,9 +6173,9 @@ paths:
schema: schema:
$ref: '#/components/schemas/HTTPValidationError' $ref: '#/components/schemas/HTTPValidationError'
security: security:
- frigateUserAuth: [] - frigateAdminAuth: []
x-required-role: camera x-required-role: admin
description: '**Access:** Authenticated user with access to the referenced camera.' description: '**Access:** Admin role required.'
/{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4: /{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4:
get: get:
tags: tags:
@@ -8378,6 +8453,9 @@ components:
has_snapshot: has_snapshot:
type: boolean type: boolean
title: Has Snapshot title: Has Snapshot
retain_indefinitely:
type: boolean
title: Retain Indefinitely
plus_id: plus_id:
anyOf: anyOf:
- type: string - type: string
@@ -8415,6 +8493,7 @@ components:
- thumbnail - thumbnail
- has_clip - has_clip
- has_snapshot - has_snapshot
- retain_indefinitely
- plus_id - plus_id
- model_hash - model_hash
- detector_type - detector_type
+6 -16
View File
@@ -40,7 +40,6 @@ from frigate.api.defs.request.app_body import (
MediaSyncBody, MediaSyncBody,
) )
from frigate.api.defs.tags import Tags 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 import FrigateConfig, GenAIConfig, GenAIProviderEnum
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
@@ -55,7 +54,7 @@ from frigate.jobs.media_sync import (
start_media_sync_job, start_media_sync_job,
) )
from frigate.models import Event, Timeline 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.stats.prometheus import get_metrics, update_metrics
from frigate.types import JobStatusTypesEnum from frigate.types import JobStatusTypesEnum
from frigate.util.builtin import ( from frigate.util.builtin import (
@@ -1666,10 +1665,7 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
status_code=400, status_code=400,
) )
try: models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
if not models["list"]: if not models["list"]:
return JSONResponse( return JSONResponse(
@@ -1709,17 +1705,11 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))]) @router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
async def validate_plus_key(request: Request): async def validate_plus_key(request: Request):
"""Validate the configured Frigate+ API key with the Frigate+ server.""" """Validate the configured Frigate+ API key with the Frigate+ server."""
plus_api = request.app.frigate_config.plus_api status = await request.app.frigate_config.plus_api.validate_key()
status = await plus_api.validate_key()
content: dict[str, Any] = {
"success": status == PlusKeyStatus.valid,
"status": status.value,
}
if status == PlusKeyStatus.rate_limited: return JSONResponse(
content["retry_after"] = plus_api.rate_limit_remaining() content={"success": status == PlusKeyStatus.valid, "status": status.value}
)
return JSONResponse(content=content)
@router.get( @router.get(
@@ -29,6 +29,7 @@ class EventsQueryParams(BaseModel):
), ),
deprecated=True, deprecated=True,
) )
favorites: int | None = None
min_score: float | None = None min_score: float | None = None
max_score: float | None = None max_score: float | None = None
min_speed: float | None = None min_speed: float | None = None
@@ -15,6 +15,7 @@ class EventResponse(BaseModel):
thumbnail: str | None thumbnail: str | None
has_clip: bool has_clip: bool
has_snapshot: bool has_snapshot: bool
retain_indefinitely: bool
plus_id: str | None plus_id: str | None
model_hash: str | None model_hash: str | None
detector_type: str | None detector_type: str | None
+99 -61
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.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags 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.comms.event_metadata_updater import EventMetadataTypeEnum
from frigate.config.classification import ObjectClassificationType from frigate.config.classification import ObjectClassificationType
from frigate.const import CLIPS_DIR from frigate.const import CLIPS_DIR
from frigate.embeddings import EmbeddingsContext from frigate.embeddings import EmbeddingsContext
from frigate.models import Event, ReviewSegment, Timeline, Trigger from frigate.models import Event, ReviewSegment, Timeline, Trigger
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObject from frigate.track.object_processing import TrackedObject
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
from frigate.util.path import get_trigger_thumbnail_path, safe_join from frigate.util.path import get_trigger_thumbnail_path, safe_join
@@ -69,9 +67,6 @@ logger = logging.getLogger(__name__)
router = APIRouter(tags=[Tags.events]) router = APIRouter(tags=[Tags.events])
# event.data key holding a Frigate+ image id until its annotation is uploaded
PLUS_PENDING_ID_KEY = "plus_pending_id"
def _build_attribute_filter_clause(attributes: str): def _build_attribute_filter_clause(attributes: str):
filtered_attributes = [ filtered_attributes = [
@@ -142,6 +137,7 @@ def events(
has_snapshot = params.has_snapshot has_snapshot = params.has_snapshot
in_progress = params.in_progress in_progress = params.in_progress
include_thumbnails = params.include_thumbnails include_thumbnails = params.include_thumbnails
favorites = params.favorites
min_score = params.min_score min_score = params.min_score
max_score = params.max_score max_score = params.max_score
min_speed = params.min_speed min_speed = params.min_speed
@@ -166,6 +162,7 @@ def events(
Event.has_clip, Event.has_clip,
Event.has_snapshot, Event.has_snapshot,
Event.plus_id, Event.plus_id,
Event.retain_indefinitely,
Event.sub_label, Event.sub_label,
Event.top_score, Event.top_score,
Event.false_positive, Event.false_positive,
@@ -310,6 +307,9 @@ def events(
if include_thumbnails: if include_thumbnails:
selected_columns.append(Event.thumbnail) selected_columns.append(Event.thumbnail)
if favorites:
clauses.append(Event.retain_indefinitely == favorites)
if max_score is not None: if max_score is not None:
clauses.append(Event.data["score"] <= max_score) clauses.append(Event.data["score"] <= max_score)
@@ -410,6 +410,7 @@ def events_explore(
Event.has_clip, Event.has_clip,
Event.has_snapshot, Event.has_snapshot,
Event.plus_id, Event.plus_id,
Event.retain_indefinitely,
Event.top_score, Event.top_score,
Event.false_positive, Event.false_positive,
Event.box, Event.box,
@@ -450,6 +451,7 @@ def events_explore(
"has_clip": event.has_clip, "has_clip": event.has_clip,
"has_snapshot": event.has_snapshot, "has_snapshot": event.has_snapshot,
"plus_id": event.plus_id, "plus_id": event.plus_id,
"retain_indefinitely": event.retain_indefinitely,
"sub_label": event.sub_label, "sub_label": event.sub_label,
"top_score": event.top_score, "top_score": event.top_score,
"false_positive": event.false_positive, "false_positive": event.false_positive,
@@ -1024,6 +1026,34 @@ async def event(event_id: str, request: Request):
return JSONResponse(content="Event not found", status_code=404) return JSONResponse(content="Event not found", status_code=404)
@router.post(
"/events/{event_id}/retain",
response_model=GenericResponse,
dependencies=[Depends(require_role(["admin"]))],
summary="Set event retain indefinitely.",
description="""Sets an event to retain indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
""",
)
def set_retain(event_id: str):
try:
event = Event.get(Event.id == event_id)
except DoesNotExist:
return JSONResponse(
content=({"success": False, "message": "Event " + event_id + " not found"}),
status_code=404,
)
event.retain_indefinitely = True
event.save()
return JSONResponse(
content=({"success": True, "message": "Event " + event_id + " retained"}),
status_code=200,
)
@router.post( @router.post(
"/events/{event_id}/plus", "/events/{event_id}/plus",
response_model=EventUploadPlusResponse, response_model=EventUploadPlusResponse,
@@ -1082,55 +1112,43 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
content=({"success": False, "message": message}), status_code=400 content=({"success": False, "message": message}), status_code=400
) )
# an image uploaded by an earlier attempt whose annotation failed, so a try:
# retry finishes that submission instead of uploading the image again image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True)
plus_id = event.data.get(PLUS_PENDING_ID_KEY) except Exception:
logger.error(f"Unable to load clean snapshot for event: {event.id}")
return JSONResponse(
content=(
{"success": False, "message": "Unable to load clean snapshot for event"}
),
status_code=400,
)
if plus_id is None: if not is_clean_snapshot or image is None or image.size == 0:
try: logger.error(f"Unable to find clean snapshot for event: {event.id}")
image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True) return JSONResponse(
except Exception: content=(
logger.error(f"Unable to load clean snapshot for event: {event.id}") {
return JSONResponse( "success": False,
content=( "message": "Unable to find clean snapshot for event",
{ }
"success": False, ),
"message": "Unable to load clean snapshot for event", status_code=400,
} )
),
status_code=400,
)
if not is_clean_snapshot or image is None or image.size == 0: try:
logger.error(f"Unable to find clean snapshot for event: {event.id}") plus_id = await asyncio.to_thread(
return JSONResponse( request.app.frigate_config.plus_api.upload_image, image, event.camera
content=( )
{ except Exception as ex:
"success": False, logger.exception(ex)
"message": "Unable to find clean snapshot for event", return JSONResponse(
} content=({"success": False, "message": "Error uploading image"}),
), status_code=400,
status_code=400, )
)
try: # store image id in the database
plus_id = await asyncio.to_thread( event.plus_id = plus_id
request.app.frigate_config.plus_api.upload_image, image, event.camera event.save()
)
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except Exception as ex:
logger.exception(ex)
return JSONResponse(
content=({"success": False, "message": "Error uploading image"}),
status_code=400,
)
if include_annotation is not None:
# the image isn't marked submitted until its annotation is, or a
# failed annotation could never be retried
event.data[PLUS_PENDING_ID_KEY] = plus_id
event.save()
if include_annotation is not None: if include_annotation is not None:
box = event.data["box"] box = event.data["box"]
@@ -1138,12 +1156,10 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
try: try:
await asyncio.to_thread( await asyncio.to_thread(
request.app.frigate_config.plus_api.add_annotation, request.app.frigate_config.plus_api.add_annotation,
plus_id, event.plus_id,
box, box,
event.label, event.label,
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError: except ValueError:
message = "Error uploading annotation, unsupported label provided." message = "Error uploading annotation, unsupported label provided."
logger.error(message) logger.error(message)
@@ -1158,11 +1174,6 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
status_code=400, status_code=400,
) )
# store image id in the database
event.plus_id = plus_id
event.data.pop(PLUS_PENDING_ID_KEY, None)
event.save()
return JSONResponse( return JSONResponse(
content=({"success": True, "plus_id": plus_id}), status_code=200 content=({"success": True, "plus_id": plus_id}), status_code=200
) )
@@ -1245,8 +1256,6 @@ async def false_positive(request: Request, event_id: str):
event.model_type, event.model_type,
event.detector_type, event.detector_type,
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError: except ValueError:
message = "Error uploading false positive, unsupported label provided." message = "Error uploading false positive, unsupported label provided."
logger.error(message) logger.error(message)
@@ -1269,6 +1278,35 @@ async def false_positive(request: Request, event_id: str):
) )
@router.delete(
"/events/{event_id}/retain",
response_model=GenericResponse,
dependencies=[Depends(require_role(["admin"]))],
summary="Stop event from being retained indefinitely",
description="""Stops an event from being retained indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
""",
)
async def delete_retain(event_id: str, request: Request):
try:
event = Event.get(Event.id == event_id)
await require_camera_access(event.camera, request=request)
except DoesNotExist:
return JSONResponse(
content=({"success": False, "message": "Event " + event_id + " not found"}),
status_code=404,
)
event.retain_indefinitely = False
event.save()
return JSONResponse(
content=({"success": True, "message": "Event " + event_id + " un-retained"}),
status_code=200,
)
@router.post( @router.post(
"/events/{event_id}/sub_label", "/events/{event_id}/sub_label",
response_model=GenericResponse, response_model=GenericResponse,
+4 -9
View File
@@ -36,7 +36,6 @@ from frigate.api.defs.query.media_query_parameters import (
MediaMjpegFeedQueryParams, MediaMjpegFeedQueryParams,
) )
from frigate.api.defs.tags import Tags 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.camera.state import CameraState
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.config.camera.snapshots import SnapshotsConfig from frigate.config.camera.snapshots import SnapshotsConfig
@@ -52,7 +51,6 @@ from frigate.output.preview import (
get_most_recent_preview_frame, get_most_recent_preview_frame,
is_camera_preview_frame, is_camera_preview_frame,
) )
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObjectProcessor from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.ffmpeg import terminate_ffmpeg_stream from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.file import ( from frigate.util.file import (
@@ -436,7 +434,7 @@ async def get_snapshot_from_recording(
@router.post( @router.post(
"/{camera_name}/plus/{frame_time}", dependencies=[Depends(require_camera_access)] "/{camera_name}/plus/{frame_time}", dependencies=[Depends(require_role(["admin"]))]
) )
async def submit_recording_snapshot_to_plus( async def submit_recording_snapshot_to_plus(
request: Request, camera_name: str, frame_time: str request: Request, camera_name: str, frame_time: str
@@ -481,12 +479,9 @@ async def submit_recording_snapshot_to_plus(
) )
nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR) nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
try: await asyncio.to_thread(
await asyncio.to_thread( request.app.frigate_config.plus_api.upload_image, nd, camera_name
request.app.frigate_config.plus_api.upload_image, nd, camera_name )
)
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
return JSONResponse( return JSONResponse(
content={ content={
+6 -6
View File
@@ -20,7 +20,7 @@ from urllib.parse import unquote
from peewee import DoesNotExist, Field from peewee import DoesNotExist, Field
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR, EXPORT_DIR, SUB_CACHE_TAG from frigate.const import CLIPS_DIR, EXPORT_DIR
from frigate.models import Export, User from frigate.models import Export, User
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -137,12 +137,11 @@ def _resolve_recording(
# /recordings/{date} → neutral # /recordings/{date} → neutral
# /recordings/{date}/{hour} → multi-camera listing # /recordings/{date}/{hour} → multi-camera listing
# /recordings/{date}/{hour}/{cam}/... → camera # /recordings/{date}/{hour}/{cam}/... → camera
# /recordings/{date}/{hour}/{cam}@sub/... → camera (sub stream)
if len(parts) <= 2: if len(parts) <= 2:
return MediaAuthResolution.LISTING_NEUTRAL, None return MediaAuthResolution.LISTING_NEUTRAL, None
if len(parts) == 3: if len(parts) == 3:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[3].removesuffix(SUB_CACHE_TAG) return MediaAuthResolution.CAMERA, parts[3]
def _resolve_clip( def _resolve_clip(
@@ -151,7 +150,6 @@ def _resolve_clip(
# /clips → multi-camera listing # /clips → multi-camera listing
# /clips/thumbs/{cam}/... → camera # /clips/thumbs/{cam}/... → camera
# /clips/previews/{cam}/... → camera # /clips/previews/{cam}/... → camera
# /clips/triggers/{cam}/... → camera
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed) # /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
# /clips/export/{export_id}.{ext} → camera (DB lookup) # /clips/export/{export_id}.{ext} → camera (DB lookup)
# /clips/faces/... → admin-only # /clips/faces/... → admin-only
@@ -165,7 +163,7 @@ def _resolve_clip(
second = parts[1] second = parts[1]
if second in ("thumbs", "previews", "triggers"): if second in ("thumbs", "previews"):
if len(parts) == 2: if len(parts) == 2:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[2] return MediaAuthResolution.CAMERA, parts[2]
@@ -313,6 +311,9 @@ def deny_response_for_media_uri(
if not role or role == "admin": if not role or role == "admin":
return None return None
if resolution == MediaAuthResolution.ADMIN_ONLY:
return 403
if not is_role_restricted(role, frigate_config): if not is_role_restricted(role, frigate_config):
return None return None
@@ -321,7 +322,6 @@ def deny_response_for_media_uri(
if resolution in ( if resolution in (
MediaAuthResolution.LISTING_MULTI_CAMERA, MediaAuthResolution.LISTING_MULTI_CAMERA,
MediaAuthResolution.ADMIN_ONLY,
MediaAuthResolution.UNRESOLVED_MEDIA, MediaAuthResolution.UNRESOLVED_MEDIA,
): ):
return 403 return 403
-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,
)
+9 -3
View File
@@ -713,12 +713,18 @@ def motion_activity(
response_model=ReviewSegmentResponse, response_model=ReviewSegmentResponse,
dependencies=[Depends(allow_any_authenticated())], dependencies=[Depends(allow_any_authenticated())],
) )
async def get_review_from_event(request: Request, event_id: str): async def get_review_from_event(
event_id: str,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
):
try: try:
review = ReviewSegment.get( review = ReviewSegment.get(
ReviewSegment.data["detections"].cast("text") % f'*"{event_id}"*' (ReviewSegment.camera << allowed_cameras)
& (
fn.instr(ReviewSegment.data["detections"].cast("text"), f'"{event_id}"')
> 0
)
) )
await require_camera_access(review.camera, request=request)
return JSONResponse(model_to_dict(review)) return JSONResponse(model_to_dict(review))
except DoesNotExist: except DoesNotExist:
return JSONResponse( return JSONResponse(
+1 -1
View File
@@ -685,7 +685,7 @@ class WebPushClient(Communicator):
title = f"{name.replace('_', ' ')} triggered on {camera_name}" title = f"{name.replace('_', ' ')} triggered on {camera_name}"
message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}" message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}"
image = f"api/events/{event_id}/thumbnail.webp" image = f"clips/triggers/{camera}/{event_id}.webp"
direct_url = f"/explore?event_id={event_id}" direct_url = f"/explore?event_id={event_id}"
ttl = 0 ttl = 0
+1 -23
View File
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
from pydantic.fields import PrivateAttr from pydantic.fields import PrivateAttr
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR 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 from frigate.util.builtin import generate_color_palette, load_labels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -52,16 +52,6 @@ DEFAULT_SCENE = "default"
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$" 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): class ModelConfig(BaseModel):
scene: str = Field( scene: str = Field(
default=DEFAULT_SCENE, default=DEFAULT_SCENE,
@@ -203,16 +193,6 @@ class ModelConfig(BaseModel):
raise ValueError( raise ValueError(
f"Unable to connect to Frigate+ to download model {model_id}" f"Unable to connect to Frigate+ to download model {model_id}"
) from e ) 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: with open(self.path, "wb") as f:
f.write(r.content) f.write(r.content)
@@ -225,8 +205,6 @@ class ModelConfig(BaseModel):
raise ValueError( raise ValueError(
f"Unable to connect to Frigate+ to download model info for {model_id}" f"Unable to connect to Frigate+ to download model info for {model_id}"
) from e ) from e
except PlusRateLimitError as e:
raise ValueError(_rate_limited_message(model_id, e)) from e
with open(model_info_path, "w") as f: with open(model_info_path, "w") as f:
json.dump(model_info, f) json.dump(model_info, f)
+5
View File
@@ -89,6 +89,7 @@ class EventCleanup(threading.Thread):
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.label == event.label, Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True, Event.has_snapshot == True,
) )
.namedtuples() .namedtuples()
@@ -110,6 +111,7 @@ class EventCleanup(threading.Thread):
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.label == event.label, Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True, Event.has_snapshot == True,
) )
@@ -165,6 +167,7 @@ class EventCleanup(threading.Thread):
Event.camera == name, Event.camera == name,
Event.start_time < expire_after, Event.start_time < expire_after,
Event.label == event.label, Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True, Event.has_snapshot == True,
) )
.namedtuples() .namedtuples()
@@ -209,6 +212,7 @@ class EventCleanup(threading.Thread):
query = Event.select(Event.id).where( query = Event.select(Event.id).where(
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.retain_indefinitely == False,
Event.has_clip == True, Event.has_clip == True,
) )
@@ -254,6 +258,7 @@ class EventCleanup(threading.Thread):
) )
.where( .where(
Event.camera == name, Event.camera == name,
Event.retain_indefinitely == False,
Event.has_clip == True, Event.has_clip == True,
( (
( (
+1
View File
@@ -40,6 +40,7 @@ class Event(Model):
area = ( area = (
IntegerField() IntegerField()
) # TODO remove when columns can be dropped without rebuilding table ) # TODO remove when columns can be dropped without rebuilding table
retain_indefinitely = BooleanField(default=False)
ratio = FloatField( ratio = FloatField(
default=1.0 default=1.0
) # TODO remove when columns can be dropped without rebuilding table ) # TODO remove when columns can be dropped without rebuilding table
+14 -135
View File
@@ -1,12 +1,8 @@
import datetime import datetime
import email.utils
import json import json
import logging import logging
import math
import os import os
import re import re
import threading
import time
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from typing import Any, TypeGuard from typing import Any, TypeGuard
@@ -25,11 +21,6 @@ logger = logging.getLogger(__name__)
PLUS_VALIDATE_TIMEOUT = 10 PLUS_VALIDATE_TIMEOUT = 10
# Requests run on several threads, and a reply that arrives late must not
# shorten a wait recorded from another one. The lock is kept out of PlusApi
# because the client is pickled with the config to start worker processes.
_rate_limit_lock = threading.Lock()
class PlusKeyStatus(str, Enum): class PlusKeyStatus(str, Enum):
"""Result of validating a Frigate+ API key with the server.""" """Result of validating a Frigate+ API key with the server."""
@@ -37,7 +28,6 @@ class PlusKeyStatus(str, Enum):
valid = "valid" valid = "valid"
invalid = "invalid" invalid = "invalid"
unreachable = "unreachable" unreachable = "unreachable"
rate_limited = "rate_limited"
not_set = "not_set" not_set = "not_set"
@@ -80,51 +70,6 @@ def load_plus_model_info(model_id: str) -> dict[str, Any] | None:
return add_hailo_alias(model_info) 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: def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
if image.shape[1] >= image.shape[0]: if image.shape[1] >= image.shape[0]:
width = min(max_dim, image.shape[1]) width = min(max_dim, image.shape[1])
@@ -183,62 +128,14 @@ class PlusApi:
self._is_active: bool = self.key is not None self._is_active: bool = self.key is not None
self._token_data: dict = {} 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 # Retry connection failures so a network that comes up late at startup
# doesn't fail the Frigate+ model download. Retry-After is not honored # doesn't fail the Frigate+ model download
# here, since urllib3 would block the calling thread for as long as the
# server asks; a 429 is raised to the caller as PlusRateLimitError.
self._session = requests.Session() self._session = requests.Session()
self._session.mount( self._session.mount(
self.host, self.host, HTTPAdapter(max_retries=Retry(connect=5, backoff_factor=1))
HTTPAdapter(
max_retries=Retry(
connect=5, backoff_factor=1, respect_retry_after_header=False
)
),
) )
def rate_limit_remaining(self) -> int | None:
"""Seconds until Frigate+ accepts requests again, or None if not limited."""
rate_limited_until = self._rate_limited_until
if rate_limited_until is None:
return None
remaining = math.ceil(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 None:
return
until = time.time() + retry_after
with _rate_limit_lock:
if self._rate_limited_until is None or until > self._rate_limited_until:
self._rate_limited_until = until
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: def _refresh_token_if_needed(self) -> None:
if ( if (
self._token_data.get("expires") is None self._token_data.get("expires") is None
@@ -248,12 +145,10 @@ class PlusApi:
raise Exception( raise Exception(
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key" "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(":") parts = self.key.split(":")
r = self._session.get( r = self._session.get(
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1]) f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
) )
self._check_rate_limit(r)
if not r.ok: if not r.ok:
raise Exception(f"Unable to refresh API token: {r.text}") raise Exception(f"Unable to refresh API token: {r.text}")
self._token_data = r.json() self._token_data = r.json()
@@ -262,30 +157,24 @@ class PlusApi:
self._refresh_token_if_needed() self._refresh_token_if_needed()
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"} return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
def _request(self, method: str, path: str, data: dict | None = None) -> Response: def _get(self, path: str) -> Response:
"""Make an authenticated Frigate+ request. return self._session.get(
f"{self.host}/v1/{path}", headers=self._get_authorization_header()
)
Raises: def _post(self, path: str, data: dict) -> Response:
PlusRateLimitError: Frigate+ is rate limiting requests return self._session.post(
"""
self._raise_if_rate_limited()
r = self._session.request(
method,
f"{self.host}/v1/{path}", f"{self.host}/v1/{path}",
headers=self._get_authorization_header(), headers=self._get_authorization_header(),
json=data, 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: 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: def is_active(self) -> bool:
return self._is_active return self._is_active
@@ -298,16 +187,11 @@ class PlusApi:
result reflects the key's current state rather than a cached token. result reflects the key's current state rather than a cached token.
Returns: Returns:
The key's status as reported by the Frigate+ server. When it is The key's status as reported by the Frigate+ server
rate_limited, rate_limit_remaining() gives the wait if known.
""" """
if self.key is None: if self.key is None:
return PlusKeyStatus.not_set 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(":") key_id, _, secret = self.key.partition(":")
# Use a single request with a timeout instead of the retrying session, # Use a single request with a timeout instead of the retrying session,
@@ -323,7 +207,6 @@ class PlusApi:
auth=aiohttp.BasicAuth(key_id, secret), auth=aiohttp.BasicAuth(key_id, secret),
) as r: ) as r:
status = r.status 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 token_data = await r.json(content_type=None) if r.ok else None
except (aiohttp.ClientError, TimeoutError) as err: except (aiohttp.ClientError, TimeoutError) as err:
logger.warning("Unable to reach Frigate+ to validate API key: %s", err) logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
@@ -335,10 +218,6 @@ class PlusApi:
if status in (401, 403): if status in (401, 403):
return PlusKeyStatus.invalid return PlusKeyStatus.invalid
if status == 429:
self._note_rate_limit(retry_after)
return PlusKeyStatus.rate_limited
if status >= 400: if status >= 400:
logger.warning( logger.warning(
"Unexpected response validating Frigate+ API key: %s", status "Unexpected response validating Frigate+ API key: %s", status
+76 -8
View File
@@ -260,24 +260,92 @@ class StorageMaintainer(threading.Thread):
.iterator() .iterator()
) )
retained_events = (
Event.select(
Event.start_time,
Event.end_time,
)
.where(
Event.retain_indefinitely == True,
Event.has_clip,
)
.order_by(Event.start_time.asc())
.namedtuples()
)
event_start = 0
deleted_recordings = [] deleted_recordings = []
for recording in recordings: for recording in recordings:
# check if 1 hour of storage has been reclaimed # check if 1 hour of storage has been reclaimed
if deleted_segments_size > hourly_bandwidth: if deleted_segments_size > hourly_bandwidth:
break break
try: keep = False
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_recordings.append(recording)
deleted_segments_size += recording.segment_size
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
# Now look for a reason to keep this recording segment
for idx in range(event_start, len(retained_events)):
event = retained_events[idx]
# if the event starts in the future, stop checking events
# and let this recording segment expire
if event.start_time > recording.end_time:
keep = False
break
# if the event is in progress or ends after the recording starts, keep it
# and stop looking at events
if event.end_time is None or event.end_time >= recording.start_time:
keep = True
break
# if the event ends before this recording segment starts, skip
# this event and check the next event for an overlap.
# since the events and recordings are sorted, we can skip events
# that end before the previous recording segment started on future segments
if event.end_time < recording.start_time:
event_start = idx
# Delete recordings not retained indefinitely
if not keep:
try:
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_recordings.append(recording)
deleted_segments_size += recording.segment_size
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
# check if need to delete retained segments
if deleted_segments_size < hourly_bandwidth: if deleted_segments_size < hourly_bandwidth:
logger.error( logger.error(
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared." f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared. Retained recordings must be deleted."
) )
recordings = (
Recordings.select(
Recordings.id,
Recordings.camera,
Recordings.start_time,
Recordings.end_time,
Recordings.path,
Recordings.segment_size,
)
.order_by(Recordings.start_time.asc())
.namedtuples()
.iterator()
)
for recording in recordings:
if deleted_segments_size > hourly_bandwidth:
break
try:
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_segments_size += recording.segment_size
deleted_recordings.append(recording)
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
self.retention_unmet = True self.retention_unmet = True
else: else:
logger.info(f"Cleaned up {deleted_segments_size:.2f} MB of recordings") logger.info(f"Cleaned up {deleted_segments_size:.2f} MB of recordings")
+33 -3
View File
@@ -374,6 +374,22 @@ class TestHttpApp(BaseTestHttp):
event_after_delete = client.get(f"/events/{id}") event_after_delete = client.get(f"/events/{id}")
assert event_after_delete.status_code == 404 assert event_after_delete.status_code == 404
def test_event_retention(self):
id = "123456.random"
with AuthTestClient(self.app) as client:
super().insert_mock_event(id)
client.post(f"/events/{id}/retain", headers={"remote-role": "admin"})
event = client.get(f"/events/{id}").json()
assert event
assert event["id"] == id
assert event["retain_indefinitely"] is True
client.delete(f"/events/{id}/retain", headers={"remote-role": "admin"})
event = client.get(f"/events/{id}").json()
assert event
assert event["id"] == id
assert event["retain_indefinitely"] is False
def test_event_time_filtering(self): def test_event_time_filtering(self):
morning_id = "123456.random" morning_id = "123456.random"
evening_id = "654321.random" evening_id = "654321.random"
@@ -511,32 +527,42 @@ class TestHttpApp(BaseTestHttp):
with AuthTestClient(self.app) as client: with AuthTestClient(self.app) as client:
ts_start = datetime.now().timestamp() ts_start = datetime.now().timestamp()
ts_end = ts_start + 30 ts_end = ts_start + 30
_insert_mock_event(id="abcde.random", start=ts_start, end=ts_end) _insert_mock_event(
_insert_mock_event(id="01234.random", start=ts_start, end=ts_end) id="abcde.random", start=ts_start, end=ts_end, retain=True
_insert_mock_event(id="56789.random", start=ts_start, end=ts_end) )
_insert_mock_event(
id="01234.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event(
id="56789.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event( _insert_mock_event(
id="101112.random", id="101112.random",
label="outside", label="outside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="131415.random", id="131415.random",
label="outside", label="outside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="161718.random", id="161718.random",
camera="porch", camera="porch",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="192021.random", id="192021.random",
camera="porch", camera="porch",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="222324.random", id="222324.random",
@@ -544,6 +570,7 @@ class TestHttpApp(BaseTestHttp):
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="252627.random", id="252627.random",
@@ -551,18 +578,21 @@ class TestHttpApp(BaseTestHttp):
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="282930.random", id="282930.random",
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="313233.random", id="313233.random",
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
stats_emitter = Mock(spec=StatsEmitter) stats_emitter = Mock(spec=StatsEmitter)
-20
View File
@@ -14,7 +14,6 @@ from fastapi import Request
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user
from frigate.const import MAX_SEGMENT_DURATION from frigate.const import MAX_SEGMENT_DURATION
from frigate.models import Event, Recordings from frigate.models import Event, Recordings
from frigate.plus import PlusRateLimitError
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -2145,22 +2144,3 @@ class TestHttpMedia(BaseTestHttp):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
upload.assert_called_once_with("frame", "front_door") 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 -120
View File
@@ -3,10 +3,8 @@
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
import numpy as np
from frigate.models import Event 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 from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -14,13 +12,11 @@ class TestHttpPlusValidate(BaseTestHttp):
def setUp(self): def setUp(self):
super().setUp([Event]) super().setUp([Event])
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict: def _validate(self, status: PlusKeyStatus) -> dict:
app = self.create_app() app = self.create_app()
plus_api = app.frigate_config.plus_api
with ( with patch.object(
patch.object(plus_api, "validate_key", return_value=status), app.frigate_config.plus_api, "validate_key", return_value=status
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
): ):
with AuthTestClient(app) as client: with AuthTestClient(app) as client:
response = client.post("/plus/validate") response = client.post("/plus/validate")
@@ -39,12 +35,6 @@ class TestHttpPlusValidate(BaseTestHttp):
{"success": False, "status": "invalid"}, {"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): def test_viewers_cannot_validate(self):
app = self.create_app() app = self.create_app()
@@ -57,111 +47,5 @@ class TestHttpPlusValidate(BaseTestHttp):
self.assertEqual(response.status_code, 403) 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_a_rate_limited_annotation_can_be_retried(self):
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
snapshot = patch(
"frigate.api.event.load_event_snapshot_image",
return_value=(np.ones((10, 10, 3), np.uint8), True),
)
with (
snapshot,
patch.object(self.plus_api, "upload_image", return_value="img") as upload,
patch.object(
self.plus_api,
"add_annotation",
side_effect=[PlusRateLimitError(30), None],
) as annotate,
AuthTestClient(self.app) as client,
):
first = client.post("/events/event/plus", json={"include_annotation": 1})
# the image isn't marked submitted while its annotation is missing
self.assertIsNone(Event.get(Event.id == "event").plus_id)
retry = client.post("/events/event/plus", json={"include_annotation": 1})
self._assert_rate_limited(first, 30)
self.assertEqual(retry.status_code, 200)
self.assertEqual(retry.json()["plus_id"], "img")
upload.assert_called_once()
self.assertEqual(
[call.args[0] for call in annotate.call_args_list], ["img", "img"]
)
event = Event.get(Event.id == "event")
self.assertEqual(event.plus_id, "img")
self.assertNotIn("plus_pending_id", event.data)
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__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)
+37
View File
@@ -1,4 +1,5 @@
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from urllib.parse import quote
from fastapi import Request from fastapi import Request
from peewee import DoesNotExist from peewee import DoesNotExist
@@ -840,6 +841,42 @@ class TestHttpReview(BaseTestHttp):
response_json, response_json,
) )
def test_review_event_wildcards_match_literally(self):
now = datetime.now().timestamp()
super().insert_mock_review_segment(
"123456.review.random",
now + 1,
now + 2,
data={"detections": ["1763812345.0-abc123"]},
)
with AuthTestClient(self.app) as client:
for pattern in ["1763812345*", "176381234?.0-abc123", "176381234[0-9]*"]:
response = client.get(f"/review/event/{quote(pattern, safe='')}")
assert response.status_code == 404
response = client.get("/review/event/1763812345.0-abc123")
assert response.status_code == 200
def test_review_event_on_forbidden_camera_is_not_found(self):
now = datetime.now().timestamp()
event_id = "1763812345.0-abc123"
super().insert_mock_review_segment(
"123456.review.random",
now + 1,
now + 2,
data={"detections": [event_id]},
camera="back_door",
)
with AuthTestClient(self.app) as client:
response = client.get(f"/review/event/{event_id}")
assert response.status_code == 404
self.assertDictEqual(
{"success": False, "message": "Review item not found"},
response.json(),
)
#################################################################################################################### ####################################################################################################################
################################### GET /review/{review_id} Endpoint ####################################### ################################### GET /review/{review_id} Endpoint #######################################
#################################################################################################################### ####################################################################################################################
@@ -122,6 +122,7 @@ class TestExecuteFindSimilarObjects(unittest.TestCase):
region=[0, 0, 1, 1], region=[0, 0, 1, 1],
box=[0, 0, 1, 1], box=[0, 0, 1, 1],
area=1, area=1,
retain_indefinitely=False,
ratio=1.0, ratio=1.0,
plus_id="", plus_id="",
model_hash="", model_hash="",
+1
View File
@@ -259,6 +259,7 @@ class DatabaseTestCase(unittest.TestCase):
region=[0, 0, 1, 1], region=[0, 0, 1, 1],
box=[0, 0, 1, 1], box=[0, 0, 1, 1],
area=1, area=1,
retain_indefinitely=False,
ratio=1.0, ratio=1.0,
plus_id="", plus_id="",
model_hash="", model_hash="",
+1 -57
View File
@@ -1,10 +1,9 @@
import json import json
import os import os
import pickle
import tempfile import tempfile
import unittest import unittest
from copy import deepcopy from copy import deepcopy
from unittest.mock import MagicMock, patch from unittest.mock import patch
import numpy as np import numpy as np
import requests import requests
@@ -15,7 +14,6 @@ from frigate.config import BirdseyeModeEnum, FrigateConfig, RetainModeEnum
from frigate.const import MODEL_CACHE_DIR from frigate.const import MODEL_CACHE_DIR
from frigate.detectors import DetectorTypeEnum from frigate.detectors import DetectorTypeEnum
from frigate.detectors.device import build_detector_config, runner_names from frigate.detectors.device import build_detector_config, runner_names
from frigate.plus import PlusApi, PlusRateLimitError
from frigate.util.builtin import deep_merge from frigate.util.builtin import deep_merge
from frigate.util.config import resolve_ffmpeg_path from frigate.util.config import resolve_ffmpeg_path
@@ -1639,60 +1637,6 @@ class TestConfig(unittest.TestCase):
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"): with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
FrigateConfig(**config) 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_config_can_be_sent_to_a_worker_process(self):
# worker processes start from the forkserver, which pickles the config
# along with the Frigate+ client it holds
frigate_config = FrigateConfig(**self.minimal)
copy = pickle.loads(pickle.dumps(frigate_config))
self.assertIsInstance(copy.plus_api, PlusApi)
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): def test_fails_on_invalid_role(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
+1
View File
@@ -68,6 +68,7 @@ class TestEventCleanup(unittest.TestCase):
region=[], region=[],
box=[], box=[],
area=0, area=0,
retain_indefinitely=False,
plus_id="", plus_id="",
model_hash="", model_hash="",
detector_type="cpu", detector_type="cpu",
@@ -59,6 +59,7 @@ class TestEventCleanupSnapshots(unittest.TestCase):
region=[], region=[],
box=[], box=[],
area=0, area=0,
retain_indefinitely=False,
plus_id="", plus_id="",
model_hash="", model_hash="",
detector_type="cpu", detector_type="cpu",
+1
View File
@@ -68,6 +68,7 @@ class TestEventCleanupSubRetention(unittest.TestCase):
region=[], region=[],
box=[], box=[],
area=0, area=0,
retain_indefinitely=False,
plus_id="", plus_id="",
model_hash="", model_hash="",
detector_type="cpu", detector_type="cpu",
+12 -30
View File
@@ -122,11 +122,6 @@ class TestResolveMediaUri(unittest.TestCase):
MediaAuthResolution.CAMERA, MediaAuthResolution.CAMERA,
camera="back_door", camera="back_door",
) )
self._assert(
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4",
MediaAuthResolution.CAMERA,
camera="back_door",
)
def test_clip_flat_filename_resolves_camera(self): def test_clip_flat_filename_resolves_camera(self):
self._assert( self._assert(
@@ -182,14 +177,6 @@ class TestResolveMediaUri(unittest.TestCase):
camera="back_door", camera="back_door",
) )
def test_clip_triggers(self):
self._assert("/clips/triggers/", MediaAuthResolution.LISTING_MULTI_CAMERA)
self._assert(
"/clips/triggers/back_door/abc.webp",
MediaAuthResolution.CAMERA,
camera="back_door",
)
def test_clip_review_thumbs(self): def test_clip_review_thumbs(self):
# Format: /clips/review/thumb-{camera}-{review_id}.webp (frigate/review/maintainer.py). # Format: /clips/review/thumb-{camera}-{review_id}.webp (frigate/review/maintainer.py).
self._assert( self._assert(
@@ -345,6 +332,18 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertIsNone(self._deny("/clips/back_door-1.jpg", "viewer")) self.assertIsNone(self._deny("/clips/back_door-1.jpg", "viewer"))
self.assertIsNone(self._deny("/clips/", "viewer")) self.assertIsNone(self._deny("/clips/", "viewer"))
def test_unrestricted_role_blocked_admin_only(self):
for uri in (
"/clips/faces/",
"/clips/faces/train/foo.webp",
"/clips/faces/alice/ref.webp",
"/clips/genai-requests/x/0.jpg",
"/clips/preview_restart_cache/x.mp4",
"/clips/some_model/train/x.jpg",
"/clips/some_model/dataset/cat/x.jpg",
):
self.assertEqual(self._deny(uri, "viewer"), 403, uri)
def test_restricted_role_allowed_camera(self): def test_restricted_role_allowed_camera(self):
self.assertIsNone(self._deny("/clips/front_door-1.jpg", "limited_user")) self.assertIsNone(self._deny("/clips/front_door-1.jpg", "limited_user"))
self.assertIsNone( self.assertIsNone(
@@ -353,14 +352,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertIsNone( self.assertIsNone(
self._deny("/clips/thumbs/front_door/abc.webp", "limited_user") self._deny("/clips/thumbs/front_door/abc.webp", "limited_user")
) )
self.assertIsNone(
self._deny(
"/recordings/2026-05-11/14/front_door@sub/00.00.mp4", "limited_user"
)
)
self.assertIsNone(
self._deny("/clips/triggers/front_door/abc.webp", "limited_user")
)
def test_restricted_role_blocked_other_camera(self): def test_restricted_role_blocked_other_camera(self):
self.assertEqual(self._deny("/clips/back_door-1.jpg", "limited_user"), 403) self.assertEqual(self._deny("/clips/back_door-1.jpg", "limited_user"), 403)
@@ -371,15 +362,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertEqual( self.assertEqual(
self._deny("/clips/thumbs/back_door/abc.webp", "limited_user"), 403 self._deny("/clips/thumbs/back_door/abc.webp", "limited_user"), 403
) )
self.assertEqual(
self._deny(
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4", "limited_user"
),
403,
)
self.assertEqual(
self._deny("/clips/triggers/back_door/abc.webp", "limited_user"), 403
)
def test_restricted_role_blocked_admin_only(self): def test_restricted_role_blocked_admin_only(self):
self.assertEqual(self._deny("/clips/faces/train/foo.webp", "limited_user"), 403) self.assertEqual(self._deny("/clips/faces/train/foo.webp", "limited_user"), 403)
-65
View File
@@ -1,65 +0,0 @@
"""Tests for media sync orphan cleanup."""
import os
import tempfile
import unittest
from unittest.mock import patch
from peewee import SqliteDatabase
from frigate.models import Export, ExportCase
from frigate.util.media import sync_exports
class TestSyncExports(unittest.TestCase):
def setUp(self):
self.db = SqliteDatabase(":memory:")
self.enterContext(self.db.bind_ctx([Export, ExportCase]))
self.db.create_tables([Export, ExportCase])
self.tmp = tempfile.TemporaryDirectory()
self.clips_dir = os.path.join(self.tmp.name, "clips")
self.export_dir = os.path.join(self.tmp.name, "exports")
self.thumb_dir = os.path.join(self.clips_dir, "export")
os.makedirs(self.thumb_dir)
os.makedirs(self.export_dir)
patcher_clips = patch("frigate.util.media.CLIPS_DIR", self.clips_dir)
patcher_exports = patch("frigate.util.media.EXPORT_DIR", self.export_dir)
patcher_clips.start()
patcher_exports.start()
self.addCleanup(patcher_clips.stop)
self.addCleanup(patcher_exports.stop)
def tearDown(self):
self.db.close()
self.tmp.cleanup()
def _touch(self, path: str) -> str:
open(path, "wb").close()
return path
def test_orphaned_webp_and_jpg_thumbnails_are_removed(self):
for i, ext in enumerate(("webp", "jpg")):
Export.insert(
id=f"front_{i}",
camera="front",
name=f"export {i}",
date=0,
video_path=self._touch(os.path.join(self.export_dir, f"{i}.mp4")),
thumb_path=self._touch(os.path.join(self.thumb_dir, f"{i}.{ext}")),
in_progress=False,
).execute()
orphan_webp = self._touch(os.path.join(self.thumb_dir, "gone.webp"))
orphan_jpg = self._touch(os.path.join(self.thumb_dir, "gone.jpg"))
result = sync_exports()
self.assertEqual(sorted(result.orphan_paths), sorted([orphan_jpg, orphan_webp]))
self.assertEqual(result.orphans_deleted, 2)
self.assertEqual(sorted(os.listdir(self.thumb_dir)), ["0.webp", "1.jpg"])
if __name__ == "__main__":
unittest.main()
+4 -218
View File
@@ -1,15 +1,9 @@
"""Tests for Frigate+ model metadata.""" """Tests for Frigate+ model metadata."""
import asyncio import asyncio
import datetime
import email.utils
import http.server
import json import json
import os import os
import pickle
import tempfile import tempfile
import threading
import time
import unittest import unittest
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
@@ -17,16 +11,7 @@ import aiohttp
from aiohttp import web from aiohttp import web
from aiohttp.test_utils import TestServer from aiohttp.test_utils import TestServer
from frigate.const import PLUS_ENV_VAR from frigate.plus import PlusApi, PlusKeyStatus, load_plus_model_info
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}"
class TestHailoAlias(unittest.TestCase): class TestHailoAlias(unittest.TestCase):
@@ -114,26 +99,18 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
api.host = host api.host = host
api.key = key api.key = key
api._token_data = dict(self.CACHED_TOKEN) api._token_data = dict(self.CACHED_TOKEN)
api._rate_limited_until = None
return api return api
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]: async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
api = self._api(await self._serve(handler)) api = self._api(await self._serve(handler))
return await api.validate_key(), api return await api.validate_key(), api
def _replies( def _replies(self, status: int = 200, body: object = None, text: str | None = None):
self,
status: int = 200,
body: object = None,
text: str | None = None,
headers: dict[str, str] | None = None,
):
async def handler(request: web.Request) -> web.Response: async def handler(request: web.Request) -> web.Response:
self.auth = request.headers.get("Authorization") self.auth = request.headers.get("Authorization")
self.requests_seen = getattr(self, "requests_seen", 0) + 1
if text is not None: if text is not None:
return web.Response(status=status, text=text, headers=headers) return web.Response(status=status, text=text)
return web.json_response(body, status=status, headers=headers) return web.json_response(body, status=status)
return handler return handler
@@ -157,25 +134,6 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
self.assertEqual(status, PlusKeyStatus.unreachable) 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): async def test_unusable_replies_keep_the_cached_token(self):
# a successful reply without a usable token must not replace one that # a successful reply without a usable token must not replace one that
# later Frigate+ requests depend on # later Frigate+ requests depend on
@@ -254,177 +212,5 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
self.assertEqual(requests_seen, []) 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_shorter_wait_arriving_later_keeps_the_longer_one(self):
# two requests in flight are both refused, and the reply with the
# longer wait is handled first
self.api._note_rate_limit(120)
self.api._note_rate_limit(10)
self.assertAlmostEqual(self.api.rate_limit_remaining(), 120, delta=1)
# a longer wait still extends it
self.api._note_rate_limit(300)
self.assertAlmostEqual(self.api.rate_limit_remaining(), 300, delta=1)
def test_concurrent_replies_keep_the_longest_wait(self):
waits = list(range(1, 201))
threads = [
threading.Thread(target=self.api._note_rate_limit, args=(wait,))
for wait in waits
]
with patch("frigate.plus.logger"):
for thread in threads:
thread.start()
for thread in threads:
thread.join()
self.assertAlmostEqual(self.api.rate_limit_remaining(), max(waits), delta=1)
def test_the_client_can_be_sent_to_a_worker_process(self):
# worker processes start from the forkserver, which pickles the
# config and the Frigate+ client it holds
self.api._note_rate_limit(60)
copy = pickle.loads(pickle.dumps(self.api))
self.assertAlmostEqual(copy.rate_limit_remaining(), 60, delta=1)
copy._note_rate_limit(120)
self.assertAlmostEqual(copy.rate_limit_remaining(), 120, delta=1)
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__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)
@@ -98,6 +98,7 @@ class TestRegeneratedSubLabels(unittest.TestCase):
region=[], region=[],
box=[], box=[],
area=0, area=0,
retain_indefinitely=False,
plus_id="", plus_id="",
model_hash="", model_hash="",
detector_type="cpu", detector_type="cpu",
+17 -19
View File
@@ -1,5 +1,4 @@
import datetime import datetime
import gc
import logging import logging
import os import os
import tempfile import tempfile
@@ -478,7 +477,12 @@ class TestHttp(unittest.TestCase):
id = "123456.keep" id = "123456.keep"
time_keep = datetime.datetime.now().timestamp() time_keep = datetime.datetime.now().timestamp()
_insert_mock_event(id, time_keep, time_keep + 30) _insert_mock_event(
id,
time_keep,
time_keep + 30,
True,
)
rec_k_id = "1234567.keep" rec_k_id = "1234567.keep"
rec_k2_id = "1234568.keep" rec_k2_id = "1234568.keep"
rec_k3_id = "1234569.keep" rec_k3_id = "1234569.keep"
@@ -503,7 +507,7 @@ class TestHttp(unittest.TestCase):
id2 = "7890.delete" id2 = "7890.delete"
time_delete = datetime.datetime.now().timestamp() - 360 time_delete = datetime.datetime.now().timestamp() - 360
_insert_mock_event(id2, time_delete, time_delete + 30) _insert_mock_event(id2, time_delete, time_delete + 30, False)
rec_d_id = "78901.delete" rec_d_id = "78901.delete"
rec_d2_id = "78902.delete" rec_d2_id = "78902.delete"
rec_d3_id = "78903.delete" rec_d3_id = "78903.delete"
@@ -536,15 +540,14 @@ class TestHttp(unittest.TestCase):
Recordings.get(Recordings.id == rec_d2_id) Recordings.get(Recordings.id == rec_d2_id)
Recordings.get(Recordings.id == rec_d3_id) Recordings.get(Recordings.id == rec_d3_id)
def test_storage_cleanup_deletes_oldest_first(self): def test_storage_cleanup_keeps_retained(self):
"""Ensure cleanup deletes the oldest segments and only expires their events.""" """Ensure cleanup steps over retained segments to reach newer ones."""
config = FrigateConfig(**self.minimal_config) config = FrigateConfig(**self.minimal_config)
storage = StorageMaintainer(config, MagicMock()) storage = StorageMaintainer(config, MagicMock())
seg_len = 600 seg_len = 600
base = datetime.datetime.now().timestamp() - 7200 base = datetime.datetime.now().timestamp() - 7200
_insert_mock_event("old.event", base, base + 2.5 * seg_len) _insert_mock_event("123456.keep", base, base + 2.5 * seg_len, True)
_insert_mock_event("new.event", base + 8 * seg_len, base + 9.5 * seg_len)
paths = {} paths = {}
for i in range(10): for i in range(10):
@@ -554,23 +557,16 @@ class TestHttp(unittest.TestCase):
rec_id, paths[rec_id], base + i * seg_len, base + (i + 1) * seg_len rec_id, paths[rec_id], base + i * seg_len, base + (i + 1) * seg_len
) )
# Hourly bandwidth is 48 MB, so cleanup removes the oldest 56 MB # 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.calculate_camera_bandwidth()
storage.reduce_storage_consumption() storage.reduce_storage_consumption()
# flush the queued writes, and collect the abandoned recordings retained = {"segment-0", "segment-1", "segment-2"}
# cursor so this connection stops reading its stale snapshot
self.db.stop()
self.db.start()
gc.collect()
kept = {"segment-7", "segment-8", "segment-9"}
remaining = {r.id for r in Recordings.select(Recordings.id)} 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)} on_disk = {rec_id for rec_id, path in paths.items() if os.path.exists(path)}
self.assertEqual(remaining, kept) self.assertEqual(remaining, retained)
self.assertEqual(on_disk, kept) self.assertEqual(on_disk, retained)
self.assertFalse(Event.get(Event.id == "old.event").has_clip)
self.assertTrue(Event.get(Event.id == "new.event").has_clip)
self.assertFalse(storage.retention_unmet) self.assertFalse(storage.retention_unmet)
def test_unmet_retention_sets_the_live_flag(self): def test_unmet_retention_sets_the_live_flag(self):
@@ -600,6 +596,7 @@ def _insert_mock_event(
id: str, id: str,
start: int, start: int,
end: int, end: int,
retain: bool,
camera: str = "front_door", camera: str = "front_door",
label: str = "Mock", label: str = "Mock",
) -> Event: ) -> Event:
@@ -619,6 +616,7 @@ def _insert_mock_event(
area=0, area=0,
has_clip=True, has_clip=True,
has_snapshot=True, has_snapshot=True,
retain_indefinitely=retain,
).execute() ).execute()
-42
View File
@@ -1,42 +0,0 @@
"""Tests for trigger push notifications."""
import unittest
from types import SimpleNamespace
from unittest.mock import MagicMock
from frigate.comms.webpush import WebPushClient
class TestTriggerNotification(unittest.TestCase):
def test_image_is_the_triggering_event_thumbnail(self):
client = WebPushClient.__new__(WebPushClient)
client.config = SimpleNamespace(
notifications=SimpleNamespace(email="admin@example.com"),
cameras={"front_door": SimpleNamespace(friendly_name=None)},
)
client.web_pushers = {"admin": []}
client.user_cameras = {"admin": {"front_door"}}
client.last_camera_notification_time = {}
client._within_cooldown = MagicMock(return_value=False)
client.check_registrations = MagicMock()
client.cleanup_registrations = MagicMock()
client.send_push_notification = MagicMock()
client.send_trigger(
{
"camera": "front_door",
"event_id": "1700000000.0-abc123",
"name": "red_car",
"type": "thumbnail",
"score": 0.9,
}
)
self.assertEqual(
client.send_push_notification.call_args.kwargs["image"],
"api/events/1700000000.0-abc123/thumbnail.webp",
)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -639,7 +639,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
"""Sync export files - delete files not referenced by any export record. """Sync export files - delete files not referenced by any export record.
Export videos are stored at: EXPORT_DIR/*.mp4 Export videos are stored at: EXPORT_DIR/*.mp4
Export thumbnails are stored at: CLIPS_DIR/export/*.webp (legacy *.jpg) Export thumbnails are stored at: CLIPS_DIR/export/*.jpg
The paths are stored in Export.video_path and Export.thumb_path The paths are stored in Export.video_path and Export.thumb_path
""" """
result = SyncResult(media_type="exports") result = SyncResult(media_type="exports")
@@ -667,7 +667,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
thumb_files: list[str] = [] thumb_files: list[str] = []
if os.path.isdir(export_thumb_dir): if os.path.isdir(export_thumb_dir):
for file in os.listdir(export_thumb_dir): for file in os.listdir(export_thumb_dir):
if file.endswith((".webp", ".jpg")): if file.endswith(".jpg"):
file_path = os.path.join(export_thumb_dir, file) file_path = os.path.join(export_thumb_dir, file)
thumb_files.append(file_path) thumb_files.append(file_path)
+6 -4
View File
@@ -23,15 +23,17 @@ Some examples (model - class or model name)::
import peewee as pw import peewee as pw
from frigate.models import Event
SQL = pw.SQL SQL = pw.SQL
def migrate(migrator, database, fake=False, **kwargs): def migrate(migrator, database, fake=False, **kwargs):
# raw SQL keeps the dropped field off the Event model (removed in 041) migrator.add_fields(
migrator.sql( Event,
'ALTER TABLE "event" ADD COLUMN "retain_indefinitely" INTEGER NOT NULL DEFAULT 0' retain_indefinitely=pw.BooleanField(default=False),
) )
def rollback(migrator, database, fake=False, **kwargs): def rollback(migrator, database, fake=False, **kwargs):
migrator.sql('ALTER TABLE "event" DROP COLUMN "retain_indefinitely"') migrator.remove_fields(Event, ["retain_indefinitely"])
@@ -1,15 +0,0 @@
"""Peewee migrations -- 041_remove_retain_indefinitely.py."""
import peewee as pw
SQL = pw.SQL
def migrate(migrator, database, fake=False, **kwargs):
migrator.sql('ALTER TABLE "event" DROP COLUMN "retain_indefinitely"')
def rollback(migrator, database, fake=False, **kwargs):
migrator.sql(
'ALTER TABLE "event" ADD COLUMN "retain_indefinitely" INTEGER NOT NULL DEFAULT 0'
)
+1 -1
View File
@@ -1 +1 @@
[{"id": "event-person-001", "label": "person", "sub_label": null, "camera": "front_door", "start_time": 1780677009.365581, "end_time": 1780677039.365581, "false_positive": false, "zones": ["front_yard"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "plus_id": null, "model_hash": "abc123", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.92, "score": 0.92, "region": [0.1, 0.1, 0.5, 0.8], "box": [0.2, 0.15, 0.45, 0.75], "area": 0.18, "ratio": 0.6, "type": "object", "description": "A person walking toward the front door", "average_estimated_speed": 1.2, "velocity_angle": 45.0, "path_data": [[[0.2, 0.5], 0.0], [[0.3, 0.5], 1.0]]}}, {"id": "event-car-001", "label": "car", "sub_label": null, "camera": "backyard", "start_time": 1780673409.365581, "end_time": 1780673454.365581, "false_positive": false, "zones": ["driveway"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "plus_id": null, "model_hash": "def456", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.87, "score": 0.87, "region": [0.3, 0.2, 0.9, 0.7], "box": [0.35, 0.25, 0.85, 0.65], "area": 0.2, "ratio": 1.25, "type": "object", "description": "A car parked in the driveway", "average_estimated_speed": 0.0, "velocity_angle": 0.0, "path_data": []}}, {"id": "event-person-002", "label": "person", "sub_label": null, "camera": "garage", "start_time": 1780669809.365581, "end_time": 1780669829.365581, "false_positive": false, "zones": [], "thumbnail": null, "has_clip": false, "has_snapshot": true, "plus_id": null, "model_hash": "ghi789", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.78, "score": 0.78, "region": [0.0, 0.0, 0.6, 0.9], "box": [0.1, 0.05, 0.5, 0.85], "area": 0.32, "ratio": 0.5, "type": "object", "description": null, "average_estimated_speed": 0.5, "velocity_angle": 90.0, "path_data": [[[0.1, 0.4], 0.0]]}}] [{"id": "event-person-001", "label": "person", "sub_label": null, "camera": "front_door", "start_time": 1780677009.365581, "end_time": 1780677039.365581, "false_positive": false, "zones": ["front_yard"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "retain_indefinitely": false, "plus_id": null, "model_hash": "abc123", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.92, "score": 0.92, "region": [0.1, 0.1, 0.5, 0.8], "box": [0.2, 0.15, 0.45, 0.75], "area": 0.18, "ratio": 0.6, "type": "object", "description": "A person walking toward the front door", "average_estimated_speed": 1.2, "velocity_angle": 45.0, "path_data": [[[0.2, 0.5], 0.0], [[0.3, 0.5], 1.0]]}}, {"id": "event-car-001", "label": "car", "sub_label": null, "camera": "backyard", "start_time": 1780673409.365581, "end_time": 1780673454.365581, "false_positive": false, "zones": ["driveway"], "thumbnail": null, "has_clip": true, "has_snapshot": true, "retain_indefinitely": false, "plus_id": null, "model_hash": "def456", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.87, "score": 0.87, "region": [0.3, 0.2, 0.9, 0.7], "box": [0.35, 0.25, 0.85, 0.65], "area": 0.2, "ratio": 1.25, "type": "object", "description": "A car parked in the driveway", "average_estimated_speed": 0.0, "velocity_angle": 0.0, "path_data": []}}, {"id": "event-person-002", "label": "person", "sub_label": null, "camera": "garage", "start_time": 1780669809.365581, "end_time": 1780669829.365581, "false_positive": false, "zones": [], "thumbnail": null, "has_clip": false, "has_snapshot": true, "retain_indefinitely": false, "plus_id": null, "model_hash": "ghi789", "detector_type": "cpu", "model_type": "ssd", "data": {"top_score": 0.78, "score": 0.78, "region": [0.0, 0.0, 0.6, 0.9], "box": [0.1, 0.05, 0.5, 0.85], "area": 0.32, "ratio": 0.5, "type": "object", "description": null, "average_estimated_speed": 0.5, "velocity_angle": 90.0, "path_data": [[[0.1, 0.4], 0.0]]}}]
@@ -234,6 +234,7 @@ def generate_events():
thumbnail=None, thumbnail=None,
has_clip=True, has_clip=True,
has_snapshot=True, has_snapshot=True,
retain_indefinitely=False,
plus_id=None, plus_id=None,
model_hash="abc123", model_hash="abc123",
detector_type="cpu", detector_type="cpu",
@@ -264,6 +265,7 @@ def generate_events():
thumbnail=None, thumbnail=None,
has_clip=True, has_clip=True,
has_snapshot=True, has_snapshot=True,
retain_indefinitely=False,
plus_id=None, plus_id=None,
model_hash="def456", model_hash="def456",
detector_type="cpu", detector_type="cpu",
@@ -294,6 +296,7 @@ def generate_events():
thumbnail=None, thumbnail=None,
has_clip=False, has_clip=False,
has_snapshot=True, has_snapshot=True,
retain_indefinitely=False,
plus_id=None, plus_id=None,
model_hash="ghi789", model_hash="ghi789",
detector_type="cpu", detector_type="cpu",
-33
View File
@@ -342,37 +342,4 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
dialog.getByRole("button", { name: "Yes", exact: true }), dialog.getByRole("button", { name: "Yes", exact: true }),
).toBeVisible(); ).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();
});
}); });
+2
View File
@@ -42,6 +42,7 @@ const GROUPED_EVENT = {
thumbnail: null, thumbnail: null,
has_clip: true, has_clip: true,
has_snapshot: true, has_snapshot: true,
retain_indefinitely: false,
plus_id: null, plus_id: null,
model_hash: "abc123", model_hash: "abc123",
detector_type: "cpu", detector_type: "cpu",
@@ -425,6 +426,7 @@ test.describe("FaceSelectionDialog @high", () => {
thumbnail: null, thumbnail: null,
has_clip: true, has_clip: true,
has_snapshot: true, has_snapshot: true,
retain_indefinitely: false,
plus_id: null, plus_id: null,
model_hash: "abc123", model_hash: "abc123",
detector_type: "cpu", detector_type: "cpu",
@@ -459,36 +459,6 @@ test.describe("Detection models settings @high", () => {
); );
}); });
test("a Frigate+ rate limit says how long to wait, including days", 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": "90000" },
json: { success: false, retry_after: 90000 },
}),
);
await openPage(frigateApp);
await expect(frigateApp.page.locator("#pageRoot")).toContainText(
"Frigate+ is rate limiting requests. Try again in 1 day, 1 hour.",
);
});
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({ test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
frigateApp, frigateApp,
}) => { }) => {
-4
View File
@@ -327,10 +327,6 @@
"copyDetails": "Copy details", "copyDetails": "Copy details",
"copyFailed": "Could not copy details to clipboard" "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}}", "selectItem": "Select {{item}}",
"readTheDocumentation": "Read the documentation", "readTheDocumentation": "Read the documentation",
"information": { "information": {
@@ -14,7 +14,6 @@ import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { FrigateConfig } from "@/types/frigateConfig"; import type { FrigateConfig } from "@/types/frigateConfig";
import { describeSupportedDetectors } from "@/utils/plusModels"; import { describeSupportedDetectors } from "@/utils/plusModels";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
export type FrigatePlusModel = { export type FrigatePlusModel = {
id: string; id: string;
@@ -66,26 +65,20 @@ export function ModelSourcePicker({
// metadata of whatever model was saved before it // metadata of whatever model was saved before it
const selectedId = plusModelId(path) ?? plus?.id; const selectedId = plusModelId(path) ?? plus?.id;
const { getRateLimitMessage } = usePlusRateLimit(); const { data: availableModels, isLoading } = useSWR<
const { Record<string, FrigatePlusModel>
data: availableModels, >(plusEnabled ? "/plus/models" : null, {
error: modelsError, fetcher: async (url) => {
isLoading, const res = await axios.get(url, { withCredentials: true });
} = useSWR<Record<string, FrigatePlusModel>>( return res.data.reduce(
plusEnabled ? "/plus/models" : null, (obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
{ obj[model.id] = model;
fetcher: async (url) => { return obj;
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 [showIncompatible, setShowIncompatible] = useState(false);
const showIncompatibleId = useId(); const showIncompatibleId = useId();
@@ -108,7 +101,6 @@ export function ModelSourcePicker({
const isCompatible = (model: FrigatePlusModel) => const isCompatible = (model: FrigatePlusModel) =>
!detector || model.supportedDetectors.includes(detector); !detector || model.supportedDetectors.includes(detector);
const rateLimitMessage = getRateLimitMessage(modelsError);
const allEntries = Object.entries(availableModels ?? {}); const allEntries = Object.entries(availableModels ?? {});
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model)); const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
@@ -171,8 +163,7 @@ export function ModelSourcePicker({
<SelectGroup> <SelectGroup>
{entries.length === 0 ? ( {entries.length === 0 ? (
<div className="px-4 py-3 text-center text-sm text-muted-foreground"> <div className="px-4 py-3 text-center text-sm text-muted-foreground">
{rateLimitMessage ?? {t("frigatePlus.modelInfo.noModelsAvailable")}
t("frigatePlus.modelInfo.noModelsAvailable")}
</div> </div>
) : ( ) : (
entries.map(([id, model]) => ( entries.map(([id, model]) => (
@@ -193,9 +184,6 @@ export function ModelSourcePicker({
</SelectGroup> </SelectGroup>
</SelectContent> </SelectContent>
</Select> </Select>
{rateLimitMessage && (
<p className="text-xs text-danger">{rateLimitMessage}</p>
)}
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans> <Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
</p> </p>
@@ -87,7 +87,6 @@ import TextEntryDialog from "@/components/overlay/dialog/TextEntryDialog";
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog"; import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
import { Trans, useTranslation } from "react-i18next"; import { Trans, useTranslation } from "react-i18next";
import { useIsAdmin } from "@/hooks/use-is-admin"; import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import { getTranslatedLabel } from "@/utils/i18n"; import { getTranslatedLabel } from "@/utils/i18n";
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel"; import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
import { DialogPortal } from "@radix-ui/react-dialog"; import { DialogPortal } from "@radix-ui/react-dialog";
@@ -700,7 +699,6 @@ function ObjectDetailsTab({
"views/faceLibrary", "views/faceLibrary",
"components/dialog", "components/dialog",
]); ]);
const { getRateLimitMessage } = usePlusRateLimit();
const apiHost = useApiHost(); const apiHost = useApiHost();
const hasCustomClassificationModels = useMemo( const hasCustomClassificationModels = useMemo(
@@ -1288,7 +1286,7 @@ function ObjectDetailsTab({
revalidate: false, revalidate: false,
}, },
); );
} catch (error) { } catch {
if (displayedIdRef.current === eventId) { if (displayedIdRef.current === eventId) {
setState("reviewing"); setState("reviewing");
} }
@@ -1296,13 +1294,12 @@ function ObjectDetailsTab({
// the toast is not object specific, so it is always shown to avoid // the toast is not object specific, so it is always shown to avoid
// silently dropping a failed submission // silently dropping a failed submission
toast.error( 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" }, { position: "top-center" },
); );
} }
}, },
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage], [search, mutate, mapSearchResults, isEventsKey, t],
); );
const popoverContainerRef = useRef<HTMLDivElement | null>(null); const popoverContainerRef = useRef<HTMLDivElement | null>(null);
@@ -54,7 +54,6 @@ import { useApiHost } from "@/api";
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator"; import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
import ObjectTrackOverlay from "../ObjectTrackOverlay"; import ObjectTrackOverlay from "../ObjectTrackOverlay";
import { useIsAdmin } from "@/hooks/use-is-admin"; import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import { VideoResolutionType } from "@/types/live"; import { VideoResolutionType } from "@/types/live";
import { VodManifest } from "@/types/playback"; import { VodManifest } from "@/types/playback";
@@ -935,7 +934,6 @@ function LifecycleIconRow({
annotationOffset, annotationOffset,
}: LifecycleIconRowProps) { }: LifecycleIconRowProps) {
const { t } = useTranslation(["views/explore", "components/player"]); const { t } = useTranslation(["views/explore", "components/player"]);
const { getRateLimitMessage } = usePlusRateLimit();
const { data: config } = useSWR<FrigateConfig>("config"); const { data: config } = useSWR<FrigateConfig>("config");
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [showAdvancedScores, setShowAdvancedScores] = useState(false); const [showAdvancedScores, setShowAdvancedScores] = useState(false);
@@ -1253,12 +1251,11 @@ function LifecycleIconRow({
position: "top-center", position: "top-center",
}, },
); );
} catch (error) { } catch {
toast.error( toast.error(
getRateLimitMessage(error) ?? t("toast.error.submitFrigatePlusFailed", {
t("toast.error.submitFrigatePlusFailed", { ns: "components/player",
ns: "components/player", }),
}),
{ {
position: "top-center", position: "top-center",
}, },
@@ -22,7 +22,6 @@ import { baseUrl } from "@/api/baseUrl";
import { getTranslatedLabel } from "@/utils/i18n"; import { getTranslatedLabel } from "@/utils/i18n";
import useImageLoaded from "@/hooks/use-image-loaded"; import useImageLoaded from "@/hooks/use-image-loaded";
import { useIsAdmin } from "@/hooks/use-is-admin"; import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
export type FrigatePlusDialogProps = { export type FrigatePlusDialogProps = {
upload?: Event; upload?: Event;
@@ -38,7 +37,6 @@ export function FrigatePlusDialog({
onEventUploaded, onEventUploaded,
}: FrigatePlusDialogProps) { }: FrigatePlusDialogProps) {
const { t, i18n } = useTranslation(["components/dialog"]); const { t, i18n } = useTranslation(["components/dialog"]);
const { getRateLimitMessage } = usePlusRateLimit();
type SubmissionState = "reviewing" | "uploading" | "submitted"; type SubmissionState = "reviewing" | "uploading" | "submitted";
const [state, setState] = useState<SubmissionState>( const [state, setState] = useState<SubmissionState>(
@@ -65,15 +63,14 @@ export function FrigatePlusDialog({
setState("submitted"); setState("submitted");
onEventUploaded(); onEventUploaded();
} catch (error) { } catch {
setState("reviewing"); setState("reviewing");
toast.error( toast.error(t("explore.plus.review.toast.error"), {
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"), position: "top-center",
{ position: "top-center" }, });
);
} }
}, },
[upload, onEventUploaded, t, getRateLimitMessage], [upload, onEventUploaded, t],
); );
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded(); 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 { useTranslation } from "react-i18next";
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay"; import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
import { useIsAdmin } from "@/hooks/use-is-admin"; import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
// Android native hls does not seek correctly // Android native hls does not seek correctly
const USE_NATIVE_HLS = false; const USE_NATIVE_HLS = false;
@@ -110,7 +109,6 @@ export default function HlsVideoPlayer({
transformedOverlay, transformedOverlay,
}: HlsVideoPlayerProps) { }: HlsVideoPlayerProps) {
const { t } = useTranslation("components/player"); const { t } = useTranslation("components/player");
const { getRateLimitMessage } = usePlusRateLimit();
const { data: config } = useSWR<FrigateConfig>("config"); const { data: config } = useSWR<FrigateConfig>("config");
const isAdmin = useIsAdmin(); const isAdmin = useIsAdmin();
@@ -527,26 +525,18 @@ export default function HlsVideoPlayer({
onUploadFrame={async () => { onUploadFrame={async () => {
const frameTime = getVideoTime(); const frameTime = getVideoTime();
if (!frameTime || !onUploadFrame) { if (frameTime && onUploadFrame) {
return;
}
try {
const resp = await onUploadFrame(frameTime); const resp = await onUploadFrame(frameTime);
if (resp?.status !== 200) { if (resp && resp.status == 200) {
throw new Error(); 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} onSnapshot={onSnapshot ? handleSnapshot : undefined}
+8 -13
View File
@@ -10,7 +10,6 @@ import {
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { useDocDomain } from "@/hooks/use-doc-domain"; import { useDocDomain } from "@/hooks/use-doc-domain";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
import type { FrigateConfig } from "@/types/frigateConfig"; import type { FrigateConfig } from "@/types/frigateConfig";
import type { DetectionHardware } from "@/types/hardware"; import type { DetectionHardware } from "@/types/hardware";
import { recommendedDetectorCount } from "@/utils/detectionHardware"; import { recommendedDetectorCount } from "@/utils/detectionHardware";
@@ -80,16 +79,15 @@ export default function SetupDetector({
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector); const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
const { getRateLimitMessage } = usePlusRateLimit(); const { data: plusModels } = useSWR<FrigatePlusModel[]>(
const { data: plusModels, error: plusModelsError } = useSWR< plusEnabled && needsModel ? "/plus/models" : null,
FrigatePlusModel[] {
>(plusEnabled && needsModel ? "/plus/models" : null, { fetcher: async (url) => {
fetcher: async (url) => { const res = await axios.get(url, { withCredentials: true });
const res = await axios.get(url, { withCredentials: true }); return res.data;
return res.data; },
}, },
}); );
const plusRateLimitMessage = getRateLimitMessage(plusModelsError);
const [plusModelId, setPlusModelId] = useState(""); const [plusModelId, setPlusModelId] = useState("");
const compatiblePlusModels = useMemo( const compatiblePlusModels = useMemo(
@@ -219,9 +217,6 @@ export default function SetupDetector({
<p> <p>
{t("setupWizard.detector.modelRequired", { name: selected.name })} {t("setupWizard.detector.modelRequired", { name: selected.name })}
</p> </p>
{plusEnabled && plusRateLimitMessage && (
<p className="text-danger">{plusRateLimitMessage}</p>
)}
{plusEnabled ? ( {plusEnabled ? (
<Select value={plusModelId} onValueChange={setPlusModelId}> <Select value={plusModelId} onValueChange={setPlusModelId}>
<SelectTrigger className="max-w-xs"> <SelectTrigger className="max-w-xs">
-69
View File
@@ -1,69 +0,0 @@
import axios from "axios";
import { formatDuration, Locale } from "date-fns";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useDateLocale } from "@/hooks/use-date-locale";
/**
* 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;
}
/**
* A wait in seconds as a readable duration, such as "1 day, 1 hour".
*
* Waits can last days, so the days are kept rather than folded away or
* turned into calendar months.
*/
export function formatPlusWait(seconds: number, locale?: Locale): string {
const total = Math.ceil(seconds);
return formatDuration(
{
days: Math.floor(total / 86400),
hours: Math.floor((total % 86400) / 3600),
minutes: Math.floor((total % 3600) / 60),
seconds: total % 60,
},
{ delimiter: ", ", locale },
);
}
/** 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: formatPlusWait(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
View File
@@ -10,6 +10,7 @@ export interface Event {
thumbnail: string; thumbnail: string;
has_clip: boolean; has_clip: boolean;
has_snapshot: boolean; has_snapshot: boolean;
retain_indefinitely: boolean;
plus_id?: string; plus_id?: string;
model_hash?: string; model_hash?: string;
data: { data: {
@@ -20,17 +20,10 @@ import { isReplayCamera } from "@/utils/cameraUtil";
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage"; import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
import { getPrimaryModel } from "@/utils/modelUtil"; import { getPrimaryModel } from "@/utils/modelUtil";
import { useIsAdmin } from "@/hooks/use-is-admin"; import { useIsAdmin } from "@/hooks/use-is-admin";
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
type PlusKeyStatus = type PlusKeyStatus = "valid" | "invalid" | "unreachable" | "not_set";
"valid" | "invalid" | "unreachable" | "rate_limited" | "not_set";
type PlusValidateResponse = { type PlusValidateResponse = { success: boolean; status: PlusKeyStatus };
success: boolean;
status: PlusKeyStatus;
// seconds until Frigate+ accepts requests again, when rate limited
retry_after?: number | null;
};
export default function FrigatePlusSettingsView(_props: SettingsPageProps) { export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
const { t } = useTranslation("views/settings"); const { t } = useTranslation("views/settings");
@@ -41,8 +34,6 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
const [isValidating, setIsValidating] = useState(false); const [isValidating, setIsValidating] = useState(false);
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>(); const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
const [retryAfter, setRetryAfter] = useState<number | null>(null);
const { formatRateLimit } = usePlusRateLimit();
const validateKey = useCallback(async () => { const validateKey = useCallback(async () => {
setIsValidating(true); setIsValidating(true);
@@ -50,7 +41,6 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
try { try {
const response = await axios.post<PlusValidateResponse>("plus/validate"); const response = await axios.post<PlusValidateResponse>("plus/validate");
setKeyStatus(response.data.status); setKeyStatus(response.data.status);
setRetryAfter(response.data.retry_after ?? null);
} catch { } catch {
setKeyStatus("unreachable"); setKeyStatus("unreachable");
} finally { } finally {
@@ -134,8 +124,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{keyStatus === "valid" ? ( {keyStatus === "valid" ? (
<CheckCircle2 className="size-5 shrink-0 text-green-500" /> <CheckCircle2 className="size-5 shrink-0 text-green-500" />
) : keyStatus === "unreachable" || ) : keyStatus === "unreachable" ? (
keyStatus === "rate_limited" ? (
<AlertTriangle className="size-5 shrink-0 text-yellow-500" /> <AlertTriangle className="size-5 shrink-0 text-yellow-500" />
) : ( ) : (
<XCircle className="size-5 shrink-0 text-red-500" /> <XCircle className="size-5 shrink-0 text-red-500" />
@@ -145,9 +134,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
? t("frigatePlus.apiKey.serverValid") ? t("frigatePlus.apiKey.serverValid")
: keyStatus === "unreachable" : keyStatus === "unreachable"
? t("frigatePlus.apiKey.serverUnreachable") ? t("frigatePlus.apiKey.serverUnreachable")
: keyStatus === "rate_limited" : t("frigatePlus.apiKey.serverInvalid")}
? formatRateLimit(retryAfter)
: t("frigatePlus.apiKey.serverInvalid")}
</span> </span>
</div> </div>
)} )}