From a8533f5c598fd34c397d1949d0ef8d38bc05bb90 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Wed, 25 Nov 2026 23:57:52 +0800 Subject: [PATCH] =?UTF-8?q?fix(mediaserver,subscribe):=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=20Emby=20=E8=BF=9B=E5=BA=A6=E5=9B=9E=E9=80=80?= =?UTF-8?q?=E3=80=81=E8=BF=9C=E7=AB=AF=E5=AD=98=E5=82=A8=E6=B5=81=E5=BC=8F?= =?UTF-8?q?=E6=92=AD=E6=94=BE=E4=B8=8E=E8=AE=A2=E9=98=85=E7=A9=BA=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Emby 进度上报在 UserData/PlayedItems 不可用时自动回退至 /Users/{UserId}/PlayingItems/{ItemId}[/Progress](#53) - 为 SMB、OpenList/Alist、阿里云盘、115 等远端存储扩展流式票据与 HTTP Range 渐进流式读取(#58) - 规范化订阅媒体类型并拦截空白 name/type 写入与刷新异常(#61) --- app/adapters/mediastream.py | 194 +++++++++++++----- app/api/endpoints/mediaserver.py | 90 ++++++-- app/api/endpoints/subscribe.py | 48 ++++- app/application/subscription/contract.py | 27 ++- app/chain/storage.py | 24 +++ app/chain/subscribe/metadata.py | 17 +- app/chain/subscribe/query.py | 27 ++- app/chain/subscribe/refresh.py | 11 +- app/modules/_base/embybrowse.py | 84 +++++++- app/modules/filemanager/module.py | 39 ++++ app/modules/filemanager/storages/__init__.py | 20 ++ app/modules/filemanager/storages/alipan.py | 28 +++ app/modules/filemanager/storages/alist.py | 99 +++++---- app/modules/filemanager/storages/smb.py | 20 ++ app/modules/filemanager/storages/u115.py | 23 +++ .../architecture/dependency-baseline.json | 11 +- .../runtime-contract-baseline.json | 25 ++- tests/test_mediaserver_browse_detail.py | 17 ++ tests/test_mediaserver_streaming.py | 90 ++++++++ tests/test_subscribe_endpoint.py | 62 ++++++ 20 files changed, 830 insertions(+), 126 deletions(-) diff --git a/app/adapters/mediastream.py b/app/adapters/mediastream.py index c6c7e3803..3288c33ae 100644 --- a/app/adapters/mediastream.py +++ b/app/adapters/mediastream.py @@ -18,6 +18,7 @@ from fastapi.responses import StreamingResponse from app.adapters.network.http import RequestUtils from app.runtime.settings import get_runtime_setting +from app.schemas.file import FileItem as _SchemaFileItem from app.schemas.mediaserver import MediaServerSubtitleTrack as _SchemaMediaServerSubtitleTrack _STREAM_CHUNK_SIZE = 256 * 1024 @@ -184,6 +185,74 @@ def _file_stream_ticket_media_type(item_id: str) -> str: return "audio" if isinstance(payload, dict) and payload.get("media_type") == "audio" else "video" +def _create_storage_file_stream_ticket( + fileitem: _SchemaFileItem, user_id: int, media_type: str = "video" +) -> str: + """ + 为远端存储(SMB / OpenList / 阿里云盘 / 115 等)媒体文件创建带用途和有效期的加密播放票据。 + + :param fileitem: 已通过管理权限与存储存在性校验的远端文件项 + :param user_id: 签发票据的当前用户主键 + :param media_type: 原生播放器使用的媒体类型(video / audio) + :return: URL 安全的 `file.` 票据标识 + :raises HTTPException: 路径无效或序列化超限时 + """ + raw_path = (fileitem.path or "").strip() + if not fileitem.storage or not raw_path or len(raw_path.encode("utf-8")) > 2048: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="媒体文件路径无效") + compact_item: dict[str, Any] = { + "storage": fileitem.storage, + "type": "file", + "path": raw_path, + "name": fileitem.name or Path(raw_path).name, + } + if fileitem.fileid: + compact_item["fileid"] = fileitem.fileid + if fileitem.drive_id: + compact_item["drive_id"] = fileitem.drive_id + if fileitem.pickcode: + compact_item["pickcode"] = fileitem.pickcode + if fileitem.size is not None: + compact_item["size"] = int(fileitem.size) + payload = json.dumps( + { + "purpose": "storage-file", + "media_type": media_type, + "user_id": user_id, + "fileitem": compact_item, + }, + separators=(",", ":"), + ).encode("utf-8") + token = _file_ticket_cipher().encrypt(payload).decode("ascii").rstrip("=") + return f"{_FILE_TICKET_PREFIX}{token}" + + +def _resolve_storage_file_stream_ticket( + item_id: str, user_id: Optional[int] +) -> Optional[tuple[_SchemaFileItem, str]]: + """ + 若票据属于远端存储文件票据(`purpose="storage-file"`),校验并还原 `(FileItem, media_type)`; + 若属于本地文件票据则返回 None,交由 `_resolve_file_stream_ticket` 处理。 + """ + token = item_id.removeprefix(_FILE_TICKET_PREFIX) + if not re.fullmatch(r"[A-Za-z0-9_-]{64,4096}", token): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到已入库媒体") + token += "=" * (-len(token) % 4) + try: + payload = json.loads(_file_ticket_cipher().decrypt(token.encode("ascii"), ttl=_FILE_TICKET_TTL_SECONDS)) + except (InvalidToken, ValueError, json.JSONDecodeError): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到已入库媒体") from None + if not isinstance(payload, dict) or payload.get("user_id") != user_id: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到已入库媒体") + if payload.get("purpose") != "storage-file": + return None + raw_item = payload.get("fileitem") + if not isinstance(raw_item, dict) or not raw_item.get("storage") or not raw_item.get("path"): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到已入库媒体") + media_type = "audio" if payload.get("media_type") == "audio" else "video" + return _SchemaFileItem(**raw_item), media_type + + def _is_file_stream_ticket(item_id: str) -> bool: """ 判断媒体条目标识是否使用受控的单文件票据格式。 @@ -592,6 +661,75 @@ def _parse_range_header(range_header: Optional[str], size: int) -> tuple[int, in return start, end, status.HTTP_206_PARTIAL_CONTENT +def _seekable_stream_response( + stream: Any, + size: int, + filename: str, + range_header: Optional[str], + *, + head_only: bool = False, +) -> StreamingResponse: + """ + 将任意支持 `seek`/`read`/`close` 的二进制只读流(本地文件、SMB 共享文件等)按 HTTP Range 分块输出。 + + - 音频文件显式返回 IANA MIME 并采用 64KB 分片,便于移动端播放器边缓冲边播放; + - 支持 `HEAD` 元数据/Range 探测请求。 + """ + try: + start, end, response_status = _parse_range_header(range_header, size) + except HTTPException: + stream.close() + raise + length = max(0, end - start + 1) + headers = { + "Accept-Ranges": "bytes", + "Cache-Control": "private, no-store", + "Content-Length": str(length), + "Content-Disposition": f"inline; filename*=UTF-8''{quote(filename, safe='')}", + } + if response_status == status.HTTP_206_PARTIAL_CONTENT: + headers["Content-Range"] = f"bytes {start}-{end}/{size}" + suffix = Path(filename).suffix.casefold() + content_type = ( + _SUBTITLE_MIME_TYPES.get(suffix) + or _AUDIO_MIME_TYPES.get(suffix) + or mimetypes.guess_type(filename)[0] + ) + chunk_size = _AUDIO_STREAM_CHUNK_SIZE if suffix in _AUDIO_EXTENSIONS else _STREAM_CHUNK_SIZE + + if head_only: + stream.close() + return StreamingResponse( + iter(()), + status_code=response_status, + media_type=content_type or "application/octet-stream", + headers=headers, + ) + + def chunks() -> Iterator[bytes]: + """ + 从所选范围读取固定大小数据块并在客户端断开时关闭句柄。 + """ + remaining = length + try: + stream.seek(start) + while remaining > 0: + chunk = stream.read(min(chunk_size, remaining)) + if not chunk: + break + remaining -= len(chunk) + yield chunk + finally: + stream.close() + + return StreamingResponse( + chunks(), + status_code=response_status, + media_type=content_type or "application/octet-stream", + headers=headers, + ) + + def _file_stream_response( path: Path, range_header: Optional[str], @@ -614,61 +752,7 @@ def _file_stream_response( size = path.stat().st_size except OSError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="媒体文件不可读取") from None - try: - start, end, response_status = _parse_range_header(range_header, size) - except HTTPException: - file.close() - raise - length = max(0, end - start + 1) - headers = { - "Accept-Ranges": "bytes", - "Cache-Control": "private, no-store", - "Content-Length": str(length), - "Content-Disposition": f"inline; filename*=UTF-8''{quote(path.name, safe='')}", - } - if response_status == status.HTTP_206_PARTIAL_CONTENT: - headers["Content-Range"] = f"bytes {start}-{end}/{size}" - suffix = path.suffix.casefold() - content_type = ( - _SUBTITLE_MIME_TYPES.get(suffix) - or _AUDIO_MIME_TYPES.get(suffix) - or mimetypes.guess_type(path.name)[0] - ) - chunk_size = _AUDIO_STREAM_CHUNK_SIZE if suffix in _AUDIO_EXTENSIONS else _STREAM_CHUNK_SIZE - - if head_only: - file.close() - return StreamingResponse( - iter(()), - status_code=response_status, - media_type=content_type or "application/octet-stream", - headers=headers, - ) - - def chunks() -> Iterator[bytes]: - """ - 从所选范围读取固定大小数据块并在客户端断开时关闭文件。 - - :yields: 文件内容块 - """ - remaining = length - try: - file.seek(start) - while remaining > 0: - chunk = file.read(min(chunk_size, remaining)) - if not chunk: - break - remaining -= len(chunk) - yield chunk - finally: - file.close() - - return StreamingResponse( - chunks(), - status_code=response_status, - media_type=content_type or "application/octet-stream", - headers=headers, - ) + return _seekable_stream_response(file, size, path.name, range_header, head_only=head_only) def _validate_range_syntax(range_header: Optional[str]) -> None: diff --git a/app/api/endpoints/mediaserver.py b/app/api/endpoints/mediaserver.py index 081ca9b1e..187a74a2f 100644 --- a/app/api/endpoints/mediaserver.py +++ b/app/api/endpoints/mediaserver.py @@ -20,13 +20,18 @@ from app.adapters.mediastream import ( _is_file_stream_ticket, _remote_stream_response, _resolve_file_stream_ticket, + _resolve_storage_file_stream_ticket, _sanitize_strm_direct_url, + _seekable_stream_response, _stream_source, _subtitle_tracks, _validate_stream_url, ) from app.adapters.mediastream import _configured_stream_hosts as _configured_media_stream_hosts from app.adapters.mediastream import _create_file_stream_ticket as _create_media_file_stream_ticket +from app.adapters.mediastream import ( + _create_storage_file_stream_ticket as _create_media_storage_file_stream_ticket, +) from app.adapters.web.security.access import verify_resource_token, verify_token from app.api.dependencies.auth import get_current_active_manage_user from app.api.dependencies.history import get_mediaserver_query_service @@ -59,12 +64,14 @@ from app.application.playback import ( from app.application.storage import StorageHelper from app.chain.download import DownloadChain from app.chain.mediaserver import MediaServerChain +from app.chain.storage import StorageChain from app.chain.tmdb import TmdbChain from app.domain.context import MediaInfo from app.domain.context import MusicInfo as _DomainMusicInfo 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.file import FileItem as _SchemaFileItem from app.schemas.media import build_media_key, resolve_media_identity from app.schemas.mediaserver import MediaServerAccountBinding as _SchemaMediaServerAccountBinding from app.schemas.mediaserver import MediaServerAccountBindRequest as _SchemaMediaServerAccountBindRequest @@ -151,6 +158,22 @@ def _resolve_stream_item( if not _is_file_stream_ticket(itemid): server_name, item, path = _find_stream_item(itemid, **({"server": server} if server else {})) return server_name, item, path + storage_ticket = _resolve_storage_file_stream_ticket(itemid, user_id) + if storage_ticket is not None: + storage_item, ticket_media_type = storage_ticket + item_type = "Audio" if ticket_media_type == "audio" else "Episode" + filename = storage_item.name or Path(storage_item.path or "").name or itemid + return ( + None, + _SchemaMediaServerItem( + item_id=itemid, + title=Path(filename).stem or filename, + item_type=item_type, + path=storage_item.path, + note={"storage_file_item": storage_item.model_dump(exclude_none=True)}, + ), + None, + ) path = _resolve_file_stream_ticket(itemid, user_id) item_type = "Audio" if _file_stream_ticket_media_type(itemid) == "audio" else "Episode" return None, _SchemaMediaServerItem(item_id=itemid, title=path.stem, item_type=item_type, path=str(path)), path @@ -342,6 +365,8 @@ def _playback_source( hosts = _configured_stream_hosts(path, include_media_servers=True) return "server", _validate_stream_url(upstream, configured_hosts=hosts), hosts if not path: + if isinstance(item.note, dict) and isinstance(item.note.get("storage_file_item"), dict): + return "storage", itemid, set() raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="媒体服务器不支持文件流且本地文件不可读取") hosts = _configured_stream_hosts(path) source_type, source = _stream_source(path, hosts) @@ -437,7 +462,7 @@ def _is_audio_item(item: _SchemaMediaServerItem, path: Optional[Path]) -> bool: @router.post( "/stream-ticket", - summary="为文件管理器选中的本地媒体签发播放票据", + summary="为文件管理器选中的媒体文件签发流式播放票据", response_model=_SchemaResponse[_SchemaMediaServerFileStreamTicket], ) def create_file_stream_ticket( @@ -445,25 +470,39 @@ def create_file_stream_ticket( current_user: ApiPrincipal = Depends(get_current_active_manage_user), ) -> _SchemaResponse[_SchemaMediaServerFileStreamTicket]: """ - 验证管理用户可访问的本地媒体文件并签发短期单文件票据。 + 验证管理用户可访问的媒体文件(本地或支持 Range 流式的远端存储,如 SMB / OpenList / 阿里云盘 / 115)并签发短期票据。 - :param request: 文件管理器提交的文件条目,仅接受本地支持格式的媒体或 STRM 文件 + :param request: 文件管理器提交的文件条目 :param current_user: 已验证且拥有管理权限的当前用户 - :return: 与当前用户及签发时文件身份绑定的短期播放标识 - :raises HTTPException: 用户无权访问文件、文件不可读或格式不受支持时 + :return: 与当前用户及文件身份绑定的短期播放标识 + :raises HTTPException: 用户无权访问文件、存储不支持在线流、文件不可读或格式不受支持时 """ fileitem = request.file - if fileitem.storage != "local" or fileitem.type != "file": - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="仅支持本地媒体文件") + if fileitem.type != "file": + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="仅支持媒体文件") authorized_item = _ensure_manage_storage_item(fileitem, current_user) - path = Path(authorized_item.path or "") - if not path.is_absolute(): - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="媒体文件路径无效") + raw_path = authorized_item.path or "" + path = Path(raw_path) media_type = request.media_type supported_extensions = _AUDIO_EXTENSIONS if media_type == "audio" else _VIDEO_EXTENSIONS - if path.suffix.casefold() != ".strm" and path.suffix.casefold() not in supported_extensions: - raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="该文件格式不支持在线播放") - item_id = _create_media_file_stream_ticket(path, current_user.id, media_type) + suffix = Path(authorized_item.name or raw_path).suffix.casefold() + if authorized_item.storage == "local": + if not path.is_absolute(): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="媒体文件路径无效") + if suffix != ".strm" and suffix not in supported_extensions: + raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="该文件格式不支持在线播放") + item_id = _create_media_file_stream_ticket(path, current_user.id, media_type) + return _SchemaResponse( + success=True, + data=_SchemaMediaServerFileStreamTicket( + item_id=item_id, title=authorized_item.name or path.stem, media_type=media_type + ), + ) + if suffix == ".strm" or suffix not in supported_extensions: + raise HTTPException(status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, detail="该文件格式不支持在线流式播放") + if not authorized_item.storage or not StorageChain().supports_file_stream(authorized_item.storage): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="该存储暂不支持在线流式播放") + item_id = _create_media_storage_file_stream_ticket(authorized_item, current_user.id, media_type) return _SchemaResponse( success=True, data=_SchemaMediaServerFileStreamTicket( @@ -919,6 +958,31 @@ def stream_item_content( raise configured_hosts = _configured_stream_hosts(path) source_type, source = _stream_source(path, configured_hosts) + if source_type == "storage": + raw_storage_item = item.note.get("storage_file_item") if isinstance(item.note, dict) else None + if not isinstance(raw_storage_item, dict): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="未找到远端媒体文件") + storage_file = _SchemaFileItem.model_validate(raw_storage_item) + chain = StorageChain() + stream_url_result = chain.get_file_stream_url(storage_file) + if stream_url_result: + stream_url, storage_headers = stream_url_result + hosts = _configured_stream_hosts(None, include_media_servers=True) + return _remote_stream_response( + stream_url, + range_header, + hosts, + extra_headers=storage_headers or None, + head_only=head_only, + ) + seekable_result = chain.open_file_stream(storage_file) + if seekable_result: + stream_handle, stream_size = seekable_result + filename = storage_file.name or Path(storage_file.path or "media").name + return _seekable_stream_response( + stream_handle, stream_size, filename, range_header, head_only=head_only + ) + raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="该存储暂不支持在线流式播放") if source_type == "file": return _file_stream_response(Path(source), range_header, head_only=head_only) return _remote_stream_response(str(source), range_header, configured_hosts, head_only=head_only) diff --git a/app/api/endpoints/subscribe.py b/app/api/endpoints/subscribe.py index 60eec4e49..54b925586 100644 --- a/app/api/endpoints/subscribe.py +++ b/app/api/endpoints/subscribe.py @@ -305,8 +305,17 @@ async def create_subscribe( 新增订阅 """ # 类型转换 - if subscribe_in.type: - mtype = MediaType.from_agent(subscribe_in.type) or MediaType(subscribe_in.type) + if subscribe_in.type and str(subscribe_in.type).strip(): + raw_type = str(subscribe_in.type).strip() + mtype = MediaType.from_agent(raw_type) + if mtype is None: + try: + mtype = MediaType(raw_type) + except ValueError: + return _SchemaResponse( + success=False, + message=f"订阅媒体类型无效:{raw_type}", + ) else: mtype = None # 非 TMDB 来源的标题可能自带季标记,入库前统一拆分。 @@ -351,6 +360,39 @@ async def create_subscribe( ) +def _sanitize_subscribe_core_fields( + subscribe_dict: dict[str, Any], + subscribe: Any, +) -> Optional[str]: + """ + 保护订阅的核心 name / type 字段不被局部编辑误传空白清空,并归一化英文媒体类型。 + + :return: 校验失败时返回中文错误信息,通过返回 None + """ + if "name" in subscribe_dict and not str(subscribe_dict.get("name") or "").strip(): + if getattr(subscribe, "name", None): + subscribe_dict["name"] = subscribe.name + else: + subscribe_dict.pop("name", None) + if "type" not in subscribe_dict: + return None + raw_type = str(subscribe_dict.get("type") or "").strip() + if not raw_type: + if getattr(subscribe, "type", None): + subscribe_dict["type"] = subscribe.type + else: + subscribe_dict.pop("type", None) + return None + normalized_type = MediaType.from_agent(raw_type) + if normalized_type is None: + try: + normalized_type = MediaType(raw_type) + except ValueError: + return f"订阅媒体类型无效:{raw_type}" + subscribe_dict["type"] = normalized_type.value + return None + + @router.put("/", summary="更新订阅", response_model=_SchemaResponse[None]) async def update_subscribe( *, @@ -372,6 +414,8 @@ async def update_subscribe( if not subscribe: return _SchemaResponse(success=False, message="订阅不存在") subscribe_dict = subscribe_in.to_public_write_payload(exclude_unset=True) + if core_error := _sanitize_subscribe_core_fields(subscribe_dict, subscribe): + return _SchemaResponse(success=False, message=core_error) identity_fields = {"media_source", "media_id"}.intersection(subscribe_in.model_fields_set) if identity_fields: media_source, media_id = resolve_media_identity( diff --git a/app/application/subscription/contract.py b/app/application/subscription/contract.py index 32f7bda9d..4a7295856 100644 --- a/app/application/subscription/contract.py +++ b/app/application/subscription/contract.py @@ -1086,11 +1086,32 @@ class SessionSubscriptionPort( """ +def resolve_subscribe_media_type(raw_type: Optional[str]) -> Optional[MediaType]: + """ + 将订阅记录中的媒体类型归一化为标准 `MediaType`(兼容中英文枚举值与前后空白)。 + """ + if not raw_type: + return None + cleaned = str(raw_type).strip() + if not cleaned: + return None + agent_type = MediaType.from_agent(cleaned) + if agent_type is not None: + return agent_type + try: + return MediaType(cleaned) + except ValueError: + return None + + def build_subscribe_meta(subscribe: SubscriptionSnapshot) -> MetaBase: """ 按订阅快照构造主程序链路共用的媒体元数据。 """ - if subscribe.type == MediaType.MUSIC.value: + resolved_type = resolve_subscribe_media_type(subscribe.type) + if subscribe.type and resolved_type is None: + raise ValueError(f"订阅 #{subscribe.id} 类型错误:{subscribe.type}") + if resolved_type == MediaType.MUSIC: is_album = subscribe.music_type == MUSIC_ENTITY_ALBUM music_year: Optional[int] = None if subscribe.year: @@ -1109,8 +1130,8 @@ def build_subscribe_meta(subscribe: SubscriptionSnapshot) -> MetaBase: meta = MetaInfo(subscribe.name) meta.year = subscribe.year meta.begin_season = subscribe.season - if subscribe.type: - meta.type = MediaType(subscribe.type) + if resolved_type is not None: + meta.type = resolved_type meta.media_source = subscribe.media_source meta.media_id = subscribe.media_id return meta diff --git a/app/chain/storage.py b/app/chain/storage.py index 3614c92ee..469592182 100644 --- a/app/chain/storage.py +++ b/app/chain/storage.py @@ -66,6 +66,30 @@ class StorageChain(ChainBase): """ return cast(Optional[Path], self.run_module("download_file", fileitem=fileitem, path=path)) + def supports_file_stream(self, storage: str) -> bool: + """ + 查询目标存储是否支持渐进式 Range 流媒体读取。 + """ + return bool(self.run_module("supports_file_stream", storage=storage)) + + def get_file_stream_url(self, fileitem: _SchemaFileItem) -> Optional[tuple[str, dict[str, str]]]: + """ + 查询远端存储的 HTTP(S) 直链与上游请求头。 + """ + return cast( + Optional[tuple[str, dict[str, str]]], + self.run_module("get_file_stream_url", fileitem=fileitem), + ) + + def open_file_stream(self, fileitem: _SchemaFileItem) -> Optional[tuple[Any, int]]: + """ + 以可随机定位二进制流打开远端存储文件(如 SMB)。 + """ + return cast( + Optional[tuple[Any, int]], + self.run_module("open_file_stream", fileitem=fileitem), + ) + def upload_file(self, fileitem: _SchemaFileItem, path: Path, new_name: Optional[str] = None) -> Optional[_SchemaFileItem]: """ diff --git a/app/chain/subscribe/metadata.py b/app/chain/subscribe/metadata.py index c883ef81b..12b03f360 100644 --- a/app/chain/subscribe/metadata.py +++ b/app/chain/subscribe/metadata.py @@ -13,6 +13,7 @@ from app.application.mediaserver import MediaServerQueryError from app.application.subscription.contract import ( SubscriptionSnapshot, build_subscribe_meta, + resolve_subscribe_media_type, subscribe_media_key, ) from app.application.subscription.facts import FreshFactLease @@ -225,10 +226,19 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase): """ 刷新单条订阅元数据,并按需复用同一事实执行完成对账。 """ + if not (subscribe.name or "").strip() or resolve_subscribe_media_type(subscribe.type) is None: + logger.warning( + f"跳过无效订阅元数据刷新:id={subscribe.id},标题={subscribe.name or '<空>'}," + f"类型={subscribe.type or '<空>'}" + ) + return None try: meta = build_subscribe_meta(subscribe) except ValueError: - logger.error(f"订阅 {subscribe.name} 类型错误:{subscribe.type}") + logger.warning( + f"跳过类型异常的订阅:id={subscribe.id},标题={subscribe.name or '<空>'}," + f"类型={subscribe.type or '<空>'}" + ) return None converted_subscribe = self._retry_subscribe_media_identity( subscribe, @@ -240,7 +250,10 @@ class SubscribeMetadataOwner(_SubscribeOwnerBase): try: meta = build_subscribe_meta(subscribe) except ValueError: - logger.error(f"订阅 {subscribe.name} 类型错误:{subscribe.type}") + logger.warning( + f"跳过类型异常的订阅:id={subscribe.id},标题={subscribe.name or '<空>'}," + f"类型={subscribe.type or '<空>'}" + ) return None if meta.type == MediaType.MUSIC: mediainfo = self._recognize_music_subscribe(subscribe) diff --git a/app/chain/subscribe/query.py b/app/chain/subscribe/query.py index f11d1bdd2..d6578acc0 100644 --- a/app/chain/subscribe/query.py +++ b/app/chain/subscribe/query.py @@ -11,6 +11,7 @@ from app.application.subscription.contract import ( SubscriptionRepository, SubscriptionSnapshot, build_subscribe_meta, + resolve_subscribe_media_type, ) from app.chain.download import DownloadChain from app.chain.media import MediaChain @@ -44,6 +45,26 @@ from app.schemas.types import ( ) +def _build_valid_subscribe_meta(subscribe: SubscriptionSnapshot) -> Optional[MetaBase]: + """ + 校验订阅名称与媒体类型后构造元数据;损坏或空白记录记录告警并返回 None。 + """ + if not (subscribe.name or "").strip() or resolve_subscribe_media_type(subscribe.type) is None: + logger.warning( + f"跳过无效订阅文件查询:id={subscribe.id},标题={subscribe.name or '<空>'}," + f"类型={subscribe.type or '<空>'}" + ) + return None + try: + return build_subscribe_meta(subscribe) + except ValueError: + logger.warning( + f"跳过类型异常的订阅文件查询:id={subscribe.id},标题={subscribe.name or '<空>'}," + f"类型={subscribe.type or '<空>'}" + ) + return None + + def _public_subscribe_view(subscribe: SubscriptionSnapshot) -> _SchemaSubscribe: """ 将订阅内部快照投影为公开 DTO,并隐藏活动音轨事实。 @@ -367,10 +388,8 @@ class SubscribeQueryOwner(_SubscribeOwnerBase): episodes[0].download = downloads downloads.append(download_file_info) - try: - meta = build_subscribe_meta(subscribe) - except ValueError: - logger.error(f"订阅 {subscribe.name} 类型错误:{subscribe.type}") + meta = _build_valid_subscribe_meta(subscribe) + if meta is None: return subscribe_info mediainfo = MediaChain().recognize_media( meta=meta, diff --git a/app/chain/subscribe/refresh.py b/app/chain/subscribe/refresh.py index c37d08ef3..e4536b8e3 100644 --- a/app/chain/subscribe/refresh.py +++ b/app/chain/subscribe/refresh.py @@ -15,6 +15,7 @@ from app.application.subscription.activity import activity_time, subscription_ac from app.application.subscription.contract import ( SubscriptionSnapshot, build_subscribe_meta, + resolve_subscribe_media_type, subscribe_media_key, subscribe_media_keys, ) @@ -298,10 +299,12 @@ class SubscribeRefreshOwner(SubscribeMetadataOwner): "current": subscribe.id, }, ) - try: - mtype = MediaType(subscribe.type) - except ValueError: - logger.error(f"订阅 {subscribe.name} 类型错误:{subscribe.type}") + mtype = resolve_subscribe_media_type(subscribe.type) + if mtype is None: + logger.warning( + f"跳过无效订阅记录:id={subscribe.id},标题={subscribe.name or '<空>'}," + f"类型={subscribe.type or '<空>'}" + ) continue # 先按订阅的主媒体身份预热对应数据源,再对 TMDB 额外预热分集接口。 if mtype == MediaType.MUSIC: diff --git a/app/modules/_base/embybrowse.py b/app/modules/_base/embybrowse.py index 549377b8b..083cfab37 100644 --- a/app/modules/_base/embybrowse.py +++ b/app/modules/_base/embybrowse.py @@ -1147,6 +1147,54 @@ def _post_emby_userdata_with_compat( return False +def _report_emby_playstate_user_endpoint( + cfg: EmbyBrowseConfig, + *, + item_id: str, + position_ms: int, + is_paused: bool, + state: str, + media_source_id: Optional[str] = None, + play_session_id: Optional[str] = None, + event_name: Optional[str] = None, +) -> bool: + """ + 通过 Emby/Jellyfin 服务端 PlaystateService 用户路径(`Users/{UserId}/PlayingItems/{ItemId}`)上报进度。 + + 当仅配置全局 API Key 且服务端不支持直接 `POST .../UserData`(如部分 Emby 4.7/4.8 实例返回 404/405)时, + 以此兼容接口同步播放位置与暂停/停止状态。 + """ + if not cfg.host or not cfg.api_key or not cfg.user_id: + return False + quoted_item = quote(str(item_id), safe="") + quoted_user = quote(str(cfg.user_id), safe="") + base_url = f"{cfg.host}{cfg.api_prefix}Users/{quoted_user}/PlayingItems/{quoted_item}" + ticks = max(0, int(position_ms)) * _TICKS_PER_MS + extra: dict[str, Any] = {"PositionTicks": ticks} + if media_source_id: + extra["MediaSourceId"] = media_source_id + if play_session_id: + extra["PlaySessionId"] = play_session_id + if state != "stopped": + extra["PlayMethod"] = "DirectPlay" + if state in {"playing", "paused"}: + extra["IsPaused"] = "true" if (is_paused or state == "paused") else "false" + extra["EventName"] = event_name or ("Pause" if (is_paused or state == "paused") else "TimeUpdate") + params = _api_params(cfg, extra) + try: + http = cfg.request_factory() + if state == "stopped": + res = http.delete_res(url=base_url, params=params) + elif state == "started": + res = http.post_res(url=base_url, params=params) + else: + res = http.post_res(url=f"{base_url}/Progress", params=params) + return bool(res and res.status_code in {200, 204}) + except Exception as err: + logger.debug(f"兜底通过 PlayingItems 上报 {cfg.server_type} 播放进度失败:{err}") + return False + + def _emby_report_userdata_fallback( cfg: EmbyBrowseConfig, *, @@ -1156,9 +1204,13 @@ def _emby_report_userdata_fallback( state: str, allow_userdata_write: bool, token_invalid: bool, + media_source_id: Optional[str] = None, + play_session_id: Optional[str] = None, + is_paused: bool = False, + event_name: Optional[str] = None, ) -> dict[str, Any]: """ - 在仅配置全局服务端 API Key(无用户级令牌)时,通过 UserData / PlayedItems 持久化断点与已看状态。 + 在仅配置全局服务端 API Key(无用户级令牌)时,通过 UserData / PlayedItems / PlayingItems 持久化断点与已看状态。 :return: 包含 `reported`、`mode="userdata"`、`userdata_written`、`needs_account_bind` 的结构化回执 """ @@ -1207,6 +1259,17 @@ def _emby_report_userdata_fallback( fallback_params=None, json_body=None, ) + if not ok: + ok = _report_emby_playstate_user_endpoint( + cfg, + item_id=item_id, + position_ms=position_ms, + is_paused=is_paused, + state=state, + media_source_id=media_source_id, + play_session_id=play_session_id, + event_name=event_name, + ) base_result["reported"] = ok base_result["userdata_written"] = ok return base_result @@ -1234,6 +1297,17 @@ def _emby_report_userdata_fallback( fallback_params=None, json_body=body, ) + if not ok: + ok = _report_emby_playstate_user_endpoint( + cfg, + item_id=item_id, + position_ms=position_ms, + is_paused=is_paused, + state=state, + media_source_id=media_source_id, + play_session_id=play_session_id, + event_name=event_name, + ) base_result["reported"] = ok base_result["userdata_written"] = ok return base_result @@ -1306,6 +1380,10 @@ def emby_report_progress_detail( state=state, allow_userdata_write=allow_userdata_write, token_invalid=True, + media_source_id=media_source_id, + play_session_id=resolved_session_id, + is_paused=is_paused, + event_name=event_name, ) return _emby_report_userdata_fallback( cfg, @@ -1315,6 +1393,10 @@ def emby_report_progress_detail( state=state, allow_userdata_write=allow_userdata_write, token_invalid=False, + media_source_id=media_source_id, + play_session_id=resolved_session_id, + is_paused=is_paused, + event_name=event_name, ) diff --git a/app/modules/filemanager/module.py b/app/modules/filemanager/module.py index f942e8f99..ae78aac25 100644 --- a/app/modules/filemanager/module.py +++ b/app/modules/filemanager/module.py @@ -434,6 +434,45 @@ class FileManagerModule(_ModuleBase): return None return storage_oper.download(fileitem, path=path) + def supports_file_stream(self, storage: str) -> bool: + """ + 检查指定存储实现是否支持按需 HTTP Range 流式读取(无需整文件落盘)。 + """ + if storage == "local": + return True + if storage not in self._support_storages: + return False + storage_oper = self.__get_storage_oper(storage) + if not storage_oper: + return False + storage_cls = type(storage_oper) + return ( + storage_cls.get_stream_url is not StorageBase.get_stream_url + or storage_cls.open_file_stream is not StorageBase.open_file_stream + ) + + def get_file_stream_url(self, fileitem: FileItem) -> Optional[tuple[str, dict[str, str]]]: + """ + 委托远端存储解析可 Range 代理的 HTTP(S) 直链与上游请求头。 + """ + if fileitem.storage not in self._support_storages: + return None + storage_oper = self.__get_storage_oper(fileitem.storage) + if not storage_oper: + return None + return storage_oper.get_stream_url(fileitem) + + def open_file_stream(self, fileitem: FileItem) -> Optional[tuple[Any, int]]: + """ + 委托远端存储以可 seek 二进制流打开文件用于 HTTP Range 渐进传输。 + """ + if fileitem.storage not in self._support_storages: + return None + storage_oper = self.__get_storage_oper(fileitem.storage) + if not storage_oper: + return None + return storage_oper.open_file_stream(fileitem) + def upload_file(self, fileitem: FileItem, path: Path, new_name: Optional[str] = None) -> Optional[FileItem]: """ 委托目标存储接收本地文件。 diff --git a/app/modules/filemanager/storages/__init__.py b/app/modules/filemanager/storages/__init__.py index 0b8bacb9c..a7eff19d8 100644 --- a/app/modules/filemanager/storages/__init__.py +++ b/app/modules/filemanager/storages/__init__.py @@ -323,6 +323,26 @@ class StorageBase(metaclass=ABCMeta): """ pass + def get_stream_url(self, fileitem: _SchemaFileItem) -> Optional[Tuple[str, dict[str, str]]]: + """ + 返回支持 HTTP Range 渐进流式播放的远端文件直链与可选上游请求头。 + + :param fileitem: 远端文件项 + :return: ``(url, headers)`` 二元组;存储不支持 HTTP 直链流式读取时返回 None + """ + _ = fileitem + return None + + def open_file_stream(self, fileitem: _SchemaFileItem) -> Optional[Tuple[Any, int]]: + """ + 以可随机定位的二进制只读流打开远端文件(例如 SMB),用于按需分块 Range 传输。 + + :param fileitem: 远端文件项 + :return: ``(seekable_binary_stream, file_size)`` 二元组;不支持时返回 None + """ + _ = fileitem + return None + @abstractmethod def upload(self, fileitem: _SchemaFileItem, path: Path, new_name: Optional[str] = None) -> Optional[_SchemaFileItem]: diff --git a/app/modules/filemanager/storages/alipan.py b/app/modules/filemanager/storages/alipan.py index b2410dc50..e4e03fd6e 100644 --- a/app/modules/filemanager/storages/alipan.py +++ b/app/modules/filemanager/storages/alipan.py @@ -884,6 +884,34 @@ class AliPan(StorageBase, metaclass=WeakSingleton): ) return self.__get_fileitem(result, parent=target_dir_path) + def get_stream_url(self, fileitem: _SchemaFileItem) -> Optional[Tuple[str, dict[str, str]]]: + """ + 返回阿里云盘文件的直链与必要上游请求头,用于 HTTP Range 渐进式流媒体代理。 + """ + if not fileitem.path: + return None + drive_id = fileitem.drive_id + file_id = fileitem.fileid + if not drive_id or not file_id: + detail = self.get_item(Path(fileitem.path)) + if not detail or not detail.drive_id or not detail.fileid: + return None + drive_id = detail.drive_id + file_id = detail.fileid + download_info = self._request_api( + "POST", + "/adrive/v1.0/openFile/getDownloadUrl", + json={"drive_id": drive_id, "file_id": file_id}, + ) + download_url = download_info.get("url") if isinstance(download_info, dict) else None + if not download_url: + return None + headers = { + "User-Agent": str(get_runtime_setting("NORMAL_USER_AGENT")), + "Referer": "https://www.aliyundrive.com/", + } + return str(download_url), headers + def download(self, fileitem: _SchemaFileItem, path: Optional[Path] = None) -> Optional[Path]: """ 下载云端文件到本地目录并报告进度。 diff --git a/app/modules/filemanager/storages/alist.py b/app/modules/filemanager/storages/alist.py index 163bf4cfd..b1e44c028 100644 --- a/app/modules/filemanager/storages/alist.py +++ b/app/modules/filemanager/storages/alist.py @@ -555,6 +555,64 @@ class Alist(StorageBase, metaclass=WeakSingleton): return True + def _resolve_download_url( + self, + fileitem: _SchemaFileItem, + password: Optional[str] = "", + ) -> Optional[tuple[str, Optional[int]]]: + """ + 向 OpenList/AList 查询单文件的签名直链或 `/d` 下载地址及可选文件大小。 + """ + if not fileitem.path: + return None + resp = RequestUtils(headers=self.__get_header_with_token()).post_res( + self.__get_api_url("/api/fs/get"), + json={ + "path": fileitem.path, + "password": password, + "page": 1, + "per_page": 0, + "refresh": False, + }, + ) + if not resp: + logger.warn(f"【OpenList】请求获取文件 {fileitem.path} 失败,无法连接alist服务") + return None + if resp.status_code != 200: + logger.warn( + f"【OpenList】请求获取文件 {fileitem.path} 失败,状态码:{resp.status_code}" + ) + return None + + result = resp.json() + if result["code"] != 200: + logger.warn( + f"【OpenList】获取文件 {fileitem.path} 失败,错误信息:{result['message']}" + ) + return None + + data = result.get("data") or {} + remote_size = data.get("size") + if data.get("raw_url"): + return str(data["raw_url"]), remote_size + download_url = UrlUtils.adapt_request_url( + self.__get_base_url, f"/d{fileitem.path}" + ) + if download_url and data.get("sign"): + download_url = download_url + "?sign=" + data["sign"] + if not download_url: + return None + return download_url, remote_size + + def get_stream_url(self, fileitem: _SchemaFileItem) -> Optional[tuple[str, dict[str, str]]]: + """ + 返回 OpenList/AList 文件的 HTTP 直链用于 Range 流式播放。 + """ + resolved = self._resolve_download_url(fileitem) + if not resolved: + return None + return resolved[0], {} + def download( self, fileitem: _SchemaFileItem, @@ -574,44 +632,11 @@ class Alist(StorageBase, metaclass=WeakSingleton): """ if not fileitem.path: return None - resp = RequestUtils(headers=self.__get_header_with_token()).post_res( - self.__get_api_url("/api/fs/get"), - json={ - "path": fileitem.path, - "password": password, - "page": 1, - "per_page": 0, - "refresh": False, - }, - ) - if not resp: - logger.warn(f"【OpenList】请求获取文件 {path} 失败,无法连接alist服务") - return None - if resp.status_code != 200: - logger.warn( - f"【OpenList】请求获取文件 {path} 失败,状态码:{resp.status_code}" - ) - return None - - result = resp.json() - if result["code"] != 200: - logger.warn( - f"【OpenList】获取文件 {path} 失败,错误信息:{result['message']}" - ) - return None - - if result["data"]["raw_url"]: - download_url = result["data"]["raw_url"] - else: - download_url = UrlUtils.adapt_request_url( - self.__get_base_url, f"/d{fileitem.path}" - ) - if download_url and result["data"]["sign"]: - download_url = download_url + "?sign=" + result["data"]["sign"] - + resolved = self._resolve_download_url(fileitem, password=password) local_path = self._build_download_path(fileitem, path or get_runtime_setting('TEMP_PATH')) - if local_path is None or not download_url: + if local_path is None or not resolved: return None + download_url, remote_size = resolved # 下载使用 raw_url 或带 sign 的 /d 地址,API 令牌不属于文件服务及其重定向目标。 request_utils = RequestUtils() @@ -630,7 +655,7 @@ class Alist(StorageBase, metaclass=WeakSingleton): downloaded_size += len(chunk) expected_size = fileitem.size if expected_size is None: - expected_size = result["data"].get("size") + expected_size = remote_size if expected_size is None and r.headers.get("Content-Length"): expected_size = int(r.headers["Content-Length"]) if expected_size is not None and downloaded_size != expected_size: diff --git a/app/modules/filemanager/storages/smb.py b/app/modules/filemanager/storages/smb.py index 5e95713fd..b5cc5ee63 100644 --- a/app/modules/filemanager/storages/smb.py +++ b/app/modules/filemanager/storages/smb.py @@ -657,6 +657,26 @@ class SMB(StorageBase, metaclass=WeakSingleton): logger.error(f"【SMB】重命名失败: {e}") return False + def open_file_stream(self, fileitem: _SchemaFileItem) -> Optional[tuple[Any, int]]: + """ + 以可随机定位的二进制只读句柄打开 SMB 共享文件,供流媒体端点按 HTTP Range 边加载边播放。 + """ + import smbclient + + file_path = fileitem.path + if not file_path: + return None + smb_path = self._normalize_path(file_path) + try: + self._check_connection() + stat_info = smbclient.stat(smb_path) + size = int(stat_info.st_size) + stream = smbclient.open_file(smb_path, mode="rb") + return stream, size + except Exception as e: + logger.error(f"【SMB】打开流式读取失败: {fileitem.name} - {e}") + return None + def download(self, fileitem: _SchemaFileItem, path: Optional[Path] = None) -> Optional[Path]: """ 分块读取 SMB 文件到本地路径并报告进度。 diff --git a/app/modules/filemanager/storages/u115.py b/app/modules/filemanager/storages/u115.py index 83e0da6d5..1a37ae7cc 100644 --- a/app/modules/filemanager/storages/u115.py +++ b/app/modules/filemanager/storages/u115.py @@ -1072,6 +1072,29 @@ class U115Pan(StorageBase, metaclass=WeakSingleton): modify_time=local_path.stat().st_mtime if local_path.exists() else None, ) + def get_stream_url(self, fileitem: _SchemaFileItem) -> Optional[Tuple[str, dict[str, str]]]: + """ + 返回 115 网盘文件的直链与请求头,用于 HTTP Range 渐进式流媒体代理。 + """ + if not fileitem.path: + return None + pickcode = fileitem.pickcode + if not pickcode: + detail = self.get_item(Path(fileitem.path)) + if not detail or not detail.pickcode: + return None + pickcode = detail.pickcode + download_info = self._request_api( + "POST", "/open/ufile/downurl", "data", data={"pick_code": pickcode} + ) + if not isinstance(download_info, dict) or not download_info: + return None + download_url = list(download_info.values())[0].get("url", {}).get("url") + if not download_url: + return None + ua = getattr(self._request_utils, "_ua", None) or str(get_runtime_setting("NORMAL_USER_AGENT")) + return str(download_url), {"User-Agent": str(ua)} + def download(self, fileitem: _SchemaFileItem, path: Optional[Path] = None) -> Optional[Path]: """ 查询下载地址后将云端文件写入本地目录并报告进度。 diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index df7f19e18..6a78f8ba0 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -563,7 +563,7 @@ "from:smbclient.reset_connection_cache as reset_connection_cache", "import:smbclient as smbclient" ], - "fingerprint": "37619f050b03598fa559c6ae2df94bda6adf7cffd1cc42d9db9059f1fb41af47", + "fingerprint": "bfc6993d05d5d33dfcb8044fda6c89a3cc3c599fecb0fe327cefd9e1f9145092", "kind": "network_sdk", "source": "app.modules.filemanager.storages.smb", "target": "smbclient", @@ -600,6 +600,8 @@ "SMB.list|call:listdir", "SMB.list|call:stat", "SMB.move|call:rename", + "SMB.open_file_stream|call:open_file", + "SMB.open_file_stream|call:stat", "SMB.rename|call:rename", "SMB.upload|call:open_file", "SMB.upload|call:write", @@ -978,8 +980,8 @@ "runtime_only": true } }, - "edge_count": 10675, - "edge_sha256": "a7a8da5510b7e44d2feaec5ccbcfb60b82cf95111e75b19dbc568c4b3d8a279c", + "edge_count": 10678, + "edge_sha256": "faf9bdd85757d382b62b5b20e3148fc82cf9f95e75f1d215520eb487b26a7581", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -1105,6 +1107,7 @@ "app.adapters.mediastream -> app.runtime", "app.adapters.mediastream -> app.runtime.settings", "app.adapters.mediastream -> app.schemas", + "app.adapters.mediastream -> app.schemas.file", "app.adapters.mediastream -> app.schemas.mediaserver", "app.adapters.network.browser -> app.adapters", "app.adapters.network.browser -> app.adapters.network", @@ -2928,6 +2931,7 @@ "app.api.endpoints.mediaserver -> app.chain", "app.api.endpoints.mediaserver -> app.chain.download", "app.api.endpoints.mediaserver -> app.chain.mediaserver", + "app.api.endpoints.mediaserver -> app.chain.storage", "app.api.endpoints.mediaserver -> app.chain.tmdb", "app.api.endpoints.mediaserver -> app.domain", "app.api.endpoints.mediaserver -> app.domain.context", @@ -2935,6 +2939,7 @@ "app.api.endpoints.mediaserver -> app.schemas", "app.api.endpoints.mediaserver -> app.schemas.common", "app.api.endpoints.mediaserver -> app.schemas.context", + "app.api.endpoints.mediaserver -> app.schemas.file", "app.api.endpoints.mediaserver -> app.schemas.media", "app.api.endpoints.mediaserver -> app.schemas.mediaserver", "app.api.endpoints.mediaserver -> app.schemas.response", diff --git a/tests/fixtures/architecture/runtime-contract-baseline.json b/tests/fixtures/architecture/runtime-contract-baseline.json index a2a2bba2a..11c54f792 100644 --- a/tests/fixtures/architecture/runtime-contract-baseline.json +++ b/tests/fixtures/architecture/runtime-contract-baseline.json @@ -8941,10 +8941,10 @@ } }, "run_module": { - "call_count": 289, + "call_count": 292, "dynamic_call_count": 0, "dynamic_calls": [], - "method_count": 234, + "method_count": 237, "methods": { "anilist_credits": [ { @@ -9869,6 +9869,13 @@ "mode": "sync" } ], + "get_file_stream_url": [ + { + "caller": "app.chain.storage", + "count": 1, + "mode": "sync" + } + ], "get_folder": [ { "caller": "app.chain.storage", @@ -10337,6 +10344,13 @@ "mode": "sync" } ], + "open_file_stream": [ + { + "caller": "app.chain.storage", + "count": 1, + "mode": "sync" + } + ], "parse_torrent_download_response": [ { "caller": "app.chain.download.submission", @@ -10530,6 +10544,13 @@ "mode": "sync" } ], + "supports_file_stream": [ + { + "caller": "app.chain.storage", + "count": 1, + "mode": "sync" + } + ], "test_site": [ { "caller": "app.chain.site", diff --git a/tests/test_mediaserver_browse_detail.py b/tests/test_mediaserver_browse_detail.py index 5aa2cba35..6558e64d1 100644 --- a/tests/test_mediaserver_browse_detail.py +++ b/tests/test_mediaserver_browse_detail.py @@ -229,6 +229,23 @@ def test_emby_browse_filters_detail_seasons_episodes_and_subtitles() -> None: assert emby_report_progress(session_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 + # 8. Emby API Key 兜底:当 POST .../UserData 返回 404/405 时自动回退到 PlaystateService PlayingItems + http.post_res.reset_mock() + http.delete_res.reset_mock() + http.post_res.side_effect = [Mock(status_code=405), Mock(status_code=204)] + assert emby_report_progress(cfg, "ep-1", 180_000, media_source_id="src-4k", state="paused", is_paused=True) is True + assert http.post_res.call_count == 2 + assert "/PlayingItems/ep-1/Progress" in http.post_res.call_args.kwargs["url"] + assert http.post_res.call_args.kwargs["params"]["PositionTicks"] == 1_800_000_000 + assert http.post_res.call_args.kwargs["params"]["IsPaused"] == "true" + + http.post_res.side_effect = None + http.post_res.return_value = Mock(status_code=404) + http.delete_res.return_value = Mock(status_code=204) + assert emby_report_progress(cfg, "ep-1", 240_000, media_source_id="src-4k", state="stopped") is True + assert "/PlayingItems/ep-1" in http.delete_res.call_args.kwargs["url"] + assert http.delete_res.call_args.kwargs["params"]["PositionTicks"] == 2_400_000_000 + def test_plex_browse_detail_seasons_episodes_and_progress() -> None: """验证 Plex 浏览、筛选、详情轨道解析、三层剧集、字幕流及进度回传。""" diff --git a/tests/test_mediaserver_streaming.py b/tests/test_mediaserver_streaming.py index 270f7da9d..2e9fb8807 100644 --- a/tests/test_mediaserver_streaming.py +++ b/tests/test_mediaserver_streaming.py @@ -814,3 +814,93 @@ def test_stream_route_supports_head_and_range_for_local_audio_ticket( assert range_resp.status_code == 206 assert range_resp.headers["content-range"] == "bytes 0-3/16" assert range_resp.content == b"0123" + + +def test_remote_storage_smb_and_http_progressive_stream_tickets( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """验证 SMB(可随机定位流)与 OpenList/网盘(HTTP 直链)远端文件支持签发流票据并按 Range 边加载边播放。""" + import io + + payload = b"0123456789abcdefghijklmnopqrstuvwxyz" + monkeypatch.setattr(mediastream, "get_runtime_setting", lambda _key: "test-resource-secret") + monkeypatch.setattr(mediaserver, "_ensure_manage_storage_item", lambda fileitem, _user: fileitem) + + class _FakeStorageChain: + def supports_file_stream(self, storage: str) -> bool: + return storage in {"smb", "alist"} + + def get_file_stream_url(self, fileitem): + if fileitem.storage == "alist": + return ("https://cdn.example.com/movie.mp4", {"Referer": "https://alist.example.com/"}) + return None + + def open_file_stream(self, fileitem): + if fileitem.storage == "smb": + return io.BytesIO(payload), len(payload) + return None + + monkeypatch.setattr(mediaserver, "StorageChain", _FakeStorageChain) + monkeypatch.setattr( + mediaserver, + "_remote_stream_response", + lambda url, range_header, _hosts, extra_headers=None, head_only=False: mediaserver.StreamingResponse( + iter(() if head_only else [b"ABCD"]), + status_code=206 if range_header else 200, + media_type="video/mp4", + headers={"Accept-Ranges": "bytes", "X-Upstream-Url": url, "X-Has-Referer": str(bool(extra_headers))}, + ), + ) + + current_user = SimpleNamespace(id=21, is_superuser=True, permissions={}) + app = FastAPI() + app.include_router(mediaserver.router, prefix="/api/v1/mediaserver") + app.dependency_overrides[mediaserver.get_current_active_manage_user] = lambda: current_user + app.dependency_overrides[mediaserver.verify_token] = lambda: TokenPayload(sub=21) + app.dependency_overrides[mediaserver.verify_resource_token] = lambda: TokenPayload(sub=21) + + with TestClient(app) as client: + # 1. SMB 可 seek 分块 Range 流式读取 + smb_ticket = client.post( + "/api/v1/mediaserver/stream-ticket", + json={ + "file": {"storage": "smb", "type": "file", "name": "demo.mp4", "path": "/share/demo.mp4"}, + "media_type": "video", + }, + ) + assert smb_ticket.status_code == 200 + smb_id = smb_ticket.json()["data"]["item_id"] + smb_manifest = client.get("/api/v1/mediaserver/stream-info", params={"itemid": smb_id}).json()["data"] + smb_head = client.head(smb_manifest["content_url"]) + smb_range = client.get(smb_manifest["content_url"], headers={"Range": "bytes=10-15"}) + assert smb_head.status_code == 200 + assert smb_head.headers["content-length"] == str(len(payload)) + assert smb_range.status_code == 206 + assert smb_range.headers["content-range"] == f"bytes 10-15/{len(payload)}" + assert smb_range.content == b"abcdef" + + # 2. OpenList HTTP 直链代理 + alist_ticket = client.post( + "/api/v1/mediaserver/stream-ticket", + json={ + "file": {"storage": "alist", "type": "file", "name": "movie.mp4", "path": "/media/movie.mp4"}, + "media_type": "video", + }, + ) + assert alist_ticket.status_code == 200 + alist_id = alist_ticket.json()["data"]["item_id"] + alist_manifest = client.get("/api/v1/mediaserver/stream-info", params={"itemid": alist_id}).json()["data"] + alist_range = client.get(alist_manifest["content_url"], headers={"Range": "bytes=0-3"}) + assert alist_range.status_code == 206 + assert alist_range.headers["x-upstream-url"] == "https://cdn.example.com/movie.mp4" + assert alist_range.content == b"ABCD" + + # 3. 不支持流式的存储返回 400 + unsupported = client.post( + "/api/v1/mediaserver/stream-ticket", + json={ + "file": {"storage": "rclone", "type": "file", "name": "movie.mp4", "path": "/media/movie.mp4"}, + "media_type": "video", + }, + ) + assert unsupported.status_code == 400 diff --git a/tests/test_subscribe_endpoint.py b/tests/test_subscribe_endpoint.py index 5a825f2ae..91c96d6fb 100644 --- a/tests/test_subscribe_endpoint.py +++ b/tests/test_subscribe_endpoint.py @@ -520,6 +520,68 @@ class TestSubscribeEndpoint: assert updated.music_type == "album" assert updated.total_tracks == 11 + def test_update_subscribe_guards_blank_name_type_and_normalizes_agent_type(self): + """ + 局部编辑传入空白 name / type 不得清空已有有效字段,英文类型自动归一化,非法类型应明确拒绝。 + """ + from app.api.endpoints.subscribe import update_subscribe + from app.application.subscription.contract import resolve_subscribe_media_type + + assert resolve_subscribe_media_type("movie") == MediaType.MOVIE + assert resolve_subscribe_media_type(" 电视剧 ") == MediaType.TV + assert resolve_subscribe_media_type("") is None + assert resolve_subscribe_media_type("invalid") is None + + subscribe = _EndpointSubscribe( + id=29, + username="alice", + name="沙丘", + type=MediaType.MOVIE.value, + ) + repository = _SubscriptionRepositoryFake(subscribe) + + with patch( + "app.runtime.events.eventmanager.async_send_event", + new=AsyncMock(), + ): + # 传入空 name/type 时必须保留原有有效字段 + resp_blank = asyncio.run( + update_subscribe( + subscribe_in=Subscribe(id=29, name=" ", type=""), + mutation=_subscription_mutation(repository), + current_user=_EndpointUser(name="alice", is_superuser=False), + ) + ) + assert resp_blank.success + kept = repository.get(29) + assert kept is not None + assert kept.name == "沙丘" + assert kept.type == MediaType.MOVIE.value + + # 传入英文枚举名自动归一化为标准值 + resp_agent = asyncio.run( + update_subscribe( + subscribe_in=Subscribe(id=29, type="tv"), + mutation=_subscription_mutation(repository), + current_user=_EndpointUser(name="alice", is_superuser=False), + ) + ) + assert resp_agent.success + normalized = repository.get(29) + assert normalized is not None + assert normalized.type == MediaType.TV.value + + # 传入非法类型应被拒绝而非破坏记录 + resp_bad = asyncio.run( + update_subscribe( + subscribe_in=Subscribe(id=29, type="bogus_type"), + mutation=_subscription_mutation(repository), + current_user=_EndpointUser(name="alice", is_superuser=False), + ) + ) + assert not resp_bad.success + assert "无效" in (resp_bad.message or "") + def test_superuser_can_update_other_and_legacy_subscribe(self): """ 超级用户可以管理他人和 legacy 订阅。