From a2d24a54a816bf69146f74aa92f36fbc7f3a4811 Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 09:33:42 +0800 Subject: [PATCH 1/5] fix: replace recordings lock with asyncio.Lock to prevent event-loop deadlock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit add_recording/remove_recording/clear_all_recordings are coroutines that await disk writes while holding the lock. With a threading.Lock, another recording operation started during that await window blocks the entire event-loop thread — the holder can never resume to release the lock, so the whole app freezes (UI unresponsive, monitoring stops, only a process kill recovers). Verified with a repro: the old pattern deadlocks the loop deterministically while an asyncio.Lock completes the same workload. --- app/core/recording/record_manager.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/app/core/recording/record_manager.py b/app/core/recording/record_manager.py index b2ab7bb0..25eb187b 100644 --- a/app/core/recording/record_manager.py +++ b/app/core/recording/record_manager.py @@ -1,5 +1,4 @@ import asyncio -import threading from collections import defaultdict from datetime import datetime, timedelta @@ -15,7 +14,11 @@ class GlobalRecordingState: recordings = [] - lock = threading.Lock() + # Async lock: the guard methods are coroutines that await disk writes while + # holding it. A threading.Lock would block the event-loop thread whenever + # another operation tried to acquire it during that await window, + # deadlocking the whole app (UI freeze, monitoring stops). + lock = asyncio.Lock() class RecordingManager: @@ -68,17 +71,17 @@ def initialize_dynamic_state(self): recording.showed_checking_status = True async def add_recording(self, recording): - with GlobalRecordingState.lock: + async with GlobalRecordingState.lock: GlobalRecordingState.recordings.append(recording) await self.persist_recordings() async def remove_recording(self, recording: Recording): - with GlobalRecordingState.lock: + async with GlobalRecordingState.lock: GlobalRecordingState.recordings.remove(recording) await self.persist_recordings() async def clear_all_recordings(self): - with GlobalRecordingState.lock: + async with GlobalRecordingState.lock: GlobalRecordingState.recordings.clear() await self.persist_recordings() From 39848496f3159c3d9c45e62cbbcdcecec6d9168e Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 09:33:43 +0800 Subject: [PATCH 2/5] fix: back up corrupted user_settings.json before rebuilding it An empty or JSON-corrupt user config (disk glitch, sync conflict, bad manual edit) evaluated falsy and was silently overwritten by the default template, destroying all user settings with no recovery. The file is now copied to user_settings.json.bak (with a warning log) before rebuilding from defaults; valid configs are untouched. --- app/core/config/config_manager.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/app/core/config/config_manager.py b/app/core/config/config_manager.py index b9cb057e..661b5c19 100644 --- a/app/core/config/config_manager.py +++ b/app/core/config/config_manager.py @@ -52,8 +52,21 @@ def init_default_config(self): self._init_config(self.default_config_path, default_config) def init_user_config(self): - if os.path.exists(self.user_config_path) and self.load_user_config(): - return + if os.path.exists(self.user_config_path): + if self.load_user_config(): + return + # The file exists but is empty or has invalid JSON. Back it up + # before rebuilding from defaults — silently overwriting it would + # destroy all user settings with no way to recover them. + backup_path = f"{self.user_config_path}.bak" + try: + shutil.copy(self.user_config_path, backup_path) + logger.warning( + f"User config is empty or corrupted, backed up to: {backup_path}, " + f"rebuilding from defaults: {self.user_config_path}" + ) + except OSError as e: + logger.error(f"Failed to back up corrupted user config: {e}") shutil.copy(self.default_config_path, self.user_config_path) def init_cookies_config(self): From ba2703cb4546863389b044493f50cb2eb2bc13e2 Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 09:33:43 +0800 Subject: [PATCH 3/5] fix: treat Telegram push failures as failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit send_to_telegram returned success unconditionally: _async_post swallows every exception into {'error': ...} and the Telegram API reports rejections as HTTP 200 + {'ok': false}, so a wrong token/chat_id or dead proxy still logged 'pushed successfully'. The response is now checked — {'ok': true} is required, otherwise the failure (with description) is reported. --- app/messages/notification_service.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/app/messages/notification_service.py b/app/messages/notification_service.py index e8ee402a..17ddbe61 100644 --- a/app/messages/notification_service.py +++ b/app/messages/notification_service.py @@ -111,8 +111,15 @@ async def send_to_telegram( try: json_data = {"chat_id": chat_id, "text": content} url = "https://api.telegram.org/bot" + token + "/sendMessage" - _resp = await self._async_post(url, json_data, proxy or None) - return {"success": [1], "error": []} + resp = await self._async_post(url, json_data, proxy or None) + # _async_post swallows every exception and returns {"error": ...}, + # and the Telegram API reports failures as HTTP 200 + {"ok": false} + # — both must be treated as failures, not as a successful push. + if isinstance(resp, dict) and resp.get("ok") is True: + return {"success": [1], "error": []} + error_detail = resp.get("description") or resp.get("error") if isinstance(resp, dict) else resp + logger.info(f"Telegram push failed, chat ID: {chat_id}, Error message: {error_detail}") + return {"success": [], "error": [1]} except Exception as e: logger.info(f"Telegram push failed, chat ID: {chat_id}, Error message: {e}") return {"success": [], "error": [1]} From c8e8165abeb688f698b64e204a8762aa60a5b3a4 Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 09:34:42 +0800 Subject: [PATCH 4/5] fix: release recorder registration on error paths and reset stuck flags MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two related stuck-state bugs that made a room unrecoverable until app restart: - start_ffmpeg/start_direct_download never unregistered the recorder on their exception paths (e.g. ffmpeg missing, spawn failure). The rec_id stayed in active_recorders forever, and since check_if_live skips rooms present in that dict — while replacing an entry also requires going through check_if_live — the room was permanently skipped. - start_recording's preparation block (filename/output dir/makedirs) ran before any try/except while start_update() had already flipped is_recording=True. Any failure there was silently swallowed by the fire-and-forget runner, leaving a fake 'recording' card with no file (as reported in #471) and blocking monitoring forever. The block now resets is_recording, marks the room as errored and unregisters. Also make remove_active_recorder unregister only itself (identity check), so a stale recorder exiting late cannot drop the registration of the newer recorder that replaced it. --- app/core/recording/stream_manager.py | 45 +++++++++++++++++++++------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/app/core/recording/stream_manager.py b/app/core/recording/stream_manager.py index 21a816d7..2bbf0d90 100644 --- a/app/core/recording/stream_manager.py +++ b/app/core/recording/stream_manager.py @@ -260,13 +260,25 @@ async def start_recording(self, stream_info: StreamData): Construct ffmpeg recording parameters and start recording """ - self.save_format, use_direct_download = self._get_record_format(stream_info) - filename = self._get_filename(stream_info) - self.output_dir = self._get_output_dir(stream_info) - save_path = self._get_save_path(filename, use_direct_download) - logger.info(f"Save Path: {save_path}") - self.recording.recording_dir = os.path.dirname(save_path) - os.makedirs(self.recording.recording_dir, exist_ok=True) + try: + self.save_format, use_direct_download = self._get_record_format(stream_info) + filename = self._get_filename(stream_info) + self.output_dir = self._get_output_dir(stream_info) + save_path = self._get_save_path(filename, use_direct_download) + logger.info(f"Save Path: {save_path}") + self.recording.recording_dir = os.path.dirname(save_path) + os.makedirs(self.recording.recording_dir, exist_ok=True) + except Exception as e: + # The flag was already flipped by start_update() before this + # coroutine was scheduled (fire-and-forget, errors never surface). + # Without resetting it here the room stays "recording" forever with + # no file written, and monitoring skips it permanently. + logger.error(f"Failed to prepare recording for {stream_info.anchor_name}: {e}") + self.recording.is_recording = False + self.recording.status_info = RecordingStatus.RECORDING_ERROR + await self.remove_active_recorder() + self.services.broadcast_card_update(self.recording) + return record_url = self._get_record_url(stream_info) self.set_preview_url(stream_info) @@ -333,9 +345,13 @@ async def start_recording(self, stream_info: StreamData): async def remove_active_recorder(self): try: - if self.recording.rec_id in self.services.recording_manager.active_recorders: - del self.services.recording_manager.active_recorders[self.recording.rec_id] - logger.info(f"Removed recorder from active_recorders: {self.recording.rec_id}") + rec_id = self.recording.rec_id + active = self.services.recording_manager.active_recorders + # Only unregister ourselves: a stale recorder exiting late must not + # drop the registration of a newer recorder that replaced it. + if active.get(rec_id) is self: + del active[rec_id] + logger.info(f"Removed recorder from active_recorders: {rec_id}") except Exception as e: logger.error(f"Failed to remove recorder instance: {e}") @@ -511,6 +527,11 @@ async def start_ffmpeg( except Exception as e: logger.error(f"An error occurred during the subprocess execution: {e}") self._handle_recording_error(record_name, self._["no_ffmpeg_tip"], duration=4000) + # Clean up the recorder registration and flag: leaving the rec_id in + # active_recorders permanently blocks check_if_live for this room + # (the guard skips it forever and only a restart recovers). + await self.remove_active_recorder() + self.recording.is_recording = False return False finally: if process is not None and process.returncode is None: @@ -777,6 +798,10 @@ async def start_direct_download( except Exception as e: logger.error(f"Error occurred during direct download: {e}") self._handle_recording_error(record_name, self._["record_stream_error"]) + # Same as start_ffmpeg: release the registration so the room keeps + # being monitored instead of being skipped forever. + await self.remove_active_recorder() + self.recording.is_recording = False return False finally: self.recording.record_url = None From 2a5fb986845b2a4067b305d74937e92602a4e629 Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 09:34:43 +0800 Subject: [PATCH 5/5] fix: report direct-download failures instead of 'recording completed' DirectStreamDownloader swallowed every failure (expired URL / HTTP 403, DNS error, proxy failure) with a log line, and start_direct_download treated any finished task as success: empty/partial files produced a 'Direct Downloading Completed' push notification. The downloader now records the failure (self.error) and the caller marks the room as RECORDING_ERROR without the completion notification, then lets recheck_live_status retry with a fresh stream URL. Manual stops keep the previous behavior. --- app/core/media/direct_downloader.py | 6 ++++++ app/core/recording/stream_manager.py | 13 ++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/core/media/direct_downloader.py b/app/core/media/direct_downloader.py index 127cc58c..bb9234c3 100644 --- a/app/core/media/direct_downloader.py +++ b/app/core/media/direct_downloader.py @@ -32,6 +32,10 @@ def __init__( self.download_task = None self.total_bytes = 0 self.start_time = None + # Set when the download ended in failure (HTTP error status, network + # exception...). Callers use it to tell a real completion from a + # failed download instead of reporting "recording completed". + self.error: str | None = None async def start_download(self) -> bool: self.start_time = time.time() @@ -59,6 +63,7 @@ async def _download_stream(self) -> None: async with client.stream("GET", self.record_url) as response: # Accept 2xx status codes (200, 201, 206, etc.) if not (200 <= response.status_code < 300): + self.error = f"HTTP {response.status_code}" logger.error(f"Request Stream Failed, Status Code: {response.status_code}") return @@ -88,4 +93,5 @@ async def _download_stream(self) -> None: except asyncio.CancelledError: logger.info(f"Download Task Canceled: {self.record_url}") except Exception as e: + self.error = str(e) logger.error(f"Download Error: {e}") diff --git a/app/core/recording/stream_manager.py b/app/core/recording/stream_manager.py index 2bbf0d90..15c43bce 100644 --- a/app/core/recording/stream_manager.py +++ b/app/core/recording/stream_manager.py @@ -760,7 +760,18 @@ async def start_direct_download( await self.remove_active_recorder() self.recording.is_recording = False - if not self.recording.is_recording: + download_error = self.direct_downloader.error if self.direct_downloader else None + if download_error and not self.recording.manually_stopped: + # The download failed (expired URL, DNS/proxy failure...): report + # an error instead of pushing a "recording completed" message for + # a missing/empty file; recheck_live_status retries the room. + logger.error(f"Direct download failed for {record_name}: {download_error}") + self.recording.status_info = RecordingStatus.RECORDING_ERROR + self.recording.is_live = False + self.recording.live_title = None + self.services.broadcast_card_update(self.recording) + self.services.broadcast_pubsub("update", self.recording) + elif not self.recording.is_recording: await self._handle_recording_finished( record_name, stop_msg=f"Direct Downloading Stopped: {record_name}",