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
14 changes: 13 additions & 1 deletion app/core/media/direct_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,19 @@ async def stop_download(self) -> None:
try:
await asyncio.wait_for(self.download_task, timeout=10.0)
except asyncio.TimeoutError:
logger.warning(f"Download Timeout: {self.record_url}")
# A hung HTTP read (stalled stream) never yields another
# chunk, so the stop_event above is never observed. Cancel
# the task to release the file handle and connection.
logger.warning(f"Download Timeout, cancelling task: {self.record_url}")
self.download_task.cancel()
try:
await asyncio.wait_for(self.download_task, timeout=5.0)
except asyncio.CancelledError:
pass
except asyncio.TimeoutError:
logger.error(f"Download task ignored cancellation: {self.record_url}")
except Exception as e:
logger.error(f"Download Cancel Error: {e}")
except Exception as e:
logger.error(f"Download Error: {e}")

Expand Down
93 changes: 93 additions & 0 deletions app/core/platforms/platform_handlers/handlers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,102 @@
import re

import httpx
import streamget
from deprecated import deprecated

from ....utils.logger import logger
from ....utils.utils import trace_error_decorator
from .base import PlatformHandler, StreamData

# Cookie used by upstream streamget when fetching the Douyin share/profile page
# (see streamget/platforms/douyin/utils.py). Kept in sync so the fallback below
# behaves exactly like the original request.
_DOUYIN_TTWID_COOKIE = (
"ttwid=1%7C4ejCkU2bKY76IySQENJwvGhg1IQZrgGEupSyTKKfuyk%7C1740470403%7Cbc9d"
"2ee341f1a162f9e27f4641778030d1ae91e31f9df6553a8f2efa3bdb7b4; __ac_nonce=06"
"83e59f3009cc48fbab0; __ac_signature=_02B4Z6wo00f01mG6waQAAIDB9JUCzFb6.TZhmsU"
"AAPBf34; __ac_referer=__ac_blank"
)


async def _fetch_douyin_short_id(
url: str, proxy_addr: str | None = None, headers: dict | None = None
) -> str | None:
"""Resolve a Douyin profile link and extract ``short_id`` from the response.

Upstream streamget only looks for ``unique_id``; some profiles leave it
empty and only expose ``short_id`` (both work in ``live.douyin.com/<id>``
URLs), which broke short-link resolution (StreamCap issue #315).
"""
from streamget.platforms.douyin.utils import DouyinUtils

if not headers or all(k.lower() not in ("user-agent", "cookie") for k in headers):
headers = DouyinUtils.HEADERS
headers = dict(headers)
headers["cookie"] = _DOUYIN_TTWID_COOKIE

try:
async with httpx.AsyncClient(proxy=proxy_addr, timeout=15, follow_redirects=True) as client:
response = await client.get(url, headers=headers)
sec_user_id = str(response.url).split("?")[0].rsplit("/", maxsplit=1)[1]
profile_response = await client.get(
f"https://www.iesdouyin.com/share/user/{sec_user_id}", headers=headers
)
# The id may appear in plain JSON or escaped inside a JS string.
for pattern in (r'short_id":"(\w+)"', r'short_id\\":\\"(\w+)'):
matches = re.findall(pattern, profile_response.text)
if matches and matches[-1]:
return matches[-1]
except Exception as e:
logger.debug(f"Douyin short_id fallback request failed: {e}")
return None


def _patch_douyin_unique_id_fallback() -> None:
"""Patch streamget's ``DouyinUtils.get_unique_id`` to fall back to ``short_id``.

Fixes mobile-shared profile links whose response has an empty ``unique_id``
(StreamCap issue #315). No-op when streamget is missing or already patched,
so the app keeps working with future streamget layouts.
"""
try:
from streamget.platforms.douyin.utils import DouyinUtils
except ImportError:
logger.warning("streamget DouyinUtils not found; skip unique_id fallback patch")
return

if getattr(DouyinUtils, "_streamcap_short_id_fallback", False):
return

original_get_unique_id = DouyinUtils.get_unique_id

async def get_unique_id_with_fallback(url, proxy_addr=None, headers=None):
error: Exception | None = None
unique_id = None
try:
unique_id = await original_get_unique_id(url, proxy_addr, headers)
except RuntimeError as e:
# Upstream wraps "unique_id not found" (and network errors) in
# RuntimeError. UnsupportedUrlError must keep propagating as-is,
# callers rely on it to distinguish room links from profile links.
error = e
if unique_id:
return unique_id
short_id = await _fetch_douyin_short_id(url, proxy_addr, headers)
if short_id:
logger.info(f"Douyin unique_id missing, using short_id fallback: {short_id}")
return short_id
if error is not None:
raise error
raise RuntimeError("Could not find unique_id or short_id in the response.")

DouyinUtils.get_unique_id = staticmethod(get_unique_id_with_fallback)
DouyinUtils._streamcap_short_id_fallback = True
logger.info("Applied Douyin unique_id -> short_id fallback patch (issue #315)")


_patch_douyin_unique_id_fallback()


class CustomHandler(PlatformHandler):
platform = "custom"
Expand Down
95 changes: 91 additions & 4 deletions app/core/recording/stream_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ def __init__(self, services, recording, recording_info):
self.recording_info = recording_info
self.subprocess_start_info = services.subprocess_start_up_info
self.should_stop = False # manually stopped
# Set when the output stopped growing because the stream went dead
# while ffmpeg/the downloader task stayed alive (issue #325).
self.stalled = False

self.user_config = self.settings.user_config
self.account_config = self.settings.accounts_config
Expand Down Expand Up @@ -84,10 +87,14 @@ def _get_filename(self, stream_info: StreamData) -> str:
stream_info.title = self._clean_and_truncate_title(stream_info.title) or stream_info.title
live_title = stream_info.title

original_anchor_name = stream_info.anchor_name
if self.recording.streamer_name and self.recording.streamer_name != self._["live_room"]:
stream_info.anchor_name = utils.clean_name(self.recording.streamer_name)
else:
stream_info.anchor_name = utils.clean_name(stream_info.anchor_name, self._["live_room"])
if not stream_info.anchor_name:
# A custom name made only of emoji/symbols is cleaned to None
# (issue #435); fall back to the streamer name from the platform,
# then to the localized default, so the save path always stays valid.
stream_info.anchor_name = utils.clean_name(original_anchor_name, self._["live_room"])

now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())

Expand Down Expand Up @@ -339,9 +346,74 @@ async def remove_active_recorder(self):
except Exception as e:
logger.error(f"Failed to remove recorder instance: {e}")

@staticmethod
def _get_output_dir_size(directory: str) -> int:
"""Total size of the files currently written into ``directory``.

Returns -1 when the directory cannot be read, so callers treat the
sample as "unknown" instead of "no data".
"""
total = 0
try:
with os.scandir(directory) as entries:
for entry in entries:
if entry.is_file():
try:
total += entry.stat().st_size
except OSError:
continue
return total
except OSError:
return -1

def _check_stream_stall(self, save_file_path: str, state: dict) -> bool:
"""Detect a dead stream whose process is still alive (issue #325).

After an anchor reconnects, the old stream URL stops delivering data
while ffmpeg (or the direct download task) keeps waiting on it: the
card stays "recording" but nothing is written. Sampling the output
directory size every few seconds catches that — when it stops growing
for ``stalled_stream_timeout`` seconds (0 disables the check), the
recorder is stopped and ``check_if_live`` restarts it with the fresh
stream URL.
"""
timeout = self.user_config.get("stalled_stream_timeout", 90)
try:
timeout = float(timeout or 0)
except (TypeError, ValueError):
timeout = 90.0
if timeout <= 0:
return False

now = time.time()
if now < state.get("next_check_time", 0):
return False
state["next_check_time"] = now + 15

size = self._get_output_dir_size(os.path.dirname(save_file_path))
if size < 0:
return False

if size > 0 and size != state.get("last_size"):
state["last_size"] = size
state["last_growth_time"] = now
return False

stalled_since = now - state.get("last_growth_time", self.recording_start_time or now)
never_wrote = size == 0 and self.recording_start_time and now - self.recording_start_time >= timeout
if stalled_since >= timeout or never_wrote:
logger.warning(
f"Stream stalled for {int(stalled_since)}s with no new data written: {self.live_url}"
)
self.stalled = True
self.should_stop = True # go through the graceful stop path; recheck restarts us
return True
return False

async def recheck_live_status(self):
if not self.should_stop:
# not manually stopped
if not self.should_stop or self.stalled:
# not manually stopped (a stall-triggered stop must recheck, so the
# room is restarted with the fresh stream URL — issue #325)
recording_duration = time.time() - self.recording_start_time
if recording_duration > self.min_valid_recording_duration:
if self.services.recording_enabled and not self.is_flv_preferred_platform:
Expand Down Expand Up @@ -380,6 +452,7 @@ async def start_ffmpeg(

logger.info(f"Starting ffmpeg recording - recorder id: {id(self)}, rec_id: {self.recording.rec_id}")
self.should_stop = False
self.stalled = False
process = None
stderr_task = None

Expand All @@ -402,6 +475,7 @@ async def start_ffmpeg(
logger.log("STREAM", f"Recording Stream URL: {record_url}")
self.recording_start_time = time.time()

stall_state: dict = {}
while True:
if self.should_stop or self.recording.force_stop or not self.services.recording_enabled:
logger.info(f"Preparing to End Recording: {live_url}")
Expand Down Expand Up @@ -438,6 +512,10 @@ async def start_ffmpeg(
self.recording.is_recording = False
break

# Dead-stream detection (issue #325): ffmpeg can stay alive on a
# stale URL after the anchor reconnects, writing nothing.
self._check_stream_stall(save_file_path, stall_state)

await asyncio.sleep(1)

await process.wait()
Expand Down Expand Up @@ -712,6 +790,7 @@ async def start_direct_download(

logger.info(f"Starting direct download - recorder id: {id(self)}, rec_id: {self.recording.rec_id}")
self.should_stop = False
self.stalled = False

try:
await self.direct_downloader.start_download()
Expand All @@ -722,6 +801,7 @@ async def start_direct_download(
logger.log("STREAM", f"Direct Download Stream URL: {record_url}")
self.recording_start_time = time.time()

stall_state: dict = {}
while True:
if self.should_stop or self.recording.force_stop or not self.services.recording_enabled:
logger.info(f"Prepare to end direct download: {live_url}")
Expand All @@ -733,6 +813,13 @@ async def start_direct_download(

await asyncio.sleep(1)

# Dead-stream detection (issue #325): a hung HTTP read keeps the
# download task alive while nothing is written to disk.
self._check_stream_stall(save_file_path, stall_state)

if self.direct_downloader.download_task and self.direct_downloader.download_task.done():
break

if self.direct_downloader.download_task and self.direct_downloader.download_task.done():
break

Expand Down
22 changes: 20 additions & 2 deletions app/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,23 @@
"\U0001fa00-\U0001fa6f" # Chess Symbols
"\U0001fa70-\U0001faff" # Symbols and Pictographs Extended-A
"\U00002702-\U000027b0" # Dingbats
"\u2600-\u27bf" # Misc symbols, Dingbats (☀ ♠ ✂ …)
"\u2b00-\u2bff" # Misc symbols and arrows (⭐ U+2B50 …)
"\ufe00-\ufe0f" # variation selectors (emoji presentation, issue #435)
"\U0001f3fb-\U0001f3ff" # skin tone modifiers
"\u20e3" # combining enclosing keycap
"\u200d" # zero width joiner (ZWJ sequences: 👨‍👩‍👧‍👦, issue #435)
"]+",
flags=re.UNICODE,
)

# Zero-width / formatting / control characters that survive EMOJI_PATTERN and
# are invisible in filenames (or illegal on Windows), producing unusable save
# paths when an anchor name consists only of emoji (issue #435).
INVISIBLE_CHAR_PATTERN = re.compile(
"[\x00-\x1f\u200b\u200c\u200e\u200f\u2028\u2029\u202a-\u202e\u2060-\u2064\ufffe\uffff\ufeff\ufff9-\ufffb]"
)

URL_PATTERN = re.compile(r"^(https?://)" r"([a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{1,6}" r"(:\d+)?" r"(/\S*)?$")

CONTAINS_URL_PATTERN = re.compile(r"(?i)\bhttps?://" r"(?:[a-zA-Z0-9-]+\.)+[a-zA-Z0-9]{1,6}" r"(?::\d+)?" r"(?:/\S*)?")
Expand Down Expand Up @@ -246,10 +259,15 @@ def is_time_interval_exceeded(last_check_time, interval_seconds=60):

def clean_name(input_text, default=None):
if input_text and input_text.strip():
rstr = r"[\/\\\::\*\??\"\<\>\|&#.。,, ~!· ]"
rstr = r"[\/\\\::\*\??\"\<\>\|&#.。,, ~!· ]"
cleaned_name = input_text.strip().replace("(", "(").replace(")", ")")
cleaned_name = re.sub(rstr, "_", cleaned_name)
cleaned_name = remove_emojis(cleaned_name, "_").replace("__", "_").strip("_")
cleaned_name = remove_emojis(cleaned_name, "_")
# Strip invisible/control characters so a name made only of emoji (plus
# variation selectors / ZWJ) degrades to `default` instead of leaving
# an unusable invisible filename (issue #435).
cleaned_name = INVISIBLE_CHAR_PATTERN.sub("", cleaned_name)
cleaned_name = cleaned_name.replace("__", "_").strip("_").strip()
return cleaned_name or default
return default

Expand Down
Loading