diff --git a/app/core/media/direct_downloader.py b/app/core/media/direct_downloader.py index 127cc58c..915e082c 100644 --- a/app/core/media/direct_downloader.py +++ b/app/core/media/direct_downloader.py @@ -44,7 +44,7 @@ async def stop_download(self) -> None: if self.download_task: try: await asyncio.wait_for(self.download_task, timeout=10.0) - except asyncio.TimeoutError: + except TimeoutError: logger.warning(f"Download Timeout: {self.record_url}") except Exception as e: logger.error(f"Download Error: {e}") diff --git a/app/core/platforms/platform_handlers/streamlink_fallback.py b/app/core/platforms/platform_handlers/streamlink_fallback.py new file mode 100644 index 00000000..5c03d8e9 --- /dev/null +++ b/app/core/platforms/platform_handlers/streamlink_fallback.py @@ -0,0 +1,102 @@ +import asyncio +from urllib.parse import urlparse + +from ....utils.logger import logger +from .base import PlatformHandler, StreamData + +try: + import streamlink + + streamlink_session_factory = streamlink.Streamlink +except ImportError: + streamlink = None + +# Map StreamCap quality presets to streamlink quality candidates, tried in order. +QUALITY_CANDIDATES = { + "OD": ["best"], + "UHD": ["2160p", "1440p", "best"], + "HD": ["1080p", "720p", "best"], + "SD": ["480p", "360p", "best"], + "LD": ["360p", "240p", "worst"], +} + + +def _pick_stream(streams: dict, record_quality: str | None): + """Pick the preferred stream variant from a streamlink streams mapping.""" + non_audio = {k: v for k, v in streams.items() if k != "audio" and not k.endswith("_unselected")} + for name in QUALITY_CANDIDATES.get(record_quality or "OD", ["best"]): + if name in non_audio: + return non_audio[name] + # Fall back to the highest resolution key like "1080p" / "720p60". + resolution_keys = [k for k in non_audio if k.rstrip("0123456789") == "p" and k[:-1].isdigit()] + if resolution_keys: + best_key = max(resolution_keys, key=lambda k: int(k[:-1])) + return non_audio[best_key] + return non_audio.get("best") or non_audio.get("worst") + + +class StreamLinkFallbackHandler(PlatformHandler): + """Fallback extractor for live URLs that no built-in platform handler matches. + + Uses the optional ``streamlink`` dependency to resolve the stream. It is + never registered in the URL-pattern registry; it is invoked explicitly from + ``stream_manager.fetch_stream`` when no built-in handler matched.""" + + platform = "streamlink" + + def __init__( + self, + proxy: str | None = None, + cookies: str | None = None, + record_quality: str | None = None, + platform: str | None = None, + ) -> None: + super().__init__(proxy, cookies, record_quality, platform) + self._session = None + + def _get_session(self): + if streamlink is None: + return None + if self._session is None: + try: + self._session = streamlink_session_factory() + except Exception as e: + logger.error(f"Failed to create streamlink session: {e}") + return self._session + + async def get_stream_info(self, live_url: str) -> StreamData | None: + session = self._get_session() + if session is None: + logger.info("streamlink is not installed, skip fallback extraction (optional: pip install streamlink)") + return None + + try: + # streamlink resolves plugins with blocking I/O, keep it off the event loop. + streams = await asyncio.to_thread(session.streams, live_url) + except Exception as e: + logger.warning(f"streamlink fallback failed for {live_url}: {e}") + return None + + if not streams: + logger.info(f"streamlink fallback found no stream: {live_url}") + return None + + stream = _pick_stream(streams, self.record_quality) + if stream is None or not getattr(stream, "url", None): + logger.warning(f"streamlink fallback found no usable stream URL: {live_url}") + return None + + stream_url = stream.url + anchor_name = urlparse(live_url).netloc or "StreamLink" + stream_data = StreamData( + platform="StreamLink", + anchor_name=anchor_name, + is_live=True, + record_url=stream_url, + ) + if ".m3u8" in stream_url: + stream_data.m3u8_url = stream_url + elif ".flv" in stream_url: + stream_data.flv_url = stream_url + logger.info(f"streamlink fallback resolved stream for {anchor_name}: {stream_url[:80]}") + return stream_data diff --git a/app/core/recording/stream_manager.py b/app/core/recording/stream_manager.py index 21a816d7..c9e80788 100644 --- a/app/core/recording/stream_manager.py +++ b/app/core/recording/stream_manager.py @@ -1,5 +1,6 @@ import asyncio import os +import shlex import shutil import subprocess import sys @@ -16,6 +17,7 @@ from ..media.direct_downloader import DirectStreamDownloader from ..platforms import platform_handlers from ..platforms.platform_handlers import StreamData +from ..platforms.platform_handlers.streamlink_fallback import StreamLinkFallbackHandler from ..runtime.process_manager import BackgroundService T = TypeVar("T") @@ -49,7 +51,8 @@ def __init__(self, services, recording, recording_info): self.save_format = self._get_info("save_format", default=self.DEFAULT_SAVE_FORMAT).lower() self.proxy = self.is_use_proxy() self.direct_downloader = None - self.min_valid_recording_duration = 25 + self.min_valid_recording_duration = int(self.user_config.get("min_valid_recording_duration", 25) or 25) + self.delayed_recheck_interval = int(self.user_config.get("delayed_recheck_interval", 30) or 30) self.recording_start_time = 0 os.makedirs(self.output_dir, exist_ok=True) self.services.language_manager.add_observer(self) @@ -249,8 +252,13 @@ async def fetch_stream(self) -> StreamData | None: account_type=self.account_config.get(self.platform_key, {}).get("account_type"), ) if not handler: - logger.error(f"No handler found for platform: {self.recording.url}") - return + logger.info(f"No built-in handler matched: {self.recording.url}, trying streamlink fallback") + fallback = StreamLinkFallbackHandler(proxy=self.proxy, cookies=self.cookies, record_quality=self.quality) + stream_info = await fallback.get_stream_info(self.live_url) + if stream_info is None: + logger.error(f"No handler found for platform: {self.recording.url}") + self.recording.is_checking = False + return stream_info stream_info = await handler.get_stream_info(self.live_url) self.recording.is_checking = False return stream_info @@ -339,15 +347,28 @@ async def remove_active_recorder(self): except Exception as e: logger.error(f"Failed to remove recorder instance: {e}") - async def recheck_live_status(self): - if not self.should_stop: - # not manually stopped - 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: - self.services.run_coro(self.services.recording_manager.check_if_live(self.recording)) - else: - self.recording.status_info = RecordingStatus.RECORDING_ERROR + async def recheck_live_status(self, delay: float = 0): + """Recording ended: re-check live status promptly to avoid missing a + subsequent broadcast (previously douyin/tiktok were excluded entirely, + leaving the next check up to one full polling cycle away).""" + if delay: + await asyncio.sleep(delay) + if self.should_stop: + return + recording_duration = time.time() - self.recording_start_time + if recording_duration < self.min_valid_recording_duration: + self.recording.status_info = RecordingStatus.RECORDING_ERROR + return + if not self.services.recording_enabled: + return + if self.is_flv_preferred_platform: + # douyin/tiktok streams may still briefly report is_live=True right + # after the recording exits; wait before re-checking to avoid an + # immediate re-record loop instead of skipping the re-check. + await asyncio.sleep(self.delayed_recheck_interval) + if self.should_stop or self.recording.is_recording: + return + self.services.run_coro(self.services.recording_manager.check_if_live(self.recording)) @staticmethod async def _capture_stream_tail( @@ -424,7 +445,7 @@ async def start_ffmpeg( process.stdin.close() await asyncio.wait_for(process.wait(), timeout=15.0) - except asyncio.TimeoutError: + except TimeoutError: logger.warning(f"FFmpeg process did not exit gracefully, forcing termination: {live_url}") process.kill() await process.wait() @@ -650,10 +671,20 @@ def run_script_sync(self, command: str) -> None: finally: loop.close() + @staticmethod + def _split_command(command: str) -> list: + """Split a custom script command respecting quotes. + + posix=False keeps Windows-style backslash paths intact; surrounding + quotes are stripped afterwards so quoted arguments work on both + platforms (a bare str.split() breaks paths containing spaces).""" + tokens = shlex.split(command.strip(), posix=False) + return [t[1:-1] if len(t) > 1 and t[0] == t[-1] and t[0] in "\"'" else t for t in tokens if t] + async def run_script_async(self, command: str) -> None: try: process = await asyncio.create_subprocess_exec( - *command.split(), + *self._split_command(command), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, startupinfo=self.subprocess_start_info, diff --git a/app/core/runtime/process_manager.py b/app/core/runtime/process_manager.py index 2aa2d60c..9fee3f53 100644 --- a/app/core/runtime/process_manager.py +++ b/app/core/runtime/process_manager.py @@ -70,7 +70,7 @@ async def cleanup(self): try: await asyncio.wait_for(process.wait(), timeout=5.0) - except asyncio.TimeoutError: + except TimeoutError: logger.warning(f"Process {process.pid} did not terminate, killing it") process.kill() await process.wait() diff --git a/app/messages/notification_service.py b/app/messages/notification_service.py index e8ee402a..0c7e35f2 100644 --- a/app/messages/notification_service.py +++ b/app/messages/notification_service.py @@ -98,7 +98,7 @@ def send_sync() -> dict[str, list[str]]: try: overall_timeout = max(timeout * 4, timeout + 5) return await asyncio.wait_for(asyncio.to_thread(send_sync), timeout=overall_timeout) - except asyncio.TimeoutError: + except TimeoutError: logger.error(f"Email push timed out, SMTP server: {email_host}") except (smtplib.SMTPException, OSError, ValueError) as e: logger.error(f"Email push failed, SMTP server: {email_host}, Error message: {e}") diff --git a/pyproject.toml b/pyproject.toml index 00bc2d96..ce737d56 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,6 +22,9 @@ dependencies = [ "deprecated>=1.3.1" ] +[project.optional-dependencies] +streamlink = ["streamlink>=8.0.0"] + [project.urls] Documentation = "https://github.com/ihmily/StreamCap/wiki" Homepage = "https://github.com/ihmily/StreamCap" diff --git a/requirements.txt b/requirements.txt index f862ee52..b0523a6b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,5 @@ streamget>=4.0.10 python-dotenv>=1.2.1 pystray>=0.19.5 plyer>=2.1.0 -deprecated>=1.3.1 \ No newline at end of file +deprecated>=1.3.1 +# streamlink>=8.0.0 # optional: enable streamlink fallback for platforms without a built-in handler \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..2fb1314c --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# Test package for StreamCap optimizations. diff --git a/tests/test_platform_info.py b/tests/test_platform_info.py new file mode 100644 index 00000000..ba264d5f --- /dev/null +++ b/tests/test_platform_info.py @@ -0,0 +1,21 @@ +import unittest + +from app.core.platforms.platform_handlers import get_platform_info + + +class TestGetPlatformInfo(unittest.TestCase): + def test_douyin(self): + self.assertEqual(get_platform_info("https://live.douyin.com/123456"), ("抖音直播", "douyin")) + + def test_twitch(self): + self.assertEqual(get_platform_info("https://www.twitch.tv/somechannel"), ("TwitchTV", "twitch")) + + def test_custom_m3u8(self): + self.assertEqual(get_platform_info("http://example.com/stream.m3u8"), ("自定义录制直播", "custom")) + + def test_unknown_platform(self): + self.assertEqual(get_platform_info("https://unknown.example.com/live"), (None, None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_split_command.py b/tests/test_split_command.py new file mode 100644 index 00000000..96c9bd61 --- /dev/null +++ b/tests/test_split_command.py @@ -0,0 +1,35 @@ +import unittest + +from app.core.recording.stream_manager import LiveStreamRecorder + + +class TestSplitCommand(unittest.TestCase): + def test_simple_command(self): + self.assertEqual(LiveStreamRecorder._split_command("python script.py"), ["python", "script.py"]) + + def test_windows_path_with_spaces(self): + cmd = 'python "C:\\my dir\\post.py" --record_name "room 1"' + self.assertEqual( + LiveStreamRecorder._split_command(cmd), + ["python", "C:\\my dir\\post.py", "--record_name", "room 1"], + ) + + def test_posix_single_quotes(self): + self.assertEqual( + LiveStreamRecorder._split_command("bash '/home/user/my script.sh' arg"), + ["bash", "/home/user/my script.sh", "arg"], + ) + + def test_extra_whitespace(self): + self.assertEqual(LiveStreamRecorder._split_command("python a b "), ["python", "a", "b"]) + + def test_ffmpeg_args(self): + cmd = 'ffmpeg -i "C:\\a b\\in.flv" -c copy out.mp4' + self.assertEqual( + LiveStreamRecorder._split_command(cmd), + ["ffmpeg", "-i", "C:\\a b\\in.flv", "-c", "copy", "out.mp4"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_streamlink_fallback.py b/tests/test_streamlink_fallback.py new file mode 100644 index 00000000..4beb0b09 --- /dev/null +++ b/tests/test_streamlink_fallback.py @@ -0,0 +1,37 @@ +import unittest + +from app.core.platforms.platform_handlers.streamlink_fallback import _pick_stream + + +class FakeStream: + def __init__(self, url): + self.url = url + + +class TestPickStream(unittest.TestCase): + def test_empty_streams(self): + self.assertIsNone(_pick_stream({}, "OD")) + + def test_best_for_od(self): + streams = {"720p": FakeStream("a"), "best": FakeStream("b")} + self.assertIs(_pick_stream(streams, "OD"), streams["best"]) + + def test_hd_prefers_1080p(self): + streams = {"720p": FakeStream("a"), "1080p": FakeStream("b"), "best": FakeStream("c")} + self.assertIs(_pick_stream(streams, "HD"), streams["1080p"]) + + def test_hd_falls_back_to_highest_resolution(self): + streams = {"720p": FakeStream("a"), "480p": FakeStream("b")} + self.assertIs(_pick_stream(streams, "HD"), streams["720p"]) + + def test_audio_excluded(self): + streams = {"audio": FakeStream("a"), "worst": FakeStream("b")} + self.assertIs(_pick_stream(streams, "LD"), streams["worst"]) + + def test_none_quality_defaults_to_best(self): + streams = {"best": FakeStream("b")} + self.assertIs(_pick_stream(streams, None), streams["best"]) + + +if __name__ == "__main__": + unittest.main()