mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-25 13:22:03 +08:00
feat(mediaserver): add unified browse, filter, 3-level detail, track selection, and progress APIs across all media servers
This commit is contained in:
@@ -52,17 +52,23 @@ from app.domain.metainfo import MetaInfo
|
||||
from app.schemas.common import ServiceClientInfo as _SchemaServiceClientInfo
|
||||
from app.schemas.context import MediaInfo as _SchemaMediaInfo
|
||||
from app.schemas.media import build_media_key, resolve_media_identity
|
||||
from app.schemas.mediaserver import MediaServerBrowseItem as _SchemaMediaServerBrowseItem
|
||||
from app.schemas.mediaserver import MediaServerBrowsePage as _SchemaMediaServerBrowsePage
|
||||
from app.schemas.mediaserver import MediaServerExistingEpisodes as _SchemaMediaServerExistingEpisodes
|
||||
from app.schemas.mediaserver import MediaServerExistsData as _SchemaMediaServerExistsData
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerQueryOptions, NotExistMediaInfo
|
||||
from app.schemas.mediaserver import MediaServerFileStreamTicket as _SchemaMediaServerFileStreamTicket
|
||||
from app.schemas.mediaserver import MediaServerFileStreamTicketRequest as _SchemaMediaServerFileStreamTicketRequest
|
||||
from app.schemas.mediaserver import MediaServerFilterOptions as _SchemaMediaServerFilterOptions
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import MediaServerItemDetail as _SchemaMediaServerItemDetail
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerMusicStreamRequest as _SchemaMediaServerMusicStreamRequest
|
||||
from app.schemas.mediaserver import MediaServerPlayData as _SchemaMediaServerPlayData
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
from app.schemas.mediaserver import MediaServerProgressReportRequest as _SchemaMediaServerProgressReportRequest
|
||||
from app.schemas.mediaserver import MediaServerStreamInfo as _SchemaMediaServerStreamInfo
|
||||
from app.schemas.mediaserver import MediaServerSubtitleTrack as _SchemaMediaServerSubtitleTrack
|
||||
from app.schemas.mediaserver import NotExistMediaInfo as _SchemaNotExistMediaInfo
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.tmdb import TmdbEpisode as _SchemaTmdbEpisode
|
||||
@@ -172,7 +178,11 @@ def _find_music_stream_item(
|
||||
|
||||
|
||||
def _playback_source(
|
||||
server: Optional[str], itemid: str, item: _SchemaMediaServerItem, path: Optional[Path]
|
||||
server: Optional[str],
|
||||
itemid: str,
|
||||
item: _SchemaMediaServerItem,
|
||||
path: Optional[Path],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> tuple[str, Path | str, set[str]]:
|
||||
"""
|
||||
优先选择媒体服务器原始流,适配器不支持时才解析本地文件或 STRM。
|
||||
@@ -183,11 +193,17 @@ def _playback_source(
|
||||
:param itemid: 已授权的条目标识或单文件票据
|
||||
:param item: 已授权的媒体服务器条目
|
||||
:param path: 可选的本机媒体文件路径
|
||||
:param media_source_id: 可选指定多版本媒体源标识
|
||||
:return: 流来源类型、文件路径或上游 URL,以及允许的已配置主机名
|
||||
:raises HTTPException: 媒体服务器不支持原始流且本地文件不可读取时
|
||||
"""
|
||||
if server:
|
||||
upstream = MediaServerChain().get_stream_url(server, itemid, item.item_type)
|
||||
chain = MediaServerChain()
|
||||
upstream = (
|
||||
chain.get_stream_url(server, itemid, item.item_type, media_source_id=media_source_id)
|
||||
if media_source_id
|
||||
else chain.get_stream_url(server, itemid, item.item_type)
|
||||
)
|
||||
if upstream:
|
||||
hosts = _configured_stream_hosts(path, include_media_servers=True)
|
||||
return "server", _validate_stream_url(upstream, configured_hosts=hosts), hosts
|
||||
@@ -198,6 +214,48 @@ def _playback_source(
|
||||
return source_type, source, hosts
|
||||
|
||||
|
||||
def _server_subtitle_tracks(
|
||||
detail: Optional[_SchemaMediaServerItemDetail],
|
||||
itemid: str,
|
||||
request: Request,
|
||||
server: Optional[str],
|
||||
media_source_id: Optional[str],
|
||||
) -> list[_SchemaMediaServerSubtitleTrack]:
|
||||
"""
|
||||
从媒体服务器详情的媒体源轨道中收集可代理的外挂字幕清单。
|
||||
|
||||
:param detail: 可选媒体服务器详情模型
|
||||
:param itemid: 条目标识
|
||||
:param request: 当前请求,用于构造本实例字幕代理地址
|
||||
:param server: 媒体服务器配置名
|
||||
:param media_source_id: 可选目标媒体源标识;省略时采用首个媒体源
|
||||
:return: 代理后的服务端外挂字幕列表
|
||||
"""
|
||||
if not detail or not detail.media_sources:
|
||||
return []
|
||||
target_source = next(
|
||||
(src for src in detail.media_sources if media_source_id and src.id == media_source_id),
|
||||
detail.media_sources[0],
|
||||
)
|
||||
tracks: list[_SchemaMediaServerSubtitleTrack] = []
|
||||
for stream in target_source.streams:
|
||||
if stream.type != "subtitle" or not stream.subtitle_id:
|
||||
continue
|
||||
query = {"itemid": itemid, "subtitle_id": stream.subtitle_id}
|
||||
if server:
|
||||
query["server"] = server
|
||||
url = str(request.url_for("stream_item_subtitle").include_query_params(**query))
|
||||
tracks.append(
|
||||
_SchemaMediaServerSubtitleTrack(
|
||||
subtitle_id=stream.subtitle_id,
|
||||
title=stream.display_title or stream.title or stream.language or "外挂字幕",
|
||||
language=stream.language,
|
||||
url=url,
|
||||
)
|
||||
)
|
||||
return tracks
|
||||
|
||||
|
||||
def _stream_item_note(item: _SchemaMediaServerItem, key: str) -> Optional[str]:
|
||||
"""
|
||||
从媒体服务器的扩展信息中读取可展示的音乐文本,忽略非文本值。
|
||||
@@ -282,60 +340,93 @@ def create_file_stream_ticket(
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
summary="搜索已配置媒体服务器中的电视剧和音乐单曲",
|
||||
summary="搜索已配置媒体服务器中的电影、电视剧和音乐单曲",
|
||||
response_model=_SchemaResponse[List[_SchemaMediaServerPlayItem]],
|
||||
)
|
||||
def search_library(
|
||||
keyword: str = Query(min_length=1, max_length=120),
|
||||
type_filter: Optional[List[str]] = Query(default=None, alias="type"),
|
||||
limit: int = Query(default=30, ge=1, le=50),
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
_: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[List[_SchemaMediaServerPlayItem]]:
|
||||
"""
|
||||
使用已配置媒体服务器自身的搜索接口查找电视剧和音乐单曲。
|
||||
使用已配置媒体服务器自身的搜索接口查找电影、电视剧和音乐单曲。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param type_filter: 可选业务类型,省略时搜索电视剧和音乐
|
||||
:param type_filter: 可选业务类型,省略时搜索电影、电视剧和音乐
|
||||
:param limit: 最多返回的结果数
|
||||
:param server: 可选媒体服务器配置名,限定单一服务器搜索
|
||||
:param library_id: 可选媒体库标识,限定单一媒体库内搜索
|
||||
:param _: 已验证的访问令牌
|
||||
:return: 带海报、服务器来源和本地播放标识的媒体列表
|
||||
"""
|
||||
allowed_types = {MediaType.TV.value, MediaType.MUSIC.value}
|
||||
allowed_types = {MediaType.MOVIE.value, MediaType.TV.value, MediaType.MUSIC.value}
|
||||
default_types = [MediaType.MOVIE.value, MediaType.TV.value, MediaType.MUSIC.value]
|
||||
selected_types = list(
|
||||
dict.fromkeys(value for value in (type_filter or [MediaType.TV.value, MediaType.MUSIC.value]) if value in allowed_types)
|
||||
dict.fromkeys(value for value in (type_filter or default_types) if value in allowed_types)
|
||||
)
|
||||
if not selected_types:
|
||||
return _SchemaResponse(success=True, data=[])
|
||||
results = MediaServerChain().search_library(keyword, selected_types, limit)
|
||||
search_kwargs: dict[str, Any] = {}
|
||||
if server:
|
||||
search_kwargs["server"] = server
|
||||
if library_id:
|
||||
search_kwargs["library_id"] = library_id
|
||||
results = MediaServerChain().search_library(keyword, selected_types, limit, **search_kwargs)
|
||||
return _SchemaResponse(success=True, data=results)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/stream-info",
|
||||
summary="查询媒体流与同名字幕",
|
||||
summary="查询媒体流与外挂字幕",
|
||||
response_model=_SchemaResponse[_SchemaMediaServerStreamInfo],
|
||||
)
|
||||
def stream_info(
|
||||
itemid: str,
|
||||
request: Request,
|
||||
server: Optional[str] = None,
|
||||
media_source_id: Optional[str] = None,
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[_SchemaMediaServerStreamInfo]:
|
||||
"""
|
||||
返回当前实例代理的媒体流地址;媒体服务器条目优先通过服务器原始流播放。
|
||||
返回当前实例代理的媒体流地址;媒体服务器条目优先通过服务器原始流播放并合并外挂字幕。
|
||||
|
||||
:param itemid: 媒体服务器条目标识
|
||||
:param request: 当前请求,用于构造本实例流地址
|
||||
:param server: 可选媒体服务器配置名,精确绑定搜索结果来源
|
||||
:param media_source_id: 可选多版本媒体源标识
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 可供原生播放器读取的媒体流清单
|
||||
"""
|
||||
server_name, item, path = _resolve_stream_item(itemid, userinfo.sub, server=server)
|
||||
_playback_source(server_name, itemid, item, path)
|
||||
_playback_source(server_name, itemid, item, path, media_source_id=media_source_id)
|
||||
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)
|
||||
resolved_source_id = media_source_id or (
|
||||
detail.media_sources[0].id if detail and detail.media_sources else None
|
||||
)
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=_SchemaMediaServerStreamInfo(
|
||||
@@ -343,11 +434,14 @@ def stream_info(
|
||||
server=server_name,
|
||||
title=item.title or (path.stem if path else itemid),
|
||||
content_url=str(content_url),
|
||||
media_type="audio" if _is_audio_item(item, path) else "video",
|
||||
media_type="audio" if is_audio else "video",
|
||||
artist=_stream_item_note(item, "artist"),
|
||||
album=_stream_item_note(item, "album"),
|
||||
subtitles=[] if not path or _is_audio_item(item, path) else _subtitle_tracks(itemid, path, request, server),
|
||||
lyrics_url=_lyrics_url(itemid, path, request, server) if path and _is_audio_item(item, path) else None,
|
||||
subtitles=subtitles,
|
||||
lyrics_url=_lyrics_url(itemid, path, request, server_name) if path and is_audio else None,
|
||||
media_source_id=resolved_source_id,
|
||||
resume_position_ms=detail.resume_position_ms if detail else None,
|
||||
duration_ms=detail.duration_ms if detail else None,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -404,6 +498,7 @@ def stream_item_content(
|
||||
itemid: str,
|
||||
request: Request,
|
||||
server: Optional[str] = None,
|
||||
media_source_id: Optional[str] = None,
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_resource_token),
|
||||
) -> StreamingResponse:
|
||||
"""
|
||||
@@ -412,11 +507,14 @@ def stream_item_content(
|
||||
:param itemid: 媒体服务器条目标识
|
||||
:param request: 当前请求,包含可选 Range 头
|
||||
:param server: 可选媒体服务器配置名,精确绑定搜索结果来源
|
||||
:param media_source_id: 可选指定的多版本媒体源标识
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 本地文件或受控 STRM 上游流式响应
|
||||
"""
|
||||
server_name, item, path = _resolve_stream_item(itemid, userinfo.sub, server=server)
|
||||
source_type, source, configured_hosts = _playback_source(server_name, itemid, item, path)
|
||||
source_type, source, configured_hosts = _playback_source(
|
||||
server_name, itemid, item, path, media_source_id=media_source_id
|
||||
)
|
||||
range_header = request.headers.get("range")
|
||||
if source_type == "server":
|
||||
try:
|
||||
@@ -450,17 +548,26 @@ def stream_item_subtitle(
|
||||
server: Optional[str] = None,
|
||||
) -> StreamingResponse:
|
||||
"""
|
||||
只读取当前影片同目录且名称匹配的字幕文件。
|
||||
读取影片同目录外挂字幕或代理媒体服务器托管的外挂字幕流。
|
||||
|
||||
:param itemid: 媒体服务器条目标识
|
||||
:param subtitle_id: 字幕文件名,不接受目录片段
|
||||
:param subtitle_id: 字幕文件名或 `ms:` 前缀的服务端字幕标识
|
||||
:param request: 当前请求,包含可选 Range 头
|
||||
:param server: 可选媒体服务器配置名,精确绑定搜索结果来源
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 字幕文件流式响应
|
||||
:raises HTTPException: 字幕不存在或不属于当前影片时返回 404
|
||||
"""
|
||||
_, _, video_path = _resolve_stream_item(itemid, userinfo.sub, server=server)
|
||||
server_name, item, video_path = _resolve_stream_item(itemid, userinfo.sub, server=server)
|
||||
if subtitle_id.startswith("ms:") and server_name:
|
||||
upstream = MediaServerChain().get_subtitle_url(
|
||||
server=server_name, item_id=item.item_id or itemid, subtitle_id=subtitle_id
|
||||
)
|
||||
if not upstream:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到媒体服务器字幕")
|
||||
hosts = _configured_stream_hosts(video_path, include_media_servers=True)
|
||||
validated = _validate_stream_url(upstream, configured_hosts=hosts)
|
||||
return _remote_stream_response(validated, request.headers.get("range"), hosts)
|
||||
if not video_path:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到同名字幕")
|
||||
subtitle_path = _find_subtitle_path(video_path, subtitle_id)
|
||||
@@ -864,6 +971,213 @@ def library(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/browse",
|
||||
summary="分页浏览媒体服务器媒体库内容",
|
||||
response_model=_SchemaResponse[_SchemaMediaServerBrowsePage],
|
||||
)
|
||||
def browse_library(
|
||||
server: str,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = Query(default=0, ge=0),
|
||||
limit: int = Query(default=30, ge=1, le=100),
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[_SchemaMediaServerBrowsePage]:
|
||||
"""
|
||||
按统一契约分页浏览媒体服务器媒体库,支持筛选、排序和库内搜索。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param library_id: 可选媒体库标识
|
||||
:param parent_id: 可选父目录标识
|
||||
:param item_type: 可选维度或媒体类型过滤
|
||||
:param genre: 可选风格过滤
|
||||
:param year: 可选年份过滤
|
||||
:param played_filter: 可选观看状态过滤(played / unplayed)
|
||||
:param sort_by: 排序字段(date_created / premiere_date / rating / name / random)
|
||||
:param sort_order: 排序方向(asc / desc)
|
||||
:param keyword: 可选关键词搜索
|
||||
:param start_index: 零基分页偏移
|
||||
:param limit: 单页数量上限
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 分页浏览结果
|
||||
"""
|
||||
page = MediaServerChain().browse_items(
|
||||
server=server,
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
username=userinfo.username,
|
||||
)
|
||||
if page is None:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="媒体服务器浏览请求失败")
|
||||
return _SchemaResponse(success=True, data=page)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/filters",
|
||||
summary="查询媒体库可用的筛选与排序选项",
|
||||
response_model=_SchemaResponse[_SchemaMediaServerFilterOptions],
|
||||
)
|
||||
def library_filters(
|
||||
server: str,
|
||||
library_id: Optional[str] = None,
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[_SchemaMediaServerFilterOptions]:
|
||||
"""
|
||||
返回指定媒体服务器媒体库支持的风格、年份和排序键列表。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param library_id: 可选媒体库标识
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 可用筛选项模型
|
||||
"""
|
||||
options = MediaServerChain().filter_options(
|
||||
server=server, library_id=library_id, username=userinfo.username
|
||||
)
|
||||
return _SchemaResponse(
|
||||
success=True,
|
||||
data=options
|
||||
or _SchemaMediaServerFilterOptions(
|
||||
sort_options=["date_created", "premiere_date", "rating", "name"]
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/detail",
|
||||
summary="查询媒体服务器单个条目完整详情",
|
||||
response_model=_SchemaResponse[_SchemaMediaServerItemDetail],
|
||||
)
|
||||
def item_detail(
|
||||
itemid: str,
|
||||
server: Optional[str] = None,
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[_SchemaMediaServerItemDetail]:
|
||||
"""
|
||||
返回电影、剧集、季、集或音乐条目的完整详情(含多版本与音轨字幕轨道)。
|
||||
|
||||
:param itemid: 媒体服务器条目标识
|
||||
:param server: 可选媒体服务器配置名称;省略时依次查询已启用服务器
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 条目完整详情
|
||||
:raises HTTPException: 未找到条目时返回 404
|
||||
"""
|
||||
chain = MediaServerChain()
|
||||
servers = [server] if server else [c.name for c in get_mediaserver_configs() if c.name]
|
||||
for server_name in servers:
|
||||
if not server_name:
|
||||
continue
|
||||
detail = chain.item_detail(server=server_name, item_id=itemid, username=userinfo.username)
|
||||
if detail:
|
||||
return _SchemaResponse(success=True, data=detail)
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到媒体服务器条目详情")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/seasons",
|
||||
summary="查询电视剧全部季卡片信息",
|
||||
response_model=_SchemaResponse[List[_SchemaMediaServerBrowseItem]],
|
||||
)
|
||||
def item_seasons(
|
||||
itemid: str,
|
||||
server: str,
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
按季号升序返回媒体服务器中指定电视剧的全部季信息。
|
||||
|
||||
:param itemid: 电视剧在媒体服务器中的条目标识
|
||||
:param server: 媒体服务器配置名称
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 季卡片列表
|
||||
"""
|
||||
seasons = MediaServerChain().seasons(
|
||||
server=server, item_id=itemid, username=userinfo.username
|
||||
)
|
||||
if seasons is None:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="媒体服务器季列表查询失败")
|
||||
return _SchemaResponse(success=True, data=seasons)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/season-episodes",
|
||||
summary="查询指定季的全部单集详情卡片",
|
||||
response_model=_SchemaResponse[List[_SchemaMediaServerBrowseItem]],
|
||||
)
|
||||
def item_season_episodes(
|
||||
itemid: str,
|
||||
server: str,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = Query(default=None, ge=0),
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
返回媒体服务器中指定电视剧单季的全部单集详情卡片(含剧照、时长、简介与播放状态)。
|
||||
|
||||
:param itemid: 电视剧或专辑条目标识
|
||||
:param server: 媒体服务器配置名称
|
||||
:param season_id: 可选季条目标识,优先级高于 season
|
||||
:param season: 可选季号,0 表示特别篇
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 单集卡片列表
|
||||
"""
|
||||
episodes = MediaServerChain().season_episodes(
|
||||
server=server,
|
||||
item_id=itemid,
|
||||
season_id=season_id,
|
||||
season=season,
|
||||
username=userinfo.username,
|
||||
)
|
||||
if episodes is None:
|
||||
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail="媒体服务器分集列表查询失败")
|
||||
return _SchemaResponse(success=True, data=episodes)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/progress",
|
||||
summary="回传原生播放器播放进度到媒体服务器",
|
||||
response_model=_SchemaResponse[None],
|
||||
)
|
||||
def report_progress(
|
||||
payload: _SchemaMediaServerProgressReportRequest,
|
||||
userinfo: _SchemaTokenPayload = Depends(verify_token),
|
||||
) -> _SchemaResponse[None]:
|
||||
"""
|
||||
将客户端当前播放位置与状态同步回源媒体服务器,更新继续观看与已看标记。
|
||||
|
||||
:param payload: 播放进度回传请求体
|
||||
:param userinfo: 已验证的访问令牌
|
||||
:return: 回传是否成功的响应包装
|
||||
"""
|
||||
reported = MediaServerChain().report_progress(
|
||||
server=payload.server,
|
||||
item_id=payload.item_id,
|
||||
position_ms=payload.position_ms,
|
||||
media_source_id=payload.media_source_id,
|
||||
duration_ms=payload.duration_ms,
|
||||
is_paused=payload.is_paused,
|
||||
state=payload.state,
|
||||
username=userinfo.username,
|
||||
)
|
||||
return _SchemaResponse(success=reported, message="" if reported else "当前媒体服务器未记录播放进度")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/clients",
|
||||
summary="查询可用媒体服务器",
|
||||
|
||||
@@ -16,8 +16,12 @@ from app.chain.base import ChainBase
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.stop import runtime_stop_state
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem,
|
||||
MediaServerBrowsePage,
|
||||
MediaServerField,
|
||||
MediaServerFilterOptions,
|
||||
MediaServerItem,
|
||||
MediaServerItemDetail,
|
||||
MediaServerLibrary,
|
||||
MediaServerPlayItem,
|
||||
MediaServerQueryOptions,
|
||||
@@ -93,18 +97,43 @@ class MediaServerChain(ChainBase):
|
||||
return libraries
|
||||
|
||||
def _sign_play_item_images(
|
||||
self, items: Optional[List[MediaServerPlayItem]]
|
||||
self, items: Optional[List[MediaServerPlayItem]], *, server: Optional[str] = None
|
||||
) -> Optional[List[MediaServerPlayItem]]:
|
||||
"""
|
||||
给媒体服务器播放条目中的图片 URL 添加代理签名,并保留提供方失败状态。
|
||||
给媒体服务器播放条目中的图片 URL 添加代理签名,并补充服务器配置名。
|
||||
|
||||
:param items: 媒体服务器播放条目列表
|
||||
:param server: 可选服务器配置名称,补全缺失的 `item.server`
|
||||
:return: 签名后的条目列表,输入为 None 时原样返回
|
||||
"""
|
||||
if items is None:
|
||||
return None
|
||||
for item in items:
|
||||
if server and not item.server:
|
||||
item.server = server
|
||||
if item.image:
|
||||
item.image = self._sign_image_url(item.image)
|
||||
return items
|
||||
|
||||
def _sign_browse_item_images(self, item: MediaServerBrowseItem) -> MediaServerBrowseItem:
|
||||
"""
|
||||
为媒体服务器浏览卡片或详情条目中的图片 URL 添加代理签名。
|
||||
|
||||
:param item: 浏览卡片或详情对象
|
||||
:return: 原地签名后的对象
|
||||
"""
|
||||
if item.poster:
|
||||
item.poster = self._sign_image_url(item.poster)
|
||||
if item.backdrop:
|
||||
item.backdrop = self._sign_image_url(item.backdrop)
|
||||
if item.thumb:
|
||||
item.thumb = self._sign_image_url(item.thumb)
|
||||
if isinstance(item, MediaServerItemDetail):
|
||||
for person in item.people:
|
||||
if person.image:
|
||||
person.image = self._sign_image_url(person.image)
|
||||
return item
|
||||
|
||||
def librarys(
|
||||
self,
|
||||
server: str,
|
||||
@@ -231,19 +260,30 @@ class MediaServerChain(ChainBase):
|
||||
keyword: str,
|
||||
types: Optional[List[str]] = None,
|
||||
limit: int = 30,
|
||||
*,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[MediaServerPlayItem]:
|
||||
"""
|
||||
在已配置媒体服务器中搜索电视剧和音乐单曲,并代理签名海报地址。
|
||||
在已配置媒体服务器中搜索电影、电视剧和音乐单曲,并代理签名海报地址。
|
||||
|
||||
:param keyword: 用户输入的搜索词
|
||||
:param types: 允许的业务类型;省略时搜索电视剧和音乐
|
||||
:param types: 允许的业务类型;省略时搜索电影、电视剧和音乐
|
||||
:param limit: 返回的最大结果数,服务端适配器也会按此限制请求
|
||||
:param server: 可选媒体服务器配置名,省略时跨所有已启用实例搜索
|
||||
:param library_id: 可选媒体库标识,仅在指定媒体库内检索
|
||||
:return: 带媒体服务器配置名的海报结果
|
||||
"""
|
||||
query = keyword.strip()
|
||||
if not query:
|
||||
return []
|
||||
selected_types = [value for value in (types or [MediaType.TV.value, MediaType.MUSIC.value]) if value]
|
||||
default_types = [MediaType.MOVIE.value, MediaType.TV.value, MediaType.MUSIC.value]
|
||||
selected_types = [value for value in (types or default_types) if value]
|
||||
extra_kwargs: Dict[str, Any] = {}
|
||||
if server:
|
||||
extra_kwargs["server"] = server
|
||||
if library_id:
|
||||
extra_kwargs["library_id"] = library_id
|
||||
items = cast(
|
||||
List[MediaServerPlayItem],
|
||||
self.run_module(
|
||||
@@ -251,6 +291,7 @@ class MediaServerChain(ChainBase):
|
||||
keyword=query,
|
||||
types=selected_types,
|
||||
limit=max(1, min(limit, 50)),
|
||||
**extra_kwargs,
|
||||
),
|
||||
)
|
||||
filtered = [item for item in items or [] if item.type in selected_types and item.item_id]
|
||||
@@ -266,6 +307,247 @@ class MediaServerChain(ChainBase):
|
||||
results.append(item)
|
||||
return results[:max(1, min(limit, 50))]
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
server: str,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[MediaServerBrowsePage]:
|
||||
"""
|
||||
分页浏览指定媒体服务器媒体库,并签名返回图片地址。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param library_id: 可选媒体库标识
|
||||
:param parent_id: 可选父目录标识
|
||||
:param item_type: 可选条目维度过滤
|
||||
:param genre: 可选风格过滤
|
||||
:param year: 可选年份过滤
|
||||
:param played_filter: 可选观看状态过滤
|
||||
:param sort_by: 排序键
|
||||
:param sort_order: 排序方向
|
||||
:param keyword: 库内关键词搜索
|
||||
:param start_index: 零基分页偏移
|
||||
:param limit: 单页数量上限
|
||||
:param username: 当前请求用户名
|
||||
:return: 分页浏览结果;服务器不可用时返回 None
|
||||
"""
|
||||
page = cast(
|
||||
Optional[MediaServerBrowsePage],
|
||||
self.run_module(
|
||||
"mediaserver_browse_items",
|
||||
server=server,
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
if page:
|
||||
for item in page.items:
|
||||
if not item.server:
|
||||
item.server = server
|
||||
self._sign_browse_item_images(item)
|
||||
return page
|
||||
|
||||
def filter_options(
|
||||
self,
|
||||
server: str,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[MediaServerFilterOptions]:
|
||||
"""
|
||||
查询指定媒体服务器媒体库可用的风格、年份与排序选项。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param library_id: 可选媒体库标识
|
||||
:param username: 当前请求用户名
|
||||
:return: 筛选项模型;不支持时返回 None
|
||||
"""
|
||||
return cast(
|
||||
Optional[MediaServerFilterOptions],
|
||||
self.run_module(
|
||||
"mediaserver_filter_options",
|
||||
server=server,
|
||||
library_id=library_id,
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
|
||||
def item_detail(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
*,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[MediaServerItemDetail]:
|
||||
"""
|
||||
获取单个媒体服务器条目的完整详情并签名图片。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体服务器条目标识
|
||||
:param username: 当前请求用户名
|
||||
:return: 完整详情模型;未找到时返回 None
|
||||
"""
|
||||
detail = cast(
|
||||
Optional[MediaServerItemDetail],
|
||||
self.run_module(
|
||||
"mediaserver_item_detail",
|
||||
server=server,
|
||||
item_id=str(item_id),
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
if detail:
|
||||
if not detail.server:
|
||||
detail.server = server
|
||||
self._sign_browse_item_images(detail)
|
||||
return detail
|
||||
|
||||
def seasons(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
*,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[MediaServerBrowseItem]]:
|
||||
"""
|
||||
查询电视剧的全部季卡片信息并签名图片。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 电视剧条目标识
|
||||
:param username: 当前请求用户名
|
||||
:return: 季卡片列表;失败时返回 None
|
||||
"""
|
||||
items = cast(
|
||||
Optional[List[MediaServerBrowseItem]],
|
||||
self.run_module(
|
||||
"mediaserver_seasons",
|
||||
server=server,
|
||||
item_id=str(item_id),
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
if items is not None:
|
||||
for item in items:
|
||||
if not item.server:
|
||||
item.server = server
|
||||
self._sign_browse_item_images(item)
|
||||
return items
|
||||
|
||||
def season_episodes(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[MediaServerBrowseItem]]:
|
||||
"""
|
||||
查询指定季的全部单集详情卡片并签名图片。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 电视剧或专辑条目标识
|
||||
:param season_id: 可选季条目标识
|
||||
:param season: 可选季号
|
||||
:param username: 当前请求用户名
|
||||
:return: 单集卡片列表;失败时返回 None
|
||||
"""
|
||||
items = cast(
|
||||
Optional[List[MediaServerBrowseItem]],
|
||||
self.run_module(
|
||||
"mediaserver_season_episodes",
|
||||
server=server,
|
||||
item_id=str(item_id),
|
||||
season_id=season_id,
|
||||
season=season,
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
if items is not None:
|
||||
for item in items:
|
||||
if not item.server:
|
||||
item.server = server
|
||||
self._sign_browse_item_images(item)
|
||||
return items
|
||||
|
||||
def get_subtitle_url(self, server: str, item_id: Union[str, int], subtitle_id: str) -> Optional[str]:
|
||||
"""
|
||||
获取媒体服务器托管的外挂或可提取字幕上游流地址。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体条目标识
|
||||
:param subtitle_id: 代理字幕标识
|
||||
:return: 上游字幕流地址;不支持或未匹配时返回 None
|
||||
"""
|
||||
return cast(
|
||||
Optional[str],
|
||||
self.run_module(
|
||||
"mediaserver_subtitle_url",
|
||||
server=server,
|
||||
item_id=str(item_id),
|
||||
subtitle_id=subtitle_id,
|
||||
),
|
||||
)
|
||||
|
||||
def report_progress(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
position_ms: int,
|
||||
*,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
将客户端播放进度回传给媒体服务器。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体条目标识
|
||||
:param position_ms: 当前播放位置(毫秒)
|
||||
:param media_source_id: 可选媒体源标识
|
||||
:param duration_ms: 可选总时长(毫秒)
|
||||
:param is_paused: 是否暂停
|
||||
:param state: 播放状态
|
||||
:param username: 当前用户名
|
||||
:return: 回传成功返回 True
|
||||
"""
|
||||
result = self.run_module(
|
||||
"mediaserver_report_progress",
|
||||
server=server,
|
||||
item_id=str(item_id),
|
||||
position_ms=position_ms,
|
||||
media_source_id=media_source_id,
|
||||
duration_ms=duration_ms,
|
||||
is_paused=is_paused,
|
||||
state=state,
|
||||
username=username,
|
||||
)
|
||||
return bool(result)
|
||||
|
||||
def episodes(
|
||||
self, server: str, item_id: Union[str, int], *, query: Optional[MediaServerQueryOptions] = None
|
||||
) -> List[MediaServerSeasonInfo]:
|
||||
@@ -298,7 +580,8 @@ class MediaServerChain(ChainBase):
|
||||
server=server,
|
||||
username=username,
|
||||
**({"query": query} if query is not None else {}),
|
||||
)
|
||||
),
|
||||
server=server,
|
||||
)
|
||||
|
||||
def latest(
|
||||
@@ -321,7 +604,8 @@ class MediaServerChain(ChainBase):
|
||||
server=server,
|
||||
username=username,
|
||||
**({"query": query} if query is not None else {}),
|
||||
)
|
||||
),
|
||||
server=server,
|
||||
)
|
||||
|
||||
def get_latest_wallpapers(
|
||||
@@ -382,20 +666,30 @@ class MediaServerChain(ChainBase):
|
||||
return cast(Optional[str], self.run_module("mediaserver_play_url", server=server, item_id=item_id))
|
||||
|
||||
def get_stream_url(
|
||||
self, server: str, item_id: Union[str, int], item_type: Optional[str]
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
获取媒体服务器支持 HTTP Range 的原始媒体流地址。
|
||||
获取媒体服务器支持 HTTP Range 的原始媒体流地址,支持指定多版本媒体源。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体服务器条目标识
|
||||
:param item_type: 媒体服务器返回的条目类型
|
||||
:param media_source_id: 可选指定的多版本媒体源标识
|
||||
:return: 原始媒体流地址;当前适配器不支持时返回 None
|
||||
"""
|
||||
extra = {"media_source_id": media_source_id} if media_source_id else {}
|
||||
return cast(
|
||||
Optional[str],
|
||||
self.run_module(
|
||||
"mediaserver_stream_url", server=server, item_id=item_id, item_type=item_type
|
||||
"mediaserver_stream_url",
|
||||
server=server,
|
||||
item_id=item_id,
|
||||
item_type=item_type,
|
||||
**extra,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
878
app/modules/_base/emby_browse.py
Normal file
878
app/modules/_base/emby_browse.py
Normal file
@@ -0,0 +1,878 @@
|
||||
"""
|
||||
Emby 系媒体服务器(Emby / Jellyfin / 极影视 / 绿联媒体库服务)共用的浏览、详情、三层剧集与播放辅助。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Mapping, Optional
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem,
|
||||
MediaServerBrowsePage,
|
||||
MediaServerFilterOptions,
|
||||
MediaServerItemDetail,
|
||||
MediaServerMediaSource,
|
||||
MediaServerMediaStream,
|
||||
MediaServerPerson,
|
||||
MediaServerPlayItem,
|
||||
)
|
||||
from app.schemas.types import MediaType
|
||||
|
||||
_TICKS_PER_MS = 10_000
|
||||
_BROWSE_FIELDS = (
|
||||
"Overview,ProductionYear,PremiereDate,CommunityRating,OfficialRating,"
|
||||
"RunTimeTicks,ChildCount,RecursiveItemCount,UserData,ImageTags,"
|
||||
"BackdropImageTags,ParentBackdropImageTags,ParentBackdropItemId,"
|
||||
"SeriesName,SeriesId,SeasonId,SeasonName,ParentIndexNumber,IndexNumber,"
|
||||
"OriginalTitle,Genres,MediaSources"
|
||||
)
|
||||
_SORT_BY_MAP = {
|
||||
"date_created": "DateCreated,SortName",
|
||||
"premiere_date": "PremiereDate,ProductionYear,SortName",
|
||||
"rating": "CommunityRating,SortName",
|
||||
"name": "SortName",
|
||||
"random": "Random",
|
||||
}
|
||||
_DEFAULT_SORT_OPTIONS = ["date_created", "premiere_date", "rating", "name", "random"]
|
||||
_SUBTITLE_EXT_MAP = {
|
||||
"subrip": "srt",
|
||||
"srt": "srt",
|
||||
"ass": "ass",
|
||||
"ssa": "ass",
|
||||
"webvtt": "vtt",
|
||||
"vtt": "vtt",
|
||||
"smi": "smi",
|
||||
"sami": "smi",
|
||||
"sub": "sub",
|
||||
}
|
||||
_SUBTITLE_ID_RE = re.compile(r"^ms:([^:]+):(\d+)\.([a-z0-9]{2,6})$", re.IGNORECASE)
|
||||
_ITEM_TYPE_MAP = {
|
||||
"movie": "Movie",
|
||||
"电影": "Movie",
|
||||
"series": "Series",
|
||||
"tv": "Series",
|
||||
"电视剧": "Series",
|
||||
"season": "Season",
|
||||
"episode": "Episode",
|
||||
"musicalbum": "MusicAlbum",
|
||||
"album": "MusicAlbum",
|
||||
"audio": "Audio",
|
||||
"music": "MusicAlbum,Audio",
|
||||
"音乐": "MusicAlbum,Audio",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EmbyBrowseConfig:
|
||||
"""
|
||||
封装 Emby 系客户端的协议差异配置,供共用浏览与详情函数调用。
|
||||
|
||||
:param host: 服务端根地址(以 `/` 结尾)
|
||||
:param api_key: API 密钥或访问令牌
|
||||
:param user_id: 当前查询的用户标识
|
||||
:param server_type: 媒体服务器类型标识(如 emby、jellyfin、zspace、ugreen)
|
||||
:param api_prefix: 接口路径前缀,Emby/ZSpace 为 `"emby/"`,Jellyfin/Ugreen 为 `""`
|
||||
:param play_host: 可选外网播放地址
|
||||
:param server_id: 可选服务器标识
|
||||
:param request_factory: 构造带鉴权请求头的 `RequestUtils` 工厂函数
|
||||
:param include_api_key_param: 是否在查询参数中附加 `api_key`
|
||||
:param image_api_key: 是否在图片 URL 中附加 `api_key` 参数
|
||||
:param play_url_builder: 可选自定义网页播放地址构造器
|
||||
"""
|
||||
|
||||
host: str
|
||||
api_key: str
|
||||
user_id: str
|
||||
server_type: str
|
||||
api_prefix: str = "emby/"
|
||||
play_host: Optional[str] = None
|
||||
server_id: Optional[str] = None
|
||||
request_factory: Callable[[], RequestUtils] = RequestUtils
|
||||
include_api_key_param: bool = True
|
||||
image_api_key: bool = True
|
||||
play_url_builder: Optional[Callable[[str], Optional[str]]] = None
|
||||
|
||||
|
||||
def _ticks_to_ms(value: Any) -> Optional[int]:
|
||||
"""
|
||||
将 Emby 的 100 纳秒时间刻度转换为毫秒。
|
||||
|
||||
:param value: 服务端原始刻度值
|
||||
:return: 非负毫秒整数,无效时返回 None
|
||||
"""
|
||||
if isinstance(value, (int, float)) and value > 0:
|
||||
return int(value // _TICKS_PER_MS)
|
||||
return None
|
||||
|
||||
|
||||
def _api_params(cfg: EmbyBrowseConfig, extra: Optional[Mapping[str, Any]] = None) -> dict[str, Any]:
|
||||
"""
|
||||
组装 Emby 系请求参数并按配置附加 `api_key`。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param extra: 业务查询参数
|
||||
:return: 过滤空值后的查询字典
|
||||
"""
|
||||
params: dict[str, Any] = {}
|
||||
if cfg.include_api_key_param and cfg.api_key:
|
||||
params["api_key"] = cfg.api_key
|
||||
for key, val in (extra or {}).items():
|
||||
if val is not None and val != "":
|
||||
params[key] = val
|
||||
return params
|
||||
|
||||
|
||||
def _image_url(
|
||||
cfg: EmbyBrowseConfig,
|
||||
item_id: Optional[str],
|
||||
image_type: str = "Primary",
|
||||
tag: Optional[str] = None,
|
||||
max_width: Optional[int] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
构造 Emby 系条目的图片内网地址(后续由 Chain 层统一签名)。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param item_id: 条目或演职员标识
|
||||
:param image_type: 图片类型,例如 Primary、Backdrop、Thumb
|
||||
:param tag: 可选图片版本标签
|
||||
:param max_width: 可选最大宽度像素,控制移动端流量
|
||||
:return: 完整图片地址,缺少标识时返回 None
|
||||
"""
|
||||
if not cfg.host or not item_id:
|
||||
return None
|
||||
query: dict[str, Any] = {}
|
||||
if tag:
|
||||
query["tag"] = tag
|
||||
if max_width:
|
||||
query["maxWidth"] = max_width
|
||||
if cfg.image_api_key and cfg.api_key:
|
||||
query["api_key"] = cfg.api_key
|
||||
base = f"{cfg.host}Items/{quote(str(item_id), safe='')}/Images/{image_type}"
|
||||
return f"{base}?{urlencode(query)}" if query else base
|
||||
|
||||
|
||||
def _resolve_images(cfg: EmbyBrowseConfig, raw: Mapping[str, Any]) -> tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""
|
||||
为任意维度条目(电影/剧集/季/集/音乐)解析最合适的 poster、backdrop 与 thumb。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param raw: 服务端原始条目字典
|
||||
:return: `(poster, backdrop, thumb)` 三元组
|
||||
"""
|
||||
item_id = str(raw.get("Id") or "")
|
||||
item_type = str(raw.get("Type") or "")
|
||||
raw_tags = raw.get("ImageTags")
|
||||
image_tags: Mapping[str, Any] = raw_tags if isinstance(raw_tags, Mapping) else {}
|
||||
primary_tag = image_tags.get("Primary")
|
||||
thumb_tag = image_tags.get("Thumb")
|
||||
backdrop_tags = raw.get("BackdropImageTags") or []
|
||||
parent_backdrop_tags = raw.get("ParentBackdropImageTags") or []
|
||||
parent_backdrop_id = raw.get("ParentBackdropItemId") or raw.get("SeriesId")
|
||||
|
||||
primary_url = _image_url(cfg, item_id, "Primary", primary_tag, max_width=600) if primary_tag else None
|
||||
thumb_url = _image_url(cfg, item_id, "Thumb", thumb_tag, max_width=800) if thumb_tag else None
|
||||
backdrop_url: Optional[str] = None
|
||||
if backdrop_tags:
|
||||
backdrop_url = _image_url(cfg, item_id, "Backdrop", str(backdrop_tags[0]), max_width=1280)
|
||||
elif parent_backdrop_id and parent_backdrop_tags:
|
||||
backdrop_url = _image_url(cfg, str(parent_backdrop_id), "Backdrop", str(parent_backdrop_tags[0]), max_width=1280)
|
||||
|
||||
series_id = str(raw.get("SeriesId") or "")
|
||||
series_tag = raw.get("SeriesPrimaryImageTag")
|
||||
series_poster = _image_url(cfg, series_id, "Primary", series_tag, max_width=600) if series_id else None
|
||||
|
||||
if item_type == "Episode":
|
||||
still = primary_url or thumb_url or backdrop_url
|
||||
return series_poster or still, backdrop_url or still, still
|
||||
if item_type == "Season":
|
||||
return primary_url or series_poster, backdrop_url, thumb_url or backdrop_url
|
||||
return primary_url or thumb_url, backdrop_url, thumb_url or backdrop_url
|
||||
|
||||
|
||||
def _media_type_for_item(item_type: str) -> str:
|
||||
"""
|
||||
将 Emby 条目维度映射到 MoviePilot 业务媒体类型。
|
||||
|
||||
:param item_type: Emby 原始 Type 字段
|
||||
: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
|
||||
return MediaType.MOVIE.value
|
||||
|
||||
|
||||
def _subtitle_for_browse_item(raw: Mapping[str, Any]) -> Optional[str]:
|
||||
"""
|
||||
生成浏览卡片与季集卡片的简洁副标题。
|
||||
|
||||
:param raw: 服务端原始条目字典
|
||||
:return: 副标题文本或 None
|
||||
"""
|
||||
item_type = str(raw.get("Type") or "")
|
||||
if item_type == "Episode":
|
||||
season_num = raw.get("ParentIndexNumber")
|
||||
ep_num = raw.get("IndexNumber")
|
||||
if season_num is not None and ep_num is not None:
|
||||
return f"S{int(season_num):02d}E{int(ep_num):02d}"
|
||||
if ep_num is not None:
|
||||
return f"第 {int(ep_num)} 集"
|
||||
return raw.get("SeriesName")
|
||||
if item_type == "Audio":
|
||||
artists = raw.get("Artists") or []
|
||||
artist = next((str(a.get("Name") if isinstance(a, Mapping) else a) for a in artists if a), None)
|
||||
album = raw.get("Album")
|
||||
parts = [part for part in (artist, album) if part]
|
||||
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)
|
||||
year = raw.get("ProductionYear")
|
||||
return str(year) if year else None
|
||||
|
||||
|
||||
def _build_browse_item(cfg: EmbyBrowseConfig, raw: Mapping[str, Any]) -> Optional[MediaServerBrowseItem]:
|
||||
"""
|
||||
将 Emby 原始 JSON 字典转换为统一 `MediaServerBrowseItem`。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param raw: 服务端原始条目字典
|
||||
:return: 统一轻量卡片模型;缺少标识或名称时返回 None
|
||||
"""
|
||||
item_id = str(raw.get("Id") or "").strip()
|
||||
title = str(raw.get("Name") or "").strip()
|
||||
if not item_id or not title:
|
||||
return None
|
||||
item_type = str(raw.get("Type") or "Movie")
|
||||
poster, backdrop, thumb = _resolve_images(cfg, raw)
|
||||
raw_user_data = raw.get("UserData")
|
||||
user_data: Mapping[str, Any] = raw_user_data if isinstance(raw_user_data, Mapping) else {}
|
||||
duration_ms = _ticks_to_ms(raw.get("RunTimeTicks"))
|
||||
resume_ms = _ticks_to_ms(user_data.get("PlaybackPositionTicks"))
|
||||
percentage = user_data.get("PlayedPercentage")
|
||||
if percentage is None and duration_ms and resume_ms:
|
||||
percentage = round(min(100.0, resume_ms / duration_ms * 100.0), 1)
|
||||
season_num = raw.get("ParentIndexNumber") if item_type == "Episode" else (
|
||||
raw.get("IndexNumber") if item_type == "Season" else None
|
||||
)
|
||||
episode_num = raw.get("IndexNumber") if item_type == "Episode" else None
|
||||
premiere = raw.get("PremiereDate")
|
||||
premiere_str = str(premiere)[:10] if isinstance(premiere, str) and premiere else None
|
||||
rating = raw.get("CommunityRating")
|
||||
return MediaServerBrowseItem(
|
||||
item_id=item_id,
|
||||
server_type=cfg.server_type,
|
||||
item_type=item_type,
|
||||
media_type=_media_type_for_item(item_type),
|
||||
title=title,
|
||||
original_title=raw.get("OriginalTitle"),
|
||||
subtitle=_subtitle_for_browse_item(raw),
|
||||
overview=raw.get("Overview"),
|
||||
year=raw.get("ProductionYear"),
|
||||
premiere_date=premiere_str,
|
||||
rating=round(float(rating), 1) if isinstance(rating, (int, float)) else None,
|
||||
duration_ms=duration_ms,
|
||||
poster=poster,
|
||||
backdrop=backdrop,
|
||||
thumb=thumb,
|
||||
series_id=str(raw.get("SeriesId")) if raw.get("SeriesId") else None,
|
||||
series_name=raw.get("SeriesName"),
|
||||
season_id=str(raw.get("SeasonId")) if raw.get("SeasonId") else None,
|
||||
season_number=int(season_num) if isinstance(season_num, int) else None,
|
||||
episode_number=int(episode_num) if isinstance(episode_num, int) else None,
|
||||
child_count=raw.get("ChildCount") if isinstance(raw.get("ChildCount"), int) else None,
|
||||
played=bool(user_data.get("Played")) if "Played" in user_data else None,
|
||||
played_percentage=float(percentage) if isinstance(percentage, (int, float)) else None,
|
||||
resume_position_ms=resume_ms,
|
||||
)
|
||||
|
||||
|
||||
def _format_stream_display(stream: Mapping[str, Any], stream_type: str) -> str:
|
||||
"""
|
||||
为轨道生成人类可读的展示标题,优先采用服务端 `DisplayTitle`。
|
||||
|
||||
:param stream: 原始 MediaStream 字典
|
||||
:param stream_type: 归一化后的轨道类型
|
||||
:return: 展示文本
|
||||
"""
|
||||
if stream.get("DisplayTitle"):
|
||||
return str(stream["DisplayTitle"])
|
||||
parts: list[str] = []
|
||||
for key in ("Title", "Language", "Codec"):
|
||||
val = stream.get(key)
|
||||
if val and str(val) not in parts:
|
||||
parts.append(str(val).upper() if key == "Codec" else str(val))
|
||||
if stream_type == "audio" and stream.get("ChannelLayout"):
|
||||
parts.append(str(stream["ChannelLayout"]))
|
||||
return " · ".join(parts) if parts else ("音轨" if stream_type == "audio" else "字幕")
|
||||
|
||||
|
||||
def _parse_media_stream(source_id: str, raw: Mapping[str, Any]) -> MediaServerMediaStream:
|
||||
"""
|
||||
将 Emby `MediaStream` 转换为统一轨道模型,并为外挂字幕生成代理标识。
|
||||
|
||||
:param source_id: 所属媒体源标识
|
||||
:param raw: 原始 MediaStream 字典
|
||||
:return: 统一轨道模型
|
||||
"""
|
||||
raw_type = str(raw.get("Type") or "").casefold()
|
||||
stream_type: Any = raw_type if raw_type in {"video", "audio", "subtitle"} else "unknown"
|
||||
index = raw.get("Index") if isinstance(raw.get("Index"), int) else None
|
||||
codec = str(raw.get("Codec") or "").lower() or None
|
||||
is_external = bool(raw.get("IsExternal"))
|
||||
subtitle_id: Optional[str] = None
|
||||
if stream_type == "subtitle" and index is not None and (is_external or raw.get("DeliveryUrl")):
|
||||
ext = _SUBTITLE_EXT_MAP.get(codec or "", "srt")
|
||||
subtitle_id = f"ms:{source_id}:{index}.{ext}"
|
||||
return MediaServerMediaStream(
|
||||
index=index,
|
||||
type=stream_type,
|
||||
codec=codec,
|
||||
language=raw.get("Language"),
|
||||
title=raw.get("Title"),
|
||||
display_title=_format_stream_display(raw, stream_type),
|
||||
is_default=bool(raw.get("IsDefault")),
|
||||
is_forced=bool(raw.get("IsForced")),
|
||||
is_external=is_external,
|
||||
subtitle_id=subtitle_id,
|
||||
channels=raw.get("Channels") if isinstance(raw.get("Channels"), int) else None,
|
||||
channel_layout=raw.get("ChannelLayout"),
|
||||
bitrate=raw.get("BitRate") if isinstance(raw.get("BitRate"), int) else None,
|
||||
width=raw.get("Width") if isinstance(raw.get("Width"), int) else None,
|
||||
height=raw.get("Height") if isinstance(raw.get("Height"), int) else None,
|
||||
video_range=raw.get("VideoRange") or raw.get("VideoRangeType"),
|
||||
)
|
||||
|
||||
|
||||
def _parse_media_sources(raw: Mapping[str, Any]) -> list[MediaServerMediaSource]:
|
||||
"""
|
||||
提取条目的全部多版本媒体源及其视频、音频和字幕轨道。
|
||||
|
||||
:param raw: 服务端原始条目字典
|
||||
:return: 统一媒体源列表
|
||||
"""
|
||||
sources: list[MediaServerMediaSource] = []
|
||||
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
|
||||
streams = [
|
||||
_parse_media_stream(source_id, item)
|
||||
for item in (source.get("MediaStreams") or [])
|
||||
if isinstance(item, Mapping)
|
||||
]
|
||||
sources.append(
|
||||
MediaServerMediaSource(
|
||||
id=source_id,
|
||||
name=source.get("Name") or source.get("Container"),
|
||||
container=source.get("Container"),
|
||||
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")),
|
||||
streams=streams,
|
||||
)
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
def _parse_people(cfg: EmbyBrowseConfig, raw: Mapping[str, Any]) -> list[MediaServerPerson]:
|
||||
"""
|
||||
解析演职员列表并构造头像地址(最多保留 24 位避免冗余体积)。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param raw: 服务端原始条目字典
|
||||
:return: 演职员列表
|
||||
"""
|
||||
people: list[MediaServerPerson] = []
|
||||
for person in (raw.get("People") or [])[:24]:
|
||||
if not isinstance(person, Mapping) or not person.get("Name"):
|
||||
continue
|
||||
person_id = str(person.get("Id") or "") or None
|
||||
tag = person.get("PrimaryImageTag")
|
||||
image = _image_url(cfg, person_id, "Primary", str(tag), max_width=300) if person_id and tag else None
|
||||
people.append(
|
||||
MediaServerPerson(
|
||||
id=person_id,
|
||||
name=str(person["Name"]),
|
||||
role=person.get("Role"),
|
||||
type=person.get("Type"),
|
||||
image=image,
|
||||
)
|
||||
)
|
||||
return people
|
||||
|
||||
|
||||
def emby_browse_items(
|
||||
cfg: EmbyBrowseConfig,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
) -> Optional[MediaServerBrowsePage]:
|
||||
"""
|
||||
在 Emby 系服务器中按分页、筛选、排序与搜索浏览媒体库条目。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param library_id: 媒体库标识
|
||||
:param parent_id: 可选父目录标识,优先级高于 library_id
|
||||
:param item_type: 维度或业务媒体类型过滤
|
||||
:param genre: 风格标签过滤
|
||||
:param year: 年份过滤
|
||||
:param played_filter: 观看状态过滤:played / unplayed
|
||||
:param sort_by: 规范化排序键
|
||||
:param sort_order: 排序方向:asc / desc
|
||||
:param keyword: 库内关键词搜索
|
||||
:param start_index: 零基分页偏移
|
||||
:param limit: 单页数量上限
|
||||
:return: 分页浏览结果;服务请求失败时返回 None
|
||||
"""
|
||||
if not cfg.host or not cfg.user_id:
|
||||
return None
|
||||
resolved_types = _ITEM_TYPE_MAP.get(str(item_type or "").strip().casefold()) or (
|
||||
item_type if item_type else "Movie,Series,MusicAlbum"
|
||||
)
|
||||
sort_key = (sort_by or "date_created").strip().casefold()
|
||||
emby_sort = _SORT_BY_MAP.get(sort_key, _SORT_BY_MAP["date_created"])
|
||||
default_order = "asc" if sort_key == "name" else "desc"
|
||||
resolved_order = "Ascending" if (sort_order or default_order).casefold() == "asc" else "Descending"
|
||||
filters = "IsPlayed" if played_filter == "played" else ("IsUnplayed" if played_filter == "unplayed" else None)
|
||||
safe_start = max(0, int(start_index))
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
|
||||
url = f"{cfg.host}{cfg.api_prefix}Users/{cfg.user_id}/Items"
|
||||
params = _api_params(
|
||||
cfg,
|
||||
{
|
||||
"ParentId": parent_id or library_id,
|
||||
"Recursive": "true",
|
||||
"IncludeItemTypes": resolved_types,
|
||||
"Genres": genre,
|
||||
"Years": str(year) if year else None,
|
||||
"Filters": filters,
|
||||
"SearchTerm": keyword.strip() if keyword and keyword.strip() else None,
|
||||
"SortBy": emby_sort,
|
||||
"SortOrder": resolved_order,
|
||||
"Fields": _BROWSE_FIELDS,
|
||||
"StartIndex": safe_start,
|
||||
"Limit": safe_limit,
|
||||
},
|
||||
)
|
||||
try:
|
||||
res = cfg.request_factory().get_res(url, params)
|
||||
if not res or res.status_code != 200:
|
||||
return None
|
||||
payload = res.json() or {}
|
||||
raw_items = payload.get("Items") or []
|
||||
items = [built for raw in raw_items if isinstance(raw, Mapping) and (built := _build_browse_item(cfg, raw))]
|
||||
total_raw = payload.get("TotalRecordCount")
|
||||
total = int(total_raw) if isinstance(total_raw, int) else (safe_start + len(items))
|
||||
return MediaServerBrowsePage(
|
||||
items=items,
|
||||
total_count=total,
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=(safe_start + len(items)) < total,
|
||||
)
|
||||
except Exception as err:
|
||||
logger.error(f"浏览 {cfg.server_type} 媒体库失败:{err}")
|
||||
return None
|
||||
|
||||
|
||||
def emby_filter_options(cfg: EmbyBrowseConfig, library_id: Optional[str] = None) -> MediaServerFilterOptions:
|
||||
"""
|
||||
获取 Emby 系指定媒体库可用的风格、年份和排序筛选选项。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param library_id: 可选媒体库标识
|
||||
:return: 可用筛选项模型
|
||||
"""
|
||||
genres: list[str] = []
|
||||
years: list[int] = []
|
||||
if cfg.host and cfg.user_id:
|
||||
url = f"{cfg.host}{cfg.api_prefix}Items/Filters"
|
||||
params = _api_params(cfg, {"UserId": cfg.user_id, "ParentId": library_id, "Recursive": "true"})
|
||||
try:
|
||||
res = cfg.request_factory().get_res(url, params)
|
||||
if res and res.status_code == 200:
|
||||
data = res.json() or {}
|
||||
genres = [str(g) for g in (data.get("Genres") or []) if g]
|
||||
years = sorted({int(y) for y in (data.get("Years") or []) if str(y).isdigit()}, reverse=True)
|
||||
except Exception as err:
|
||||
logger.debug(f"读取 {cfg.server_type} 筛选项失败:{err}")
|
||||
if not genres:
|
||||
genres = _fallback_emby_genres(cfg, library_id)
|
||||
return MediaServerFilterOptions(
|
||||
genres=genres,
|
||||
years=years,
|
||||
item_types=["Movie", "Series", "MusicAlbum"],
|
||||
sort_options=list(_DEFAULT_SORT_OPTIONS),
|
||||
)
|
||||
|
||||
|
||||
def _fallback_emby_genres(cfg: EmbyBrowseConfig, library_id: Optional[str]) -> list[str]:
|
||||
"""
|
||||
当 `Items/Filters` 未返回风格时回退读取 `Genres` 端点。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param library_id: 可选媒体库标识
|
||||
:return: 风格名称列表
|
||||
"""
|
||||
try:
|
||||
res = cfg.request_factory().get_res(
|
||||
f"{cfg.host}{cfg.api_prefix}Genres",
|
||||
_api_params(cfg, {"UserId": cfg.user_id, "ParentId": library_id, "Recursive": "true"}),
|
||||
)
|
||||
if res and res.status_code == 200:
|
||||
return [str(item["Name"]) for item in (res.json().get("Items") or []) if isinstance(item, Mapping) and item.get("Name")]
|
||||
except Exception as err:
|
||||
logger.debug(f"回退读取 {cfg.server_type} Genres 失败:{err}")
|
||||
return []
|
||||
|
||||
|
||||
def emby_item_detail(cfg: EmbyBrowseConfig, item_id: str) -> Optional[MediaServerItemDetail]:
|
||||
"""
|
||||
查询 Emby 系单个条目的完整详情,含演职员、外部 ID、多版本及音轨字幕轨道。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param item_id: 媒体服务器条目标识
|
||||
:return: 完整详情模型;条目不存在或请求失败时返回 None
|
||||
"""
|
||||
if not cfg.host or not cfg.user_id or not item_id:
|
||||
return None
|
||||
url = f"{cfg.host}{cfg.api_prefix}Users/{cfg.user_id}/Items/{quote(str(item_id), safe='')}"
|
||||
try:
|
||||
res = cfg.request_factory().get_res(url, _api_params(cfg))
|
||||
if not res or res.status_code != 200:
|
||||
return None
|
||||
raw = res.json()
|
||||
if not isinstance(raw, Mapping):
|
||||
return None
|
||||
except Exception as err:
|
||||
logger.error(f"查询 {cfg.server_type} 条目详情 {item_id} 失败:{err}")
|
||||
return None
|
||||
|
||||
base = _build_browse_item(cfg, raw)
|
||||
if not base:
|
||||
return None
|
||||
raw_provider_ids = raw.get("ProviderIds")
|
||||
provider_ids: Mapping[str, Any] = raw_provider_ids if isinstance(raw_provider_ids, Mapping) else {}
|
||||
media_source, media_id = MediaServerIdentityHelper.from_provider_ids(provider_ids)
|
||||
taglines = raw.get("Taglines") or []
|
||||
studios = [
|
||||
str(studio["Name"]) if isinstance(studio, Mapping) and studio.get("Name") else str(studio)
|
||||
for studio in (raw.get("Studios") or [])
|
||||
if studio
|
||||
]
|
||||
media_sources = _parse_media_sources(raw)
|
||||
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
|
||||
episode_count = (
|
||||
raw.get("ChildCount") if item_type == "Season" and isinstance(raw.get("ChildCount"), int)
|
||||
else (raw.get("RecursiveItemCount") if item_type == "Series" and isinstance(raw.get("RecursiveItemCount"), int) else None)
|
||||
)
|
||||
return MediaServerItemDetail(
|
||||
**base.model_dump(),
|
||||
tagline=str(taglines[0]) if taglines else None,
|
||||
official_rating=raw.get("OfficialRating"),
|
||||
genres=[str(g) for g in (raw.get("Genres") or []) if g],
|
||||
studios=studios,
|
||||
people=_parse_people(cfg, raw),
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
imdb_id=str(provider_ids.get("Imdb") or "") or None,
|
||||
tmdb_id=str(provider_ids.get("Tmdb") or "") or None,
|
||||
tvdb_id=str(provider_ids.get("Tvdb") or "") or None,
|
||||
douban_id=str(provider_ids.get("Douban") or "") or None,
|
||||
parent_id=str(raw.get("ParentId")) if raw.get("ParentId") else None,
|
||||
season_name=raw.get("SeasonName"),
|
||||
season_count=season_count,
|
||||
episode_count=episode_count,
|
||||
media_sources=media_sources,
|
||||
play_url=play_url,
|
||||
can_play=item_type in {"Movie", "Episode", "Audio"} or bool(media_sources),
|
||||
)
|
||||
|
||||
|
||||
def emby_seasons(cfg: EmbyBrowseConfig, series_id: str) -> Optional[list[MediaServerBrowseItem]]:
|
||||
"""
|
||||
查询 Emby 系电视剧的全部季卡片信息。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param series_id: 电视剧条目标识
|
||||
:return: 按季号升序排列的季列表;失败时返回 None
|
||||
"""
|
||||
if not cfg.host or not cfg.user_id or not series_id:
|
||||
return None
|
||||
url = f"{cfg.host}{cfg.api_prefix}Shows/{quote(str(series_id), safe='')}/Seasons"
|
||||
params = _api_params(cfg, {"UserId": cfg.user_id, "Fields": _BROWSE_FIELDS})
|
||||
try:
|
||||
res = cfg.request_factory().get_res(url, params)
|
||||
if not res or res.status_code != 200:
|
||||
return None
|
||||
raw_items = (res.json() or {}).get("Items") or []
|
||||
seasons = [built for raw in raw_items if isinstance(raw, Mapping) and (built := _build_browse_item(cfg, raw))]
|
||||
seasons.sort(key=lambda item: (item.season_number is None, item.season_number or 0))
|
||||
return seasons
|
||||
except Exception as err:
|
||||
logger.error(f"查询 {cfg.server_type} 剧集 {series_id} 季列表失败:{err}")
|
||||
return None
|
||||
|
||||
|
||||
def emby_season_episodes(
|
||||
cfg: EmbyBrowseConfig,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
) -> Optional[list[MediaServerBrowseItem]]:
|
||||
"""
|
||||
查询 Emby 系指定季的全部单集详情卡片(含剧照、时长、简介与播放状态)。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param series_id: 电视剧条目标识
|
||||
:param season_id: 可选季条目标识,优先级高于季号
|
||||
:param season: 可选季号(0 表示特别篇)
|
||||
:return: 按集号升序排列的单集列表;失败时返回 None
|
||||
"""
|
||||
if not cfg.host or not cfg.user_id or not series_id:
|
||||
return None
|
||||
url = f"{cfg.host}{cfg.api_prefix}Shows/{quote(str(series_id), safe='')}/Episodes"
|
||||
params = _api_params(
|
||||
cfg,
|
||||
{
|
||||
"UserId": cfg.user_id,
|
||||
"SeasonId": season_id,
|
||||
"Season": season if season_id is None and season is not None else None,
|
||||
"Fields": _BROWSE_FIELDS,
|
||||
},
|
||||
)
|
||||
try:
|
||||
res = cfg.request_factory().get_res(url, params)
|
||||
if not res or res.status_code != 200:
|
||||
return None
|
||||
raw_items = (res.json() or {}).get("Items") or []
|
||||
episodes = [built for raw in raw_items if isinstance(raw, Mapping) and (built := _build_browse_item(cfg, raw))]
|
||||
episodes.sort(key=lambda item: (item.season_number or 0, item.episode_number or 0))
|
||||
return episodes
|
||||
except Exception as err:
|
||||
logger.error(f"查询 {cfg.server_type} 剧集 {series_id} 分集列表失败:{err}")
|
||||
return None
|
||||
|
||||
|
||||
def emby_stream_url(
|
||||
cfg: EmbyBrowseConfig,
|
||||
item_id: str,
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
为 Emby 系服务器构造支持 HTTP Range 的原始静态媒体流地址,支持指定多版本 `media_source_id`。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param item_id: 媒体条目标识
|
||||
:param item_type: 媒体类型,用于选择 Audio 或 Videos 端点
|
||||
:param media_source_id: 可选指定媒体源标识
|
||||
:return: 上游原始媒体流地址;不可用时返回 None
|
||||
"""
|
||||
if not cfg.host or not cfg.api_key or not item_id:
|
||||
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}")
|
||||
return None
|
||||
|
||||
route = "Audio" if (item_type or "").casefold() in {"audio", "music", MediaType.MUSIC.value.casefold()} else "Videos"
|
||||
play_session_id = hashlib.sha256(
|
||||
f"{cfg.host}:{cfg.user_id}:{item_id}".encode("utf-8")
|
||||
if not media_source_id
|
||||
else f"{cfg.host}:{cfg.user_id}:{item_id}:{selected_source_id}".encode("utf-8")
|
||||
).hexdigest()[:32]
|
||||
query = urlencode({
|
||||
"static": "true",
|
||||
"MediaSourceId": selected_source_id,
|
||||
"PlaySessionId": play_session_id,
|
||||
"api_key": cfg.api_key,
|
||||
})
|
||||
return f"{cfg.host}{cfg.api_prefix}{route}/{quote(str(item_id), safe='')}/stream?{query}"
|
||||
|
||||
|
||||
def emby_subtitle_url(cfg: EmbyBrowseConfig, item_id: str, subtitle_id: str) -> Optional[str]:
|
||||
"""
|
||||
将代理字幕标识 `ms:<media_source_id>:<index>.<ext>` 解析为 Emby 系上游字幕下载流地址。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param item_id: 媒体条目标识
|
||||
:param subtitle_id: 代理字幕标识
|
||||
:return: 上游字幕下载地址;格式不匹配或未配置时返回 None
|
||||
"""
|
||||
if not cfg.host or not cfg.api_key or not item_id:
|
||||
return None
|
||||
match = _SUBTITLE_ID_RE.match(subtitle_id.strip())
|
||||
if not match:
|
||||
return None
|
||||
source_id, stream_index, ext = match.groups()
|
||||
query = urlencode({"api_key": cfg.api_key})
|
||||
return (
|
||||
f"{cfg.host}{cfg.api_prefix}Videos/{quote(str(item_id), safe='')}/"
|
||||
f"{quote(source_id, safe='')}/Subtitles/{stream_index}/Stream.{ext}?{query}"
|
||||
)
|
||||
|
||||
|
||||
def emby_report_progress(
|
||||
cfg: EmbyBrowseConfig,
|
||||
item_id: str,
|
||||
position_ms: int,
|
||||
*,
|
||||
media_source_id: Optional[str] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
) -> bool:
|
||||
"""
|
||||
将客户端播放进度回传给 Emby 系服务器,同步继续观看和已看状态。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param item_id: 正在播放的条目标识
|
||||
:param position_ms: 当前播放位置(毫秒)
|
||||
:param media_source_id: 可选媒体源标识
|
||||
:param is_paused: 是否处于暂停状态
|
||||
:param state: 事件状态:playing / paused / stopped
|
||||
:return: 服务端接收成功时返回 True
|
||||
"""
|
||||
if not cfg.host or not cfg.api_key or not item_id:
|
||||
return False
|
||||
endpoint = "Sessions/Playing/Stopped" if state == "stopped" else "Sessions/Playing/Progress"
|
||||
play_session_id = hashlib.sha256(f"{cfg.host}:{cfg.user_id}:{item_id}".encode("utf-8")).hexdigest()[:32]
|
||||
payload: dict[str, Any] = {
|
||||
"ItemId": str(item_id),
|
||||
"PositionTicks": max(0, int(position_ms)) * _TICKS_PER_MS,
|
||||
"IsPaused": bool(is_paused or state == "paused"),
|
||||
"PlayMethod": "DirectPlay",
|
||||
"PlaySessionId": play_session_id,
|
||||
}
|
||||
if media_source_id:
|
||||
payload["MediaSourceId"] = media_source_id
|
||||
url = f"{cfg.host}{cfg.api_prefix}{endpoint}"
|
||||
try:
|
||||
res = cfg.request_factory().post_res(
|
||||
url=url,
|
||||
params=_api_params(cfg),
|
||||
json=payload,
|
||||
)
|
||||
return bool(res and res.status_code in {200, 204})
|
||||
except Exception as err:
|
||||
logger.debug(f"回传 {cfg.server_type} 播放进度失败:{err}")
|
||||
return False
|
||||
|
||||
|
||||
def emby_search_library(
|
||||
cfg: EmbyBrowseConfig,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> list[MediaServerPlayItem]:
|
||||
"""
|
||||
在 Emby 系服务器中搜索电影、电视剧与音乐单曲。
|
||||
|
||||
:param cfg: Emby 系协议配置
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 允许的业务类型列表(电影、电视剧、音乐)
|
||||
:param limit: 返回条数上限
|
||||
:param library_id: 可选媒体库标识限定
|
||||
:return: 统一搜索结果列表
|
||||
"""
|
||||
if not cfg.host or not cfg.user_id or not keyword.strip():
|
||||
return []
|
||||
server_types: list[str] = []
|
||||
if MediaType.MOVIE.value in types:
|
||||
server_types.append("Movie")
|
||||
if MediaType.TV.value in types:
|
||||
server_types.append("Series")
|
||||
if MediaType.MUSIC.value in types:
|
||||
server_types.append("Audio")
|
||||
if not server_types:
|
||||
return []
|
||||
url = f"{cfg.host}{cfg.api_prefix}Users/{cfg.user_id}/Items"
|
||||
params = _api_params(
|
||||
cfg,
|
||||
{
|
||||
"ParentId": library_id,
|
||||
"IncludeItemTypes": ",".join(server_types),
|
||||
"Fields": "ProductionYear,Album,Artists,AlbumArtist,ImageTags",
|
||||
"Recursive": "true",
|
||||
"SearchTerm": keyword.strip(),
|
||||
"StartIndex": 0,
|
||||
"Limit": max(1, min(limit, 50)),
|
||||
},
|
||||
)
|
||||
try:
|
||||
response = cfg.request_factory().get_res(url, params)
|
||||
if not response or response.status_code != 200:
|
||||
return []
|
||||
results: list[MediaServerPlayItem] = []
|
||||
for item in response.json().get("Items") or []:
|
||||
if not isinstance(item, Mapping):
|
||||
continue
|
||||
item_id = str(item.get("Id") or "")
|
||||
title = str(item.get("Name") or "")
|
||||
raw_type = str(item.get("Type") or "")
|
||||
if not item_id or not title or raw_type not in server_types:
|
||||
continue
|
||||
image_tag = (item.get("ImageTags") or {}).get("Primary") if isinstance(item.get("ImageTags"), Mapping) else None
|
||||
results.append(
|
||||
MediaServerPlayItem(
|
||||
id=item_id,
|
||||
item_id=item_id,
|
||||
title=title,
|
||||
subtitle=_subtitle_for_browse_item(item),
|
||||
year=item.get("ProductionYear"),
|
||||
type=_media_type_for_item(raw_type),
|
||||
image=_image_url(cfg, item_id, "Primary", image_tag, max_width=600),
|
||||
server_type=cfg.server_type,
|
||||
)
|
||||
)
|
||||
if len(results) >= limit:
|
||||
break
|
||||
return results
|
||||
except Exception as err:
|
||||
logger.debug(f"搜索 {cfg.server_type} 媒体库失败:{err}")
|
||||
return []
|
||||
@@ -15,7 +15,11 @@ from app.runtime.log import logger
|
||||
from app.schemas.event import AuthCredentials as _SchemaAuthCredentials
|
||||
from app.schemas.event import AuthInterceptCredentials as _SchemaAuthInterceptCredentials
|
||||
from app.schemas.mediaserver import ExistMediaInfo as _SchemaExistMediaInfo
|
||||
from app.schemas.mediaserver import MediaServerBrowseItem as _SchemaMediaServerBrowseItem
|
||||
from app.schemas.mediaserver import MediaServerBrowsePage as _SchemaMediaServerBrowsePage
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerQueryOptions
|
||||
from app.schemas.mediaserver import MediaServerFilterOptions as _SchemaMediaServerFilterOptions
|
||||
from app.schemas.mediaserver import MediaServerItemDetail as _SchemaMediaServerItemDetail
|
||||
from app.schemas.types import ChainEventType, MediaType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -185,17 +189,256 @@ class _MediaServerModuleBase(_ModuleBase, _MediaServerBase[TService]):
|
||||
_query_options_supported: bool = False
|
||||
|
||||
def mediaserver_stream_url(
|
||||
self, server: str, item_id: Union[str, int], item_type: Optional[str]
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
为没有声明原始流接口的媒体服务器适配器提供兼容性空结果。
|
||||
委托客户端获取支持 Range 的原始媒体流地址;未实现时返回 None。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体服务器条目标识
|
||||
:param item_type: 媒体服务器返回的条目类型
|
||||
:return: 当前适配器不支持原始文件流时返回 None
|
||||
:param media_source_id: 可选指定的多版本媒体源标识
|
||||
:return: 上游媒体流地址;当前适配器不支持时返回 None
|
||||
"""
|
||||
return None
|
||||
server_obj = self.get_instance(server)
|
||||
getter = getattr(server_obj, "get_stream_url", None)
|
||||
if not callable(getter):
|
||||
return None
|
||||
try:
|
||||
if media_source_id:
|
||||
return cast(Optional[str], getter(str(item_id), item_type, media_source_id=media_source_id))
|
||||
return cast(Optional[str], getter(str(item_id), item_type))
|
||||
except TypeError:
|
||||
return cast(Optional[str], getter(str(item_id), item_type))
|
||||
|
||||
def mediaserver_subtitle_url(
|
||||
self, server: str, item_id: Union[str, int], subtitle_id: str
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
委托客户端解析服务端托管字幕的原始下载流地址。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体服务器条目标识
|
||||
:param subtitle_id: 代理字幕标识
|
||||
:return: 上游字幕流地址;不支持或未匹配时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
getter = getattr(server_obj, "get_subtitle_url", None)
|
||||
if not callable(getter):
|
||||
return None
|
||||
return cast(Optional[str], getter(str(item_id), subtitle_id))
|
||||
|
||||
def mediaserver_browse_items(
|
||||
self,
|
||||
server: str,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""
|
||||
分页浏览指定媒体服务器的媒体库内容并支持筛选、排序和搜索。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param library_id: 可选媒体库标识
|
||||
:param parent_id: 可选父目录标识
|
||||
:param item_type: 可选条目类型过滤
|
||||
:param genre: 可选风格过滤
|
||||
:param year: 可选年份过滤
|
||||
:param played_filter: 可选观看状态过滤
|
||||
:param sort_by: 可选排序键
|
||||
:param sort_order: 可选排序方向
|
||||
:param keyword: 可选关键词搜索
|
||||
:param start_index: 零基分页偏移
|
||||
:param limit: 单页数量上限
|
||||
:param username: 可选用户名
|
||||
:return: 分页浏览模型;实例不存在或不支持时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
browser = getattr(server_obj, "browse_items", None)
|
||||
if not callable(browser):
|
||||
return None
|
||||
page = cast(
|
||||
Optional[_SchemaMediaServerBrowsePage],
|
||||
browser(
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
if page:
|
||||
for item in page.items:
|
||||
item.server = server
|
||||
return page
|
||||
|
||||
def mediaserver_filter_options(
|
||||
self,
|
||||
server: str,
|
||||
library_id: Optional[str] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerFilterOptions]:
|
||||
"""
|
||||
读取指定媒体库可用的风格、年份与排序筛选选项。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param library_id: 可选媒体库标识
|
||||
:param username: 可选用户名
|
||||
:return: 筛选项模型;实例不存在或不支持时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
getter = getattr(server_obj, "get_filter_options", None)
|
||||
if not callable(getter):
|
||||
return None
|
||||
return cast(
|
||||
Optional[_SchemaMediaServerFilterOptions],
|
||||
getter(library_id=library_id, username=username),
|
||||
)
|
||||
|
||||
def mediaserver_item_detail(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""
|
||||
读取媒体服务器单个条目的完整详情(含多版本及音轨字幕轨道)。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 媒体服务器条目标识
|
||||
:param username: 可选用户名
|
||||
:return: 详情模型;实例或条目不存在时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
getter = getattr(server_obj, "get_item_detail", None)
|
||||
if not callable(getter):
|
||||
return None
|
||||
detail = cast(
|
||||
Optional[_SchemaMediaServerItemDetail],
|
||||
getter(str(item_id), username=username),
|
||||
)
|
||||
if detail:
|
||||
detail.server = server
|
||||
return detail
|
||||
|
||||
def mediaserver_seasons(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[list[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
读取电视剧的全部季卡片信息。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 电视剧条目标识
|
||||
:param username: 可选用户名
|
||||
:return: 季卡片列表;实例不存在或不支持时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
getter = getattr(server_obj, "get_seasons", None)
|
||||
if not callable(getter):
|
||||
return None
|
||||
seasons = cast(
|
||||
Optional[list[_SchemaMediaServerBrowseItem]],
|
||||
getter(str(item_id), username=username),
|
||||
)
|
||||
if seasons is not None:
|
||||
for season_item in seasons:
|
||||
season_item.server = server
|
||||
return seasons
|
||||
|
||||
def mediaserver_season_episodes(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[list[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
读取电视剧指定季的全部单集详情卡片。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 电视剧条目标识
|
||||
:param season_id: 可选季条目标识
|
||||
:param season: 可选季号
|
||||
:param username: 可选用户名
|
||||
:return: 单集卡片列表;实例不存在或不支持时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
getter = getattr(server_obj, "get_season_episodes", None)
|
||||
if not callable(getter):
|
||||
return None
|
||||
episodes = cast(
|
||||
Optional[list[_SchemaMediaServerBrowseItem]],
|
||||
getter(str(item_id), season_id=season_id, season=season, username=username),
|
||||
)
|
||||
if episodes is not None:
|
||||
for ep in episodes:
|
||||
ep.server = server
|
||||
return episodes
|
||||
|
||||
def mediaserver_report_progress(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
position_ms: int,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[bool]:
|
||||
"""
|
||||
向媒体服务器回传客户端的播放进度状态。
|
||||
|
||||
:param server: 媒体服务器配置名称
|
||||
:param item_id: 条目标识
|
||||
:param position_ms: 当前播放位置(毫秒)
|
||||
:param media_source_id: 可选媒体源标识
|
||||
:param duration_ms: 可选总时长(毫秒)
|
||||
:param is_paused: 是否暂停
|
||||
:param state: 事件状态:playing / paused / stopped
|
||||
:param username: 可选用户名
|
||||
:return: 服务端回传成功返回 True;不支持时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
reporter = getattr(server_obj, "report_progress", None)
|
||||
if not callable(reporter):
|
||||
return None
|
||||
return cast(
|
||||
bool,
|
||||
reporter(
|
||||
str(item_id),
|
||||
position_ms=position_ms,
|
||||
media_source_id=media_source_id,
|
||||
duration_ms=duration_ms,
|
||||
is_paused=is_paused,
|
||||
state=state,
|
||||
username=username,
|
||||
),
|
||||
)
|
||||
|
||||
def user_authenticate(
|
||||
self,
|
||||
|
||||
536
app/modules/_base/plex_browse.py
Normal file
536
app/modules/_base/plex_browse.py
Normal file
@@ -0,0 +1,536 @@
|
||||
"""
|
||||
Plex 媒体服务器浏览、详情、三层剧集、音轨字幕轨道与播放进度辅助实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Callable, Optional
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from app.application.mediaserver import MediaServerIdentityHelper
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem,
|
||||
MediaServerBrowsePage,
|
||||
MediaServerFilterOptions,
|
||||
MediaServerItemDetail,
|
||||
MediaServerMediaSource,
|
||||
MediaServerMediaStream,
|
||||
MediaServerPerson,
|
||||
)
|
||||
from app.schemas.types import MediaType
|
||||
|
||||
_PLEX_SORT_MAP = {
|
||||
"date_created": "addedAt",
|
||||
"premiere_date": "originallyAvailableAt",
|
||||
"rating": "rating",
|
||||
"name": "titleSort",
|
||||
"random": "random",
|
||||
}
|
||||
_PLEX_TYPE_MAP = {
|
||||
"movie": "Movie",
|
||||
"show": "Series",
|
||||
"season": "Season",
|
||||
"episode": "Episode",
|
||||
"album": "MusicAlbum",
|
||||
"track": "Audio",
|
||||
}
|
||||
_PLEX_SUBTITLE_ID_RE = re.compile(r"^ms:plex:(\d+)\.([a-z0-9]{2,6})$", re.IGNORECASE)
|
||||
_PLEX_SUBTITLE_EXT_MAP = {"srt": "srt", "ass": "ass", "ssa": "ass", "vtt": "vtt", "smi": "smi"}
|
||||
|
||||
|
||||
def _plex_image_url(host: str, token: str, path: Optional[str]) -> Optional[str]:
|
||||
"""
|
||||
将 Plex 相对或绝对图片路径规范化为带令牌的内网图片地址。
|
||||
|
||||
:param host: Plex 服务根地址
|
||||
:param token: Plex 访问令牌
|
||||
:param path: 条目 thumb 或 art 字段
|
||||
:return: 可由 MoviePilot 代理签名的图片地址
|
||||
"""
|
||||
if not path or not host or not token:
|
||||
return None
|
||||
if str(path).startswith(("http://", "https://")):
|
||||
return str(path)
|
||||
return UrlUtils.combine_url(host=host, path=str(path), query={"X-Plex-Token": token})
|
||||
|
||||
|
||||
def _plex_media_type(plex_type: str) -> str:
|
||||
"""
|
||||
将 Plex 原始类型映射为 MoviePilot 业务媒体类型。
|
||||
|
||||
:param plex_type: Plex 条目 type 字段
|
||||
:return: `电影`、`电视剧` 或 `音乐`
|
||||
"""
|
||||
if plex_type in {"show", "season", "episode"}:
|
||||
return MediaType.TV.value
|
||||
if plex_type in {"artist", "album", "track"}:
|
||||
return MediaType.MUSIC.value
|
||||
return MediaType.MOVIE.value
|
||||
|
||||
|
||||
def _plex_item_id(item: Any) -> str:
|
||||
"""
|
||||
读取 Plex 条目的稳定标识,优先使用 ratingKey。
|
||||
|
||||
:param item: Plex SDK 条目对象
|
||||
:return: 字符串标识
|
||||
"""
|
||||
rating_key = getattr(item, "ratingKey", None)
|
||||
if rating_key is not None:
|
||||
return str(rating_key)
|
||||
return str(getattr(item, "key", "") or "")
|
||||
|
||||
|
||||
def _build_plex_browse_item(host: str, token: str, item: Any) -> Optional[MediaServerBrowseItem]:
|
||||
"""
|
||||
将 Plex SDK 条目转换为统一 `MediaServerBrowseItem`。
|
||||
|
||||
:param host: Plex 服务根地址
|
||||
:param token: Plex 访问令牌
|
||||
:param item: Plex SDK 条目对象
|
||||
:return: 轻量卡片模型;缺少标识或名称时返回 None
|
||||
"""
|
||||
item_id = _plex_item_id(item)
|
||||
title = str(getattr(item, "title", "") or "").strip()
|
||||
if not item_id or not title:
|
||||
return None
|
||||
raw_type = str(getattr(item, "type", "") or "movie").casefold()
|
||||
norm_type = _PLEX_TYPE_MAP.get(raw_type, "Movie")
|
||||
thumb_url = _plex_image_url(host, token, getattr(item, "thumb", None))
|
||||
art_url = _plex_image_url(host, token, getattr(item, "art", None))
|
||||
parent_thumb = _plex_image_url(host, token, getattr(item, "parentThumb", None))
|
||||
grandparent_thumb = _plex_image_url(host, token, getattr(item, "grandparentThumb", None))
|
||||
duration_ms = getattr(item, "duration", None)
|
||||
view_offset = getattr(item, "viewOffset", None) or 0
|
||||
percentage = round(min(100.0, view_offset / duration_ms * 100.0), 1) if duration_ms and view_offset else None
|
||||
season_num = getattr(item, "parentIndex", None) if raw_type == "episode" else (
|
||||
getattr(item, "index", None) if raw_type == "season" else None
|
||||
)
|
||||
ep_num = getattr(item, "index", None) if raw_type == "episode" else None
|
||||
subtitle: Optional[str] = None
|
||||
if raw_type == "episode" and season_num is not None and ep_num is not None:
|
||||
subtitle = f"S{int(season_num):02d}E{int(ep_num):02d}"
|
||||
elif raw_type == "track":
|
||||
parts = [p for p in (getattr(item, "grandparentTitle", None), getattr(item, "parentTitle", None)) if p]
|
||||
subtitle = " · ".join(str(p) for p in parts) if parts else None
|
||||
elif getattr(item, "year", None):
|
||||
subtitle = str(item.year)
|
||||
avail = getattr(item, "originallyAvailableAt", None)
|
||||
premiere = avail.strftime("%Y-%m-%d") if avail is not None and hasattr(avail, "strftime") else None
|
||||
rating = getattr(item, "audienceRating", None) or getattr(item, "rating", None)
|
||||
poster = (grandparent_thumb or parent_thumb or thumb_url) if raw_type == "episode" else (thumb_url or grandparent_thumb)
|
||||
still = thumb_url if raw_type == "episode" else art_url
|
||||
return MediaServerBrowseItem(
|
||||
item_id=item_id,
|
||||
server_type="plex",
|
||||
item_type=norm_type,
|
||||
media_type=_plex_media_type(raw_type),
|
||||
title=title,
|
||||
original_title=getattr(item, "originalTitle", None),
|
||||
subtitle=subtitle,
|
||||
overview=getattr(item, "summary", None),
|
||||
year=getattr(item, "year", None),
|
||||
premiere_date=premiere,
|
||||
rating=round(float(rating), 1) if isinstance(rating, (int, float)) else None,
|
||||
duration_ms=int(duration_ms) if isinstance(duration_ms, (int, float)) and duration_ms > 0 else None,
|
||||
poster=poster,
|
||||
backdrop=art_url or still,
|
||||
thumb=still or art_url,
|
||||
series_id=str(getattr(item, "grandparentRatingKey", None) or getattr(item, "parentRatingKey", "") or "") or None
|
||||
if raw_type in {"episode", "season"}
|
||||
else None,
|
||||
series_name=getattr(item, "grandparentTitle", None) if raw_type == "episode" else (
|
||||
getattr(item, "parentTitle", None) if raw_type == "season" else None
|
||||
),
|
||||
season_id=str(getattr(item, "parentRatingKey", "") or "") or None if raw_type == "episode" else None,
|
||||
season_number=int(season_num) if isinstance(season_num, int) else None,
|
||||
episode_number=int(ep_num) if isinstance(ep_num, int) else None,
|
||||
child_count=getattr(item, "childCount", None) or getattr(item, "leafCount", None),
|
||||
played=bool(getattr(item, "isPlayed", False)),
|
||||
played_percentage=percentage,
|
||||
resume_position_ms=int(view_offset) if view_offset > 0 else None,
|
||||
)
|
||||
|
||||
|
||||
def _parse_plex_stream(stream: Any) -> MediaServerMediaStream:
|
||||
"""
|
||||
将 Plex 轨道对象转换为统一 `MediaServerMediaStream`。
|
||||
|
||||
:param stream: Plex SDK 轨道对象
|
||||
:return: 统一轨道模型
|
||||
"""
|
||||
raw_type = getattr(stream, "streamType", 0)
|
||||
stream_type: Any = {1: "video", 2: "audio", 3: "subtitle"}.get(raw_type, "unknown")
|
||||
codec = str(getattr(stream, "codec", "") or "").lower() or None
|
||||
is_external = bool(stream_type == "subtitle" and getattr(stream, "key", None))
|
||||
subtitle_id: Optional[str] = None
|
||||
stream_id = getattr(stream, "id", None)
|
||||
if is_external and stream_id is not None:
|
||||
ext = _PLEX_SUBTITLE_EXT_MAP.get(codec or "", "srt")
|
||||
subtitle_id = f"ms:plex:{stream_id}.{ext}"
|
||||
display = getattr(stream, "extendedDisplayTitle", None) or getattr(stream, "displayTitle", None)
|
||||
return MediaServerMediaStream(
|
||||
index=getattr(stream, "index", None) if isinstance(getattr(stream, "index", None), int) else None,
|
||||
type=stream_type,
|
||||
codec=codec,
|
||||
language=getattr(stream, "languageCode", None) or getattr(stream, "language", None),
|
||||
title=getattr(stream, "title", None),
|
||||
display_title=str(display) if display else (codec.upper() if codec else "轨道"),
|
||||
is_default=bool(getattr(stream, "default", False) or getattr(stream, "selected", False)),
|
||||
is_forced=bool(getattr(stream, "forced", False)),
|
||||
is_external=is_external,
|
||||
subtitle_id=subtitle_id,
|
||||
channels=getattr(stream, "channels", None) if isinstance(getattr(stream, "channels", None), int) else None,
|
||||
channel_layout=getattr(stream, "audioChannelLayout", None),
|
||||
bitrate=getattr(stream, "bitrate", None) if isinstance(getattr(stream, "bitrate", None), int) else None,
|
||||
width=getattr(stream, "width", None) if isinstance(getattr(stream, "width", None), int) else None,
|
||||
height=getattr(stream, "height", None) if isinstance(getattr(stream, "height", None), int) else None,
|
||||
)
|
||||
|
||||
|
||||
def _parse_plex_sources(item: Any) -> list[MediaServerMediaSource]:
|
||||
"""
|
||||
从 Plex 条目的 media/parts 提取多版本及全部音视频和字幕轨道。
|
||||
|
||||
:param item: Plex SDK 媒体对象
|
||||
:return: 统一媒体源列表
|
||||
"""
|
||||
sources: list[MediaServerMediaSource] = []
|
||||
for media in getattr(item, "media", None) or []:
|
||||
parts = getattr(media, "parts", None) or []
|
||||
for part in parts:
|
||||
part_id = str(getattr(part, "id", "") or "")
|
||||
if not part_id:
|
||||
continue
|
||||
streams = [_parse_plex_stream(s) for s in (getattr(part, "streams", None) or [])]
|
||||
res_label = getattr(media, "videoResolution", None)
|
||||
container = getattr(part, "container", None) or getattr(media, "container", None)
|
||||
name_parts = [str(p).upper() for p in (res_label, container) if p]
|
||||
sources.append(
|
||||
MediaServerMediaSource(
|
||||
id=part_id,
|
||||
name=" · ".join(name_parts) or f"版本 {part_id}",
|
||||
container=container,
|
||||
size=getattr(part, "size", None) if isinstance(getattr(part, "size", None), int) else None,
|
||||
bitrate=getattr(media, "bitrate", None) if isinstance(getattr(media, "bitrate", None), int) else None,
|
||||
duration_ms=getattr(part, "duration", None) or getattr(media, "duration", None),
|
||||
streams=streams,
|
||||
)
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
def plex_browse_items(
|
||||
plex: Any,
|
||||
host: str,
|
||||
token: str,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
) -> Optional[MediaServerBrowsePage]:
|
||||
"""
|
||||
使用 Plex Section 搜索接口实现分页浏览、筛选、排序与关键词搜索。
|
||||
|
||||
:param plex: 已连接的 PlexServer 实例
|
||||
:param host: Plex 服务根地址
|
||||
:param token: Plex 访问令牌
|
||||
:param library_id: 目标媒体库数字标识
|
||||
:param item_type: 可选维度过滤
|
||||
:param genre: 可选风格过滤
|
||||
:param year: 可选年份过滤
|
||||
:param played_filter: 观看状态过滤:played / unplayed
|
||||
:param sort_by: 规范化排序键
|
||||
:param sort_order: 排序方向:asc / desc
|
||||
:param keyword: 关键词搜索
|
||||
:param start_index: 零基分页偏移
|
||||
:param limit: 单页数量上限
|
||||
:return: 分页浏览结果;失败时返回 None
|
||||
"""
|
||||
if not plex:
|
||||
return None
|
||||
safe_start = max(0, int(start_index))
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
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"
|
||||
order_suffix = "asc" if (sort_order or default_order).casefold() == "asc" else "desc"
|
||||
filters: dict[str, Any] = {}
|
||||
if genre:
|
||||
filters["genre"] = genre
|
||||
if year:
|
||||
filters["year"] = int(year)
|
||||
if played_filter == "unplayed":
|
||||
filters["unwatched"] = True
|
||||
elif played_filter == "played":
|
||||
filters["unwatched"] = False
|
||||
try:
|
||||
section = plex.library.sectionByID(int(library_id)) if library_id and str(library_id).isdigit() else None
|
||||
if section is None:
|
||||
sections = plex.library.sections()
|
||||
section = sections[0] if sections else None
|
||||
if section is None:
|
||||
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())
|
||||
if mapped:
|
||||
libtype = mapped
|
||||
results = section.search(
|
||||
title=keyword.strip() if keyword and keyword.strip() else None,
|
||||
sort=f"{plex_sort}:{order_suffix}",
|
||||
libtype=libtype,
|
||||
container_start=safe_start,
|
||||
container_size=safe_limit,
|
||||
maxresults=safe_limit,
|
||||
**filters,
|
||||
)
|
||||
items = [built for raw in results if (built := _build_plex_browse_item(host, token, raw))]
|
||||
total = getattr(section, "totalSize", None) if not (filters or keyword) else None
|
||||
total_count = int(total) if isinstance(total, int) else (safe_start + len(items) + (1 if len(items) == safe_limit else 0))
|
||||
return MediaServerBrowsePage(
|
||||
items=items,
|
||||
total_count=total_count,
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=(safe_start + len(items)) < total_count if isinstance(total, int) else len(items) == safe_limit,
|
||||
)
|
||||
except Exception as err:
|
||||
logger.error(f"浏览 Plex 媒体库失败:{err}")
|
||||
return None
|
||||
|
||||
|
||||
def plex_filter_options(plex: Any, library_id: Optional[str] = None) -> MediaServerFilterOptions:
|
||||
"""
|
||||
获取 Plex 指定媒体库可用的风格和年份筛选项。
|
||||
|
||||
:param plex: 已连接的 PlexServer 实例
|
||||
:param library_id: 媒体库数字标识
|
||||
:return: 可用筛选项模型
|
||||
"""
|
||||
genres: list[str] = []
|
||||
years: list[int] = []
|
||||
try:
|
||||
if plex and library_id and str(library_id).isdigit():
|
||||
section = plex.library.sectionByID(int(library_id))
|
||||
if section:
|
||||
genres = [str(choice.title) for choice in section.listFilterChoices("genre") if getattr(choice, "title", None)]
|
||||
years = sorted(
|
||||
{int(choice.title) for choice in section.listFilterChoices("year") if str(getattr(choice, "title", "")).isdigit()},
|
||||
reverse=True,
|
||||
)
|
||||
except Exception as err:
|
||||
logger.debug(f"获取 Plex 筛选项失败:{err}")
|
||||
return MediaServerFilterOptions(
|
||||
genres=genres,
|
||||
years=years,
|
||||
item_types=["Movie", "Series", "MusicAlbum"],
|
||||
sort_options=["date_created", "premiere_date", "rating", "name", "random"],
|
||||
)
|
||||
|
||||
|
||||
def plex_item_detail(
|
||||
plex: Any,
|
||||
host: str,
|
||||
token: str,
|
||||
item_id: str,
|
||||
play_url_builder: Optional[Callable[[str], Optional[str]]] = None,
|
||||
) -> Optional[MediaServerItemDetail]:
|
||||
"""
|
||||
读取单个 Plex 条目完整详情,含演职员、多版本及音轨字幕轨道。
|
||||
|
||||
:param plex: 已连接的 PlexServer 实例
|
||||
:param host: Plex 服务根地址
|
||||
:param token: Plex 访问令牌
|
||||
:param item_id: Plex 数字标识或 metadata key
|
||||
:param play_url_builder: 网页播放链接构造器
|
||||
:return: 统一详情模型;失败时返回 None
|
||||
"""
|
||||
if not plex or not item_id:
|
||||
return None
|
||||
try:
|
||||
lookup: Any = int(item_id) if str(item_id).isdigit() else item_id
|
||||
item = plex.fetchItem(lookup)
|
||||
if hasattr(item, "reload"):
|
||||
item.reload()
|
||||
except Exception as err:
|
||||
logger.error(f"获取 Plex 详情 {item_id} 失败:{err}")
|
||||
return None
|
||||
base = _build_plex_browse_item(host, token, item)
|
||||
if not base:
|
||||
return None
|
||||
guids = _extract_plex_guids(getattr(item, "guids", None) or [])
|
||||
media_source, media_id = MediaServerIdentityHelper.from_provider_ids(guids)
|
||||
people: list[MediaServerPerson] = []
|
||||
for role in (getattr(item, "roles", None) or [])[:20]:
|
||||
if getattr(role, "tag", None):
|
||||
people.append(
|
||||
MediaServerPerson(
|
||||
id=str(getattr(role, "id", "") or "") or None,
|
||||
name=str(role.tag),
|
||||
role=getattr(role, "role", None),
|
||||
type="Actor",
|
||||
image=_plex_image_url(host, token, getattr(role, "thumb", None)),
|
||||
)
|
||||
)
|
||||
for director in (getattr(item, "directors", None) or [])[:4]:
|
||||
if getattr(director, "tag", None):
|
||||
people.append(MediaServerPerson(name=str(director.tag), role="导演", type="Director"))
|
||||
sources = _parse_plex_sources(item)
|
||||
genres = [str(g.tag) for g in (getattr(item, "genres", None) or []) if getattr(g, "tag", None)]
|
||||
studio = getattr(item, "studio", None)
|
||||
return MediaServerItemDetail(
|
||||
**base.model_dump(),
|
||||
tagline=getattr(item, "tagline", None),
|
||||
official_rating=getattr(item, "contentRating", None),
|
||||
genres=genres,
|
||||
studios=[str(studio)] if studio else [],
|
||||
people=people,
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
imdb_id=guids.get("imdb_id"),
|
||||
tmdb_id=guids.get("tmdb_id"),
|
||||
tvdb_id=guids.get("tvdb_id"),
|
||||
parent_id=str(getattr(item, "parentRatingKey", "") or "") or None,
|
||||
season_name=getattr(item, "parentTitle", None) if base.item_type == "Episode" else None,
|
||||
season_count=getattr(item, "childCount", None) if base.item_type == "Series" else None,
|
||||
episode_count=getattr(item, "leafCount", None) if base.item_type in {"Series", "Season"} else None,
|
||||
media_sources=sources,
|
||||
play_url=play_url_builder(str(getattr(item, "key", "") or item_id)) if play_url_builder else None,
|
||||
can_play=base.item_type in {"Movie", "Episode", "Audio"} or bool(sources),
|
||||
)
|
||||
|
||||
|
||||
def _extract_plex_guids(guids: list[Any]) -> dict[str, Optional[str]]:
|
||||
"""
|
||||
从 Plex Guid 列表中解析 imdb/tmdb/tvdb 标识。
|
||||
|
||||
:param guids: Plex Guid 对象列表
|
||||
:return: 标识字典
|
||||
"""
|
||||
result: dict[str, Optional[str]] = {}
|
||||
for guid in guids:
|
||||
raw = str(guid.get("id") if isinstance(guid, dict) else getattr(guid, "id", "") or "")
|
||||
for prefix, key in (("imdb://", "imdb_id"), ("tmdb://", "tmdb_id"), ("tvdb://", "tvdb_id")):
|
||||
if raw.startswith(prefix):
|
||||
result[key] = raw[len(prefix) :]
|
||||
return result
|
||||
|
||||
|
||||
def plex_seasons(plex: Any, host: str, token: str, series_id: str) -> Optional[list[MediaServerBrowseItem]]:
|
||||
"""
|
||||
获取 Plex 电视剧的全部季卡片。
|
||||
|
||||
:param plex: PlexServer 实例
|
||||
:param host: 服务根地址
|
||||
:param token: 访问令牌
|
||||
:param series_id: 剧集标识
|
||||
:return: 按季号排序的季列表
|
||||
"""
|
||||
if not plex or not series_id:
|
||||
return None
|
||||
try:
|
||||
show = plex.fetchItem(int(series_id) if str(series_id).isdigit() else series_id)
|
||||
seasons = [built for s in show.seasons() if (built := _build_plex_browse_item(host, token, s))]
|
||||
seasons.sort(key=lambda item: (item.season_number is None, item.season_number or 0))
|
||||
return seasons
|
||||
except Exception as err:
|
||||
logger.error(f"获取 Plex 剧集 {series_id} 季列表失败:{err}")
|
||||
return None
|
||||
|
||||
|
||||
def plex_season_episodes(
|
||||
plex: Any,
|
||||
host: str,
|
||||
token: str,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
) -> Optional[list[MediaServerBrowseItem]]:
|
||||
"""
|
||||
获取 Plex 指定季的全部单集详情卡片。
|
||||
|
||||
:param plex: PlexServer 实例
|
||||
:param host: 服务根地址
|
||||
:param token: 访问令牌
|
||||
:param series_id: 剧集标识
|
||||
:param season_id: 可选季标识
|
||||
:param season: 可选季号
|
||||
:return: 按集号排序的单集卡片列表
|
||||
"""
|
||||
if not plex:
|
||||
return None
|
||||
try:
|
||||
if season_id:
|
||||
container = plex.fetchItem(int(season_id) if str(season_id).isdigit() else season_id)
|
||||
raw_eps = container.episodes()
|
||||
else:
|
||||
show = plex.fetchItem(int(series_id) if str(series_id).isdigit() else series_id)
|
||||
raw_eps = show.season(season).episodes() if season is not None else show.episodes()
|
||||
episodes = [built for ep in raw_eps if (built := _build_plex_browse_item(host, token, ep))]
|
||||
episodes.sort(key=lambda item: (item.season_number or 0, item.episode_number or 0))
|
||||
return episodes
|
||||
except Exception as err:
|
||||
logger.error(f"获取 Plex 剧集 {series_id} 分集失败:{err}")
|
||||
return None
|
||||
|
||||
|
||||
def plex_subtitle_url(host: str, token: str, subtitle_id: str) -> Optional[str]:
|
||||
"""
|
||||
将 Plex 外挂字幕代理标识 `ms:plex:<stream_id>.<ext>` 解析为原始字幕下载流地址。
|
||||
|
||||
:param host: 服务根地址
|
||||
:param token: 访问令牌
|
||||
:param subtitle_id: 代理字幕标识
|
||||
:return: 上游字幕流地址;格式不符时返回 None
|
||||
"""
|
||||
if not host or not token:
|
||||
return None
|
||||
match = _PLEX_SUBTITLE_ID_RE.match(subtitle_id.strip())
|
||||
if not match:
|
||||
return None
|
||||
stream_id, _ = match.groups()
|
||||
return f"{host.rstrip('/')}/library/streams/{stream_id}?{urlencode({'X-Plex-Token': token})}"
|
||||
|
||||
|
||||
def plex_report_progress(
|
||||
plex: Any,
|
||||
item_id: str,
|
||||
position_ms: int,
|
||||
*,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
) -> bool:
|
||||
"""
|
||||
将客户端播放进度回传给 Plex 服务器。
|
||||
|
||||
:param plex: PlexServer 实例
|
||||
:param item_id: 条目标识
|
||||
:param position_ms: 当前播放位置(毫秒)
|
||||
:param duration_ms: 可选总时长(毫秒)
|
||||
:param is_paused: 是否暂停
|
||||
:param state: 事件状态
|
||||
:return: 回传成功返回 True
|
||||
"""
|
||||
if not plex or not item_id:
|
||||
return False
|
||||
try:
|
||||
item = plex.fetchItem(int(item_id) if str(item_id).isdigit() else item_id)
|
||||
plex_state = "stopped" if state == "stopped" else ("paused" if (is_paused or state == "paused") else "playing")
|
||||
item.updateTimeline(max(0, int(position_ms)), state=plex_state, duration=duration_ms or getattr(item, "duration", None))
|
||||
return True
|
||||
except Exception as err:
|
||||
logger.debug(f"回传 Plex 播放进度失败:{err}")
|
||||
return False
|
||||
@@ -150,19 +150,31 @@ class EmbyModule(_MediaServerModuleBase[Emby]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""
|
||||
在所有已启用 Emby 实例中搜索媒体库,并保留条目所属配置。
|
||||
在指定或所有已启用 Emby 实例中搜索媒体库,并保留条目所属配置。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 需要搜索的业务类型
|
||||
:param limit: 每个实例返回的最大条目数
|
||||
:param server: 可选指定实例配置名称
|
||||
:param library_id: 可选限定媒体库标识
|
||||
:return: 带 Emby 配置名的搜索结果
|
||||
"""
|
||||
items: list[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
for item in server_obj.search_library(keyword, types, limit, library_id=library_id):
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
@@ -282,7 +294,11 @@ class EmbyModule(_MediaServerModuleBase[Emby]):
|
||||
return server_obj.get_play_url(str(item_id))
|
||||
|
||||
def mediaserver_stream_url(
|
||||
self, server: str, item_id: Union[str, int], item_type: Optional[str]
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
返回 Emby 支持 Range 的静态媒体流,而不暴露服务器令牌给客户端。
|
||||
@@ -290,10 +306,15 @@ class EmbyModule(_MediaServerModuleBase[Emby]):
|
||||
:param server: Emby 配置名称
|
||||
:param item_id: Emby 条目标识
|
||||
:param item_type: 媒体服务器返回的类型,用于选择音频或视频接口
|
||||
:param media_source_id: 可选指定的多版本媒体源标识
|
||||
:return: 上游媒体流地址;实例不存在或适配器无法构造地址时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
return server_obj.get_stream_url(str(item_id), item_type) if server_obj else None
|
||||
return (
|
||||
server_obj.get_stream_url(str(item_id), item_type, media_source_id=media_source_id)
|
||||
if server_obj
|
||||
else None
|
||||
)
|
||||
|
||||
def mediaserver_season_episode_ids(
|
||||
self, server: str, item_id: Union[str, int], season: int, *, query: Optional[MediaServerQueryOptions] = None
|
||||
|
||||
@@ -15,6 +15,18 @@ from requests import Response
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper, format_emby_family_item
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.modules._base.emby_browse import (
|
||||
EmbyBrowseConfig,
|
||||
emby_browse_items,
|
||||
emby_filter_options,
|
||||
emby_item_detail,
|
||||
emby_report_progress,
|
||||
emby_search_library,
|
||||
emby_season_episodes,
|
||||
emby_seasons,
|
||||
emby_stream_url,
|
||||
emby_subtitle_url,
|
||||
)
|
||||
from app.modules._base.mediaserver import (
|
||||
emby_episode_numbers,
|
||||
emby_query_params,
|
||||
@@ -24,8 +36,20 @@ from app.modules._base.mediaserver import (
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerItem, MediaServerQueryOptions
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
from app.schemas.mediaserver import RefreshMediaItem as _SchemaRefreshMediaItem
|
||||
@@ -572,78 +596,167 @@ class Emby:
|
||||
logger.debug(f"查询Emby音乐出错:{e}")
|
||||
return []
|
||||
|
||||
def _browse_config(
|
||||
self, username: Optional[str] = None, *, require_user: bool = True
|
||||
) -> Optional[EmbyBrowseConfig]:
|
||||
"""
|
||||
构造当前 Emby 实例的统一浏览协议配置。
|
||||
|
||||
:param username: 可选用户名,用于限定用户可见数据
|
||||
:param require_user: 是否要求存在有效用户标识
|
||||
:return: 协议配置;未完成初始化或缺少所需用户时返回 None
|
||||
"""
|
||||
if not self._host or not self._apikey:
|
||||
return None
|
||||
user_id = self.get_user(username) if username else self.user
|
||||
if require_user and not user_id:
|
||||
return None
|
||||
return EmbyBrowseConfig(
|
||||
host=self._host,
|
||||
api_key=self._apikey,
|
||||
user_id=str(user_id or ""),
|
||||
server_type="emby",
|
||||
api_prefix="emby/",
|
||||
play_host=self._playhost,
|
||||
server_id=getattr(self, "serverid", None),
|
||||
request_factory=lambda: RequestUtils(timeout=15),
|
||||
include_api_key_param=True,
|
||||
image_api_key=True,
|
||||
play_url_builder=self.get_play_url,
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""
|
||||
分页浏览 Emby 媒体库并支持筛选、排序和搜索。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
if not cfg:
|
||||
return None
|
||||
return emby_browse_items(
|
||||
cfg,
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerFilterOptions]:
|
||||
"""
|
||||
获取 Emby 指定媒体库的风格、年份与排序筛选选项。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_filter_options(cfg, library_id=library_id) if cfg else None
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""
|
||||
获取 Emby 单个条目的完整详情(含多版本及音轨字幕轨道)。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_item_detail(cfg, item_id) if cfg else None
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
获取 Emby 电视剧的全部季卡片信息。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_seasons(cfg, series_id) if cfg else None
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
获取 Emby 电视剧指定季的全部单集详情卡片。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_season_episodes(cfg, series_id, season_id=season_id, season=season) if cfg else None
|
||||
|
||||
def get_subtitle_url(self, item_id: str, subtitle_id: str) -> Optional[str]:
|
||||
"""
|
||||
解析 Emby 服务端外挂或可提取字幕的上游流地址。
|
||||
"""
|
||||
cfg = self._browse_config(require_user=False)
|
||||
return emby_subtitle_url(cfg, item_id, subtitle_id) if cfg else None
|
||||
|
||||
def report_progress(
|
||||
self,
|
||||
item_id: str,
|
||||
*,
|
||||
position_ms: int,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
将客户端播放进度回传给 Emby 服务器。
|
||||
"""
|
||||
_ = duration_ms
|
||||
cfg = self._browse_config(username)
|
||||
if not cfg:
|
||||
return False
|
||||
return emby_report_progress(
|
||||
cfg,
|
||||
item_id,
|
||||
position_ms,
|
||||
media_source_id=media_source_id,
|
||||
is_paused=is_paused,
|
||||
state=state,
|
||||
)
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""
|
||||
通过 Emby Items 搜索接口查询电视剧和可播放音乐单曲。
|
||||
通过 Emby Items 搜索接口查询电影、电视剧和可播放音乐单曲。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 需要搜索的业务类型
|
||||
:param limit: 最多返回的条目数量
|
||||
:param library_id: 可选媒体库标识限定
|
||||
:return: 带封面、年份或音乐副标题的媒体服务器条目
|
||||
"""
|
||||
if not self._host or not self._apikey or not self.user or not keyword.strip():
|
||||
return []
|
||||
server_types = []
|
||||
if MediaType.TV.value in types:
|
||||
server_types.append("Series")
|
||||
if MediaType.MUSIC.value in types:
|
||||
server_types.append("Audio")
|
||||
if not server_types:
|
||||
return []
|
||||
url = f"{self._host}emby/Users/{self.user}/Items"
|
||||
params = {
|
||||
"api_key": self._apikey,
|
||||
"IncludeItemTypes": ",".join(server_types),
|
||||
"Fields": "ProductionYear,Album,Artists,AlbumArtist,ImageTags",
|
||||
"Recursive": "true",
|
||||
"SearchTerm": keyword.strip(),
|
||||
"StartIndex": 0,
|
||||
"Limit": max(1, min(limit, 50)),
|
||||
}
|
||||
try:
|
||||
response = RequestUtils().get_res(url, params)
|
||||
if not response or response.status_code != 200:
|
||||
return []
|
||||
results: list[_SchemaMediaServerPlayItem] = []
|
||||
for item in (response.json().get("Items") or []):
|
||||
item_id = _optional_text(item.get("Id"))
|
||||
title = _optional_text(item.get("Name"))
|
||||
item_type = item.get("Type")
|
||||
if not item_id or not title or item_type not in server_types:
|
||||
continue
|
||||
artists = item.get("Artists") or []
|
||||
artist_names = [
|
||||
artist.get("Name") if isinstance(artist, dict) else artist
|
||||
for artist in artists
|
||||
]
|
||||
artist = next((str(value) for value in artist_names if value), None)
|
||||
album = _optional_text(item.get("Album"))
|
||||
image_url = f"{self._host}Items/{item_id}/Images/Primary?api_key={self._apikey}"
|
||||
image_tag = (item.get("ImageTags") or {}).get("Primary")
|
||||
if image_tag:
|
||||
image_url += f"&tag={image_tag}"
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
id=item_id,
|
||||
item_id=item_id,
|
||||
title=title,
|
||||
subtitle=(str(artist or "") + (f" · {album}" if album else "")) or None
|
||||
if item_type == "Audio"
|
||||
else str(item.get("ProductionYear")) if item.get("ProductionYear") else None,
|
||||
year=item.get("ProductionYear"),
|
||||
type=MediaType.TV.value if item_type == "Series" else MediaType.MUSIC.value,
|
||||
image=image_url,
|
||||
server_type="emby",
|
||||
)
|
||||
)
|
||||
if len(results) >= limit:
|
||||
break
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.debug(f"搜索 Emby 媒体库出错:{e}")
|
||||
cfg = self._browse_config()
|
||||
if not cfg:
|
||||
return []
|
||||
return emby_search_library(cfg, keyword, types, limit, library_id=library_id)
|
||||
|
||||
def get_tv_episodes(
|
||||
self,
|
||||
@@ -1237,47 +1350,24 @@ class Emby:
|
||||
return f"{self._playhost or self._host}web/index.html#!" \
|
||||
f"/item?id={item_id}&context=home{server_query}"
|
||||
|
||||
def get_stream_url(self, item_id: str, item_type: Optional[str]) -> Optional[str]:
|
||||
def get_stream_url(
|
||||
self,
|
||||
item_id: str,
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
为原生播放器构造支持 Range 的 Emby 静态文件流地址。
|
||||
|
||||
PlaySessionId 按服务器、用户与条目稳定派生,确保多个 Range 请求继续读取同一媒体源。
|
||||
为原生播放器构造支持 Range 的 Emby 静态文件流地址,支持指定多版本媒体源。
|
||||
|
||||
:param item_id: Emby 条目标识
|
||||
:param item_type: 媒体服务器返回的条目类型
|
||||
:param media_source_id: 可选指定媒体源标识
|
||||
:return: Emby 原始媒体流地址;实例配置或条目标识缺失时返回 None
|
||||
"""
|
||||
if not self._host or not self._apikey or not item_id:
|
||||
cfg = self._browse_config(require_user=False)
|
||||
if not cfg:
|
||||
return None
|
||||
try:
|
||||
response = RequestUtils(timeout=10).get_res(
|
||||
f"{self._host}emby/Items/{quote(str(item_id), safe='')}/PlaybackInfo",
|
||||
params={"api_key": self._apikey, "UserId": self.user},
|
||||
)
|
||||
if response is None or response.status_code != 200:
|
||||
return None
|
||||
sources = response.json().get("MediaSources") or []
|
||||
source = next(
|
||||
(value for value in sources if isinstance(value, dict) and value.get("Id")
|
||||
and not value.get("RequiresOpening")),
|
||||
None,
|
||||
)
|
||||
if not source:
|
||||
return None
|
||||
except Exception:
|
||||
logger.warning("Emby 原始媒体流信息读取失败,尝试本地文件播放")
|
||||
return None
|
||||
route = "Audio" if (item_type or "").casefold() in {"audio", "music", MediaType.MUSIC.value.casefold()} else "Videos"
|
||||
play_session_id = hashlib.sha256(
|
||||
f"{self._host}:{self.user or ''}:{item_id}".encode("utf-8")
|
||||
).hexdigest()[:32]
|
||||
query = urlencode({
|
||||
"static": "true",
|
||||
"MediaSourceId": str(source["Id"]),
|
||||
"PlaySessionId": play_session_id,
|
||||
"api_key": self._apikey,
|
||||
})
|
||||
return f"{self._host}emby/{route}/{quote(str(item_id), safe='')}/stream?{query}"
|
||||
return emby_stream_url(cfg, item_id, item_type, media_source_id=media_source_id)
|
||||
|
||||
def get_backdrop_url(self, item_id: str, image_tag: str, remote: Optional[bool] = False) -> str:
|
||||
"""
|
||||
|
||||
@@ -150,19 +150,31 @@ class JellyfinModule(_MediaServerModuleBase[Jellyfin]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""
|
||||
在所有已启用 Jellyfin 实例中搜索媒体库,并保留条目所属配置。
|
||||
在指定或所有已启用 Jellyfin 实例中搜索媒体库,并保留条目所属配置。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 需要搜索的业务类型
|
||||
:param limit: 每个实例返回的最大条目数
|
||||
:param server: 可选指定实例配置名称
|
||||
:param library_id: 可选限定媒体库标识
|
||||
:return: 带 Jellyfin 配置名的搜索结果
|
||||
"""
|
||||
items: list[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
for item in server_obj.search_library(keyword, types, limit, library_id=library_id):
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
@@ -282,7 +294,11 @@ class JellyfinModule(_MediaServerModuleBase[Jellyfin]):
|
||||
return server_obj.get_play_url(str(item_id))
|
||||
|
||||
def mediaserver_stream_url(
|
||||
self, server: str, item_id: Union[str, int], item_type: Optional[str]
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
返回 Jellyfin 支持 Range 的静态媒体流,而不暴露服务器令牌给客户端。
|
||||
@@ -290,10 +306,15 @@ class JellyfinModule(_MediaServerModuleBase[Jellyfin]):
|
||||
:param server: Jellyfin 配置名称
|
||||
:param item_id: Jellyfin 条目标识
|
||||
:param item_type: 媒体服务器返回的类型,用于选择音频或视频接口
|
||||
:param media_source_id: 可选指定的多版本媒体源标识
|
||||
:return: 上游媒体流地址;实例不存在或适配器无法构造地址时返回 None
|
||||
"""
|
||||
server_obj = self.get_instance(server)
|
||||
return server_obj.get_stream_url(str(item_id), item_type) if server_obj else None
|
||||
return (
|
||||
server_obj.get_stream_url(str(item_id), item_type, media_source_id=media_source_id)
|
||||
if server_obj
|
||||
else None
|
||||
)
|
||||
|
||||
def mediaserver_season_episode_ids(
|
||||
self, server: str, item_id: Union[str, int], season: int, *, query: Optional[MediaServerQueryOptions] = None
|
||||
|
||||
@@ -13,6 +13,18 @@ from requests import Response
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper, format_emby_family_item
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.modules._base.emby_browse import (
|
||||
EmbyBrowseConfig,
|
||||
emby_browse_items,
|
||||
emby_filter_options,
|
||||
emby_item_detail,
|
||||
emby_report_progress,
|
||||
emby_search_library,
|
||||
emby_season_episodes,
|
||||
emby_seasons,
|
||||
emby_stream_url,
|
||||
emby_subtitle_url,
|
||||
)
|
||||
from app.modules._base.mediaserver import (
|
||||
emby_episode_numbers,
|
||||
emby_query_params,
|
||||
@@ -23,8 +35,20 @@ from app.runtime.cache import MemoryBackend
|
||||
from app.runtime.log import logger
|
||||
from app.runtime.settings import get_runtime_setting
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerItem, MediaServerQueryOptions
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
from app.schemas.mediaserver import WebhookEventInfo as _SchemaWebhookEventInfo
|
||||
@@ -657,74 +681,167 @@ class Jellyfin:
|
||||
logger.debug(f"查询Jellyfin音乐出错:{e}")
|
||||
return []
|
||||
|
||||
def _browse_config(
|
||||
self, username: Optional[str] = None, *, require_user: bool = True
|
||||
) -> Optional[EmbyBrowseConfig]:
|
||||
"""
|
||||
构造当前 Jellyfin 实例的统一浏览协议配置。
|
||||
|
||||
:param username: 可选用户名
|
||||
:param require_user: 是否要求存在有效用户标识
|
||||
:return: 协议配置;未完成初始化或缺少所需用户时返回 None
|
||||
"""
|
||||
if not self._host or not self._apikey:
|
||||
return None
|
||||
user_id = self.get_user(username) if username else self.user
|
||||
if require_user and not user_id:
|
||||
return None
|
||||
return EmbyBrowseConfig(
|
||||
host=self._host,
|
||||
api_key=self._apikey,
|
||||
user_id=str(user_id or ""),
|
||||
server_type="jellyfin",
|
||||
api_prefix="",
|
||||
play_host=self._playhost,
|
||||
server_id=getattr(self, "serverid", None),
|
||||
request_factory=lambda: self._request(timeout=15),
|
||||
include_api_key_param=True,
|
||||
image_api_key=True,
|
||||
play_url_builder=self.get_play_url,
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""
|
||||
分页浏览 Jellyfin 媒体库并支持筛选、排序和搜索。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
if not cfg:
|
||||
return None
|
||||
return emby_browse_items(
|
||||
cfg,
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerFilterOptions]:
|
||||
"""
|
||||
获取 Jellyfin 指定媒体库的风格、年份与排序筛选选项。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_filter_options(cfg, library_id=library_id) if cfg else None
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""
|
||||
获取 Jellyfin 单个条目的完整详情(含多版本及音轨字幕轨道)。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_item_detail(cfg, item_id) if cfg else None
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
获取 Jellyfin 电视剧的全部季卡片信息。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_seasons(cfg, series_id) if cfg else None
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""
|
||||
获取 Jellyfin 电视剧指定季的全部单集详情卡片。
|
||||
"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_season_episodes(cfg, series_id, season_id=season_id, season=season) if cfg else None
|
||||
|
||||
def get_subtitle_url(self, item_id: str, subtitle_id: str) -> Optional[str]:
|
||||
"""
|
||||
解析 Jellyfin 服务端外挂或可提取字幕的上游流地址。
|
||||
"""
|
||||
cfg = self._browse_config(require_user=False)
|
||||
return emby_subtitle_url(cfg, item_id, subtitle_id) if cfg else None
|
||||
|
||||
def report_progress(
|
||||
self,
|
||||
item_id: str,
|
||||
*,
|
||||
position_ms: int,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
将客户端播放进度回传给 Jellyfin 服务器。
|
||||
"""
|
||||
_ = duration_ms
|
||||
cfg = self._browse_config(username)
|
||||
if not cfg:
|
||||
return False
|
||||
return emby_report_progress(
|
||||
cfg,
|
||||
item_id,
|
||||
position_ms,
|
||||
media_source_id=media_source_id,
|
||||
is_paused=is_paused,
|
||||
state=state,
|
||||
)
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""
|
||||
通过 Jellyfin Items 搜索接口查询电视剧和可播放音乐单曲。
|
||||
通过 Jellyfin Items 搜索接口查询电影、电视剧和可播放音乐单曲。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 需要搜索的业务类型
|
||||
:param limit: 最多返回的条目数量
|
||||
:param library_id: 可选媒体库标识限定
|
||||
:return: 带封面、年份或音乐副标题的媒体服务器条目
|
||||
"""
|
||||
if not self._host or not self._apikey or not self.user or not keyword.strip():
|
||||
return []
|
||||
server_types = []
|
||||
if MediaType.TV.value in types:
|
||||
server_types.append("Series")
|
||||
if MediaType.MUSIC.value in types:
|
||||
server_types.append("Audio")
|
||||
if not server_types:
|
||||
return []
|
||||
url = f"{self._host}Users/{self.user}/Items"
|
||||
params = {
|
||||
"api_key": self._apikey,
|
||||
"IncludeItemTypes": ",".join(server_types),
|
||||
"Fields": "ProductionYear,Album,Artists,AlbumArtist,ImageTags",
|
||||
"Recursive": "true",
|
||||
"searchTerm": keyword.strip(),
|
||||
"StartIndex": 0,
|
||||
"Limit": max(1, min(limit, 50)),
|
||||
}
|
||||
try:
|
||||
response = self._request().get_res(url, params)
|
||||
if not response or response.status_code != 200:
|
||||
return []
|
||||
results: list[_SchemaMediaServerPlayItem] = []
|
||||
for item in (response.json().get("Items") or []):
|
||||
item_id = _optional_text(item.get("Id"))
|
||||
title = _optional_text(item.get("Name"))
|
||||
item_type = item.get("Type")
|
||||
if not item_id or not title or item_type not in server_types:
|
||||
continue
|
||||
artists = item.get("Artists") or []
|
||||
artist = next((str(value) for value in artists if value), None)
|
||||
album = _optional_text(item.get("Album"))
|
||||
image_url = f"{self._host}Items/{item_id}/Images/Primary?api_key={self._apikey}"
|
||||
image_tag = (item.get("ImageTags") or {}).get("Primary")
|
||||
if image_tag:
|
||||
image_url += f"&tag={image_tag}"
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
id=item_id,
|
||||
item_id=item_id,
|
||||
title=title,
|
||||
subtitle=(str(artist or "") + (f" · {album}" if album else "")) or None
|
||||
if item_type == "Audio"
|
||||
else str(item.get("ProductionYear")) if item.get("ProductionYear") else None,
|
||||
year=item.get("ProductionYear"),
|
||||
type=MediaType.TV.value if item_type == "Series" else MediaType.MUSIC.value,
|
||||
image=image_url,
|
||||
server_type="jellyfin",
|
||||
)
|
||||
)
|
||||
if len(results) >= limit:
|
||||
break
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.debug(f"搜索 Jellyfin 媒体库出错:{e}")
|
||||
cfg = self._browse_config()
|
||||
if not cfg:
|
||||
return []
|
||||
return emby_search_library(cfg, keyword, types, limit, library_id=library_id)
|
||||
|
||||
def get_tv_episodes(
|
||||
self,
|
||||
@@ -908,47 +1025,24 @@ class Jellyfin:
|
||||
return None
|
||||
return None
|
||||
|
||||
def get_stream_url(self, item_id: str, item_type: Optional[str]) -> Optional[str]:
|
||||
def get_stream_url(
|
||||
self,
|
||||
item_id: str,
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
为原生播放器构造支持 Range 的 Jellyfin 静态文件流地址。
|
||||
|
||||
PlaySessionId 按服务器、用户与条目稳定派生,确保多个 Range 请求继续读取同一媒体源。
|
||||
为原生播放器构造支持 Range 的 Jellyfin 静态文件流地址,支持指定多版本媒体源。
|
||||
|
||||
:param item_id: Jellyfin 条目标识
|
||||
:param item_type: 媒体服务器返回的条目类型
|
||||
:param media_source_id: 可选指定媒体源标识
|
||||
:return: Jellyfin 原始媒体流地址;实例配置或条目标识缺失时返回 None
|
||||
"""
|
||||
if not self._host or not self._apikey or not item_id:
|
||||
cfg = self._browse_config(require_user=False)
|
||||
if not cfg:
|
||||
return None
|
||||
try:
|
||||
response = self._request(timeout=10).get_res(
|
||||
f"{self._host}Items/{quote(str(item_id), safe='')}/PlaybackInfo",
|
||||
params={"api_key": self._apikey, "UserId": self.user},
|
||||
)
|
||||
if response is None or response.status_code != 200:
|
||||
return None
|
||||
sources = response.json().get("MediaSources") or []
|
||||
source = next(
|
||||
(value for value in sources if isinstance(value, dict) and value.get("Id")
|
||||
and not value.get("RequiresOpening")),
|
||||
None,
|
||||
)
|
||||
if not source:
|
||||
return None
|
||||
except Exception:
|
||||
logger.warning("Jellyfin 原始媒体流信息读取失败,尝试本地文件播放")
|
||||
return None
|
||||
route = "Audio" if (item_type or "").casefold() in {"audio", "music", MediaType.MUSIC.value.casefold()} else "Videos"
|
||||
play_session_id = hashlib.sha256(
|
||||
f"{self._host}:{self.user or ''}:{item_id}".encode("utf-8")
|
||||
).hexdigest()[:32]
|
||||
query = urlencode({
|
||||
"static": "true",
|
||||
"MediaSourceId": str(source["Id"]),
|
||||
"PlaySessionId": play_session_id,
|
||||
"api_key": self._apikey,
|
||||
})
|
||||
return f"{self._host}{route}/{quote(str(item_id), safe='')}/stream?{query}"
|
||||
return emby_stream_url(cfg, item_id, item_type, media_source_id=media_source_id)
|
||||
|
||||
def _get_webhook_item_path(self, message: dict[str, Any]) -> Optional[str]:
|
||||
"""
|
||||
|
||||
@@ -13,8 +13,20 @@ from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.event import AuthCredentials, AuthInterceptCredentials
|
||||
from app.schemas.mediaserver import ExistMediaInfo as _SchemaExistMediaInfo
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerQueryOptions
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
from app.schemas.mediaserver import MediaServerSeasonInfo as _SchemaMediaServerSeasonInfo
|
||||
@@ -299,15 +311,104 @@ class NavidromeModule(_ModuleBase, _MediaServerBase[Navidrome]):
|
||||
service = self.get_instance(server)
|
||||
return service.get_iteminfo(item_id, **({"query": query} if query is not None else {})) if service else None
|
||||
|
||||
def mediaserver_browse_items(
|
||||
self,
|
||||
server: str,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览 Navidrome 音乐库。"""
|
||||
service = self.get_instance(server)
|
||||
if not service:
|
||||
return None
|
||||
page = service.browse_items(
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
username=username,
|
||||
)
|
||||
if page:
|
||||
for item in page.items:
|
||||
item.server = server
|
||||
return page
|
||||
|
||||
def mediaserver_filter_options(
|
||||
self,
|
||||
server: str,
|
||||
library_id: Optional[str] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerFilterOptions]:
|
||||
"""获取 Navidrome 可用风格筛选项。"""
|
||||
service = self.get_instance(server)
|
||||
return service.get_filter_options(library_id=library_id, username=username) if service else None
|
||||
|
||||
def mediaserver_item_detail(
|
||||
self, server: str, item_id: Union[str, int], username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取 Navidrome 单曲或专辑详情。"""
|
||||
service = self.get_instance(server)
|
||||
if not service:
|
||||
return None
|
||||
detail = service.get_item_detail(str(item_id), username=username)
|
||||
if detail:
|
||||
detail.server = server
|
||||
return detail
|
||||
|
||||
def mediaserver_season_episodes(
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取 Navidrome 专辑内曲目列表。"""
|
||||
service = self.get_instance(server)
|
||||
if not service:
|
||||
return None
|
||||
tracks = service.get_season_episodes(str(item_id), season_id=season_id, season=season, username=username)
|
||||
if tracks is not None:
|
||||
for track in tracks:
|
||||
track.server = server
|
||||
return tracks
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: List[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: List[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""搜索所有已启用 Navidrome 实例的可播放音乐单曲。"""
|
||||
"""搜索指定或所有已启用 Navidrome 实例的可播放音乐单曲。"""
|
||||
if MediaType.MUSIC.value not in types:
|
||||
return []
|
||||
items: List[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, service in self.get_instances().items():
|
||||
for item in service.search_library(keyword, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, service in target_instances.items():
|
||||
for item in service.search_library(keyword, limit, library_id=library_id):
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
@@ -360,7 +461,11 @@ class NavidromeModule(_ModuleBase, _MediaServerBase[Navidrome]):
|
||||
return service.get_play_url(str(item_id)) if service else None
|
||||
|
||||
def mediaserver_stream_url(
|
||||
self, server: str, item_id: Union[str, int], item_type: Optional[str]
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
返回 Navidrome 已签名的原始音频流地址。
|
||||
@@ -368,8 +473,10 @@ class NavidromeModule(_ModuleBase, _MediaServerBase[Navidrome]):
|
||||
:param server: Navidrome 配置名称
|
||||
:param item_id: Navidrome 曲目标识
|
||||
:param item_type: 媒体服务器返回的类型,本适配器只服务音频条目
|
||||
:param media_source_id: 兼容统一流接口的可选媒体源标识
|
||||
:return: 上游音频流地址;条目不是音频或实例不可用时返回 None
|
||||
"""
|
||||
_ = media_source_id
|
||||
if (item_type or "").casefold() not in {"audio", "music", "track", MediaType.MUSIC.value.casefold()}:
|
||||
return None
|
||||
service = self.get_instance(server)
|
||||
|
||||
@@ -12,8 +12,20 @@ from app.adapters.network.http import RequestUtils
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerQueryOptions
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
from app.schemas.types import MediaType
|
||||
@@ -369,8 +381,177 @@ class Navidrome:
|
||||
album = (payload or {}).get("album") or {}
|
||||
return self._album_to_item(album) if album else None
|
||||
|
||||
def search_library(self, keyword: str, limit: int) -> List[_SchemaMediaServerPlayItem]:
|
||||
def _album_to_browse_item(self, album: dict[str, Any]) -> _SchemaMediaServerBrowseItem:
|
||||
"""将 Subsonic 专辑转换为统一浏览卡片模型。"""
|
||||
album_id = str(album.get("id") or "")
|
||||
cover = self._album_cover(album)
|
||||
duration_sec = album.get("duration")
|
||||
return _SchemaMediaServerBrowseItem(
|
||||
item_id=album_id,
|
||||
server_type="navidrome",
|
||||
item_type="MusicAlbum",
|
||||
media_type=MediaType.MUSIC.value,
|
||||
title=self._album_name(album) or album_id,
|
||||
subtitle=album.get("artist") or album.get("albumArtist"),
|
||||
year=album.get("year"),
|
||||
duration_ms=int(duration_sec * 1000) if isinstance(duration_sec, (int, float)) and duration_sec > 0 else None,
|
||||
poster=cover,
|
||||
backdrop=cover,
|
||||
thumb=cover,
|
||||
child_count=album.get("songCount") if isinstance(album.get("songCount"), int) else None,
|
||||
)
|
||||
|
||||
def _song_to_browse_item(self, song: dict[str, Any]) -> _SchemaMediaServerBrowseItem:
|
||||
"""将 Subsonic 单曲转换为统一浏览卡片模型。"""
|
||||
song_id = str(song.get("id") or "")
|
||||
cover = self._album_cover(song)
|
||||
duration_sec = song.get("duration")
|
||||
parts = [str(p) for p in (song.get("artist"), song.get("album")) if p]
|
||||
return _SchemaMediaServerBrowseItem(
|
||||
item_id=song_id,
|
||||
server_type="navidrome",
|
||||
item_type="Audio",
|
||||
media_type=MediaType.MUSIC.value,
|
||||
title=str(song.get("title") or song.get("name") or song_id),
|
||||
subtitle=" · ".join(parts) if parts else None,
|
||||
year=song.get("year"),
|
||||
duration_ms=int(duration_sec * 1000) if isinstance(duration_sec, (int, float)) and duration_sec > 0 else None,
|
||||
poster=cover,
|
||||
backdrop=cover,
|
||||
thumb=cover,
|
||||
episode_number=song.get("track") if isinstance(song.get("track"), int) else None,
|
||||
season_number=song.get("discNumber") if isinstance(song.get("discNumber"), int) else 1,
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览 Navidrome 音乐库(支持专辑列表、风格/年份筛选与关键词搜索)。"""
|
||||
_ = library_id, parent_id, item_type, played_filter, sort_order, username
|
||||
if not self.user:
|
||||
return None
|
||||
safe_start = max(0, int(start_index))
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
if keyword and keyword.strip():
|
||||
payload = self._call(
|
||||
"search3", query=keyword.strip(), artistCount=0, albumCount=safe_limit, songCount=safe_limit
|
||||
)
|
||||
result = (payload or {}).get("searchResult3") or {}
|
||||
albums = [self._album_to_browse_item(a) for a in (result.get("album") or []) if isinstance(a, dict)]
|
||||
songs = [self._song_to_browse_item(s) for s in (result.get("song") or []) if isinstance(s, dict)]
|
||||
combined = albums + songs
|
||||
page_items = combined[safe_start : safe_start + safe_limit]
|
||||
return _SchemaMediaServerBrowsePage(
|
||||
items=page_items,
|
||||
total_count=len(combined),
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=(safe_start + len(page_items)) < len(combined),
|
||||
)
|
||||
list_type = {
|
||||
"date_created": "newest",
|
||||
"premiere_date": "byYear",
|
||||
"name": "alphabeticalByName",
|
||||
"random": "random",
|
||||
}.get((sort_by or "date_created").casefold(), "newest")
|
||||
call_kwargs: dict[str, Any] = {"type": list_type, "size": safe_limit, "offset": safe_start}
|
||||
if genre:
|
||||
call_kwargs.update({"type": "byGenre", "genre": genre})
|
||||
elif year:
|
||||
call_kwargs.update({"type": "byYear", "fromYear": int(year), "toYear": int(year)})
|
||||
payload = self._call("getAlbumList2", **call_kwargs)
|
||||
raw_albums = ((payload or {}).get("albumList2") or {}).get("album") or []
|
||||
items = [self._album_to_browse_item(a) for a in raw_albums if isinstance(a, dict)]
|
||||
has_more = len(items) == safe_limit
|
||||
return _SchemaMediaServerBrowsePage(
|
||||
items=items,
|
||||
total_count=safe_start + len(items) + (1 if has_more else 0),
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=has_more,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> _SchemaMediaServerFilterOptions:
|
||||
"""读取 Navidrome 音乐风格列表。"""
|
||||
_ = library_id, username
|
||||
genres: list[str] = []
|
||||
if self.user:
|
||||
payload = self._call("getGenres")
|
||||
raw_genres = ((payload or {}).get("genres") or {}).get("genre") or []
|
||||
genres = [str(g.get("value")) for g in raw_genres if isinstance(g, dict) and g.get("value")]
|
||||
return _SchemaMediaServerFilterOptions(
|
||||
genres=genres,
|
||||
years=[],
|
||||
item_types=["MusicAlbum", "Audio"],
|
||||
sort_options=["date_created", "name", "random"],
|
||||
)
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取 Navidrome 单曲或专辑的完整详情。"""
|
||||
_ = username
|
||||
if not self.user or not item_id:
|
||||
return None
|
||||
song_payload = self._call("getSong", id=item_id)
|
||||
song = (song_payload or {}).get("song")
|
||||
if isinstance(song, dict) and song:
|
||||
base = self._song_to_browse_item(song)
|
||||
return _SchemaMediaServerItemDetail(
|
||||
**base.model_dump(),
|
||||
genres=[str(song["genre"])] if song.get("genre") else [],
|
||||
play_url=self.get_play_url(item_id),
|
||||
can_play=True,
|
||||
)
|
||||
album_payload = self._call("getAlbum", id=item_id)
|
||||
album = (album_payload or {}).get("album")
|
||||
if isinstance(album, dict) and album:
|
||||
base = self._album_to_browse_item(album)
|
||||
return _SchemaMediaServerItemDetail(
|
||||
**base.model_dump(),
|
||||
genres=[str(album["genre"])] if album.get("genre") else [],
|
||||
episode_count=album.get("songCount") if isinstance(album.get("songCount"), int) else None,
|
||||
play_url=self._play_host,
|
||||
can_play=False,
|
||||
)
|
||||
return None
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取 Navidrome 专辑内的全部曲目列表(复用分集端点便于统一展示与连播)。"""
|
||||
_ = season_id, season, username
|
||||
if not self.user or not series_id:
|
||||
return None
|
||||
album_payload = self._call("getAlbum", id=series_id)
|
||||
songs = ((album_payload or {}).get("album") or {}).get("song") or []
|
||||
return [self._song_to_browse_item(s) for s in songs if isinstance(s, dict)]
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, limit: int, library_id: Optional[str] = None
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""调用 Subsonic 搜索接口并返回可流式播放的单曲结果。"""
|
||||
_ = library_id
|
||||
if not keyword.strip() or not self.user:
|
||||
return []
|
||||
payload = self._call(
|
||||
|
||||
@@ -303,19 +303,31 @@ class PlexModule(_MediaServerModuleBase[Plex]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""
|
||||
在所有已启用 Plex 实例中搜索媒体库,并保留条目所属配置。
|
||||
在指定或所有已启用 Plex 实例中搜索媒体库,并保留条目所属配置。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 需要搜索的业务类型
|
||||
:param limit: 每个实例返回的最大条目数
|
||||
:param server: 可选指定实例配置名称
|
||||
:param library_id: 可选限定媒体库数字标识
|
||||
:return: 带 Plex 配置名的搜索结果
|
||||
"""
|
||||
items: list[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library_items(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
for item in server_obj.search_library_items(keyword, types, limit, library_id=library_id):
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
@@ -494,7 +506,11 @@ class PlexModule(_MediaServerModuleBase[Plex]):
|
||||
return server_obj.get_play_url(str(item_id))
|
||||
|
||||
def mediaserver_stream_url(
|
||||
self, server: str, item_id: Union[str, int], item_type: Optional[str]
|
||||
self,
|
||||
server: str,
|
||||
item_id: Union[str, int],
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
返回 Plex 原始音视频文件流地址。
|
||||
@@ -502,12 +518,13 @@ class PlexModule(_MediaServerModuleBase[Plex]):
|
||||
:param server: Plex 配置名称
|
||||
:param item_id: Plex 条目标识
|
||||
:param item_type: 媒体服务器返回的条目类型,只接受具体音视频
|
||||
:param media_source_id: 可选指定 MediaPart ID
|
||||
:return: 原始媒体流地址;实例不可用或条目不是音视频时返回 None
|
||||
"""
|
||||
if (item_type or "").casefold() not in {"movie", "episode", "audio", "music", "track"}:
|
||||
return None
|
||||
server_obj = self.get_instance(server)
|
||||
return server_obj.get_stream_url(str(item_id)) if server_obj else None
|
||||
return server_obj.get_stream_url(str(item_id), media_source_id=media_source_id) if server_obj else None
|
||||
|
||||
def mediaserver_season_episode_ids(
|
||||
self, server: str, item_id: Union[str, int], season: int, *, query: Optional[MediaServerQueryOptions] = None
|
||||
|
||||
@@ -22,10 +22,31 @@ from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.runtime.cache import cached
|
||||
from app.modules._base.plex_browse import (
|
||||
plex_browse_items,
|
||||
plex_filter_options,
|
||||
plex_item_detail,
|
||||
plex_report_progress,
|
||||
plex_season_episodes,
|
||||
plex_seasons,
|
||||
plex_subtitle_url,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerField, MediaServerItem, MediaServerQueryOptions
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItemUserState as _SchemaMediaServerItemUserState
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
@@ -484,23 +505,132 @@ class Plex:
|
||||
logger.debug(f"查询Plex音乐出错:{e}")
|
||||
return results
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览 Plex 媒体库并支持筛选、排序和搜索。"""
|
||||
_ = username
|
||||
return plex_browse_items(
|
||||
self._plex,
|
||||
self._host or "",
|
||||
self._token or "",
|
||||
library_id=parent_id or library_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> _SchemaMediaServerFilterOptions:
|
||||
"""获取 Plex 指定媒体库可用筛选选项。"""
|
||||
_ = username
|
||||
return plex_filter_options(self._plex, library_id=library_id)
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取 Plex 条目完整详情(含多版本及音轨字幕轨道)。"""
|
||||
_ = username
|
||||
return plex_item_detail(self._plex, self._host or "", self._token or "", item_id, self.get_play_url)
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取 Plex 电视剧的全部季卡片。"""
|
||||
_ = username
|
||||
return plex_seasons(self._plex, self._host or "", self._token or "", series_id)
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取 Plex 指定季的全部单集详情卡片。"""
|
||||
_ = username
|
||||
return plex_season_episodes(
|
||||
self._plex, self._host or "", self._token or "", series_id, season_id=season_id, season=season
|
||||
)
|
||||
|
||||
def get_subtitle_url(self, item_id: str, subtitle_id: str) -> Optional[str]:
|
||||
"""解析 Plex 外挂字幕代理标识为原始字幕流地址。"""
|
||||
_ = item_id
|
||||
return plex_subtitle_url(self._host or "", self._token or "", subtitle_id)
|
||||
|
||||
def report_progress(
|
||||
self,
|
||||
item_id: str,
|
||||
*,
|
||||
position_ms: int,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""向 Plex 回传客户端播放进度。"""
|
||||
_ = media_source_id, username
|
||||
return plex_report_progress(
|
||||
self._plex,
|
||||
item_id,
|
||||
position_ms,
|
||||
duration_ms=duration_ms,
|
||||
is_paused=is_paused,
|
||||
state=state,
|
||||
)
|
||||
|
||||
def search_library_items(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""
|
||||
通过 Plex Library 搜索接口查询电视剧和音乐单曲。
|
||||
通过 Plex Library 搜索接口查询电影、电视剧和音乐单曲。
|
||||
|
||||
:param keyword: 搜索关键词
|
||||
:param types: 需要搜索的业务类型
|
||||
:param limit: 最多返回的条目数量
|
||||
:param library_id: 可选限定媒体库数字标识
|
||||
:return: 带封面、年份或音乐副标题的 Plex 条目
|
||||
"""
|
||||
if not self._plex or not keyword.strip():
|
||||
return []
|
||||
results: list[_SchemaMediaServerPlayItem] = []
|
||||
seen: set[str] = set()
|
||||
if MediaType.TV.value in types:
|
||||
for item in self._plex.library.search(title=keyword.strip(), libtype="show"):
|
||||
search_target: Any = self._plex.library
|
||||
if library_id and str(library_id).isdigit():
|
||||
try:
|
||||
search_target = self._plex.library.sectionByID(int(library_id))
|
||||
except Exception:
|
||||
return []
|
||||
for media_type, libtype in ((MediaType.MOVIE.value, "movie"), (MediaType.TV.value, "show")):
|
||||
if media_type not in types:
|
||||
continue
|
||||
for item in search_target.search(title=keyword.strip(), libtype=libtype):
|
||||
item_id = str(getattr(item, "key", "") or "")
|
||||
title = getattr(item, "title", None)
|
||||
if not item_id or not title or item_id in seen:
|
||||
@@ -514,7 +644,7 @@ class Plex:
|
||||
title=title,
|
||||
subtitle=str(item.year) if getattr(item, "year", None) else None,
|
||||
year=getattr(item, "year", None),
|
||||
type=MediaType.TV.value,
|
||||
type=media_type,
|
||||
image=getattr(item, "posterUrl", None),
|
||||
server_type="plex",
|
||||
)
|
||||
@@ -1284,13 +1414,12 @@ class Plex:
|
||||
raise AttributeError("'NoneType' object has no attribute 'machineIdentifier'")
|
||||
return f'{self._playhost or self._host}web/index.html#!/server/{self._plex.machineIdentifier}/details?key={item_id}&X-Plex-Token={self._token}'
|
||||
|
||||
def get_stream_url(self, item_id: str) -> Optional[str]:
|
||||
def get_stream_url(self, item_id: str, media_source_id: Optional[str] = None) -> Optional[str]:
|
||||
"""
|
||||
从 Plex 条目解析单个原始媒体文件的服务端读取地址。
|
||||
|
||||
不使用网页链接或转码地址;多段媒体无法用一个原始流表达时保留本地回退。
|
||||
从 Plex 条目解析单个原始媒体文件的服务端读取地址,支持按 part ID 选择版本。
|
||||
|
||||
:param item_id: Plex 条目标识,可以是数字或 /library/metadata/ 路径
|
||||
:param media_source_id: 可选指定 MediaPart ID(多版本场景)
|
||||
:return: 包含服务端鉴权参数的原始文件流地址;未连接或无法解析时返回 None
|
||||
"""
|
||||
if self._plex is None or not self._host or not self._token or not item_id:
|
||||
@@ -1300,9 +1429,13 @@ class Plex:
|
||||
if not isinstance(item, (Movie, Episode, Track)):
|
||||
return None
|
||||
parts = list(item.iterParts())
|
||||
if len(parts) != 1 or not isinstance(parts[0].key, str):
|
||||
selected = next(
|
||||
(p for p in parts if media_source_id and str(getattr(p, "id", "")) == str(media_source_id)),
|
||||
parts[0] if len(parts) == 1 else (parts[0] if media_source_id and parts else None),
|
||||
)
|
||||
if not selected or not isinstance(selected.key, str):
|
||||
return None
|
||||
part_key = parts[0].key
|
||||
part_key = selected.key
|
||||
if not part_key.startswith("/library/parts/"):
|
||||
return None
|
||||
separator = "&" if "?" in part_key else "?"
|
||||
|
||||
@@ -220,12 +220,22 @@ class TrimeMediaModule(_MediaServerModuleBase[TrimeMedia]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: List[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: List[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""搜索所有已启用飞牛实例,并保留每条结果的配置名称。"""
|
||||
"""搜索指定或所有已启用飞牛实例,并保留每条结果的配置名称。"""
|
||||
items: List[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
for item in server_obj.search_library(keyword, types, limit, library_id=library_id):
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
@@ -12,7 +12,19 @@ from app.application.security.url import SecurityUtils
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItemUserState as _SchemaMediaServerItemUserState
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
@@ -643,17 +655,236 @@ class TrimeMedia:
|
||||
return self.__build_media_server_item(item)
|
||||
return None
|
||||
|
||||
def _resolve_fn_image(self, path: Optional[str]) -> Optional[str]:
|
||||
"""将飞牛相对图片路径拼接为可代理的完整 URL。"""
|
||||
if not path or not self._api:
|
||||
return None
|
||||
if str(path).startswith(("http://", "https://")):
|
||||
return str(path)
|
||||
return f"{self._api.host.rstrip('/')}/{str(path).lstrip('/')}"
|
||||
|
||||
def _build_browse_item(self, item: fnapi.Item) -> Optional[_SchemaMediaServerBrowseItem]:
|
||||
"""将飞牛条目转换为统一浏览卡片模型。"""
|
||||
if not item or not item.guid or not item.title:
|
||||
return None
|
||||
item_type = "Series" if item.type == fnapi.Type.TV else (item.type.value if item.type else "Movie")
|
||||
is_tv = item.type in {fnapi.Type.TV, fnapi.Type.SEASON, fnapi.Type.EPISODE}
|
||||
date_str = item.air_date if item.type == fnapi.Type.TV else item.release_date
|
||||
year = date_str[:4] if date_str else None
|
||||
duration_ms = int(item.duration * 1000) if item.duration and item.duration > 0 else None
|
||||
resume_ms = int(item.ts * 1000) if item.ts and item.ts > 0 else None
|
||||
percentage = round(min(100.0, item.ts / item.duration * 100.0), 1) if item.duration and item.ts else None
|
||||
rating: Optional[float] = None
|
||||
if item.vote_average:
|
||||
try:
|
||||
rating = round(float(item.vote_average), 1)
|
||||
except (TypeError, ValueError):
|
||||
rating = None
|
||||
subtitle = (
|
||||
f"S{int(item.season_number):02d}E{int(item.episode_number):02d}"
|
||||
if item.type == fnapi.Type.EPISODE and item.season_number is not None and item.episode_number is not None
|
||||
else year
|
||||
)
|
||||
poster = self._resolve_fn_image(item.poster or item.posters)
|
||||
backdrop = self._resolve_fn_image(item.backdrops)
|
||||
return _SchemaMediaServerBrowseItem(
|
||||
item_id=item.guid,
|
||||
server_type="trimemedia",
|
||||
item_type=item_type,
|
||||
media_type=MediaType.TV.value if is_tv else MediaType.MOVIE.value,
|
||||
title=item.title,
|
||||
original_title=item.original_title,
|
||||
subtitle=subtitle,
|
||||
overview=item.overview,
|
||||
year=year,
|
||||
premiere_date=date_str,
|
||||
rating=rating,
|
||||
duration_ms=duration_ms,
|
||||
poster=poster,
|
||||
backdrop=backdrop,
|
||||
thumb=backdrop or poster,
|
||||
series_name=item.tv_title,
|
||||
season_number=item.season_number,
|
||||
episode_number=item.episode_number,
|
||||
played=bool(item.watched == 1) if item.watched is not None else None,
|
||||
played_percentage=percentage,
|
||||
resume_position_ms=resume_ms,
|
||||
use_cookies=True,
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览飞牛媒体库条目。"""
|
||||
_ = genre, played_filter, sort_by, sort_order, username
|
||||
if not self.is_authenticated() or not self._api:
|
||||
return None
|
||||
safe_start = max(0, int(start_index))
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
if keyword and keyword.strip():
|
||||
raw_items = self._api.search_list(keywords=keyword.strip()) or []
|
||||
total = len(raw_items)
|
||||
raw_items = raw_items[safe_start : safe_start + safe_limit]
|
||||
else:
|
||||
target_guid = parent_id or library_id or ""
|
||||
if not target_guid:
|
||||
return _SchemaMediaServerBrowsePage(items=[], total_count=0, start_index=safe_start, limit=safe_limit, has_more=False)
|
||||
page = (safe_start // safe_limit) + 1
|
||||
res = self._api.item_list(guid=target_guid, page=page, page_size=safe_limit)
|
||||
if res is None:
|
||||
return None
|
||||
raw_items = res
|
||||
total = safe_start + len(raw_items) + (1 if len(raw_items) == safe_limit else 0)
|
||||
items: list[_SchemaMediaServerBrowseItem] = []
|
||||
for raw in raw_items:
|
||||
built = self._build_browse_item(raw)
|
||||
if not built:
|
||||
continue
|
||||
if item_type and built.item_type.casefold() != item_type.casefold() and built.media_type != item_type:
|
||||
continue
|
||||
if year and built.year and str(built.year) != str(year):
|
||||
continue
|
||||
items.append(built)
|
||||
return _SchemaMediaServerBrowsePage(
|
||||
items=items,
|
||||
total_count=total,
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=(safe_start + len(raw_items)) < total,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> _SchemaMediaServerFilterOptions:
|
||||
"""返回飞牛媒体库可用筛选与排序选项。"""
|
||||
_ = library_id, username
|
||||
return _SchemaMediaServerFilterOptions(
|
||||
genres=[],
|
||||
years=[],
|
||||
item_types=["Movie", "Series"],
|
||||
sort_options=["date_created", "premiere_date", "rating", "name"],
|
||||
)
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取飞牛单个条目完整详情。"""
|
||||
_ = username
|
||||
if not self.is_authenticated() or not self._api or not item_id:
|
||||
return None
|
||||
raw = self._api.item(guid=item_id)
|
||||
if not raw:
|
||||
return None
|
||||
base = self._build_browse_item(raw)
|
||||
if not base:
|
||||
return None
|
||||
media_source, media_id = MediaServerIdentityHelper.from_provider_ids({
|
||||
"tmdb_id": raw.tmdb_id,
|
||||
"imdb_id": raw.imdb_id,
|
||||
"douban_id": raw.douban_id,
|
||||
})
|
||||
host = (self._playhost or self._host or "").rstrip("/")
|
||||
return _SchemaMediaServerItemDetail(
|
||||
**base.model_dump(),
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
tmdb_id=str(raw.tmdb_id) if raw.tmdb_id else None,
|
||||
imdb_id=raw.imdb_id,
|
||||
douban_id=str(raw.douban_id) if raw.douban_id else None,
|
||||
parent_id=raw.ancestor_guid or None,
|
||||
season_name=raw.parent_title if raw.type == fnapi.Type.EPISODE else None,
|
||||
play_url=self.__build_play_url(host, raw) if host else None,
|
||||
can_play=raw.type in {fnapi.Type.MOVIE, fnapi.Type.EPISODE, fnapi.Type.VIDEO},
|
||||
)
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取飞牛电视剧的全部季卡片。"""
|
||||
_ = username
|
||||
if not self.is_authenticated() or not self._api or not series_id:
|
||||
return None
|
||||
raw_seasons = self._api.season_list(series_id)
|
||||
if raw_seasons is None:
|
||||
return None
|
||||
seasons = [built for s in raw_seasons if (built := self._build_browse_item(s))]
|
||||
for season_item in seasons:
|
||||
season_item.series_id = series_id
|
||||
season_item.item_type = "Season"
|
||||
seasons.sort(key=lambda item: (item.season_number is None, item.season_number or 0))
|
||||
return seasons
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取飞牛指定季的全部单集详情卡片。"""
|
||||
_ = username
|
||||
if not self.is_authenticated() or not self._api:
|
||||
return None
|
||||
target_season_id = season_id
|
||||
if not target_season_id and series_id and season is not None:
|
||||
for s in self._api.season_list(series_id) or []:
|
||||
if s.season_number == season and s.guid:
|
||||
target_season_id = s.guid
|
||||
break
|
||||
if not target_season_id:
|
||||
return []
|
||||
raw_eps = self._api.episode_list(target_season_id)
|
||||
if raw_eps is None:
|
||||
return None
|
||||
episodes = [built for ep in raw_eps if (built := self._build_browse_item(ep))]
|
||||
for ep in episodes:
|
||||
ep.series_id = series_id
|
||||
ep.season_id = target_season_id
|
||||
ep.item_type = "Episode"
|
||||
episodes.sort(key=lambda item: (item.season_number or 0, item.episode_number or 0))
|
||||
return episodes
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""通过飞牛搜索接口返回可播放的已入库电视剧。"""
|
||||
if MediaType.TV.value not in types or not keyword.strip() or not self.is_authenticated() or not self._api:
|
||||
"""通过飞牛搜索接口返回已入库电影和电视剧。"""
|
||||
_ = library_id
|
||||
if not keyword.strip() or not self.is_authenticated() or not self._api:
|
||||
return []
|
||||
want_movie = MediaType.MOVIE.value in types
|
||||
want_tv = MediaType.TV.value in types
|
||||
if not (want_movie or want_tv):
|
||||
return []
|
||||
results: List[_SchemaMediaServerPlayItem] = []
|
||||
for item in self._api.search_list(keywords=keyword.strip()) or []:
|
||||
if item.type != fnapi.Type.TV or not item.guid or not item.title:
|
||||
if not item.guid or not item.title:
|
||||
continue
|
||||
if item.type == fnapi.Type.TV and want_tv:
|
||||
media_type = MediaType.TV.value
|
||||
year = item.air_date[:4] if item.air_date else None
|
||||
elif item.type == fnapi.Type.MOVIE and want_movie:
|
||||
media_type = MediaType.MOVIE.value
|
||||
year = item.release_date[:4] if item.release_date else None
|
||||
else:
|
||||
continue
|
||||
year = item.air_date[:4] if item.air_date else None
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
id=item.guid,
|
||||
@@ -661,9 +892,10 @@ class TrimeMedia:
|
||||
title=item.title,
|
||||
subtitle=year,
|
||||
year=year,
|
||||
type=MediaType.TV.value,
|
||||
image=item.poster,
|
||||
type=media_type,
|
||||
image=self._resolve_fn_image(item.poster or item.posters),
|
||||
server_type="trimemedia",
|
||||
use_cookies=True,
|
||||
)
|
||||
)
|
||||
if len(results) >= max(1, limit):
|
||||
|
||||
@@ -221,12 +221,27 @@ class UgreenModule(_MediaServerModuleBase[Ugreen]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: List[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: List[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""搜索所有已启用绿联实例,并保留每条结果的配置名称。"""
|
||||
"""搜索指定或所有已启用绿联实例,并保留每条结果的配置名称。"""
|
||||
items: List[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
matched = (
|
||||
server_obj.search_library(keyword, types, limit, library_id=library_id)
|
||||
if library_id
|
||||
else server_obj.search_library(keyword, types, limit)
|
||||
)
|
||||
for item in matched:
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
@@ -10,6 +10,7 @@ from pathlib import Path
|
||||
from typing import Any, Dict, Generator, Iterable, List, Mapping, Optional, Union
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.configuration import get_configured_system_config
|
||||
from app.application.mediaserver import (
|
||||
MediaServerIdentityHelper,
|
||||
@@ -17,10 +18,34 @@ from app.application.mediaserver import (
|
||||
format_emby_family_item,
|
||||
)
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.modules._base.emby_browse import (
|
||||
EmbyBrowseConfig,
|
||||
emby_browse_items,
|
||||
emby_filter_options,
|
||||
emby_item_detail,
|
||||
emby_report_progress,
|
||||
emby_search_library,
|
||||
emby_season_episodes,
|
||||
emby_seasons,
|
||||
emby_stream_url,
|
||||
emby_subtitle_url,
|
||||
)
|
||||
from app.modules.ugreen.api import Api, UgreenMediaApi
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItemUserState as _SchemaMediaServerItemUserState
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
@@ -1863,83 +1888,280 @@ class Ugreen:
|
||||
|
||||
return self.__build_media_server_item(video_info, info.get("play_status"))
|
||||
|
||||
def _media_service_browse_config(self) -> Optional[EmbyBrowseConfig]:
|
||||
"""
|
||||
为绿联媒体库服务(Emby 兼容)构造统一浏览协议配置。
|
||||
"""
|
||||
if not self.__is_media_service_mode() or not self._media_api:
|
||||
return None
|
||||
if not self._media_api.host or not self._media_api.token or not self._media_api.user_id:
|
||||
return None
|
||||
verify_ssl = getattr(self, "_verify_ssl", True)
|
||||
return EmbyBrowseConfig(
|
||||
host=f"{self._media_api.host.rstrip('/')}/",
|
||||
api_key=self._media_api.token,
|
||||
user_id=self._media_api.user_id,
|
||||
server_type="ugreen",
|
||||
api_prefix="",
|
||||
play_host=self._playhost,
|
||||
server_id=self._media_api.server_id,
|
||||
request_factory=lambda: RequestUtils(timeout=15, verify=verify_ssl),
|
||||
include_api_key_param=True,
|
||||
image_api_key=True,
|
||||
play_url_builder=lambda _: self.__build_root_url(),
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览绿联媒体库(优先走 Emby 兼容媒体库服务,内部模式回退列表接口)。"""
|
||||
_ = username
|
||||
cfg = self._media_service_browse_config()
|
||||
if cfg:
|
||||
return emby_browse_items(
|
||||
cfg,
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
)
|
||||
if not self.is_authenticated() or not self._api:
|
||||
return None
|
||||
safe_start = max(0, int(start_index))
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
page_num = (safe_start // safe_limit) + 1
|
||||
classification = -103 if (item_type or "").casefold() in {"series", "tv", "电视剧"} else -102
|
||||
data = (
|
||||
self._api.search(keyword.strip())
|
||||
if keyword and keyword.strip()
|
||||
else self._api.video_all(
|
||||
classification=classification,
|
||||
page=page_num,
|
||||
page_size=safe_limit,
|
||||
)
|
||||
)
|
||||
if not isinstance(data, Mapping):
|
||||
return None
|
||||
raw_list = data.get("video_arr") or (
|
||||
list(data.get("movie_list") or []) + list(data.get("tv_list") or [])
|
||||
)
|
||||
items: list[_SchemaMediaServerBrowseItem] = []
|
||||
for entry in raw_list:
|
||||
info = entry.get("video_info") if isinstance(entry, Mapping) and isinstance(entry.get("video_info"), Mapping) else entry
|
||||
if not isinstance(info, Mapping) or not info.get("ug_video_info_id"):
|
||||
continue
|
||||
item_t = self.__map_item_type(info.get("type")) or "Movie"
|
||||
item_year = self.__parse_year(dict(info))
|
||||
if year and item_year and int(item_year) != int(year):
|
||||
continue
|
||||
poster = self.__resolve_image(info.get("poster_path"))
|
||||
backdrop = self.__resolve_image(info.get("backdrop_path"))
|
||||
items.append(
|
||||
_SchemaMediaServerBrowseItem(
|
||||
item_id=str(info["ug_video_info_id"]),
|
||||
server_type="ugreen",
|
||||
item_type=item_t,
|
||||
media_type=MediaType.TV.value if item_t == "Series" else MediaType.MOVIE.value,
|
||||
title=str(info.get("name") or ""),
|
||||
original_title=info.get("original_name"),
|
||||
subtitle=str(item_year) if item_year else None,
|
||||
overview=info.get("overview"),
|
||||
year=item_year,
|
||||
rating=float(info["vote_average"]) if isinstance(info.get("vote_average"), (int, float)) else None,
|
||||
poster=poster,
|
||||
backdrop=backdrop,
|
||||
thumb=backdrop or poster,
|
||||
)
|
||||
)
|
||||
total = int(data.get("total") or (safe_start + len(items)))
|
||||
return _SchemaMediaServerBrowsePage(
|
||||
items=items[:safe_limit],
|
||||
total_count=total,
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=(safe_start + len(items)) < total,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> _SchemaMediaServerFilterOptions:
|
||||
"""获取绿联媒体库可用筛选选项。"""
|
||||
_ = username
|
||||
cfg = self._media_service_browse_config()
|
||||
if cfg:
|
||||
return emby_filter_options(cfg, library_id=library_id)
|
||||
return _SchemaMediaServerFilterOptions(
|
||||
genres=[],
|
||||
years=[],
|
||||
item_types=["Movie", "Series"],
|
||||
sort_options=["date_created", "premiere_date", "rating", "name"],
|
||||
)
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取绿联条目完整详情。"""
|
||||
_ = username
|
||||
cfg = self._media_service_browse_config()
|
||||
if cfg:
|
||||
return emby_item_detail(cfg, item_id)
|
||||
item = self.get_iteminfo(item_id)
|
||||
if not item or not item.item_id:
|
||||
return None
|
||||
return _SchemaMediaServerItemDetail(
|
||||
item_id=item.item_id,
|
||||
server_type="ugreen",
|
||||
item_type=item.item_type or "Movie",
|
||||
media_type=MediaType.TV.value if item.item_type == "Series" else MediaType.MOVIE.value,
|
||||
title=item.title or item.item_id,
|
||||
original_title=item.original_title,
|
||||
year=item.year,
|
||||
media_source=item.media_source,
|
||||
media_id=item.media_id,
|
||||
tmdb_id=item.media_id if item.media_source == MediaSource.TMDB else None,
|
||||
play_url=self.get_play_url(item.item_id),
|
||||
can_play=item.item_type in {"Movie", "Episode"},
|
||||
)
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取绿联电视剧的全部季卡片。"""
|
||||
_ = username
|
||||
cfg = self._media_service_browse_config()
|
||||
if cfg:
|
||||
return emby_seasons(cfg, series_id)
|
||||
_, season_map = self.get_tv_episodes(item_id=series_id)
|
||||
if season_map is None:
|
||||
return None
|
||||
return [
|
||||
_SchemaMediaServerBrowseItem(
|
||||
item_id=f"{series_id}:season:{season_num}",
|
||||
server_type="ugreen",
|
||||
item_type="Season",
|
||||
media_type=MediaType.TV.value,
|
||||
title=f"第 {season_num} 季" if season_num > 0 else "特别篇",
|
||||
series_id=series_id,
|
||||
season_number=season_num,
|
||||
child_count=len(eps),
|
||||
)
|
||||
for season_num, eps in sorted(season_map.items())
|
||||
]
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取绿联指定季的全部单集详情卡片。"""
|
||||
_ = username
|
||||
cfg = self._media_service_browse_config()
|
||||
if cfg:
|
||||
return emby_season_episodes(cfg, series_id, season_id=season_id, season=season)
|
||||
return []
|
||||
|
||||
def get_stream_url(
|
||||
self,
|
||||
item_id: str,
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""获取绿联媒体库服务的静态原始流地址。"""
|
||||
cfg = self._media_service_browse_config()
|
||||
return emby_stream_url(cfg, item_id, item_type, media_source_id=media_source_id) if cfg else None
|
||||
|
||||
def get_subtitle_url(self, item_id: str, subtitle_id: str) -> Optional[str]:
|
||||
"""解析绿联媒体库服务外挂字幕流地址。"""
|
||||
cfg = self._media_service_browse_config()
|
||||
return emby_subtitle_url(cfg, item_id, subtitle_id) if cfg else None
|
||||
|
||||
def report_progress(
|
||||
self,
|
||||
item_id: str,
|
||||
*,
|
||||
position_ms: int,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""回传绿联媒体库服务的播放进度。"""
|
||||
_ = duration_ms, username
|
||||
cfg = self._media_service_browse_config()
|
||||
if not cfg:
|
||||
return False
|
||||
return emby_report_progress(
|
||||
cfg, item_id, position_ms, media_source_id=media_source_id, is_paused=is_paused, state=state
|
||||
)
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""通过绿联搜索接口返回可播放的电视剧与音乐库单曲。"""
|
||||
"""通过绿联搜索接口返回电影、电视剧与音乐库单曲。"""
|
||||
if not self.is_authenticated() or not keyword.strip():
|
||||
return []
|
||||
cfg = self._media_service_browse_config()
|
||||
if cfg:
|
||||
return emby_search_library(cfg, keyword, types, limit, library_id=library_id)
|
||||
if not self._api:
|
||||
return []
|
||||
results: List[_SchemaMediaServerPlayItem] = []
|
||||
if self.__is_media_service_mode() and self._media_api:
|
||||
item_types = []
|
||||
if MediaType.TV.value in types:
|
||||
item_types.append("Series")
|
||||
if MediaType.MUSIC.value in types:
|
||||
item_types.append("Audio")
|
||||
if not item_types:
|
||||
return []
|
||||
data = self._media_api.items(
|
||||
include_item_types=",".join(item_types),
|
||||
search_term=keyword.strip(),
|
||||
limit=max(1, min(limit, 50)),
|
||||
fields="ProductionYear,Album,Artists,AlbumArtist,ImageTags,Path,ParentId,ServerId",
|
||||
)
|
||||
for raw_item in (data or {}).get("Items") or []:
|
||||
raw_type = raw_item.get("Type")
|
||||
media_type = MediaType.TV.value if raw_type == "Series" else MediaType.MUSIC.value
|
||||
item = self.__format_media_service_item(raw_item)
|
||||
if media_type not in types or not item or not item.item_id or not item.title:
|
||||
data = self._api.search(keyword.strip()) or {}
|
||||
buckets = []
|
||||
if MediaType.MOVIE.value in types:
|
||||
buckets.append((MediaType.MOVIE.value, data.get("movie_list")))
|
||||
if MediaType.TV.value in types:
|
||||
buckets.append((MediaType.TV.value, data.get("tv_list")))
|
||||
for media_type, raw_bucket in buckets:
|
||||
for info in self.__extract_video_info_list(raw_bucket):
|
||||
item = self.__build_media_server_item(info)
|
||||
if not item or not item.item_id or not item.title:
|
||||
continue
|
||||
artists = raw_item.get("Artists") or []
|
||||
artist = next(
|
||||
(str(value.get("Name") if isinstance(value, Mapping) else value) for value in artists if value),
|
||||
None,
|
||||
image = self.__resolve_image(info.get("poster_path")) or self.__resolve_image(
|
||||
info.get("backdrop_path")
|
||||
)
|
||||
album = raw_item.get("Album")
|
||||
year = raw_item.get("ProductionYear")
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
id=item.item_id,
|
||||
item_id=item.item_id,
|
||||
server_id=item.server_id,
|
||||
title=item.title,
|
||||
subtitle=(f"{artist or ''}{f' · {album}' if album else ''}" or None)
|
||||
if media_type == MediaType.MUSIC.value
|
||||
else str(year) if year else None,
|
||||
year=year,
|
||||
subtitle=str(item.year) if item.year else None,
|
||||
year=item.year,
|
||||
type=media_type,
|
||||
image=self.__build_media_service_image_url(item.item_id, remote=True),
|
||||
image=image,
|
||||
server_type="ugreen",
|
||||
)
|
||||
)
|
||||
if len(results) >= limit:
|
||||
break
|
||||
return results
|
||||
|
||||
if MediaType.TV.value not in types or not self._api:
|
||||
return []
|
||||
data = self._api.search(keyword.strip()) or {}
|
||||
for info in self.__extract_video_info_list(data.get("tv_list")):
|
||||
item = self.__build_media_server_item(info)
|
||||
if not item or not item.item_id or not item.title:
|
||||
continue
|
||||
image = self.__resolve_image(info.get("poster_path")) or self.__resolve_image(
|
||||
info.get("backdrop_path")
|
||||
)
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
id=item.item_id,
|
||||
item_id=item.item_id,
|
||||
title=item.title,
|
||||
subtitle=str(item.year) if item.year else None,
|
||||
year=item.year,
|
||||
type=MediaType.TV.value,
|
||||
image=image,
|
||||
server_type="ugreen",
|
||||
)
|
||||
)
|
||||
if len(results) >= limit:
|
||||
break
|
||||
return results
|
||||
return results
|
||||
|
||||
def _iter_library_videos(
|
||||
|
||||
@@ -187,12 +187,27 @@ class VyoModule(_MediaServerModuleBase[Vyo]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: List[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: List[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""搜索所有已启用 Vyo 实例,并保留每条结果的配置名称。"""
|
||||
"""搜索指定或所有已启用 Vyo 实例,并保留每条结果的配置名称。"""
|
||||
items: List[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
matched = (
|
||||
server_obj.search_library(keyword, types, limit, library_id=library_id)
|
||||
if library_id
|
||||
else server_obj.search_library(keyword, types, limit)
|
||||
)
|
||||
for item in matched:
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
@@ -10,7 +10,22 @@ from app.foundation.url import UrlUtils
|
||||
from app.modules.vyo.api import Api
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerMediaSource as _SchemaMediaServerMediaSource,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItemUserState as _SchemaMediaServerItemUserState
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
@@ -384,20 +399,222 @@ class Vyo:
|
||||
movies.append(item)
|
||||
return movies
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""调用 Vyo 的剧集搜索接口并生成带海报的原生播放目标。"""
|
||||
if MediaType.TV.value not in types or not keyword.strip() or not self.is_configured():
|
||||
def _build_browse_item(self, row: Dict[str, Any]) -> Optional[_SchemaMediaServerBrowseItem]:
|
||||
"""将 Vyo 条目行转换为统一浏览卡片模型。"""
|
||||
row_id = str(row.get("id") or "")
|
||||
title = str(row.get("title") or "").strip()
|
||||
if not row_id or not title:
|
||||
return None
|
||||
kind = str(row.get("kind") or "Movie")
|
||||
is_tv = kind in {"Series", "Season", "Episode"}
|
||||
user_data = row.get("user_data") or {}
|
||||
duration_ticks = row.get("duration_ticks") or 0
|
||||
position_ticks = user_data.get("position_ticks") or 0
|
||||
duration_ms = int(duration_ticks // 10_000) if duration_ticks > 0 else None
|
||||
resume_ms = int(position_ticks // 10_000) if position_ticks > 0 else None
|
||||
percentage = round(min(100.0, position_ticks / duration_ticks * 100.0), 1) if duration_ticks and position_ticks else None
|
||||
season_num = row.get("season") if isinstance(row.get("season"), int) else None
|
||||
ep_num = row.get("episode") if isinstance(row.get("episode"), int) else None
|
||||
subtitle = (
|
||||
f"S{season_num:02d}E{ep_num:02d}"
|
||||
if kind == "Episode" and season_num is not None and ep_num is not None
|
||||
else (str(row["year"]) if row.get("year") else None)
|
||||
)
|
||||
metadata = row.get("metadata_info") or {}
|
||||
return _SchemaMediaServerBrowseItem(
|
||||
item_id=row_id,
|
||||
server_type="mediavault",
|
||||
item_type=kind,
|
||||
media_type=MediaType.TV.value if is_tv else MediaType.MOVIE.value,
|
||||
title=title,
|
||||
original_title=metadata.get("original_title"),
|
||||
subtitle=subtitle,
|
||||
overview=metadata.get("overview") or row.get("overview"),
|
||||
year=row.get("year"),
|
||||
rating=float(metadata["rating"]) if isinstance(metadata.get("rating"), (int, float)) else None,
|
||||
duration_ms=duration_ms,
|
||||
poster=self._api.image_url(str(row.get("series_id") or row_id), "primary") if kind == "Episode" else self._api.image_url(row_id, "primary"),
|
||||
backdrop=self._api.image_url(row_id, "backdrop") if row.get("has_backdrop") else None,
|
||||
thumb=self._api.image_url(row_id, "primary"),
|
||||
series_id=str(row["series_id"]) if row.get("series_id") else None,
|
||||
series_name=row.get("series_name"),
|
||||
season_id=str(row["season_id"]) if row.get("season_id") else None,
|
||||
season_number=season_num,
|
||||
episode_number=ep_num,
|
||||
played=user_data.get("played") if "played" in user_data else None,
|
||||
played_percentage=percentage,
|
||||
resume_position_ms=resume_ms,
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览 Vyo 媒体库条目。"""
|
||||
_ = genre, year, username
|
||||
if not self.is_configured():
|
||||
return None
|
||||
safe_start = max(0, int(start_index))
|
||||
safe_limit = max(1, min(int(limit), self.PAGE_LIMIT))
|
||||
page = (safe_start // safe_limit) + 1
|
||||
sort_map = {"date_created": "added", "premiere_date": "year", "rating": "rating", "name": "title"}
|
||||
kinds = {"movie": "Movie", "series": "Series", "电影": "Movie", "电视剧": "Series"}.get(
|
||||
str(item_type or "").casefold(), "Movie,Series"
|
||||
)
|
||||
result = self.__query_items(
|
||||
library_id="" if parent_id else (library_id or ""),
|
||||
parent_id=parent_id or "",
|
||||
keyword=keyword.strip() if keyword and keyword.strip() else "",
|
||||
kinds=kinds,
|
||||
filter_by=played_filter or "",
|
||||
sort_by=sort_map.get((sort_by or "date_created").casefold(), "added"),
|
||||
sort_order=(sort_order or "desc").casefold(),
|
||||
page=page,
|
||||
page_size=safe_limit,
|
||||
)
|
||||
if result is None:
|
||||
return None
|
||||
items = [built for row in (result.get("items") or []) if isinstance(row, dict) and (built := self._build_browse_item(row))]
|
||||
total = int(result.get("total") or (safe_start + len(items)))
|
||||
return _SchemaMediaServerBrowsePage(
|
||||
items=items,
|
||||
total_count=total,
|
||||
start_index=safe_start,
|
||||
limit=safe_limit,
|
||||
has_more=(safe_start + len(items)) < total,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> _SchemaMediaServerFilterOptions:
|
||||
"""返回 Vyo 支持的筛选与排序选项。"""
|
||||
_ = library_id, username
|
||||
return _SchemaMediaServerFilterOptions(
|
||||
genres=[],
|
||||
years=[],
|
||||
item_types=["Movie", "Series"],
|
||||
sort_options=["date_created", "premiere_date", "rating", "name"],
|
||||
)
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取 Vyo 单个条目完整详情。"""
|
||||
_ = username
|
||||
if not item_id or not self.is_configured():
|
||||
return None
|
||||
result = self._api.request(f"/items/{item_id}", suppress_log=True)
|
||||
if not result or not result.success or not isinstance(result.data, dict):
|
||||
return None
|
||||
row = result.data
|
||||
base = self._build_browse_item(row)
|
||||
if not base:
|
||||
return None
|
||||
metadata = row.get("metadata_info") or {}
|
||||
ext_ids = metadata.get("external_ids") or {}
|
||||
provider_ids: dict[str, Any] = {}
|
||||
if row.get("tmdb_id"):
|
||||
provider_ids["Tmdb"] = str(row["tmdb_id"])
|
||||
if ext_ids.get("imdb_id"):
|
||||
provider_ids["Imdb"] = str(ext_ids["imdb_id"])
|
||||
if ext_ids.get("tvdb_id"):
|
||||
provider_ids["Tvdb"] = str(ext_ids["tvdb_id"])
|
||||
media_source, media_id = MediaServerIdentityHelper.from_provider_ids(provider_ids)
|
||||
sources = [
|
||||
_SchemaMediaServerMediaSource(
|
||||
id=str(src.get("id") or idx),
|
||||
name=src.get("name") or Path(str(src.get("path") or "")).name or None,
|
||||
size=src.get("size") if isinstance(src.get("size"), int) else None,
|
||||
)
|
||||
for idx, src in enumerate(row.get("sources") or [])
|
||||
if isinstance(src, dict)
|
||||
]
|
||||
return _SchemaMediaServerItemDetail(
|
||||
**base.model_dump(),
|
||||
genres=[str(g) for g in (metadata.get("genres") or []) if g],
|
||||
media_source=media_source,
|
||||
media_id=media_id,
|
||||
tmdb_id=str(row["tmdb_id"]) if row.get("tmdb_id") else None,
|
||||
imdb_id=str(ext_ids["imdb_id"]) if ext_ids.get("imdb_id") else None,
|
||||
tvdb_id=str(ext_ids["tvdb_id"]) if ext_ids.get("tvdb_id") else None,
|
||||
parent_id=str(row["parent_id"]) if row.get("parent_id") else None,
|
||||
media_sources=sources,
|
||||
play_url=self.get_play_url(base.item_id),
|
||||
can_play=base.item_type in {"Movie", "Episode"},
|
||||
)
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取 Vyo 电视剧的全部季卡片。"""
|
||||
_ = username
|
||||
if not series_id or not self.is_configured():
|
||||
return None
|
||||
result = self.__query_items(parent_id=series_id, kinds="Season", page=1, page_size=self.PAGE_LIMIT)
|
||||
if result is None:
|
||||
return None
|
||||
seasons = [built for row in (result.get("items") or []) if isinstance(row, dict) and (built := self._build_browse_item(row))]
|
||||
seasons.sort(key=lambda item: (item.season_number is None, item.season_number or 0))
|
||||
return seasons
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取 Vyo 指定季的全部单集卡片。"""
|
||||
_ = username
|
||||
if not self.is_configured():
|
||||
return None
|
||||
target_parent = season_id or (self.__find_season_id(series_id, season) if season is not None else "")
|
||||
if not target_parent:
|
||||
return []
|
||||
rows = self.__search_rows(keyword=keyword.strip(), kinds="Series")
|
||||
result = self.__query_items(parent_id=target_parent, kinds="Episode", page=1, page_size=self.PAGE_LIMIT)
|
||||
if result is None:
|
||||
return None
|
||||
episodes = [built for row in (result.get("items") or []) if isinstance(row, dict) and (built := self._build_browse_item(row))]
|
||||
episodes.sort(key=lambda item: (item.season_number or 0, item.episode_number or 0))
|
||||
return episodes
|
||||
|
||||
def search_library(
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""调用 Vyo 搜索接口返回电影与电视剧。"""
|
||||
_ = library_id
|
||||
kinds_list = []
|
||||
if MediaType.MOVIE.value in types:
|
||||
kinds_list.append("Movie")
|
||||
if MediaType.TV.value in types:
|
||||
kinds_list.append("Series")
|
||||
if not kinds_list or not keyword.strip() or not self.is_configured():
|
||||
return []
|
||||
rows = self.__search_rows(keyword=keyword.strip(), kinds=",".join(kinds_list))
|
||||
if rows is None:
|
||||
return []
|
||||
results: List[_SchemaMediaServerPlayItem] = []
|
||||
try:
|
||||
for row in rows:
|
||||
item = self.__format_item_info(row)
|
||||
if not item or not item.item_id or not item.title or item.item_type != "Series":
|
||||
if not item or not item.item_id or not item.title or item.item_type not in kinds_list:
|
||||
continue
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
@@ -406,7 +623,7 @@ class Vyo:
|
||||
title=item.title,
|
||||
subtitle=str(item.year) if item.year else None,
|
||||
year=item.year,
|
||||
type=MediaType.TV.value,
|
||||
type=MediaType.TV.value if item.item_type == "Series" else MediaType.MOVIE.value,
|
||||
image=self._api.image_url(item.item_id, "primary"),
|
||||
server_type="vyo",
|
||||
)
|
||||
|
||||
@@ -191,12 +191,27 @@ class ZSpaceModule(_MediaServerModuleBase[ZSpace]):
|
||||
return None
|
||||
|
||||
def mediaserver_search(
|
||||
self, keyword: str, types: List[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: List[str],
|
||||
limit: int,
|
||||
server: Optional[str] = None,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""搜索所有已启用极影视实例,并保留每条结果的配置名称。"""
|
||||
"""搜索指定或所有已启用极影视实例,并保留每条结果的配置名称。"""
|
||||
items: List[_SchemaMediaServerPlayItem] = []
|
||||
for server_name, server_obj in self.get_instances().items():
|
||||
for item in server_obj.search_library(keyword, types, limit):
|
||||
target_instances = (
|
||||
{server: inst}
|
||||
if server and (inst := self.get_instance(server))
|
||||
else ({} if server else self.get_instances())
|
||||
)
|
||||
for server_name, server_obj in target_instances.items():
|
||||
matched = (
|
||||
server_obj.search_library(keyword, types, limit, library_id=library_id)
|
||||
if library_id
|
||||
else server_obj.search_library(keyword, types, limit)
|
||||
)
|
||||
for item in matched:
|
||||
item.server = server_name
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
@@ -13,10 +13,34 @@ from requests import Response
|
||||
from app.adapters.network.http import RequestUtils
|
||||
from app.application.mediaserver import MediaServerIdentityHelper, format_emby_family_item
|
||||
from app.foundation.url import UrlUtils
|
||||
from app.modules._base.emby_browse import (
|
||||
EmbyBrowseConfig,
|
||||
emby_browse_items,
|
||||
emby_filter_options,
|
||||
emby_item_detail,
|
||||
emby_report_progress,
|
||||
emby_search_library,
|
||||
emby_season_episodes,
|
||||
emby_seasons,
|
||||
emby_stream_url,
|
||||
emby_subtitle_url,
|
||||
)
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.dashboard import Statistic as _SchemaStatistic
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem as _SchemaMediaServerBrowseItem,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowsePage as _SchemaMediaServerBrowsePage,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerFilterOptions as _SchemaMediaServerFilterOptions,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerItem
|
||||
from app.schemas.mediaserver import MediaServerItem as _SchemaMediaServerItem
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerItemDetail as _SchemaMediaServerItemDetail,
|
||||
)
|
||||
from app.schemas.mediaserver import MediaServerLibrary as _SchemaMediaServerLibrary
|
||||
from app.schemas.mediaserver import MediaServerPlayItem as _SchemaMediaServerPlayItem
|
||||
from app.schemas.mediaserver import RefreshMediaItem as _SchemaRefreshMediaItem
|
||||
@@ -886,71 +910,140 @@ class ZSpace:
|
||||
"""
|
||||
return format_emby_family_item(item, server="zspace")
|
||||
|
||||
def _browse_config(self, username: Optional[str] = None) -> Optional[EmbyBrowseConfig]:
|
||||
"""
|
||||
构造极影视的 Emby 兼容浏览协议配置。
|
||||
"""
|
||||
_ = username
|
||||
if not self._host or not self._apikey or not self.user:
|
||||
return None
|
||||
return EmbyBrowseConfig(
|
||||
host=self._host,
|
||||
api_key=self._apikey,
|
||||
user_id=str(self.user),
|
||||
server_type="zspace",
|
||||
api_prefix="emby/",
|
||||
play_host=self._playhost,
|
||||
server_id=getattr(self, "serverid", None),
|
||||
request_factory=lambda: self.__request_utils(),
|
||||
include_api_key_param=True,
|
||||
image_api_key=True,
|
||||
play_url_builder=self.get_play_url,
|
||||
)
|
||||
|
||||
def browse_items(
|
||||
self,
|
||||
*,
|
||||
library_id: Optional[str] = None,
|
||||
parent_id: Optional[str] = None,
|
||||
item_type: Optional[str] = None,
|
||||
genre: Optional[str] = None,
|
||||
year: Optional[int] = None,
|
||||
played_filter: Optional[str] = None,
|
||||
sort_by: Optional[str] = None,
|
||||
sort_order: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
start_index: int = 0,
|
||||
limit: int = 30,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[_SchemaMediaServerBrowsePage]:
|
||||
"""分页浏览极影视媒体库并支持筛选、排序和搜索。"""
|
||||
cfg = self._browse_config(username)
|
||||
if not cfg:
|
||||
return None
|
||||
return emby_browse_items(
|
||||
cfg,
|
||||
library_id=library_id,
|
||||
parent_id=parent_id,
|
||||
item_type=item_type,
|
||||
genre=genre,
|
||||
year=year,
|
||||
played_filter=played_filter,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
keyword=keyword,
|
||||
start_index=start_index,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
def get_filter_options(
|
||||
self, library_id: Optional[str] = None, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerFilterOptions]:
|
||||
"""获取极影视媒体库可用筛选选项。"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_filter_options(cfg, library_id=library_id) if cfg else None
|
||||
|
||||
def get_item_detail(
|
||||
self, item_id: str, username: Optional[str] = None
|
||||
) -> Optional[_SchemaMediaServerItemDetail]:
|
||||
"""获取极影视条目完整详情。"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_item_detail(cfg, item_id) if cfg else None
|
||||
|
||||
def get_seasons(
|
||||
self, series_id: str, username: Optional[str] = None
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取极影视电视剧的全部季卡片。"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_seasons(cfg, series_id) if cfg else None
|
||||
|
||||
def get_season_episodes(
|
||||
self,
|
||||
series_id: str,
|
||||
*,
|
||||
season_id: Optional[str] = None,
|
||||
season: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
) -> Optional[List[_SchemaMediaServerBrowseItem]]:
|
||||
"""获取极影视指定季的全部单集卡片。"""
|
||||
cfg = self._browse_config(username)
|
||||
return emby_season_episodes(cfg, series_id, season_id=season_id, season=season) if cfg else None
|
||||
|
||||
def get_stream_url(
|
||||
self,
|
||||
item_id: str,
|
||||
item_type: Optional[str],
|
||||
media_source_id: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""获取极影视 Emby 兼容静态媒体流地址。"""
|
||||
cfg = self._browse_config()
|
||||
return emby_stream_url(cfg, item_id, item_type, media_source_id=media_source_id) if cfg else None
|
||||
|
||||
def get_subtitle_url(self, item_id: str, subtitle_id: str) -> Optional[str]:
|
||||
"""解析极影视服务端字幕下载流地址。"""
|
||||
cfg = self._browse_config()
|
||||
return emby_subtitle_url(cfg, item_id, subtitle_id) if cfg else None
|
||||
|
||||
def report_progress(
|
||||
self,
|
||||
item_id: str,
|
||||
*,
|
||||
position_ms: int,
|
||||
media_source_id: Optional[str] = None,
|
||||
duration_ms: Optional[int] = None,
|
||||
is_paused: bool = False,
|
||||
state: str = "playing",
|
||||
username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""回传极影视播放进度。"""
|
||||
_ = duration_ms
|
||||
cfg = self._browse_config(username)
|
||||
if not cfg:
|
||||
return False
|
||||
return emby_report_progress(
|
||||
cfg, item_id, position_ms, media_source_id=media_source_id, is_paused=is_paused, state=state
|
||||
)
|
||||
|
||||
def search_library(
|
||||
self, keyword: str, types: list[str], limit: int
|
||||
self,
|
||||
keyword: str,
|
||||
types: list[str],
|
||||
limit: int,
|
||||
library_id: Optional[str] = None,
|
||||
) -> List[_SchemaMediaServerPlayItem]:
|
||||
"""通过极影视 Emby 兼容接口搜索电视剧与音乐单曲。"""
|
||||
if not self._host or not self._apikey or not self.user or not keyword.strip():
|
||||
return []
|
||||
server_types = []
|
||||
if MediaType.TV.value in types:
|
||||
server_types.append("Series")
|
||||
if MediaType.MUSIC.value in types:
|
||||
server_types.append("Audio")
|
||||
if not server_types:
|
||||
return []
|
||||
url = f"{self._host}emby/Users/{self.user}/Items"
|
||||
params = {
|
||||
"api_key": self._apikey,
|
||||
"IncludeItemTypes": ",".join(server_types),
|
||||
"Fields": "ProductionYear,Album,Artists,AlbumArtist,ImageTags",
|
||||
"Recursive": "true",
|
||||
"SearchTerm": keyword.strip(),
|
||||
"StartIndex": 0,
|
||||
"Limit": max(1, min(limit, 50)),
|
||||
}
|
||||
try:
|
||||
response = self.__request_utils().get_res(url, params)
|
||||
if not response or response.status_code != 200:
|
||||
return []
|
||||
results: List[_SchemaMediaServerPlayItem] = []
|
||||
for item in (response.json().get("Items") or []):
|
||||
item_id = str(item.get("Id") or "")
|
||||
title = item.get("Name")
|
||||
item_type = item.get("Type")
|
||||
if not item_id or not title or item_type not in server_types:
|
||||
continue
|
||||
artists = item.get("Artists") or []
|
||||
artist = next(
|
||||
(str(value.get("Name") if isinstance(value, dict) else value) for value in artists if value),
|
||||
None,
|
||||
)
|
||||
album = item.get("Album")
|
||||
year = item.get("ProductionYear")
|
||||
image = f"{self._host}Items/{item_id}/Images/Primary?api_key={self._apikey}"
|
||||
image_tag = (item.get("ImageTags") or {}).get("Primary")
|
||||
if image_tag:
|
||||
image += f"&tag={image_tag}"
|
||||
results.append(
|
||||
_SchemaMediaServerPlayItem(
|
||||
id=item_id,
|
||||
item_id=item_id,
|
||||
title=title,
|
||||
subtitle=(f"{artist or ''}{f' · {album}' if album else ''}" or None)
|
||||
if item_type == "Audio"
|
||||
else str(year) if year else None,
|
||||
year=year,
|
||||
type=MediaType.TV.value if item_type == "Series" else MediaType.MUSIC.value,
|
||||
image=image,
|
||||
server_type="zspace",
|
||||
)
|
||||
)
|
||||
if len(results) >= limit:
|
||||
break
|
||||
return results
|
||||
except Exception as err:
|
||||
logger.debug(f"搜索极影视媒体库出错:{err}")
|
||||
return []
|
||||
"""通过极影视 Emby 兼容接口搜索电影、电视剧与音乐单曲。"""
|
||||
cfg = self._browse_config()
|
||||
return emby_search_library(cfg, keyword, types, limit, library_id=library_id) if cfg else []
|
||||
|
||||
def get_iteminfo(self, itemid: str) -> Optional[_SchemaMediaServerItem]:
|
||||
"""
|
||||
|
||||
@@ -228,6 +228,84 @@ _METHOD_CONTRACTS = {
|
||||
result_shape=ModuleResultShape.STRING,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server", "item_id", "item_type"),
|
||||
optional_parameters=("media_source_id",),
|
||||
public_to_plugins=False,
|
||||
),
|
||||
"mediaserver_subtitle_url": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerSubtitleUrlRequest",
|
||||
result_contract="str | None",
|
||||
result_shape=ModuleResultShape.STRING,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server", "item_id", "subtitle_id"),
|
||||
public_to_plugins=False,
|
||||
),
|
||||
"mediaserver_browse_items": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerBrowseRequest",
|
||||
result_contract="MediaServerBrowsePage | None",
|
||||
result_shape=ModuleResultShape.MODEL,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server",),
|
||||
optional_parameters=(
|
||||
"library_id",
|
||||
"parent_id",
|
||||
"item_type",
|
||||
"genre",
|
||||
"year",
|
||||
"played_filter",
|
||||
"sort_by",
|
||||
"sort_order",
|
||||
"keyword",
|
||||
"start_index",
|
||||
"limit",
|
||||
"username",
|
||||
),
|
||||
),
|
||||
"mediaserver_filter_options": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerFilterOptionsRequest",
|
||||
result_contract="MediaServerFilterOptions | None",
|
||||
result_shape=ModuleResultShape.MODEL,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server",),
|
||||
optional_parameters=("library_id", "username"),
|
||||
),
|
||||
"mediaserver_item_detail": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerItemDetailRequest",
|
||||
result_contract="MediaServerItemDetail | None",
|
||||
result_shape=ModuleResultShape.MODEL,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server", "item_id"),
|
||||
optional_parameters=("username",),
|
||||
),
|
||||
"mediaserver_seasons": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerSeasonsRequest",
|
||||
result_contract="list[MediaServerBrowseItem] | None",
|
||||
result_shape=ModuleResultShape.LIST,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server", "item_id"),
|
||||
optional_parameters=("username",),
|
||||
),
|
||||
"mediaserver_season_episodes": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerSeasonEpisodeListRequest",
|
||||
result_contract="list[MediaServerBrowseItem] | None",
|
||||
result_shape=ModuleResultShape.LIST,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server", "item_id"),
|
||||
optional_parameters=("season_id", "season", "username"),
|
||||
),
|
||||
"mediaserver_report_progress": ModuleMethodContract(
|
||||
family="media-server",
|
||||
input_contract="MediaServerProgressReportRequest",
|
||||
result_contract="bool | None",
|
||||
result_shape=ModuleResultShape.BOOLEAN,
|
||||
aggregation=ModuleResultAggregation.FIRST_NON_EMPTY,
|
||||
required_parameters=("server", "item_id", "position_ms"),
|
||||
optional_parameters=("media_source_id", "duration_ms", "is_paused", "state", "username"),
|
||||
public_to_plugins=False,
|
||||
),
|
||||
"mediaserver_tv_episodes": ModuleMethodContract(
|
||||
@@ -302,6 +380,7 @@ _METHOD_CONTRACTS = {
|
||||
result_shape=ModuleResultShape.LIST,
|
||||
aggregation=ModuleResultAggregation.ORDERED_LIST_MERGE,
|
||||
required_parameters=("keyword", "types", "limit"),
|
||||
optional_parameters=("server", "library_id"),
|
||||
),
|
||||
"mediaserver_playing": ModuleMethodContract(
|
||||
family="media-server",
|
||||
|
||||
@@ -249,8 +249,155 @@ class MediaServerStreamInfo(BaseModel):
|
||||
media_type: Literal["video", "audio"] = Field(default="video", description="播放器使用的媒体类型")
|
||||
artist: Optional[str] = Field(default=None, description="音乐表演者")
|
||||
album: Optional[str] = Field(default=None, description="音乐专辑")
|
||||
subtitles: List[MediaServerSubtitleTrack] = Field(default_factory=list, description="同目录同名外挂字幕")
|
||||
subtitles: List[MediaServerSubtitleTrack] = Field(default_factory=list, description="同目录或媒体服务器提供的外挂字幕")
|
||||
lyrics_url: Optional[str] = Field(default=None, description="当前实例的同名 LRC 歌词流地址")
|
||||
media_source_id: Optional[str] = Field(default=None, description="本次播放绑定的媒体源标识")
|
||||
resume_position_ms: Optional[int] = Field(default=None, description="服务端记录的断点续播位置(毫秒)")
|
||||
duration_ms: Optional[int] = Field(default=None, description="媒体总时长(毫秒)")
|
||||
|
||||
|
||||
class MediaServerMediaStream(BaseModel):
|
||||
"""
|
||||
媒体服务器单个媒体源中的视频、音频或字幕轨道信息。
|
||||
"""
|
||||
|
||||
index: Optional[int] = Field(default=None, description="服务端轨道序号")
|
||||
type: Literal["video", "audio", "subtitle", "unknown"] = Field(default="unknown", description="轨道类型")
|
||||
codec: Optional[str] = Field(default=None, description="轨道编解码格式")
|
||||
language: Optional[str] = Field(default=None, description="轨道语言标识")
|
||||
title: Optional[str] = Field(default=None, description="原始轨道标题")
|
||||
display_title: Optional[str] = Field(default=None, description="适合界面展示的轨道名称")
|
||||
is_default: bool = Field(default=False, description="是否为默认轨道")
|
||||
is_forced: bool = Field(default=False, description="是否为强制字幕轨道")
|
||||
is_external: bool = Field(default=False, description="是否为独立外挂字幕轨道")
|
||||
subtitle_id: Optional[str] = Field(default=None, description="可通过本实例字幕代理下载的字幕标识")
|
||||
channels: Optional[int] = Field(default=None, description="音频声道数")
|
||||
channel_layout: Optional[str] = Field(default=None, description="音频声道布局")
|
||||
bitrate: Optional[int] = Field(default=None, description="轨道码率(bps)")
|
||||
width: Optional[int] = Field(default=None, description="视频宽度(像素)")
|
||||
height: Optional[int] = Field(default=None, description="视频高度(像素)")
|
||||
video_range: Optional[str] = Field(default=None, description="视频动态范围,例如 SDR、HDR")
|
||||
|
||||
|
||||
class MediaServerMediaSource(BaseModel):
|
||||
"""
|
||||
媒体服务器可播放条目的单个文件版本或媒体源信息。
|
||||
"""
|
||||
|
||||
id: str = Field(description="媒体源标识")
|
||||
name: Optional[str] = Field(default=None, description="版本展示名称")
|
||||
container: Optional[str] = Field(default=None, description="封装容器格式")
|
||||
size: Optional[int] = Field(default=None, description="文件字节大小")
|
||||
bitrate: Optional[int] = Field(default=None, description="整体码率(bps)")
|
||||
duration_ms: Optional[int] = Field(default=None, description="媒体源时长(毫秒)")
|
||||
streams: List[MediaServerMediaStream] = Field(default_factory=list, description="包含的视频、音频与字幕轨道")
|
||||
|
||||
|
||||
class MediaServerPerson(BaseModel):
|
||||
"""
|
||||
媒体服务器条目关联的演职员信息。
|
||||
"""
|
||||
|
||||
id: Optional[str] = Field(default=None, description="演职员在媒体服务器中的标识")
|
||||
name: str = Field(description="演职员姓名")
|
||||
role: Optional[str] = Field(default=None, description="饰演角色或职务说明")
|
||||
type: Optional[str] = Field(default=None, description="人员类型,例如 Actor、Director")
|
||||
image: Optional[str] = Field(default=None, description="已签名的头像图片地址")
|
||||
|
||||
|
||||
class MediaServerBrowseItem(BaseModel):
|
||||
"""
|
||||
媒体服务器浏览列表、季列表与分集列表共用的轻量媒体卡片模型。
|
||||
"""
|
||||
|
||||
item_id: str = Field(description="媒体服务器条目标识")
|
||||
server: Optional[str] = Field(default=None, description="所属媒体服务器配置名称")
|
||||
server_type: Optional[str] = Field(default=None, description="媒体服务器类型")
|
||||
item_type: str = Field(default="Movie", description="条目维度:Movie、Series、Season、Episode、MusicAlbum、Audio、Folder")
|
||||
media_type: Optional[str] = Field(default=None, description="统一业务媒体类型:电影、电视剧、音乐")
|
||||
title: str = Field(description="展示标题")
|
||||
original_title: Optional[str] = Field(default=None, description="原始语言标题")
|
||||
subtitle: Optional[str] = Field(default=None, description="副标题或补充信息")
|
||||
overview: Optional[str] = Field(default=None, description="剧情或条目简介")
|
||||
year: Optional[Union[str, int]] = Field(default=None, description="发行或首播年份")
|
||||
premiere_date: Optional[str] = Field(default=None, description="首映或首播日期")
|
||||
rating: Optional[float] = Field(default=None, description="社区评分(0 至 10)")
|
||||
duration_ms: Optional[int] = Field(default=None, description="时长(毫秒)")
|
||||
poster: Optional[str] = Field(default=None, description="已签名的海报主图地址")
|
||||
backdrop: Optional[str] = Field(default=None, description="已签名的背景横图地址")
|
||||
thumb: Optional[str] = Field(default=None, description="已签名的剧照或缩略图地址")
|
||||
series_id: Optional[str] = Field(default=None, description="所属剧集条目标识")
|
||||
series_name: Optional[str] = Field(default=None, description="所属剧集标题")
|
||||
season_id: Optional[str] = Field(default=None, description="所属季条目标识")
|
||||
season_number: Optional[int] = Field(default=None, description="季号")
|
||||
episode_number: Optional[int] = Field(default=None, description="集号")
|
||||
child_count: Optional[int] = Field(default=None, description="子条目数量,例如季数或集数")
|
||||
played: Optional[bool] = Field(default=None, description="当前用户是否已观看完成")
|
||||
played_percentage: Optional[float] = Field(default=None, description="观看进度百分比(0 至 100)")
|
||||
resume_position_ms: Optional[int] = Field(default=None, description="续播位置(毫秒)")
|
||||
use_cookies: Optional[bool] = Field(default=None, description="图片代理访问是否需要携带服务端 Cookie")
|
||||
|
||||
|
||||
class MediaServerBrowsePage(BaseModel):
|
||||
"""
|
||||
媒体服务器媒体库分页浏览结果。
|
||||
"""
|
||||
|
||||
items: List[MediaServerBrowseItem] = Field(default_factory=list, description="当前页媒体条目")
|
||||
total_count: int = Field(default=0, description="符合筛选条件的总条目数")
|
||||
start_index: int = Field(default=0, description="当前页零基起始偏移")
|
||||
limit: int = Field(default=30, description="当前页请求上限")
|
||||
has_more: bool = Field(default=False, description="是否存在下一页数据")
|
||||
|
||||
|
||||
class MediaServerFilterOptions(BaseModel):
|
||||
"""
|
||||
媒体服务器指定媒体库可用的筛选与排序选项。
|
||||
"""
|
||||
|
||||
genres: List[str] = Field(default_factory=list, description="可用风格/类型标签列表")
|
||||
years: List[int] = Field(default_factory=list, description="可用年份列表,按降序排列")
|
||||
item_types: List[str] = Field(default_factory=list, description="可用媒体维度选项")
|
||||
sort_options: List[str] = Field(default_factory=list, description="可用排序键列表")
|
||||
|
||||
|
||||
class MediaServerItemDetail(MediaServerBrowseItem):
|
||||
"""
|
||||
媒体服务器单个条目(电影、剧集、季、集、音乐)的完整详情。
|
||||
"""
|
||||
|
||||
tagline: Optional[str] = Field(default=None, description="标语或副宣传语")
|
||||
official_rating: Optional[str] = Field(default=None, description="内容分级,例如 PG-13、TV-MA")
|
||||
genres: List[str] = Field(default_factory=list, description="风格与分类标签")
|
||||
studios: List[str] = Field(default_factory=list, description="制作公司或发行商")
|
||||
people: List[MediaServerPerson] = Field(default_factory=list, description="主要演职员列表")
|
||||
media_source: Optional[MediaSource] = Field(default=None, description="关联外部元数据源")
|
||||
media_id: Optional[str] = Field(default=None, description="关联外部元数据源标识")
|
||||
imdb_id: Optional[str] = Field(default=None, description="IMDb 编号")
|
||||
tmdb_id: Optional[str] = Field(default=None, description="TMDB 编号")
|
||||
tvdb_id: Optional[str] = Field(default=None, description="TVDB 编号")
|
||||
douban_id: Optional[str] = Field(default=None, description="豆瓣编号")
|
||||
parent_id: Optional[str] = Field(default=None, description="上级目录或父条目标识")
|
||||
season_name: Optional[str] = Field(default=None, description="所属季名称")
|
||||
season_count: Optional[int] = Field(default=None, description="剧集总季数")
|
||||
episode_count: Optional[int] = Field(default=None, description="剧集或当前季总集数")
|
||||
media_sources: List[MediaServerMediaSource] = Field(default_factory=list, description="可播放的多版本及音轨字幕轨道列表")
|
||||
play_url: Optional[str] = Field(default=None, description="媒体服务器网页跳转地址")
|
||||
can_play: bool = Field(default=False, description="当前条目是否支持直接发起播放")
|
||||
|
||||
|
||||
class MediaServerProgressReportRequest(BaseModel):
|
||||
"""
|
||||
客户端回传原生播放器播放进度的请求体。
|
||||
"""
|
||||
|
||||
item_id: str = Field(description="正在播放的媒体服务器条目标识")
|
||||
server: str = Field(description="所属媒体服务器配置名称")
|
||||
media_source_id: Optional[str] = Field(default=None, description="当前播放使用的媒体源标识")
|
||||
position_ms: int = Field(default=0, ge=0, description="当前播放位置(毫秒)")
|
||||
duration_ms: Optional[int] = Field(default=None, ge=0, description="媒体总时长(毫秒)")
|
||||
is_paused: bool = Field(default=False, description="当前是否处于暂停状态")
|
||||
state: Literal["playing", "paused", "stopped"] = Field(default="playing", description="回传事件状态")
|
||||
|
||||
|
||||
class MediaServerMusicStreamRequest(BaseModel):
|
||||
|
||||
376
tests/test_mediaserver_browse_detail.py
Normal file
376
tests/test_mediaserver_browse_detail.py
Normal file
@@ -0,0 +1,376 @@
|
||||
"""覆盖媒体服务器统一浏览、筛选、三层详情、播前音轨字幕与进度回传链路。"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.api.endpoints import mediaserver
|
||||
from app.chain.mediaserver import MediaServerChain
|
||||
from app.modules._base.emby_browse import (
|
||||
EmbyBrowseConfig,
|
||||
emby_browse_items,
|
||||
emby_filter_options,
|
||||
emby_item_detail,
|
||||
emby_report_progress,
|
||||
emby_search_library,
|
||||
emby_season_episodes,
|
||||
emby_seasons,
|
||||
emby_stream_url,
|
||||
emby_subtitle_url,
|
||||
)
|
||||
from app.modules._base.plex_browse import (
|
||||
plex_browse_items,
|
||||
plex_filter_options,
|
||||
plex_item_detail,
|
||||
plex_report_progress,
|
||||
plex_season_episodes,
|
||||
plex_seasons,
|
||||
plex_subtitle_url,
|
||||
)
|
||||
from app.schemas.mediaserver import (
|
||||
MediaServerBrowseItem,
|
||||
MediaServerBrowsePage,
|
||||
MediaServerFilterOptions,
|
||||
MediaServerItem,
|
||||
MediaServerItemDetail,
|
||||
MediaServerMediaSource,
|
||||
MediaServerMediaStream,
|
||||
MediaServerPerson,
|
||||
)
|
||||
from app.schemas.token import TokenPayload
|
||||
from app.schemas.types import MediaSource, MediaType
|
||||
|
||||
|
||||
def _mock_response(payload: object, status_code: int = 200) -> Mock:
|
||||
"""构造简易 HTTP 响应桩对象。"""
|
||||
resp = Mock(status_code=status_code)
|
||||
resp.json.return_value = payload
|
||||
return resp
|
||||
|
||||
|
||||
def _emby_config(http_mock: Mock) -> EmbyBrowseConfig:
|
||||
"""构造用于单测的 Emby 协议配置。"""
|
||||
return EmbyBrowseConfig(
|
||||
host="http://emby.test/",
|
||||
api_key="test-key",
|
||||
user_id="user-1",
|
||||
server_type="emby",
|
||||
api_prefix="emby/",
|
||||
play_host="http://emby.test/",
|
||||
server_id="srv-1",
|
||||
request_factory=lambda: http_mock,
|
||||
play_url_builder=lambda item_id: f"http://emby.test/web/index.html#!/item?id={item_id}",
|
||||
)
|
||||
|
||||
|
||||
def test_emby_browse_filters_detail_seasons_episodes_and_subtitles() -> None:
|
||||
"""验证 Emby 系浏览、筛选、三层详情、音轨字幕提取、流地址和进度回传。"""
|
||||
http = Mock()
|
||||
cfg = _emby_config(http)
|
||||
|
||||
# 1. Browse
|
||||
http.get_res.return_value = _mock_response(
|
||||
{
|
||||
"TotalRecordCount": 2,
|
||||
"Items": [
|
||||
{
|
||||
"Id": "m-1",
|
||||
"Name": "星际穿越",
|
||||
"OriginalTitle": "Interstellar",
|
||||
"Type": "Movie",
|
||||
"ProductionYear": 2014,
|
||||
"PremiereDate": "2014-11-07T00:00:00Z",
|
||||
"CommunityRating": 8.7,
|
||||
"RunTimeTicks": 101_400_000_000,
|
||||
"ImageTags": {"Primary": "p1"},
|
||||
"BackdropImageTags": ["b1"],
|
||||
"UserData": {"Played": False, "PlaybackPositionTicks": 50_700_000_000},
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
page = emby_browse_items(
|
||||
cfg,
|
||||
library_id="lib-1",
|
||||
genre="科幻",
|
||||
year=2014,
|
||||
played_filter="unplayed",
|
||||
sort_by="rating",
|
||||
sort_order="desc",
|
||||
keyword="星际",
|
||||
start_index=0,
|
||||
limit=20,
|
||||
)
|
||||
assert page is not None
|
||||
assert page.total_count == 2
|
||||
assert page.has_more is True
|
||||
assert len(page.items) == 1
|
||||
assert page.items[0].item_id == "m-1"
|
||||
assert page.items[0].played_percentage == 50.0
|
||||
assert page.items[0].resume_position_ms == 5_070_000
|
||||
|
||||
# 2. Filter options
|
||||
http.get_res.return_value = _mock_response({"Genres": ["科幻", "动作"], "Years": [2024, 2014]})
|
||||
filters = emby_filter_options(cfg, library_id="lib-1")
|
||||
assert filters.genres == ["科幻", "动作"]
|
||||
assert filters.years == [2024, 2014]
|
||||
assert "date_created" in filters.sort_options
|
||||
|
||||
# 3. Item detail with multi-source & audio/subtitle streams
|
||||
http.get_res.return_value = _mock_response(
|
||||
{
|
||||
"Id": "ep-1",
|
||||
"Name": "第一集",
|
||||
"Type": "Episode",
|
||||
"SeriesId": "series-1",
|
||||
"SeriesName": "测试剧集",
|
||||
"SeasonId": "season-1",
|
||||
"SeasonName": "第 1 季",
|
||||
"ParentIndexNumber": 1,
|
||||
"IndexNumber": 1,
|
||||
"Overview": "分集简介",
|
||||
"Taglines": ["精彩开篇"],
|
||||
"Genres": ["剧情"],
|
||||
"Studios": [{"Name": "HBO"}],
|
||||
"People": [{"Id": "actor-1", "Name": "张三", "Role": "主角", "Type": "Actor", "PrimaryImageTag": "a1"}],
|
||||
"ProviderIds": {"Tmdb": "1399", "Imdb": "tt0944947"},
|
||||
"RunTimeTicks": 36_000_000_000,
|
||||
"ImageTags": {"Primary": "still-1"},
|
||||
"ParentBackdropItemId": "series-1",
|
||||
"ParentBackdropImageTags": ["sb-1"],
|
||||
"MediaSources": [
|
||||
{
|
||||
"Id": "src-4k",
|
||||
"Name": "4K HDR",
|
||||
"Container": "mkv",
|
||||
"Size": 4_000_000_000,
|
||||
"Bitrate": 15_000_000,
|
||||
"RunTimeTicks": 36_000_000_000,
|
||||
"MediaStreams": [
|
||||
{"Index": 0, "Type": "Video", "Codec": "hevc", "Width": 3840, "Height": 2160, "VideoRange": "HDR"},
|
||||
{"Index": 1, "Type": "Audio", "Codec": "eac3", "Language": "eng", "DisplayTitle": "英语 EAC3 5.1", "Channels": 6, "ChannelLayout": "5.1", "IsDefault": True},
|
||||
{"Index": 2, "Type": "Subtitle", "Codec": "ass", "Language": "chi", "DisplayTitle": "简体中文 (内嵌)", "IsExternal": False},
|
||||
{"Index": 3, "Type": "Subtitle", "Codec": "subrip", "Language": "chi", "DisplayTitle": "简体中文 (外挂)", "IsExternal": True},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
detail = emby_item_detail(cfg, "ep-1")
|
||||
assert detail is not None
|
||||
assert detail.item_type == "Episode"
|
||||
assert detail.series_id == "series-1"
|
||||
assert detail.season_id == "season-1"
|
||||
assert detail.tmdb_id == "1399"
|
||||
assert detail.media_source == MediaSource.TMDB
|
||||
assert detail.can_play is True
|
||||
assert len(detail.media_sources) == 1
|
||||
streams = detail.media_sources[0].streams
|
||||
assert [s.type for s in streams] == ["video", "audio", "subtitle", "subtitle"]
|
||||
assert streams[2].subtitle_id is None
|
||||
assert streams[3].subtitle_id == "ms:src-4k:3.srt"
|
||||
|
||||
# 4. Subtitle URL & Stream URL with explicit media_source_id
|
||||
sub_url = emby_subtitle_url(cfg, "ep-1", "ms:src-4k:3.srt")
|
||||
assert sub_url == "http://emby.test/emby/Videos/ep-1/src-4k/Subtitles/3/Stream.srt?api_key=test-key"
|
||||
assert emby_subtitle_url(cfg, "ep-1", "invalid.srt") is None
|
||||
|
||||
stream_url = emby_stream_url(cfg, "ep-1", "Episode", media_source_id="src-4k")
|
||||
assert stream_url is not None
|
||||
assert "MediaSourceId=src-4k" in stream_url
|
||||
|
||||
# 5. Seasons & Season Episodes
|
||||
http.get_res.return_value = _mock_response(
|
||||
{"Items": [{"Id": "season-2", "Name": "第 2 季", "Type": "Season", "IndexNumber": 2}, {"Id": "season-1", "Name": "第 1 季", "Type": "Season", "IndexNumber": 1}]}
|
||||
)
|
||||
seasons = emby_seasons(cfg, "series-1")
|
||||
assert seasons is not None
|
||||
assert [s.season_number for s in seasons] == [1, 2]
|
||||
|
||||
http.get_res.return_value = _mock_response(
|
||||
{"Items": [{"Id": "ep-2", "Name": "第二集", "Type": "Episode", "ParentIndexNumber": 1, "IndexNumber": 2}]}
|
||||
)
|
||||
episodes = emby_season_episodes(cfg, "series-1", season_id="season-1")
|
||||
assert episodes is not None
|
||||
assert episodes[0].subtitle == "S01E02"
|
||||
|
||||
# 6. Search including Movie
|
||||
http.get_res.return_value = _mock_response(
|
||||
{"Items": [{"Id": "m-1", "Name": "星际穿越", "Type": "Movie", "ProductionYear": 2014}]}
|
||||
)
|
||||
search_res = emby_search_library(cfg, "星际", [MediaType.MOVIE.value, MediaType.TV.value], 10)
|
||||
assert len(search_res) == 1
|
||||
assert search_res[0].type == MediaType.MOVIE.value
|
||||
|
||||
# 7. Progress report
|
||||
http.post_res.return_value = Mock(status_code=204)
|
||||
assert emby_report_progress(cfg, "ep-1", 120_000, media_source_id="src-4k", state="paused") is True
|
||||
assert http.post_res.call_args.kwargs["json"]["PositionTicks"] == 1_200_000_000
|
||||
|
||||
|
||||
def test_plex_browse_detail_seasons_episodes_and_progress() -> None:
|
||||
"""验证 Plex 浏览、筛选、详情轨道解析、三层剧集、字幕流及进度回传。"""
|
||||
audio_stream = SimpleNamespace(streamType=2, index=1, codec="ac3", languageCode="eng", displayTitle="English 5.1", channels=6, default=True)
|
||||
ext_sub_stream = SimpleNamespace(streamType=3, id=901, index=2, codec="srt", languageCode="zho", displayTitle="中文", key="/library/streams/901")
|
||||
part = SimpleNamespace(id=55, container="mkv", size=123456, duration=3600000, streams=[audio_stream, ext_sub_stream])
|
||||
media = SimpleNamespace(videoResolution="4k", container="mkv", bitrate=10000, duration=3600000, parts=[part])
|
||||
movie = SimpleNamespace(
|
||||
ratingKey=101,
|
||||
key="/library/metadata/101",
|
||||
type="movie",
|
||||
title="黑客帝国",
|
||||
originalTitle="The Matrix",
|
||||
year=1999,
|
||||
summary="经典科幻",
|
||||
rating=8.7,
|
||||
duration=3600000,
|
||||
viewOffset=600000,
|
||||
isPlayed=False,
|
||||
thumb="/library/metadata/101/thumb",
|
||||
art="/library/metadata/101/art",
|
||||
genres=[SimpleNamespace(tag="科幻")],
|
||||
roles=[SimpleNamespace(id=1, tag="基努·里维斯", role="Neo", thumb="/thumb/1")],
|
||||
directors=[SimpleNamespace(tag="沃卓斯基")],
|
||||
guids=[SimpleNamespace(id="tmdb://603"), SimpleNamespace(id="imdb://tt0133093")],
|
||||
media=[media],
|
||||
reload=Mock(),
|
||||
updateTimeline=Mock(),
|
||||
)
|
||||
season_obj = SimpleNamespace(
|
||||
ratingKey=201, key="/library/metadata/201", type="season", title="第 1 季", index=1, parentRatingKey=200, parentTitle="测试剧", childCount=8
|
||||
)
|
||||
ep_obj = SimpleNamespace(
|
||||
ratingKey=202, key="/library/metadata/202", type="episode", title="试播集", index=1, parentIndex=1, parentRatingKey=201, grandparentRatingKey=200, grandparentTitle="测试剧"
|
||||
)
|
||||
season_obj.episodes = Mock(return_value=[ep_obj])
|
||||
show_obj = SimpleNamespace(seasons=Mock(return_value=[season_obj]), season=Mock(return_value=season_obj))
|
||||
|
||||
section = SimpleNamespace(
|
||||
TYPE="movie",
|
||||
totalSize=1,
|
||||
search=Mock(return_value=[movie]),
|
||||
listFilterChoices=Mock(side_effect=lambda kind: [SimpleNamespace(title="科幻")] if kind == "genre" else [SimpleNamespace(title="1999")]),
|
||||
)
|
||||
plex = SimpleNamespace(
|
||||
library=SimpleNamespace(sectionByID=Mock(return_value=section), sections=Mock(return_value=[section])),
|
||||
fetchItem=Mock(side_effect=lambda key: movie if str(key) == "101" else (season_obj if str(key) == "201" else show_obj)),
|
||||
)
|
||||
|
||||
page = plex_browse_items(plex, "http://plex.test", "tok", library_id="1", genre="科幻", year=1999)
|
||||
assert page is not None and len(page.items) == 1
|
||||
assert page.items[0].item_id == "101"
|
||||
|
||||
filters = plex_filter_options(plex, library_id="1")
|
||||
assert filters.genres == ["科幻"] and filters.years == [1999]
|
||||
|
||||
detail = plex_item_detail(plex, "http://plex.test", "tok", "101")
|
||||
assert detail is not None
|
||||
assert detail.tmdb_id == "603"
|
||||
assert detail.media_sources[0].streams[1].subtitle_id == "ms:plex:901.srt"
|
||||
assert plex_subtitle_url("http://plex.test", "tok", "ms:plex:901.srt") == "http://plex.test/library/streams/901?X-Plex-Token=tok"
|
||||
|
||||
assert plex_seasons(plex, "http://plex.test", "tok", "200")[0].season_number == 1
|
||||
assert plex_season_episodes(plex, "http://plex.test", "tok", "200", season_id="201")[0].subtitle == "S01E01"
|
||||
assert plex_report_progress(plex, "101", 600000, state="paused") is True
|
||||
movie.updateTimeline.assert_called_once()
|
||||
|
||||
|
||||
def test_chain_signs_browse_and_detail_images(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""验证 MediaServerChain 对浏览、详情、演职员、季与分集图片统一签名。"""
|
||||
chain = object.__new__(MediaServerChain)
|
||||
monkeypatch.setattr(chain, "_sign_image_url", lambda url: f"signed:{url}" if url else url)
|
||||
detail = MediaServerItemDetail(
|
||||
item_id="1",
|
||||
title="演示",
|
||||
poster="http://img/p",
|
||||
backdrop="http://img/b",
|
||||
thumb="http://img/t",
|
||||
people=[MediaServerPerson(name="演员", image="http://img/a")],
|
||||
)
|
||||
page = MediaServerBrowsePage(
|
||||
items=[MediaServerBrowseItem(item_id="1", title="演示", poster="http://img/p")],
|
||||
total_count=1,
|
||||
)
|
||||
monkeypatch.setattr(chain, "run_module", Mock(side_effect=[page, detail]))
|
||||
|
||||
signed_page = chain.browse_items(server="Emby")
|
||||
assert signed_page is not None
|
||||
assert signed_page.items[0].server == "Emby"
|
||||
assert signed_page.items[0].poster == "signed:http://img/p"
|
||||
|
||||
signed_detail = chain.item_detail(server="Emby", item_id="1")
|
||||
assert signed_detail is not None
|
||||
assert signed_detail.backdrop == "signed:http://img/b"
|
||||
assert signed_detail.people[0].image == "signed:http://img/a"
|
||||
|
||||
|
||||
def test_mediaserver_browse_detail_and_server_subtitle_endpoints(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""验证新 REST 端点及 stream-info / stream-subtitle 对服务端外挂字幕的代理支持。"""
|
||||
chain = Mock()
|
||||
detail = MediaServerItemDetail(
|
||||
item_id="ep-1",
|
||||
server="Emby",
|
||||
item_type="Episode",
|
||||
title="第一集",
|
||||
resume_position_ms=30000,
|
||||
duration_ms=2400000,
|
||||
media_sources=[
|
||||
MediaServerMediaSource(
|
||||
id="src-1",
|
||||
name="1080P",
|
||||
streams=[
|
||||
MediaServerMediaStream(
|
||||
index=3,
|
||||
type="subtitle",
|
||||
language="chi",
|
||||
display_title="简体中文",
|
||||
is_external=True,
|
||||
subtitle_id="ms:src-1:3.srt",
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
)
|
||||
chain.browse_items.return_value = MediaServerBrowsePage(
|
||||
items=[MediaServerBrowseItem(item_id="series-1", server="Emby", item_type="Series", title="测试剧集")],
|
||||
total_count=1,
|
||||
)
|
||||
chain.filter_options.return_value = MediaServerFilterOptions(genres=["科幻"], years=[2025], sort_options=["date_created"])
|
||||
chain.item_detail.return_value = detail
|
||||
chain.seasons.return_value = [MediaServerBrowseItem(item_id="season-1", server="Emby", item_type="Season", title="第 1 季", season_number=1)]
|
||||
chain.season_episodes.return_value = [MediaServerBrowseItem(item_id="ep-1", server="Emby", item_type="Episode", title="第一集", season_number=1, episode_number=1)]
|
||||
chain.report_progress.return_value = True
|
||||
chain.find_item.return_value = ("Emby", MediaServerItem(item_id="ep-1", title="第一集", item_type="Episode"))
|
||||
chain.get_stream_url.return_value = "http://emby.local/emby/Videos/ep-1/stream?static=true"
|
||||
chain.get_subtitle_url.return_value = "http://emby.local/emby/Videos/ep-1/src-1/Subtitles/3/Stream.srt?api_key=k"
|
||||
|
||||
monkeypatch.setattr(mediaserver, "MediaServerChain", lambda: chain)
|
||||
monkeypatch.setattr(mediaserver, "_configured_stream_hosts", lambda *_args, **_kwargs: {"emby.local"})
|
||||
monkeypatch.setattr(mediaserver, "_remote_stream_response", lambda url, _r, _h: SimpleNamespace(status_code=200, headers={}, body=url))
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(mediaserver.router, prefix="/api/v1/mediaserver")
|
||||
app.dependency_overrides[mediaserver.verify_token] = lambda: TokenPayload(sub=1, username="admin")
|
||||
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/api/v1/mediaserver/browse", params={"server": "Emby"}).json()["data"]["total_count"] == 1
|
||||
assert client.get("/api/v1/mediaserver/filters", params={"server": "Emby"}).json()["data"]["genres"] == ["科幻"]
|
||||
assert client.get("/api/v1/mediaserver/detail", params={"server": "Emby", "itemid": "ep-1"}).json()["data"]["item_id"] == "ep-1"
|
||||
assert len(client.get("/api/v1/mediaserver/seasons", params={"server": "Emby", "itemid": "series-1"}).json()["data"]) == 1
|
||||
assert len(client.get("/api/v1/mediaserver/season-episodes", params={"server": "Emby", "itemid": "series-1", "season": 1}).json()["data"]) == 1
|
||||
assert client.post(
|
||||
"/api/v1/mediaserver/progress",
|
||||
json={"item_id": "ep-1", "server": "Emby", "position_ms": 45000, "state": "paused"},
|
||||
).json()["success"] is True
|
||||
|
||||
manifest = client.get(
|
||||
"/api/v1/mediaserver/stream-info",
|
||||
params={"itemid": "ep-1", "server": "Emby", "media_source_id": "src-1"},
|
||||
).json()["data"]
|
||||
assert manifest["media_source_id"] == "src-1"
|
||||
assert manifest["resume_position_ms"] == 30000
|
||||
assert len(manifest["subtitles"]) == 1
|
||||
assert manifest["subtitles"][0]["subtitle_id"] == "ms:src-1:3.srt"
|
||||
@@ -106,7 +106,7 @@ def test_search_library_handles_empty_results_defaults_and_limit_bounds(monkeypa
|
||||
assert chain.search_library("keyword", types=[MediaType.TV.value], limit=100) == []
|
||||
|
||||
assert [call.kwargs for call in run_module.call_args_list] == [
|
||||
{"keyword": "keyword", "types": [MediaType.TV.value, MediaType.MUSIC.value], "limit": 1},
|
||||
{"keyword": "keyword", "types": [MediaType.MOVIE.value, MediaType.TV.value, MediaType.MUSIC.value], "limit": 1},
|
||||
{"keyword": "keyword", "types": [MediaType.TV.value], "limit": 50},
|
||||
]
|
||||
assert all(call.args == ("mediaserver_search",) for call in run_module.call_args_list)
|
||||
@@ -129,7 +129,7 @@ def test_search_library_signs_deduplicates_and_limits_results(monkeypatch):
|
||||
)
|
||||
invalid_id_item = MediaServerPlayItem(type=MediaType.TV.value)
|
||||
invalid_type_item = MediaServerPlayItem(
|
||||
item_id="movie", server="Server A", type=MediaType.MOVIE.value
|
||||
item_id="unknown", server="Server A", type="未知"
|
||||
)
|
||||
run_module = Mock(
|
||||
return_value=[
|
||||
@@ -157,7 +157,7 @@ def test_search_library_signs_deduplicates_and_limits_results(monkeypatch):
|
||||
run_module.assert_called_once_with(
|
||||
"mediaserver_search",
|
||||
keyword="keyword",
|
||||
types=[MediaType.TV.value, MediaType.MUSIC.value],
|
||||
types=[MediaType.MOVIE.value, MediaType.TV.value, MediaType.MUSIC.value],
|
||||
limit=2,
|
||||
)
|
||||
|
||||
|
||||
@@ -635,7 +635,7 @@ def test_strm_rejects_upstream_without_range_support(monkeypatch: pytest.MonkeyP
|
||||
|
||||
|
||||
def test_media_server_search_endpoint_filters_types_and_caps_limit(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""验证媒体库搜索只向服务模块分发电视剧和音乐类型。"""
|
||||
"""验证媒体库搜索向服务模块分发电影、电视剧和音乐类型并过滤无效类型。"""
|
||||
chain = Mock()
|
||||
chain.search_library.return_value = [
|
||||
MediaServerPlayItem(server="Emby-客厅", item_id="series-1", title="测试剧集", type="电视剧")
|
||||
@@ -653,13 +653,14 @@ def test_media_server_search_endpoint_filters_types_and_caps_limit(monkeypatch:
|
||||
("type", "电视剧"),
|
||||
("type", "电影"),
|
||||
("type", "音乐"),
|
||||
("type", "无效类型"),
|
||||
("limit", "45"),
|
||||
],
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["data"][0]["server"] == "Emby-客厅"
|
||||
chain.search_library.assert_called_once_with("测试剧集", ["电视剧", "音乐"], 45)
|
||||
chain.search_library.assert_called_once_with("测试剧集", ["电视剧", "电影", "音乐"], 45)
|
||||
|
||||
|
||||
def test_media_server_search_chain_deduplicates_per_server_and_signs_posters(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
Reference in New Issue
Block a user