feat(mediaserver): support BoxSet/Collection libraries and parent_id child browsing

This commit is contained in:
jxxghp
2026-11-22 20:26:07 +08:00
parent 3c292530f6
commit a3f28835cf
6 changed files with 131 additions and 9 deletions

View File

@@ -61,6 +61,9 @@ _ITEM_TYPE_MAP = {
"电视剧": "Series",
"season": "Season",
"episode": "Episode",
"boxset": "BoxSet",
"collection": "BoxSet",
"合集": "BoxSet",
"musicalbum": "MusicAlbum",
"album": "MusicAlbum",
"audio": "Audio",
@@ -202,13 +205,15 @@ def _media_type_for_item(item_type: str) -> str:
将 Emby 条目维度映射到 MoviePilot 业务媒体类型。
:param item_type: Emby 原始 Type 字段
:return: `电影`、`电视剧` 或 `音乐`
:return: `电影`、`电视剧`、`音乐` 或 `合集`
"""
lowered = item_type.casefold()
if lowered in {"series", "season", "episode"}:
return MediaType.TV.value
if lowered in {"audio", "musicalbum", "musicartist"}:
return MediaType.MUSIC.value
if lowered == "boxset":
return "合集"
return MediaType.MOVIE.value
@@ -236,6 +241,9 @@ def _subtitle_for_browse_item(raw: Mapping[str, Any]) -> Optional[str]:
return " · ".join(parts) if parts else None
if item_type == "MusicAlbum":
return raw.get("AlbumArtist") or (str(raw.get("ProductionYear")) if raw.get("ProductionYear") else None)
if item_type == "BoxSet":
count = raw.get("ChildCount") or raw.get("RecursiveItemCount")
return f"共 {int(count)} 部" if isinstance(count, int) and count > 0 else "合集"
year = raw.get("ProductionYear")
return str(year) if year else None
@@ -447,8 +455,9 @@ def emby_browse_items(
"""
if not cfg.host or not cfg.user_id:
return None
default_types = "Movie,Series,MusicAlbum,BoxSet,Episode" if parent_id else "Movie,Series,MusicAlbum,BoxSet"
resolved_types = _ITEM_TYPE_MAP.get(str(item_type or "").strip().casefold()) or (
item_type if item_type else "Movie,Series,MusicAlbum"
item_type if item_type else default_types
)
sort_key = (sort_by or "date_created").strip().casefold()
emby_sort = _SORT_BY_MAP.get(sort_key, _SORT_BY_MAP["date_created"])
@@ -463,7 +472,7 @@ def emby_browse_items(
cfg,
{
"ParentId": parent_id or library_id,
"Recursive": "true",
"Recursive": "false" if parent_id else "true",
"IncludeItemTypes": resolved_types,
"Genres": genre,
"Years": str(year) if year else None,

View File

@@ -34,6 +34,7 @@ _PLEX_TYPE_MAP = {
"show": "Series",
"season": "Season",
"episode": "Episode",
"collection": "BoxSet",
"album": "MusicAlbum",
"track": "Audio",
}
@@ -62,12 +63,14 @@ def _plex_media_type(plex_type: str) -> str:
将 Plex 原始类型映射为 MoviePilot 业务媒体类型。
:param plex_type: Plex 条目 type 字段
:return: `电影`、`电视剧` 或 `音乐`
:return: `电影`、`电视剧`、`音乐` 或 `合集`
"""
if plex_type in {"show", "season", "episode"}:
return MediaType.TV.value
if plex_type in {"artist", "album", "track"}:
return MediaType.MUSIC.value
if plex_type == "collection":
return "合集"
return MediaType.MOVIE.value
@@ -229,6 +232,7 @@ def plex_browse_items(
token: str,
*,
library_id: Optional[str] = None,
parent_id: Optional[str] = None,
item_type: Optional[str] = None,
genre: Optional[str] = None,
year: Optional[int] = None,
@@ -240,12 +244,13 @@ def plex_browse_items(
limit: int = 30,
) -> Optional[MediaServerBrowsePage]:
"""
使用 Plex Section 搜索接口实现分页浏览、筛选、排序与关键词搜索。
使用 Plex Section 搜索接口实现分页浏览、筛选、排序与关键词搜索(含合集下钻)。
:param plex: 已连接的 PlexServer 实例
:param host: Plex 服务根地址
:param token: Plex 访问令牌
:param library_id: 目标媒体库数字标识
:param parent_id: 可选父合集(Collection)标识
:param item_type: 可选维度过滤
:param genre: 可选风格过滤
:param year: 可选年份过滤
@@ -261,6 +266,22 @@ def plex_browse_items(
return None
safe_start = max(0, int(start_index))
safe_limit = max(1, min(int(limit), 100))
if parent_id and str(parent_id).isdigit():
try:
parent_item = plex.fetchItem(int(parent_id))
if parent_item is not None and str(getattr(parent_item, "type", "")).casefold() == "collection":
children = list(parent_item.items() or [])
sliced = children[safe_start : safe_start + safe_limit]
items = [built for obj in sliced if (built := _build_plex_browse_item(host, token, obj))]
return MediaServerBrowsePage(
items=items,
total_count=len(children),
start_index=safe_start,
limit=safe_limit,
has_more=(safe_start + len(items)) < len(children),
)
except Exception as err:
logger.debug(f"读取 Plex 合集子项失败:{err}")
sort_key = (sort_by or "date_created").strip().casefold()
plex_sort = _PLEX_SORT_MAP.get(sort_key, "addedAt")
default_order = "asc" if sort_key == "name" else "desc"
@@ -283,7 +304,15 @@ def plex_browse_items(
return MediaServerBrowsePage(items=[], total_count=0, start_index=safe_start, limit=safe_limit, has_more=False)
libtype = section.TYPE
if item_type:
mapped = {"movie": "movie", "series": "show", "musicalbum": "album", "audio": "track"}.get(item_type.casefold())
mapped = {
"movie": "movie",
"series": "show",
"musicalbum": "album",
"audio": "track",
"boxset": "collection",
"collection": "collection",
"合集": "collection",
}.get(item_type.casefold())
if mapped:
libtype = mapped
results = section.search(

View File

@@ -262,6 +262,8 @@ class Emby:
library_type = MediaType.MUSIC.value
elif library.get("CollectionType") == "tvshows":
library_type = MediaType.TV.value
elif library.get("CollectionType") == "boxsets":
library_type = "合集"
else:
library_type = MediaType.UNKNOWN.value
image = (
@@ -285,7 +287,9 @@ class Emby:
type=library_type,
item_count=self.get_items_count(
library.get("Id"),
"MusicAlbum" if library_type == MediaType.MUSIC.value else "Movie,Series",
"MusicAlbum"
if library_type == MediaType.MUSIC.value
else ("BoxSet" if library_type == "合集" else "Movie,Series"),
)
if options.includes(MediaServerField.COUNTS)
else None,

View File

@@ -286,6 +286,9 @@ class Jellyfin:
f"{self._playhost or self._host}web/index.html#!/{collection_type}"
f"?topParentId={library.get('Id')}&collectionType={collection_type}"
)
elif library.get("CollectionType") == "boxsets":
library_type = "合集"
link = f"{self._playhost or self._host}web/index.html#!/library.html?topParentId={library.get('Id')}"
elif library.get("CollectionType") in ("homevideos", "livetv"):
library_type = MediaType.UNKNOWN.value
link = (
@@ -314,7 +317,11 @@ class Jellyfin:
type=library_type,
item_count=self.get_items_count(
library.get("Id"),
include_item_types="MusicAlbum" if library_type == MediaType.MUSIC.value else "Movie,Series",
include_item_types=(
"MusicAlbum"
if library_type == MediaType.MUSIC.value
else ("BoxSet" if library_type == "合集" else "Movie,Series")
),
)
if options.includes(MediaServerField.COUNTS)
else None,

View File

@@ -527,7 +527,8 @@ class Plex:
self._plex,
self._host or "",
self._token or "",
library_id=parent_id or library_id,
library_id=library_id,
parent_id=parent_id,
item_type=item_type,
genre=genre,
year=year,

View File

@@ -374,3 +374,75 @@ def test_mediaserver_browse_detail_and_server_subtitle_endpoints(monkeypatch: py
assert manifest["resume_position_ms"] == 30000
assert len(manifest["subtitles"]) == 1
assert manifest["subtitles"][0]["subtitle_id"] == "ms:src-1:3.srt"
def test_emby_and_plex_boxset_collections() -> None:
"""验证 Emby 与 Plex 合集(BoxSet / Collection)列表浏览及按 parent_id 下钻合集子作品。"""
captured_params: list[dict[str, Any]] = []
def fake_get_res(_url: str, params: dict[str, Any]) -> Any:
captured_params.append(dict(params))
if params.get("ParentId") == "box-1":
return _mock_response(
{
"Items": [
{"Id": "m-1", "Name": "哈利·波特与魔法石", "Type": "Movie", "ProductionYear": 2001}
],
"TotalRecordCount": 1,
}
)
return _mock_response(
{
"Items": [
{"Id": "box-1", "Name": "哈利·波特合集", "Type": "BoxSet", "ChildCount": 8}
],
"TotalRecordCount": 1,
}
)
http = Mock()
http.get_res.side_effect = fake_get_res
cfg = _emby_config(http)
boxset_page = emby_browse_items(
cfg,
library_id="lib-box",
item_type="BoxSet",
)
assert boxset_page is not None and len(boxset_page.items) == 1
assert boxset_page.items[0].item_type == "BoxSet"
assert boxset_page.items[0].media_type == "合集"
assert boxset_page.items[0].subtitle == "共 8 部"
assert captured_params[0]["IncludeItemTypes"] == "BoxSet"
children_page = emby_browse_items(
cfg,
parent_id="box-1",
)
assert children_page is not None and len(children_page.items) == 1
assert children_page.items[0].item_id == "m-1"
assert captured_params[1]["Recursive"] == "false"
plex_movie = SimpleNamespace(
ratingKey="501",
type="movie",
title="指环王:护戒使者",
year=2001,
thumb="/t/501",
)
plex_collection = SimpleNamespace(
ratingKey="900",
type="collection",
title="指环王合集",
childCount=3,
thumb="/t/900",
items=Mock(return_value=[plex_movie]),
)
plex = SimpleNamespace(
fetchItem=Mock(return_value=plex_collection),
library=SimpleNamespace(sections=Mock(return_value=[])),
)
plex_children = plex_browse_items(plex, "http://plex.test", "tok", parent_id="900")
assert plex_children is not None and len(plex_children.items) == 1
assert plex_children.items[0].item_id == "501"