Compare commits

..
Author SHA1 Message Date
Josh Hawkins fc865ebc95 remove a deleted camera's recordings from disk
Camera delete removed RECORD_DIR/<camera> and CLIPS_DIR/<camera>, but recordings live under RECORD_DIR/<date>/<hour>/<camera>, so the camera's segments stayed on disk after their rows were deleted and nothing reclaimed them. Neither path holds per-camera data, so they only matched when a camera name collided with something else, like a classification model's dataset, the thumbs or faces folders, or a date-named recordings folder. Delete now removes the <camera> and <camera>@sub folders under each recordings hour, plus the camera's thumbs, previews, lpr, and triggers folders.
2026-11-23 15:51:21 -06:00
8 changed files with 54 additions and 148 deletions
+3 -5
View File
@@ -20,7 +20,7 @@ from urllib.parse import unquote
from peewee import DoesNotExist, Field
from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR, EXPORT_DIR, SUB_CACHE_TAG
from frigate.const import CLIPS_DIR, EXPORT_DIR
from frigate.models import Export, User
logger = logging.getLogger(__name__)
@@ -137,12 +137,11 @@ def _resolve_recording(
# /recordings/{date} → neutral
# /recordings/{date}/{hour} → multi-camera listing
# /recordings/{date}/{hour}/{cam}/... → camera
# /recordings/{date}/{hour}/{cam}@sub/... → camera (sub stream)
if len(parts) <= 2:
return MediaAuthResolution.LISTING_NEUTRAL, None
if len(parts) == 3:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[3].removesuffix(SUB_CACHE_TAG)
return MediaAuthResolution.CAMERA, parts[3]
def _resolve_clip(
@@ -151,7 +150,6 @@ def _resolve_clip(
# /clips → multi-camera listing
# /clips/thumbs/{cam}/... → camera
# /clips/previews/{cam}/... → camera
# /clips/triggers/{cam}/... → camera
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
# /clips/export/{export_id}.{ext} → camera (DB lookup)
# /clips/faces/... → admin-only
@@ -165,7 +163,7 @@ def _resolve_clip(
second = parts[1]
if second in ("thumbs", "previews", "triggers"):
if second in ("thumbs", "previews"):
if len(parts) == 2:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[2]
+1 -1
View File
@@ -685,7 +685,7 @@ class WebPushClient(Communicator):
title = f"{name.replace('_', ' ')} triggered on {camera_name}"
message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}"
image = f"api/events/{event_id}/thumbnail.webp"
image = f"clips/triggers/{camera}/{event_id}.webp"
direct_url = f"/explore?event_id={event_id}"
ttl = 0
+38
View File
@@ -264,3 +264,41 @@ class TestCameraFileCleanup(unittest.TestCase):
]
self.assertEqual(remaining, other)
def test_delete_removes_recordings_and_keeps_colliding_dirs(self):
own = [
"recordings/2026-11-22/10/front/00.00.mp4",
"recordings/2026-11-22/10/front@sub/00.00.mp4",
"recordings/2026-11-23/03/front/10.00.mp4",
"clips/thumbs/front/a.webp",
"clips/previews/front/1.mp4",
"clips/lpr/front/a/1.jpg",
"clips/triggers/front/t.webp",
]
other = [
"recordings/2026-11-22/10/front_door/00.00.mp4",
"recordings/front/keep.mp4",
"clips/front/dataset/a.jpg",
"clips/thumbs/front_door/b.webp",
]
with tempfile.TemporaryDirectory() as root:
for name in own + other:
path = os.path.join(root, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
open(path, "w").close()
clips = os.path.join(root, "clips")
with patch.multiple(
camera_cleanup,
CLIPS_DIR=clips,
RECORD_DIR=os.path.join(root, "recordings"),
THUMB_DIR=os.path.join(clips, "thumbs"),
):
camera_cleanup.cleanup_camera_files("front")
remaining = [
n for n in own + other if os.path.exists(os.path.join(root, n))
]
self.assertEqual(remaining, other)
-30
View File
@@ -122,11 +122,6 @@ class TestResolveMediaUri(unittest.TestCase):
MediaAuthResolution.CAMERA,
camera="back_door",
)
self._assert(
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4",
MediaAuthResolution.CAMERA,
camera="back_door",
)
def test_clip_flat_filename_resolves_camera(self):
self._assert(
@@ -182,14 +177,6 @@ class TestResolveMediaUri(unittest.TestCase):
camera="back_door",
)
def test_clip_triggers(self):
self._assert("/clips/triggers/", MediaAuthResolution.LISTING_MULTI_CAMERA)
self._assert(
"/clips/triggers/back_door/abc.webp",
MediaAuthResolution.CAMERA,
camera="back_door",
)
def test_clip_review_thumbs(self):
# Format: /clips/review/thumb-{camera}-{review_id}.webp (frigate/review/maintainer.py).
self._assert(
@@ -353,14 +340,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertIsNone(
self._deny("/clips/thumbs/front_door/abc.webp", "limited_user")
)
self.assertIsNone(
self._deny(
"/recordings/2026-05-11/14/front_door@sub/00.00.mp4", "limited_user"
)
)
self.assertIsNone(
self._deny("/clips/triggers/front_door/abc.webp", "limited_user")
)
def test_restricted_role_blocked_other_camera(self):
self.assertEqual(self._deny("/clips/back_door-1.jpg", "limited_user"), 403)
@@ -371,15 +350,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
self.assertEqual(
self._deny("/clips/thumbs/back_door/abc.webp", "limited_user"), 403
)
self.assertEqual(
self._deny(
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4", "limited_user"
),
403,
)
self.assertEqual(
self._deny("/clips/triggers/back_door/abc.webp", "limited_user"), 403
)
def test_restricted_role_blocked_admin_only(self):
self.assertEqual(self._deny("/clips/faces/train/foo.webp", "limited_user"), 403)
-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()
-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()
+10 -3
View File
@@ -1,11 +1,12 @@
"""Utilities for cleaning up camera data from database and filesystem."""
import glob
import logging
import os
import re
import shutil
from frigate.const import CLIPS_DIR, RECORD_DIR, THUMB_DIR
from frigate.const import CLIPS_DIR, RECORD_DIR, SUB_CACHE_TAG, THUMB_DIR
from frigate.models import (
Event,
Export,
@@ -112,12 +113,18 @@ def cleanup_camera_files(
export_paths: Optional list of export file paths to remove
"""
dirs_to_clean = [
os.path.join(RECORD_DIR, camera_name),
os.path.join(CLIPS_DIR, camera_name),
os.path.join(THUMB_DIR, camera_name),
os.path.join(CLIPS_DIR, "previews", camera_name),
os.path.join(CLIPS_DIR, "lpr", camera_name),
os.path.join(CLIPS_DIR, "triggers", camera_name),
]
# recordings live at RECORD_DIR/<date>/<hour>/<camera>
for name in (camera_name, f"{camera_name}{SUB_CACHE_TAG}"):
dirs_to_clean.extend(
glob.glob(os.path.join(glob.escape(RECORD_DIR), "*", "*", name))
)
for dir_path in dirs_to_clean:
if os.path.exists(dir_path):
try:
+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.
Export videos are stored at: EXPORT_DIR/*.mp4
Export thumbnails are stored at: CLIPS_DIR/export/*.webp (legacy *.jpg)
Export thumbnails are stored at: CLIPS_DIR/export/*.jpg
The paths are stored in Export.video_path and Export.thumb_path
"""
result = SyncResult(media_type="exports")
@@ -667,7 +667,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
thumb_files: list[str] = []
if os.path.isdir(export_thumb_dir):
for file in os.listdir(export_thumb_dir):
if file.endswith((".webp", ".jpg")):
if file.endswith(".jpg"):
file_path = os.path.join(export_thumb_dir, file)
thumb_files.append(file_path)