diff --git a/app/adapters/mediastream.py b/app/adapters/mediastream.py
index 37acea7a6..ff52bb41d 100644
--- a/app/adapters/mediastream.py
+++ b/app/adapters/mediastream.py
@@ -10,7 +10,7 @@ import socket
from contextlib import AbstractContextManager
from pathlib import Path
from typing import Any, Iterator, Optional
-from urllib.parse import quote, urljoin, urlsplit
+from urllib.parse import quote, urljoin, urlsplit, urlunsplit
from cryptography.fernet import Fernet, InvalidToken
from fastapi import HTTPException, Request, status
@@ -265,6 +265,74 @@ def _validate_stream_url(url: str, *, configured_hosts: set[str]) -> str:
return url
+def _sanitize_strm_direct_url(raw_url: str) -> Optional[str]:
+ """
+ 规范化并校验可供客户端直连播放的 STRM HTTP(S) 地址,剔除内嵌凭据与播放器附加头后缀。
+
+ 本函数不发起 DNS 或网络请求,仅用于向已认证客户端返回安全的 HTTP(S) 直链文本;
+ 服务端代理转发仍须走 ``_validate_stream_url``。
+
+ :param raw_url: STRM 文件或媒体服务器报告的原始地址
+ :return: 规范化后的 HTTP(S) 直链;非 HTTP(S)、包含账号密码或控制字符时返回 None
+ """
+ candidate = raw_url.strip().split("|", 1)[0].strip()
+ if not candidate or any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in candidate):
+ return None
+ parsed = urlsplit(candidate)
+ scheme = parsed.scheme.casefold()
+ hostname = (parsed.hostname or "").strip().rstrip(".")
+ if (
+ scheme not in {"http", "https"}
+ or not hostname
+ or parsed.username is not None
+ or parsed.password is not None
+ or parsed.fragment
+ ):
+ return None
+ safe_path = quote(parsed.path, safe="/:@!$&'()*+,;=-._~%")
+ safe_query = quote(parsed.query, safe="/?:@!$&'()*+,;=-._~%")
+ return urlunsplit((scheme, parsed.netloc, safe_path, safe_query, ""))
+
+
+def _extract_strm_target_line(content: str) -> Optional[str]:
+ """
+ 从 STRM 文本中提取唯一有效的媒体地址行,忽略空行与 ``#`` 注释指令。
+
+ :param content: STRM 文本内容
+ :return: 唯一的目标行文本;为空或包含多条媒体地址时返回 None
+ """
+ lines = [
+ stripped
+ for raw_line in content.splitlines()
+ if (stripped := raw_line.strip()) and not stripped.startswith("#")
+ ]
+ if len(lines) != 1:
+ return None
+ return lines[0]
+
+
+def _extract_local_strm_direct_url(path: Path) -> Optional[str]:
+ """
+ 从本机可读的 STRM 文件中提取供客户端直连播放的 HTTP(S) 地址。
+
+ 当 STRM 指向本地文件路径、体积超限或编码无效时不抛出异常,仅返回 None,
+ 交由常规流校验分支返回对应状态码。
+
+ :param path: 本机 STRM 文件路径
+ :return: 无内嵌凭据的 HTTP(S) 直链地址;不可直连时返回 None
+ """
+ if path.suffix.casefold() != ".strm":
+ return None
+ try:
+ if path.stat().st_size > _STRM_MAX_BYTES:
+ return None
+ content = path.read_text(encoding="utf-8-sig").strip()
+ except (OSError, UnicodeError):
+ return None
+ target = _extract_strm_target_line(content)
+ return _sanitize_strm_direct_url(target) if target else None
+
+
def _resolve_strm_source(path: Path, configured_hosts: set[str]) -> tuple[str, Path | str]:
"""
解析单行 STRM 文件为本地媒体文件或经过校验的 HTTP(S) 源。
@@ -285,13 +353,14 @@ def _resolve_strm_source(path: Path, configured_hosts: set[str]) -> tuple[str, P
except OSError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="STRM 文件不可读取") from None
- lines = [line.strip() for line in content.splitlines() if line.strip()]
- if len(lines) != 1:
+ target = _extract_strm_target_line(content)
+ if not target:
raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="STRM 文件内容无效")
- source = lines[0]
+ source = target.split("|", 1)[0].strip()
parsed = urlsplit(source)
if parsed.scheme:
- return "remote", _validate_stream_url(source, configured_hosts=configured_hosts)
+ normalized = _sanitize_strm_direct_url(source) or source
+ return "remote", _validate_stream_url(normalized, configured_hosts=configured_hosts)
source_path = Path(source)
if not source_path.is_absolute():
diff --git a/app/agent/policy/resources/api_mcp_schema.json b/app/agent/policy/resources/api_mcp_schema.json
index f13d2f5f3..5f6a83a3e 100644
--- a/app/agent/policy/resources/api_mcp_schema.json
+++ b/app/agent/policy/resources/api_mcp_schema.json
@@ -1598,7 +1598,7 @@
"type": "null"
}
],
- "description": "发布时间",
+ "description": "距离发布经过的分钟数;单值为最小等待时间,区间表示允许的时间范围",
"title": "Publish Time"
},
"rule_id": {
@@ -1627,7 +1627,7 @@
"type": "null"
}
],
- "description": "大小范围(MB)",
+ "description": "单集平均文件大小范围,单位为 MiB;a-b、>a、a、 Optional[str]:
+ """
+ 提取当前播放条目可用的无凭据 STRM HTTP(S) 客户端直链地址。
+
+ 优先读取本机 STRM 文件中的目标直链,其次采用媒体服务器详情报告的远端 STRM 媒体源,
+ 最后兼容媒体服务器条目路径本身即为 HTTP(S) STRM 目标的场景。
+
+ :param item: 已解析的媒体服务器条目或文件票据条目
+ :param path: 本机可读取的媒体或 STRM 文件路径
+ :param detail: 可选媒体服务器完整详情
+ :param media_source_id: 可选指定的多版本媒体源标识
+ :return: 规范化后的 HTTP(S) 直链地址;非 STRM 或为本地路径时返回 None
+ """
+ if path is not None and path.suffix.casefold() == ".strm":
+ local_direct = _extract_local_strm_direct_url(path)
+ if local_direct:
+ return local_direct
+ if detail and detail.media_sources:
+ target_source = next(
+ (src for src in detail.media_sources if media_source_id and src.id == media_source_id),
+ detail.media_sources[0],
+ )
+ if target_source.direct_url:
+ sanitized = _sanitize_strm_direct_url(target_source.direct_url)
+ if sanitized:
+ return sanitized
+ if item.path and item.path.strip().casefold().startswith(("http://", "https://")):
+ return _sanitize_strm_direct_url(item.path)
+ return None
+
+
@router.get(
"/stream-info",
summary="查询媒体流与外挂字幕",
@@ -391,7 +429,7 @@ def stream_info(
userinfo: _SchemaTokenPayload = Depends(verify_token),
) -> _SchemaResponse[_SchemaMediaServerStreamInfo]:
"""
- 返回当前实例代理的媒体流地址;媒体服务器条目优先通过服务器原始流播放并合并外挂字幕。
+ 返回当前实例代理的媒体流地址;当条目确认为无内嵌凭据的 HTTP(S) STRM 时同时附带客户端直链地址。
:param itemid: 媒体服务器条目标识
:param request: 当前请求,用于构造本实例流地址
@@ -401,29 +439,36 @@ def stream_info(
:return: 可供原生播放器读取的媒体流清单
"""
server_name, item, path = _resolve_stream_item(itemid, userinfo.sub, server=server)
- _playback_source(server_name, itemid, item, path, media_source_id=media_source_id)
+ is_audio = _is_audio_item(item, path)
+ detail: Optional[_SchemaMediaServerItemDetail] = None
+ item_path_is_strm = bool(item.path and item.path.strip().casefold().endswith(".strm"))
+ if server_name and (not is_audio or item_path_is_strm):
+ raw_detail = MediaServerChain().item_detail(
+ server=server_name, item_id=item.item_id or itemid, username=userinfo.username
+ )
+ if isinstance(raw_detail, _SchemaMediaServerItemDetail):
+ detail = raw_detail
+ strm_url = _resolve_manifest_strm_url(item, path, detail, media_source_id=media_source_id)
+ try:
+ _playback_source(server_name, itemid, item, path, media_source_id=media_source_id)
+ except HTTPException as exc:
+ if not (strm_url and exc.status_code == status.HTTP_501_NOT_IMPLEMENTED):
+ raise
stream_query = {"itemid": itemid}
if server_name:
stream_query["server"] = server_name
if media_source_id:
stream_query["media_source_id"] = media_source_id
content_url = request.url_for("stream_item_content").include_query_params(**stream_query)
- is_audio = _is_audio_item(item, path)
subtitles: list[_SchemaMediaServerSubtitleTrack] = (
[] if not path or is_audio else _subtitle_tracks(itemid, path, request, server_name)
)
- detail: Optional[_SchemaMediaServerItemDetail] = None
- if server_name and not is_audio:
- raw_detail = MediaServerChain().item_detail(
- server=server_name, item_id=item.item_id or itemid, username=userinfo.username
- )
- if isinstance(raw_detail, _SchemaMediaServerItemDetail):
- detail = raw_detail
- seen_ids = {track.subtitle_id for track in subtitles}
- for track in _server_subtitle_tracks(detail, itemid, request, server_name, media_source_id):
- if track.subtitle_id not in seen_ids:
- seen_ids.add(track.subtitle_id)
- subtitles.append(track)
+ if detail and not is_audio:
+ seen_ids = {track.subtitle_id for track in subtitles}
+ for track in _server_subtitle_tracks(detail, itemid, request, server_name, media_source_id):
+ if track.subtitle_id not in seen_ids:
+ seen_ids.add(track.subtitle_id)
+ subtitles.append(track)
resolved_source_id = media_source_id or (
detail.media_sources[0].id if detail and detail.media_sources else None
)
@@ -434,6 +479,7 @@ def stream_info(
server=server_name,
title=item.title or (path.stem if path else itemid),
content_url=str(content_url),
+ strm_url=strm_url,
media_type="audio" if is_audio else "video",
artist=_stream_item_note(item, "artist"),
album=_stream_item_note(item, "album"),
@@ -454,19 +500,31 @@ def stream_info(
def music_stream_info(
music: _SchemaMediaServerMusicStreamRequest,
request: Request,
- _: _SchemaTokenPayload = Depends(verify_token),
+ userinfo: _SchemaTokenPayload = Depends(verify_token),
) -> _SchemaResponse[_SchemaMediaServerStreamInfo]:
"""
将音乐元数据源的曲目身份匹配到媒体服务器中的单曲并返回流与 LRC 歌词。
:param music: 详情页选中的单曲元数据,不接受专辑或艺术家 ID
:param request: 当前请求,用于生成当前实例流地址
- :param _: 已验证的访问令牌
+ :param userinfo: 已验证的访问令牌
:return: 实际媒体服务器单曲的音频流和可选同名歌词清单
"""
server, item, path = _find_music_stream_item(music)
itemid = str(item.item_id or item.id or "")
- _playback_source(server, itemid, item, path)
+ detail: Optional[_SchemaMediaServerItemDetail] = None
+ if item.path and item.path.strip().casefold().endswith(".strm"):
+ raw_detail = MediaServerChain().item_detail(
+ server=server, item_id=itemid, username=userinfo.username
+ )
+ if isinstance(raw_detail, _SchemaMediaServerItemDetail):
+ detail = raw_detail
+ strm_url = _resolve_manifest_strm_url(item, path, detail)
+ try:
+ _playback_source(server, itemid, item, path)
+ except HTTPException as exc:
+ if not (strm_url and exc.status_code == status.HTTP_501_NOT_IMPLEMENTED):
+ raise
content_url = request.url_for("stream_item_content").include_query_params(itemid=itemid, server=server)
return _SchemaResponse(
success=True,
@@ -475,6 +533,7 @@ def music_stream_info(
server=server,
title=item.title or music.title,
content_url=str(content_url),
+ strm_url=strm_url,
media_type="audio",
artist=music.artist or music.album_artist or next(iter(music.artists), None) or _stream_item_note(item, "artist"),
album=music.album or _stream_item_note(item, "album"),
diff --git a/app/modules/_base/embybrowse.py b/app/modules/_base/embybrowse.py
index 57eba8510..b1330b1ce 100644
--- a/app/modules/_base/embybrowse.py
+++ b/app/modules/_base/embybrowse.py
@@ -8,7 +8,7 @@ import hashlib
import re
from dataclasses import dataclass
from typing import Any, Callable, Mapping, Optional
-from urllib.parse import quote, urlencode
+from urllib.parse import quote, urlencode, urlsplit, urlunsplit
from app.adapters.network.http import RequestUtils
from app.application.mediaserver import MediaServerIdentityHelper
@@ -361,20 +361,121 @@ def _parse_media_stream(source_id: str, raw: Mapping[str, Any]) -> MediaServerMe
)
-def _parse_media_sources(raw: Mapping[str, Any]) -> list[MediaServerMediaSource]:
+def _sanitize_emby_strm_url(cfg: Optional[EmbyBrowseConfig], raw_path: Any) -> Optional[str]:
"""
- 提取条目的全部多版本媒体源及其视频、音频和字幕轨道。
+ 校验并规范化 Emby 系媒体源报告的远端 STRM HTTP(S) 直链,排除包含服务端密钥或内嵌凭据的地址。
+
+ :param cfg: 可选 Emby 系协议配置,用于排除带服务端 API 密钥的地址
+ :param raw_path: 媒体源 ``Path`` 字段原始值
+ :return: 可供客户端直连播放的 HTTP(S) 地址;非远端直链或包含敏感凭据时返回 None
+ """
+ if not isinstance(raw_path, str):
+ return None
+ candidate = raw_path.strip().split("|", 1)[0].strip()
+ if not candidate or any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in candidate):
+ return None
+ if cfg and cfg.api_key and cfg.api_key in candidate:
+ return None
+ parsed = urlsplit(candidate)
+ scheme = parsed.scheme.casefold()
+ hostname = (parsed.hostname or "").strip().rstrip(".")
+ if (
+ scheme not in {"http", "https"}
+ or not hostname
+ or parsed.username is not None
+ or parsed.password is not None
+ or parsed.fragment
+ ):
+ return None
+ safe_path = quote(parsed.path, safe="/:@!$&'()*+,;=-._~%")
+ safe_query = quote(parsed.query, safe="/?:@!$&'()*+,;=-._~%")
+ return urlunsplit((scheme, parsed.netloc, safe_path, safe_query, ""))
+
+
+def _fetch_playback_sources(cfg: EmbyBrowseConfig, item_id: str) -> list[Mapping[str, Any]]:
+ """
+ 查询 Emby 系 ``PlaybackInfo`` 接口获取已展开的媒体源列表(含服务端解析后的 STRM 目标地址)。
+
+ :param cfg: Emby 系协议配置
+ :param item_id: 媒体条目标识
+ :return: 原始媒体源字典列表;查询失败时返回空列表
+ """
+ if not cfg.host or not cfg.api_key or not item_id:
+ return []
+ try:
+ pb_params: dict[str, Any] = {}
+ if cfg.user_id:
+ pb_params["UserId"] = cfg.user_id
+ response = cfg.request_factory().get_res(
+ f"{cfg.host}{cfg.api_prefix}Items/{quote(str(item_id), safe='')}/PlaybackInfo",
+ _api_params(cfg, pb_params),
+ )
+ if response is None or response.status_code != 200:
+ return []
+ sources = (response.json() or {}).get("MediaSources") or []
+ return [val for val in sources if isinstance(val, Mapping)]
+ except Exception as err:
+ logger.debug(f"读取 {cfg.server_type} PlaybackInfo 失败:{err}")
+ return []
+
+
+def _extract_emby_source_direct_url(
+ source: Mapping[str, Any], cfg: Optional[EmbyBrowseConfig] = None
+) -> Optional[str]:
+ """
+ 从单个 Emby 媒体源字典中提取 STRM HTTP(S) 直链地址。
+
+ :param source: 服务端单个 ``MediaSource`` 字典
+ :param cfg: 可选 Emby 系协议配置
+ :return: 校验通过的 HTTP(S) 直链;本地文件媒体源返回 None
+ """
+ protocol = str(source.get("Protocol") or "").strip().casefold()
+ container = str(source.get("Container") or "").strip().casefold()
+ raw_path = source.get("Path")
+ if protocol == "http" or container == "strm" or bool(source.get("IsRemote")):
+ return _sanitize_emby_strm_url(cfg, raw_path)
+ return None
+
+
+def _parse_media_sources(
+ raw: Mapping[str, Any],
+ *,
+ cfg: Optional[EmbyBrowseConfig] = None,
+ item_id: Optional[str] = None,
+) -> list[MediaServerMediaSource]:
+ """
+ 提取条目的全部多版本媒体源及其视频、音频和字幕轨道,并在 STRM 源未展开时补查直链。
:param raw: 服务端原始条目字典
+ :param cfg: 可选 Emby 系协议配置,用于在 STRM 未展开时请求 ``PlaybackInfo``
+ :param item_id: 可选媒体条目标识
:return: 统一媒体源列表
"""
sources: list[MediaServerMediaSource] = []
+ playback_by_id: Optional[dict[str, Mapping[str, Any]]] = None
+ item_path_is_strm = str(raw.get("Path") or "").strip().casefold().endswith(".strm")
for source in raw.get("MediaSources") or []:
if not isinstance(source, Mapping):
continue
source_id = str(source.get("Id") or "").strip()
if not source_id:
continue
+ direct_url = _extract_emby_source_direct_url(source, cfg)
+ source_is_strm = (
+ item_path_is_strm
+ or str(source.get("Container") or "").strip().casefold() == "strm"
+ or str(source.get("Path") or "").strip().casefold().endswith(".strm")
+ )
+ if direct_url is None and source_is_strm and cfg is not None and item_id:
+ if playback_by_id is None:
+ playback_by_id = {
+ str(pb.get("Id") or "").strip(): pb
+ for pb in _fetch_playback_sources(cfg, item_id)
+ if str(pb.get("Id") or "").strip()
+ }
+ matched_pb = playback_by_id.get(source_id) or next(iter(playback_by_id.values()), None)
+ if matched_pb is not None:
+ direct_url = _extract_emby_source_direct_url(matched_pb, cfg)
streams = [
_parse_media_stream(source_id, item)
for item in (source.get("MediaStreams") or [])
@@ -388,6 +489,7 @@ def _parse_media_sources(raw: Mapping[str, Any]) -> list[MediaServerMediaSource]
size=source.get("Size") if isinstance(source.get("Size"), int) else None,
bitrate=source.get("Bitrate") if isinstance(source.get("Bitrate"), int) else None,
duration_ms=_ticks_to_ms(source.get("RunTimeTicks")),
+ direct_url=direct_url,
streams=streams,
)
)
@@ -591,7 +693,7 @@ def emby_item_detail(cfg: EmbyBrowseConfig, item_id: str) -> Optional[MediaServe
for studio in (raw.get("Studios") or [])
if studio
]
- media_sources = _parse_media_sources(raw)
+ media_sources = _parse_media_sources(raw, cfg=cfg, item_id=base.item_id)
play_url = cfg.play_url_builder(base.item_id) if cfg.play_url_builder else None
item_type = base.item_type
season_count = raw.get("ChildCount") if item_type == "Series" and isinstance(raw.get("ChildCount"), int) else None
@@ -707,27 +809,17 @@ def emby_stream_url(
return None
selected_source_id = media_source_id
if not selected_source_id:
- try:
- pb_params: dict[str, Any] = {}
- if cfg.user_id:
- pb_params["UserId"] = cfg.user_id
- response = cfg.request_factory().get_res(
- f"{cfg.host}{cfg.api_prefix}Items/{quote(str(item_id), safe='')}/PlaybackInfo",
- _api_params(cfg, pb_params),
- )
- if response is None or response.status_code != 200:
- return None
- sources = response.json().get("MediaSources") or []
- source = next(
- (val for val in sources if isinstance(val, Mapping) and val.get("Id") and not val.get("RequiresOpening")),
- None,
- )
- if not source:
- return None
- selected_source_id = str(source["Id"])
- except Exception as err:
- logger.debug(f"读取 {cfg.server_type} PlaybackInfo 失败:{err}")
+ sources = _fetch_playback_sources(cfg, item_id)
+ source = next(
+ (val for val in sources if val.get("Id") and not val.get("RequiresOpening")),
+ None,
+ )
+ if not source:
return None
+ direct_url = _extract_emby_source_direct_url(source, cfg)
+ if direct_url:
+ return direct_url
+ selected_source_id = str(source["Id"])
route = "Audio" if (item_type or "").casefold() in {"audio", "music", MediaType.MUSIC.value.casefold()} else "Videos"
play_session_id = hashlib.sha256(
diff --git a/app/schemas/mediaserver.py b/app/schemas/mediaserver.py
index c4f20eed2..e0572cd6a 100644
--- a/app/schemas/mediaserver.py
+++ b/app/schemas/mediaserver.py
@@ -246,6 +246,10 @@ class MediaServerStreamInfo(BaseModel):
server: Optional[str] = Field(default=None, description="媒体服务器配置名称;单文件票据省略")
title: str = Field(description="媒体标题")
content_url: str = Field(description="当前 MoviePilot 实例的媒体流地址")
+ strm_url: Optional[str] = Field(
+ default=None,
+ description="STRM 条目解析出的无内嵌凭据 HTTP(S) 客户端直链地址;普通文件或需代理鉴权流时为 None",
+ )
media_type: Literal["video", "audio"] = Field(default="video", description="播放器使用的媒体类型")
artist: Optional[str] = Field(default=None, description="音乐表演者")
album: Optional[str] = Field(default=None, description="音乐专辑")
@@ -290,6 +294,10 @@ class MediaServerMediaSource(BaseModel):
size: Optional[int] = Field(default=None, description="文件字节大小")
bitrate: Optional[int] = Field(default=None, description="整体码率(bps)")
duration_ms: Optional[int] = Field(default=None, description="媒体源时长(毫秒)")
+ direct_url: Optional[str] = Field(
+ default=None,
+ description="媒体源为远端 HTTP(S) STRM 时的无凭据直链地址;本地文件源为 None",
+ )
streams: List[MediaServerMediaStream] = Field(default_factory=list, description="包含的视频、音频与字幕轨道")
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 331469db3..a03f2bee2 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -122,8 +122,8 @@ Server 使用独立 SQL 表长期保存关系,不属于识别缓存清理范
整理历史播放成功记录时使用目标文件,失败记录使用源文件;不会把媒体库目录或剧集系列作为播放对象。
`GET /api/v1/mediaserver/stream-info?itemid=...` 按已入库媒体服务器条目返回 `content_url`
-、媒体类型、所属媒体服务器 `server` 和同目录同基础文件名的外挂字幕清单;音频条目还会返回表演者、专辑和可选 LRC 歌词地址。
-响应不包含本机文件路径或 STRM 上游凭据。`POST /api/v1/mediaserver/stream-info/music` 接收
+、可选 `strm_url`、媒体类型、所属媒体服务器 `server` 和同目录同基础文件名的外挂字幕清单;音频条目还会返回表演者、专辑和可选 LRC 歌词地址。
+当条目对应无内嵌账号密码的 HTTP(S) `.strm` 媒体源时,`strm_url` 提供规范化后的客户端直链地址(供 App 优先直连播放并在不可达时回退 `content_url`);普通媒体文件及需要服务端密钥鉴权的原始流不填充 `strm_url`,响应始终不包含本机文件路径或媒体服务器密钥。`POST /api/v1/mediaserver/stream-info/music` 接收
单曲 recording 的来源、ID、标题、艺人和专辑信息,在已启用媒体服务器中执行精确匹配后返回实际单曲流清单;
专辑和艺人的元数据 ID 不可用作播放条目。
使用普通 Bearer 登录请求该清单会签发短期资源 Cookie。App 将该 Cookie 限定到当前实例的
diff --git a/tests/test_mediaserver_native_streams.py b/tests/test_mediaserver_native_streams.py
index 3521aca39..c1b6451ab 100644
--- a/tests/test_mediaserver_native_streams.py
+++ b/tests/test_mediaserver_native_streams.py
@@ -242,3 +242,72 @@ def test_plex_uses_original_part_url_instead_of_web_or_transcoding_page() -> Non
"http://media.test/library/parts/17/file.mkv?X-Plex-Token=synthetic"
)
service._plex.fetchItem.assert_called_once_with("/library/metadata/9")
+
+
+def test_emby_strm_item_exposes_direct_strm_url_without_server_key(
+ monkeypatch: pytest.MonkeyPatch, playback_client
+) -> None:
+ """
+ 验证 Emby 系 STRM 条目通过详情与 PlaybackInfo 提取客户端直链,且绝不泄露服务端 api_key。
+ """
+ from app.modules._base.embybrowse import EmbyBrowseConfig, emby_item_detail, emby_stream_url
+
+ item_payload = {
+ "Id": "strm-ep-1",
+ "Name": "云盘直链第一集",
+ "Type": "Episode",
+ "Path": "/media/tv/Show/S01E01.strm",
+ "MediaSources": [
+ {
+ "Id": "strm-src-1",
+ "Container": "strm",
+ "Protocol": "File",
+ "Path": "/media/tv/Show/S01E01.strm",
+ "MediaStreams": [],
+ }
+ ],
+ }
+ playback_payload = {
+ "MediaSources": [
+ {
+ "Id": "strm-src-1",
+ "Container": "mkv",
+ "Protocol": "Http",
+ "Path": "https://cdn.example.test/d/115/Show S01E01.mkv?sign=abc|User-Agent=Mozilla",
+ }
+ ]
+ }
+
+ def fake_get_res(url: str, _params: dict[str, object]) -> Mock:
+ resp = Mock(status_code=200)
+ resp.json.return_value = playback_payload if url.endswith("/PlaybackInfo") else item_payload
+ return resp
+
+ cfg = EmbyBrowseConfig(
+ host="http://emby.test/",
+ api_key="secret-emby-key",
+ user_id="u-1",
+ server_type="emby",
+ request_factory=lambda: Mock(get_res=Mock(side_effect=fake_get_res)),
+ )
+ detail = emby_item_detail(cfg, "strm-ep-1")
+ assert detail is not None
+ assert detail.media_sources[0].direct_url == "https://cdn.example.test/d/115/Show%20S01E01.mkv?sign=abc"
+ assert emby_stream_url(cfg, "strm-ep-1", "Episode") == "https://cdn.example.test/d/115/Show%20S01E01.mkv?sign=abc"
+
+ client, chain, _ = playback_client
+ chain.find_item.return_value = (
+ "Emby-客厅",
+ MediaServerItem(item_id="strm-ep-1", item_type="Episode", title="云盘直链第一集", path="/media/tv/Show/S01E01.strm"),
+ )
+ chain.item_detail.return_value = detail
+ chain.get_stream_url.return_value = None
+
+ manifest_response = client.get(
+ "/api/v1/mediaserver/stream-info", params={"itemid": "strm-ep-1", "server": "Emby-客厅"}
+ )
+ assert manifest_response.status_code == 200
+ manifest = manifest_response.json()["data"]
+ assert manifest["strm_url"] == "https://cdn.example.test/d/115/Show%20S01E01.mkv?sign=abc"
+ assert "secret-emby-key" not in manifest_response.text
+ assert "/media/tv/Show" not in manifest_response.text
diff --git a/tests/test_mediaserver_streaming.py b/tests/test_mediaserver_streaming.py
index a19c56bd3..4eba3fd81 100644
--- a/tests/test_mediaserver_streaming.py
+++ b/tests/test_mediaserver_streaming.py
@@ -451,6 +451,56 @@ def test_strm_rejects_unconfigured_private_targets(tmp_path: Path, monkeypatch:
assert "192.168.1.15" not in str(error.value.detail)
+def test_local_strm_ticket_returns_client_direct_url_while_proxy_blocks_unconfigured_lan(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """
+ 验证本地 STRM 文件票据向客户端返回无凭据 HTTP(S) 直链与同名字幕,同时服务端代理仍拦截未配置内网地址。
+ """
+ strm_file = tmp_path / "CloudMovie.strm"
+ strm_file.write_text("#EXTM3U\nhttp://192.168.1.15:5244/d/115/Cloud Movie.mkv\n", encoding="utf-8-sig")
+ (tmp_path / "CloudMovie.zh.srt").write_text("1\n00:00:00,000 --> 00:00:01,000\n外挂字幕\n", encoding="utf-8")
+ credential_strm = tmp_path / "Secret.strm"
+ credential_strm.write_text("http://user:secret@192.168.1.15:5244/video.mkv\n", encoding="utf-8")
+
+ monkeypatch.setattr(mediastream, "get_runtime_setting", lambda _key: "test-resource-secret")
+ monkeypatch.setattr(mediaserver, "_ensure_manage_storage_item", lambda fileitem, _user: fileitem)
+ monkeypatch.setattr(
+ mediastream.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("192.168.1.15", 5244))],
+ )
+ current_user = SimpleNamespace(id=17, is_superuser=True, permissions={})
+ app = FastAPI()
+ app.include_router(mediaserver.router, prefix="/api/v1/mediaserver")
+ app.dependency_overrides[mediaserver.get_current_active_manage_user] = lambda: current_user
+ app.dependency_overrides[mediaserver.verify_token] = lambda: TokenPayload(sub=17)
+ app.dependency_overrides[mediaserver.verify_resource_token] = lambda: TokenPayload(sub=17)
+
+ with TestClient(app) as client:
+ ticket_resp = client.post(
+ "/api/v1/mediaserver/stream-ticket",
+ json={"file": {"storage": "local", "type": "file", "name": strm_file.name, "path": str(strm_file)}},
+ )
+ item_id = ticket_resp.json()["data"]["item_id"]
+ manifest_resp = client.get("/api/v1/mediaserver/stream-info", params={"itemid": item_id})
+ manifest = manifest_resp.json()["data"]
+ proxy_resp = client.get(manifest["content_url"])
+
+ cred_ticket = client.post(
+ "/api/v1/mediaserver/stream-ticket",
+ json={"file": {"storage": "local", "type": "file", "name": credential_strm.name, "path": str(credential_strm)}},
+ ).json()["data"]["item_id"]
+ cred_manifest_resp = client.get("/api/v1/mediaserver/stream-info", params={"itemid": cred_ticket})
+
+ assert manifest_resp.status_code == 200
+ assert manifest["strm_url"] == "http://192.168.1.15:5244/d/115/Cloud%20Movie.mkv"
+ assert len(manifest["subtitles"]) == 1
+ assert proxy_resp.status_code == 501
+ assert cred_manifest_resp.status_code == 501
+ assert "secret" not in cred_manifest_resp.text
+
+
def test_configured_private_stream_host_is_allowed(monkeypatch: pytest.MonkeyPatch) -> None:
"""验证管理员配置过的私有媒体主机无需公网 DNS 也可作为 STRM 来源。"""
hosts = mediastream._configured_stream_hosts(