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
17 changes: 15 additions & 2 deletions app/core/config/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
6 changes: 6 additions & 0 deletions app/core/media/direct_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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}")
13 changes: 8 additions & 5 deletions app/core/recording/record_manager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import asyncio
import threading
from collections import defaultdict
from datetime import datetime, timedelta

Expand All @@ -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:
Expand Down Expand Up @@ -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()

Expand Down
58 changes: 47 additions & 11 deletions app/core/recording/stream_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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}")

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -739,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}",
Expand Down Expand Up @@ -777,6 +809,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
Expand Down
11 changes: 9 additions & 2 deletions app/messages/notification_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}
Expand Down
Loading