Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93a572cbb5 | ||
|
|
09618bef3d | ||
|
|
120d3ecf32 |
No files matched your search
@@ -17,6 +17,7 @@
|
|||||||
ps.pydantic
|
ps.pydantic
|
||||||
ps.asyncssh
|
ps.asyncssh
|
||||||
ps.uvicorn
|
ps.uvicorn
|
||||||
|
ps.pillow
|
||||||
];
|
];
|
||||||
|
|
||||||
testDeps = [
|
testDeps = [
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ dependencies = [
|
|||||||
"pydantic",
|
"pydantic",
|
||||||
"asyncssh",
|
"asyncssh",
|
||||||
"uvicorn",
|
"uvicorn",
|
||||||
|
"pillow",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
|
|||||||
@@ -72,6 +72,8 @@ class TvConfig(BaseModel):
|
|||||||
mcp_bearer_token: str | None = None
|
mcp_bearer_token: str | None = None
|
||||||
max_volume: int = 40
|
max_volume: int = 40
|
||||||
enable_raw_ssap: bool = False
|
enable_raw_ssap: bool = False
|
||||||
|
capture_max_width: int | None = None
|
||||||
|
capture_jpeg_quality: int | None = None
|
||||||
|
|
||||||
def __init__(self, **data: Any) -> None:
|
def __init__(self, **data: Any) -> None:
|
||||||
try:
|
try:
|
||||||
@@ -100,6 +102,20 @@ class TvConfig(BaseModel):
|
|||||||
def _validate_max_volume(cls, value: Any) -> int:
|
def _validate_max_volume(cls, value: Any) -> int:
|
||||||
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
|
return _parse_bounded_int("MAX_VOLUME", value, min_val=0, max_val=100)
|
||||||
|
|
||||||
|
@field_validator("capture_max_width", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _validate_capture_max_width(cls, value: Any) -> int | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return _parse_bounded_int("CAPTURE_MAX_WIDTH", value, min_val=64, max_val=3840)
|
||||||
|
|
||||||
|
@field_validator("capture_jpeg_quality", mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _validate_capture_jpeg_quality(cls, value: Any) -> int | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return _parse_bounded_int("CAPTURE_JPEG_QUALITY", value, min_val=1, max_val=95)
|
||||||
|
|
||||||
|
|
||||||
def _load_dotenv(env_path: Path) -> None:
|
def _load_dotenv(env_path: Path) -> None:
|
||||||
"""Populate unset os.environ keys from a .env file using stdlib only."""
|
"""Populate unset os.environ keys from a .env file using stdlib only."""
|
||||||
@@ -149,6 +165,8 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
|
|||||||
tv_ip = _optional_str("TV_IP") or ""
|
tv_ip = _optional_str("TV_IP") or ""
|
||||||
port_raw = _optional_str("PORT")
|
port_raw = _optional_str("PORT")
|
||||||
max_volume_raw = _optional_str("MAX_VOLUME")
|
max_volume_raw = _optional_str("MAX_VOLUME")
|
||||||
|
capture_max_width_raw = _optional_str("CAPTURE_MAX_WIDTH")
|
||||||
|
capture_jpeg_quality_raw = _optional_str("CAPTURE_JPEG_QUALITY")
|
||||||
|
|
||||||
host = _optional_str("HOST") or "127.0.0.1"
|
host = _optional_str("HOST") or "127.0.0.1"
|
||||||
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
|
wol_broadcast = _optional_str("WOL_BROADCAST") or "255.255.255.255"
|
||||||
@@ -177,6 +195,10 @@ def load_config(env_path: Path | None = Path(".env")) -> TvConfig:
|
|||||||
kwargs["port"] = port_raw
|
kwargs["port"] = port_raw
|
||||||
if max_volume_raw is not None:
|
if max_volume_raw is not None:
|
||||||
kwargs["max_volume"] = max_volume_raw
|
kwargs["max_volume"] = max_volume_raw
|
||||||
|
if capture_max_width_raw is not None:
|
||||||
|
kwargs["capture_max_width"] = capture_max_width_raw
|
||||||
|
if capture_jpeg_quality_raw is not None:
|
||||||
|
kwargs["capture_jpeg_quality"] = capture_jpeg_quality_raw
|
||||||
|
|
||||||
return TvConfig(**kwargs)
|
return TvConfig(**kwargs)
|
||||||
|
|
||||||
|
|||||||
@@ -160,7 +160,14 @@ def create_mcp_server(config: TvConfig, manager: TvManager | None = None) -> MCP
|
|||||||
tv_manager = (
|
tv_manager = (
|
||||||
manager
|
manager
|
||||||
if manager is not None
|
if manager is not None
|
||||||
else TvManager(config, capture_client=CaptureClient(AsyncSshCaptureTransport(config)))
|
else TvManager(
|
||||||
|
config,
|
||||||
|
capture_client=CaptureClient(
|
||||||
|
AsyncSshCaptureTransport(config),
|
||||||
|
max_width=config.capture_max_width,
|
||||||
|
jpeg_quality=config.capture_jpeg_quality,
|
||||||
|
),
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
|
|||||||
@@ -5,14 +5,57 @@ import hashlib
|
|||||||
import os
|
import os
|
||||||
from collections.abc import Awaitable, Callable
|
from collections.abc import Awaitable, Callable
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
|
from io import BytesIO
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import asyncssh
|
import asyncssh
|
||||||
|
from PIL import Image, UnidentifiedImageError
|
||||||
|
|
||||||
from lg_smtv_mcp.config import TvConfig
|
from lg_smtv_mcp.config import TvConfig
|
||||||
from lg_smtv_mcp.errors import ErrorCode, TvError
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport
|
from lg_smtv_mcp.tv_core.protocols import CaptureResult, CaptureTransport
|
||||||
|
|
||||||
|
_DEFAULT_JPEG_QUALITY = 75
|
||||||
|
|
||||||
|
|
||||||
|
def _recompress_jpeg(
|
||||||
|
raw_bytes: bytes,
|
||||||
|
*,
|
||||||
|
max_width: int | None,
|
||||||
|
jpeg_quality: int | None,
|
||||||
|
) -> bytes:
|
||||||
|
"""Optionally downscale and/or recompress JPEG bytes for inline MCP delivery."""
|
||||||
|
if max_width is None and jpeg_quality is None:
|
||||||
|
return raw_bytes
|
||||||
|
|
||||||
|
quality = jpeg_quality if jpeg_quality is not None else _DEFAULT_JPEG_QUALITY
|
||||||
|
try:
|
||||||
|
with Image.open(BytesIO(raw_bytes)) as opened:
|
||||||
|
img: Image.Image = opened
|
||||||
|
width, height = img.size
|
||||||
|
if max_width is not None and width > max_width:
|
||||||
|
target_height = max(1, round(height * (max_width / width)))
|
||||||
|
img = img.resize( # pyright: ignore[reportUnknownMemberType]
|
||||||
|
(max_width, target_height),
|
||||||
|
Image.Resampling.LANCZOS,
|
||||||
|
)
|
||||||
|
if img.mode != "RGB":
|
||||||
|
img = img.convert("RGB")
|
||||||
|
out = BytesIO()
|
||||||
|
img.save(out, format="JPEG", quality=quality)
|
||||||
|
return out.getvalue()
|
||||||
|
except (
|
||||||
|
UnidentifiedImageError,
|
||||||
|
Image.DecompressionBombError,
|
||||||
|
OSError,
|
||||||
|
ValueError,
|
||||||
|
EOFError,
|
||||||
|
) as exc:
|
||||||
|
raise TvError(
|
||||||
|
ErrorCode.SCREENSHOT_UNAVAILABLE,
|
||||||
|
f"Failed to process screenshot image: {exc}",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
class AsyncSshCaptureTransport:
|
class AsyncSshCaptureTransport:
|
||||||
"""SFTP transport for reading and removing Developer Mode screenshot captures."""
|
"""SFTP transport for reading and removing Developer Mode screenshot captures."""
|
||||||
@@ -154,8 +197,16 @@ class AsyncSshCaptureTransport:
|
|||||||
class CaptureClient:
|
class CaptureClient:
|
||||||
"""FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP."""
|
"""FrameCapturer that triggers executeOneShot and fetches JPEG via SFTP."""
|
||||||
|
|
||||||
def __init__(self, transport: CaptureTransport) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
transport: CaptureTransport,
|
||||||
|
*,
|
||||||
|
max_width: int | None = None,
|
||||||
|
jpeg_quality: int | None = None,
|
||||||
|
) -> None:
|
||||||
self._transport = transport
|
self._transport = transport
|
||||||
|
self._max_width = max_width
|
||||||
|
self._jpeg_quality = jpeg_quality
|
||||||
self._seq = 0
|
self._seq = 0
|
||||||
self._last_sha256: str | None = None
|
self._last_sha256: str | None = None
|
||||||
|
|
||||||
@@ -203,6 +254,11 @@ class CaptureClient:
|
|||||||
"Screenshot capture timed out after 6.0s",
|
"Screenshot capture timed out after 6.0s",
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
image_bytes = _recompress_jpeg(
|
||||||
|
image_bytes,
|
||||||
|
max_width=self._max_width,
|
||||||
|
jpeg_quality=self._jpeg_quality,
|
||||||
|
)
|
||||||
frame_sha256 = hashlib.sha256(image_bytes).hexdigest()
|
frame_sha256 = hashlib.sha256(image_bytes).hexdigest()
|
||||||
changed_since_last = self._last_sha256 != frame_sha256
|
changed_since_last = self._last_sha256 != frame_sha256
|
||||||
self._last_sha256 = frame_sha256
|
self._last_sha256 = frame_sha256
|
||||||
|
|||||||
@@ -3,11 +3,13 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import hashlib
|
import hashlib
|
||||||
import inspect
|
import inspect
|
||||||
|
from io import BytesIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import asyncssh
|
import asyncssh
|
||||||
import pytest
|
import pytest
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
from lg_smtv_mcp.config import TvConfig
|
from lg_smtv_mcp.config import TvConfig
|
||||||
from lg_smtv_mcp.errors import ErrorCode, TvError
|
from lg_smtv_mcp.errors import ErrorCode, TvError
|
||||||
@@ -522,3 +524,149 @@ async def test_capture_client_maps_key_import_error_to_screenshot_unavailable()
|
|||||||
await client.capture_frame(ssap_request)
|
await client.capture_frame(ssap_request)
|
||||||
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
assert "Passphrase must be specified" in exc_info.value.message
|
assert "Passphrase must be specified" in exc_info.value.message
|
||||||
|
|
||||||
|
|
||||||
|
def _make_jpeg(
|
||||||
|
width: int,
|
||||||
|
height: int,
|
||||||
|
*,
|
||||||
|
color: tuple[int, int, int] = (25, 80, 160),
|
||||||
|
quality: int = 95,
|
||||||
|
) -> bytes:
|
||||||
|
buf = BytesIO()
|
||||||
|
img = Image.new("RGB", (width, height), color=color)
|
||||||
|
# Draw varied pixels so JPEG recompression has realistic entropy differences.
|
||||||
|
for x in range(0, width, 8):
|
||||||
|
img.putpixel((x, x % height), ((x * 7) % 255, (x * 13) % 255, 200))
|
||||||
|
img.save(buf, format="JPEG", quality=quality)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_passes_raw_bytes_unchanged_when_no_resize_or_quality() -> None:
|
||||||
|
raw = b"raw-unprocessed-bytes"
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw))
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert result.image_bytes == raw
|
||||||
|
assert result.size_bytes == len(raw)
|
||||||
|
assert result.frame_sha256 == hashlib.sha256(raw).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_downscales_preserving_aspect_ratio_with_default_quality_75() -> None:
|
||||||
|
raw = _make_jpeg(1920, 1080, quality=95)
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=640)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (640, 360)
|
||||||
|
assert result.size_bytes == len(result.image_bytes)
|
||||||
|
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
|
||||||
|
assert result.image_bytes != raw
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_never_upscales_when_width_at_or_below_max_width() -> None:
|
||||||
|
raw = _make_jpeg(800, 600, quality=95)
|
||||||
|
client = CaptureClient(
|
||||||
|
FakeCaptureTransport(image_bytes=raw),
|
||||||
|
max_width=1280,
|
||||||
|
jpeg_quality=80,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (800, 600)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_recompresses_at_native_resolution_when_only_quality_set() -> None:
|
||||||
|
raw = _make_jpeg(1280, 720, quality=95)
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), jpeg_quality=30)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
result = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (1280, 720)
|
||||||
|
assert result.size_bytes < len(raw)
|
||||||
|
assert result.frame_sha256 == hashlib.sha256(result.image_bytes).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_hashes_and_tracks_changes_on_final_delivered_bytes() -> None:
|
||||||
|
raw = _make_jpeg(1280, 720, quality=95)
|
||||||
|
client = CaptureClient(
|
||||||
|
FakeCaptureTransport(image_bytes=raw),
|
||||||
|
max_width=640,
|
||||||
|
jpeg_quality=75,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
first = await client.capture_frame(ssap_request)
|
||||||
|
second = await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert first.frame_sha256 != hashlib.sha256(raw).hexdigest()
|
||||||
|
assert first.frame_sha256 == hashlib.sha256(first.image_bytes).hexdigest()
|
||||||
|
assert first.changed_since_last is True
|
||||||
|
assert second.changed_since_last is False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"kwargs",
|
||||||
|
[
|
||||||
|
{"max_width": 640},
|
||||||
|
{"jpeg_quality": 75},
|
||||||
|
{"max_width": 640, "jpeg_quality": 75},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_capture_client_raises_screenshot_unavailable_on_corrupt_image_bytes(
|
||||||
|
kwargs: dict[str, int],
|
||||||
|
) -> None:
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=b"not-a-valid-jpeg"), **kwargs)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
async def test_capture_client_maps_decompression_bomb_error_to_screenshot_unavailable(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
raw = _make_jpeg(32, 32, quality=95)
|
||||||
|
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 100)
|
||||||
|
client = CaptureClient(FakeCaptureTransport(image_bytes=raw), max_width=16)
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = (uri, payload)
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
with pytest.raises(TvError) as exc_info:
|
||||||
|
await client.capture_frame(ssap_request)
|
||||||
|
|
||||||
|
assert exc_info.value.code is ErrorCode.SCREENSHOT_UNAVAILABLE
|
||||||
@@ -22,6 +22,8 @@ def _clear_tv_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|||||||
"MCP_BEARER_TOKEN",
|
"MCP_BEARER_TOKEN",
|
||||||
"MAX_VOLUME",
|
"MAX_VOLUME",
|
||||||
"ENABLE_RAW_SSAP",
|
"ENABLE_RAW_SSAP",
|
||||||
|
"CAPTURE_MAX_WIDTH",
|
||||||
|
"CAPTURE_JPEG_QUALITY",
|
||||||
):
|
):
|
||||||
monkeypatch.delenv(key, raising=False)
|
monkeypatch.delenv(key, raising=False)
|
||||||
|
|
||||||
@@ -74,6 +76,8 @@ def test_load_config_uses_expected_defaults_when_optional_vars_unset(
|
|||||||
assert cfg.allowed_hosts == ()
|
assert cfg.allowed_hosts == ()
|
||||||
assert cfg.tv_mac is None
|
assert cfg.tv_mac is None
|
||||||
assert cfg.mcp_bearer_token is None
|
assert cfg.mcp_bearer_token is None
|
||||||
|
assert cfg.capture_max_width is None
|
||||||
|
assert cfg.capture_jpeg_quality is None
|
||||||
|
|
||||||
|
|
||||||
def test_dotenv_fallback_does_not_overwrite_existing_env(
|
def test_dotenv_fallback_does_not_overwrite_existing_env(
|
||||||
@@ -108,6 +112,12 @@ def test_dotenv_fallback_does_not_overwrite_existing_env(
|
|||||||
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
|
({"TV_IP": "192.0.2.10", "PORT": "0"}, "PORT"),
|
||||||
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
|
({"TV_IP": "192.0.2.10", "PORT": "65536"}, "PORT"),
|
||||||
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
|
({"TV_IP": "192.0.2.10", "PORT": "abc"}, "PORT"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "63"}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "3841"}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_MAX_WIDTH": "wide"}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "0"}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "96"}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"TV_IP": "192.0.2.10", "CAPTURE_JPEG_QUALITY": "high"}, "CAPTURE_JPEG_QUALITY"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_load_config_rejects_invalid_env_values_with_config_error(
|
def test_load_config_rejects_invalid_env_values_with_config_error(
|
||||||
@@ -136,6 +146,14 @@ def test_load_config_rejects_invalid_env_values_with_config_error(
|
|||||||
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
|
({"tv_ip": "192.0.2.10", "max_volume": 150}, "MAX_VOLUME"),
|
||||||
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
|
({"tv_ip": "192.0.2.10", "max_volume": 12.5}, "MAX_VOLUME"),
|
||||||
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
|
({"tv_ip": "192.0.2.10", "wol_broadcast": "bad-ip"}, "WOL_BROADCAST"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": 63}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": 3841}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": 1280.5}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_max_width": True}, "CAPTURE_MAX_WIDTH"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 0}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 96}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": 75.5}, "CAPTURE_JPEG_QUALITY"),
|
||||||
|
({"tv_ip": "192.0.2.10", "capture_jpeg_quality": False}, "CAPTURE_JPEG_QUALITY"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
|
def test_tv_config_rejects_invalid_direct_arguments_with_config_error(
|
||||||
@@ -210,3 +228,41 @@ def test_require_mac_returns_trimmed_value(monkeypatch: pytest.MonkeyPatch, tmp_
|
|||||||
|
|
||||||
cfg = load_config(env_path=tmp_path / "missing.env")
|
cfg = load_config(env_path=tmp_path / "missing.env")
|
||||||
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"
|
assert require_mac(cfg) == "AA:BB:CC:DD:EE:FF"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("width_env", "quality_env", "expected_width", "expected_quality"),
|
||||||
|
[
|
||||||
|
("64", "1", 64, 1),
|
||||||
|
("3840", "95", 3840, 95),
|
||||||
|
(" 1280 ", " 75 ", 1280, 75),
|
||||||
|
("", " ", None, None),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_load_config_parses_capture_max_width_and_jpeg_quality(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
tmp_path: Path,
|
||||||
|
width_env: str,
|
||||||
|
quality_env: str,
|
||||||
|
expected_width: int | None,
|
||||||
|
expected_quality: int | None,
|
||||||
|
) -> None:
|
||||||
|
_clear_tv_env(monkeypatch)
|
||||||
|
monkeypatch.setenv("TV_IP", "192.0.2.10")
|
||||||
|
monkeypatch.setenv("CAPTURE_MAX_WIDTH", width_env)
|
||||||
|
monkeypatch.setenv("CAPTURE_JPEG_QUALITY", quality_env)
|
||||||
|
|
||||||
|
cfg = load_config(env_path=tmp_path / "missing.env")
|
||||||
|
|
||||||
|
assert cfg.capture_max_width == expected_width
|
||||||
|
assert cfg.capture_jpeg_quality == expected_quality
|
||||||
|
|
||||||
|
|
||||||
|
def test_tv_config_accepts_explicit_none_and_valid_capture_bounds() -> None:
|
||||||
|
cfg_none = TvConfig(tv_ip="192.0.2.10", capture_max_width=None, capture_jpeg_quality=None)
|
||||||
|
assert cfg_none.capture_max_width is None
|
||||||
|
assert cfg_none.capture_jpeg_quality is None
|
||||||
|
|
||||||
|
cfg_bounds = TvConfig(tv_ip="192.0.2.10", capture_max_width=1280, capture_jpeg_quality=80)
|
||||||
|
assert cfg_bounds.capture_max_width == 1280
|
||||||
|
assert cfg_bounds.capture_jpeg_quality == 80
|
||||||
+60
-7
@@ -460,17 +460,17 @@ async def test_server_http_app_allows_authenticated_mcp_initialize_request(
|
|||||||
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
await asyncio.wait_for(lifespan_task, timeout=2.0)
|
||||||
|
|
||||||
|
|
||||||
async def test_server_create_mcp_server_wires_default_capture_client(
|
def _wire_capture_client_with_fake_ssh(
|
||||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
config: TvConfig,
|
||||||
|
) -> tuple[dict[str, Any], dict[str, bytes], list[str], list[dict[str, Any]], list[Any]]:
|
||||||
import lg_smtv_mcp.server as server_mod
|
import lg_smtv_mcp.server as server_mod
|
||||||
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
|
||||||
|
|
||||||
config = _make_config(tmp_path)
|
|
||||||
captured: dict[str, Any] = {}
|
captured: dict[str, Any] = {}
|
||||||
remote_files: dict[str, bytes] = {}
|
remote_files: dict[str, bytes] = {}
|
||||||
removed_paths: list[str] = []
|
removed_paths: list[str] = []
|
||||||
connect_calls: list[dict[str, Any]] = []
|
connect_calls: list[dict[str, Any]] = []
|
||||||
|
sftp_sessions: list[Any] = []
|
||||||
|
|
||||||
class DummyManager:
|
class DummyManager:
|
||||||
async def start(self) -> None:
|
async def start(self) -> None:
|
||||||
@@ -488,6 +488,8 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
def open(self, path: str, mode: str = "r") -> Any:
|
def open(self, path: str, mode: str = "r") -> Any:
|
||||||
|
_ = mode
|
||||||
|
|
||||||
class FakeFile:
|
class FakeFile:
|
||||||
async def __aenter__(self) -> FakeFile:
|
async def __aenter__(self) -> FakeFile:
|
||||||
return self
|
return self
|
||||||
@@ -507,8 +509,6 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
|||||||
async def exit(self) -> None:
|
async def exit(self) -> None:
|
||||||
self.closed = True
|
self.closed = True
|
||||||
|
|
||||||
sftp_sessions: list[FakeSftp] = []
|
|
||||||
|
|
||||||
class FakeSshConnection:
|
class FakeSshConnection:
|
||||||
async def start_sftp_client(self) -> FakeSftp:
|
async def start_sftp_client(self) -> FakeSftp:
|
||||||
sftp = FakeSftp()
|
sftp = FakeSftp()
|
||||||
@@ -533,6 +533,18 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
|||||||
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
|
monkeypatch.setattr(server_mod, "TvManager", fake_tv_manager)
|
||||||
monkeypatch.setattr(asyncssh, "connect", fake_connect)
|
monkeypatch.setattr(asyncssh, "connect", fake_connect)
|
||||||
server_mod.create_mcp_server(config)
|
server_mod.create_mcp_server(config)
|
||||||
|
return captured, remote_files, removed_paths, connect_calls, sftp_sessions
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_create_mcp_server_wires_default_capture_client(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||||
|
|
||||||
|
config = _make_config(tmp_path)
|
||||||
|
captured, remote_files, removed_paths, connect_calls, sftp_sessions = (
|
||||||
|
_wire_capture_client_with_fake_ssh(monkeypatch, config)
|
||||||
|
)
|
||||||
|
|
||||||
assert captured["config"] is config
|
assert captured["config"] is config
|
||||||
assert "capture_client" in captured["kwargs"]
|
assert "capture_client" in captured["kwargs"]
|
||||||
@@ -556,3 +568,44 @@ async def test_server_create_mcp_server_wires_default_capture_client(
|
|||||||
assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"]
|
assert removed_paths == ["/tmp/lg_smtv_cap_1.jpg"]
|
||||||
assert len(sftp_sessions) == 1
|
assert len(sftp_sessions) == 1
|
||||||
assert sftp_sessions[0].closed is True
|
assert sftp_sessions[0].closed is True
|
||||||
|
|
||||||
|
|
||||||
|
async def test_server_create_mcp_server_wires_capture_downscaling_config(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from lg_smtv_mcp.tv_core.capture import CaptureClient
|
||||||
|
|
||||||
|
config = TvConfig(
|
||||||
|
tv_ip="192.0.2.10",
|
||||||
|
client_key_path=tmp_path / ".client_key.json",
|
||||||
|
capture_max_width=640,
|
||||||
|
capture_jpeg_quality=60,
|
||||||
|
)
|
||||||
|
captured, remote_files, _removed_paths, _connect_calls, _sftp_sessions = (
|
||||||
|
_wire_capture_client_with_fake_ssh(monkeypatch, config)
|
||||||
|
)
|
||||||
|
|
||||||
|
capture_client = captured["kwargs"]["capture_client"]
|
||||||
|
assert isinstance(capture_client, CaptureClient)
|
||||||
|
|
||||||
|
buf = BytesIO()
|
||||||
|
Image.new("RGB", (1920, 1080), color=(30, 60, 90)).save(buf, format="JPEG", quality=95)
|
||||||
|
large_jpeg = buf.getvalue()
|
||||||
|
|
||||||
|
async def ssap_request(uri: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
_ = uri
|
||||||
|
remote_files[payload["path"]] = large_jpeg
|
||||||
|
return {"returnValue": True}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await capture_client.capture_frame(ssap_request)
|
||||||
|
finally:
|
||||||
|
await capture_client.close()
|
||||||
|
|
||||||
|
with Image.open(BytesIO(result.image_bytes)) as img:
|
||||||
|
assert img.format == "JPEG"
|
||||||
|
assert img.size == (640, 360)
|
||||||
Reference in new issue
Block a user