Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/core/media/direct_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ def __init__(
self.download_task = None
self.total_bytes = 0
self.start_time = None
# Set when the pull itself failed (non-2xx response or I/O error), so the
# caller can report a recording error instead of a completed download.
self.failed = False

async def start_download(self) -> bool:
self.start_time = time.time()
Expand Down Expand Up @@ -60,6 +63,7 @@ async def _download_stream(self) -> None:
# Accept 2xx status codes (200, 201, 206, etc.)
if not (200 <= response.status_code < 300):
logger.error(f"Request Stream Failed, Status Code: {response.status_code}")
self.failed = True
return

# Log if redirect occurred
Expand Down Expand Up @@ -88,4 +92,5 @@ async def _download_stream(self) -> None:
except asyncio.CancelledError:
logger.info(f"Download Task Canceled: {self.record_url}")
except Exception as e:
self.failed = True
logger.error(f"Download Error: {e}")
43 changes: 33 additions & 10 deletions app/core/recording/record_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ...utils import utils
from ...utils.logger import logger
from ..platforms.platform_handlers import get_platform_info
from ..runtime.paths import default_recordings_dir
from ..runtime.process_manager import BackgroundService
from .stream_manager import LiveStreamRecorder

Expand Down Expand Up @@ -236,15 +237,21 @@ async def setup_periodic_live_check(self, interval: int = 180):
async def periodic_check():
logger.info("Starting periodic live check background task")
while True:
immediate_check_on_startup = self.services.settings_config.user_config.get(
"check_live_on_browser_refresh", True
)
if immediate_check_on_startup:
await asyncio.sleep(interval)
await self.check_free_space()
if self.services.recording_enabled:
await self.check_all_live_status()
if not immediate_check_on_startup:
try:
immediate_check_on_startup = self.services.settings_config.user_config.get(
"check_live_on_browser_refresh", True
)
if immediate_check_on_startup:
await asyncio.sleep(interval)
await self.check_free_space()
if self.services.recording_enabled:
await self.check_all_live_status()
if not immediate_check_on_startup:
await asyncio.sleep(interval)
except Exception:
# One failing iteration (bad save path, platform error, ...)
# must never silently kill the whole monitoring loop.
logger.exception("Periodic live check failed; retrying on the next interval")
await asyncio.sleep(interval)

if not RecordingManager.is_periodic_task_running():
Expand Down Expand Up @@ -496,7 +503,23 @@ async def delete_recording_cards(self, recordings: list[Recording]):
async def check_free_space(self, output_dir: str | None = None):
disk_space_limit = float(self.settings.user_config.get("recording_space_threshold") or 0)
output_dir = output_dir or self.settings.get_video_save_path()
if utils.check_disk_capacity(output_dir) < disk_space_limit:
try:
free_space_gb = utils.check_disk_capacity(output_dir)
except OSError as e:
# A missing/unmounted save path (network drive offline, typo) must not
# kill the periodic check loop; retry against the default directory.
fallback_dir = str(default_recordings_dir)
logger.error(f"Cannot inspect disk space at {output_dir}: {e}")
try:
free_space_gb = utils.check_disk_capacity(fallback_dir)
except OSError as fallback_error:
logger.error(
f"Cannot inspect disk space at fallback {fallback_dir} either "
f"({fallback_error}); skipping this disk check"
)
return

if free_space_gb < disk_space_limit:
self.services.recording_enabled = False
logger.error(f"Disk space remaining is below {disk_space_limit} GB. Recording function disabled")
self.services.broadcast_snack(
Expand Down
6 changes: 6 additions & 0 deletions app/core/recording/stream_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,12 @@ async def start_direct_download(
await self.remove_active_recorder()
self.recording.is_recording = False

if self.direct_downloader.failed and not self.should_stop:
# A failed pull (non-2xx response or I/O error) must surface as a
# recording error, not as a completed download.
self._handle_recording_error(record_name, self._["record_stream_error"])
return False

if not self.recording.is_recording:
await self._handle_recording_finished(
record_name,
Expand Down
34 changes: 34 additions & 0 deletions app/lifecycle/app_close_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,46 @@

import flet as ft

from ..core.runtime.process_manager import BackgroundService
from ..utils.logger import logger
from .tray_manager import TrayManager

BACKGROUND_DRAIN_TIMEOUT_SECONDS = 120


def _wait_background_service(max_wait_seconds: int = BACKGROUND_DRAIN_TIMEOUT_SECONDS) -> None:
"""Wait for queued background tasks (transcodes, scripts, pushes) to finish.

``os._exit()`` terminates the process without running any thread, including
the non-daemon ``BackgroundService`` worker, so tasks moved to it during
shutdown would otherwise be killed mid-write and leave truncated files
behind. Wait up to ``max_wait_seconds``; past the deadline, abandon the
remaining tasks explicitly instead of pretending they ran.
"""
service = BackgroundService.get_instance()
waited = 0
while (service.is_running or service.tasks) and waited < max_wait_seconds:
time.sleep(1)
waited += 1
if waited % 10 == 0:
logger.info(
f"Waiting for background tasks to finish before exit: "
f"{len(service.tasks)} queued, running={service.is_running} ({waited}s/{max_wait_seconds}s)"
)
if service.is_running or service.tasks:
logger.error(
f"Background service still busy after {max_wait_seconds}s; abandoning "
f"{len(service.tasks)} task(s) and forcing exit"
)


async def _safe_destroy_window(page):
try:
await page.window.destroy()
except Exception as ex:
logger.error(f"close window error: {ex}")
finally:
_wait_background_service()
os._exit(0)


Expand Down Expand Up @@ -69,6 +99,10 @@ def close_app():
except Exception as ex:
logger.error(f"close window error: {ex}")
finally:
# Drain background transcodes/scripts before the hard exit,
# otherwise tasks moved to BackgroundService during shutdown
# are killed mid-write (truncated mp4 files).
_wait_background_service()
if not getattr(app, "is_web_mode", False) and hasattr(app, "tray_manager"):
app.tray_manager.stop()
page.run_task(page.window.destroy)
Expand Down
Loading