mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
fix(messaging): restore traditional media interaction for approved channel members when agent is disabled
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
|
||||
import math
|
||||
import re
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Dict, List, Optional, Tuple, Union
|
||||
|
||||
from app.application.directory import DirectoryHelper
|
||||
@@ -49,6 +50,65 @@ class MediaInteractionChain(ChainBase):
|
||||
_button_page_size = 8
|
||||
_text_page_size = 8
|
||||
_auto_download_dir_name = "自动匹配目录"
|
||||
_subscribe_actions = frozenset({"Subscribe", "ReSubscribe", "MusicSubscribe", "MusicReSubscribe"})
|
||||
_scope_labels = {"search": "搜索", "subscribe": "订阅", "download": "下载"}
|
||||
|
||||
@classmethod
|
||||
def _action_required_scope(cls, action: str) -> str:
|
||||
"""
|
||||
返回媒体交互动作所需的渠道能力键。
|
||||
|
||||
:param action: 媒体交互动作名称
|
||||
:return: 订阅类动作返回 subscribe,其余搜索类动作返回 search
|
||||
"""
|
||||
return "subscribe" if action in cls._subscribe_actions else "search"
|
||||
|
||||
@staticmethod
|
||||
def _has_scope(allowed_scopes: Optional[Mapping[str, Any]], scope: str) -> bool:
|
||||
"""
|
||||
判断当前上下文是否具备指定能力;未传权限映射时按管理员/非受限模式放行。
|
||||
|
||||
:param allowed_scopes: 受控普通成员的实时权限映射,None 表示不限制
|
||||
:param scope: 待检查的能力键
|
||||
:return: 允许执行时返回 True
|
||||
"""
|
||||
return allowed_scopes is None or allowed_scopes.get(scope) is True
|
||||
|
||||
def _require_scope(
|
||||
self,
|
||||
allowed_scopes: Optional[Mapping[str, Any]],
|
||||
scope: str,
|
||||
*,
|
||||
channel: NotificationChannel,
|
||||
source: str,
|
||||
userid: Union[str, int],
|
||||
username: str,
|
||||
) -> bool:
|
||||
"""
|
||||
在受控成员执行传统媒体交互前校验能力授权,未授权时直接回复提示。
|
||||
|
||||
:param allowed_scopes: 受控普通成员的实时权限映射,None 表示不限制
|
||||
:param scope: 本步骤所需能力键(search、subscribe 或 download)
|
||||
:param channel: 发起交互的通知渠道
|
||||
:param source: 渠道实例标识
|
||||
:param userid: 渠道平台用户标识
|
||||
:param username: 渠道展示名称
|
||||
:return: 已获授权时返回 True;拒绝时回复提示并返回 False
|
||||
"""
|
||||
if self._has_scope(allowed_scopes, scope):
|
||||
return True
|
||||
label = self._scope_labels.get(scope, scope)
|
||||
self.post_message(
|
||||
Message(
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
title=f"当前渠道成员未获授权使用{label}能力,请联系管理员调整权限",
|
||||
save_history=False,
|
||||
)
|
||||
)
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def has_pending_interaction(user_id: Union[str, int]) -> bool:
|
||||
@@ -149,9 +209,22 @@ class MediaInteractionChain(ChainBase):
|
||||
username: str,
|
||||
original_message_id: Optional[Union[str, int]] = None,
|
||||
original_chat_id: Optional[str] = None,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
处理按钮回调,并将当前视图刷新到原消息上。
|
||||
|
||||
:param callback_data: 渠道传回的按钮回调载荷
|
||||
:param channel: 通知渠道
|
||||
:param source: 渠道实例标识
|
||||
:param userid: 渠道平台用户标识
|
||||
:param username: 渠道展示名称
|
||||
:param original_message_id: 需要原地刷新的消息标识,None 表示发送新消息
|
||||
:param original_chat_id: 会话或群聊标识,None 表示使用渠道默认定位
|
||||
:param allowed_scopes: 受控普通成员的实时权限映射,None 表示不限制
|
||||
:param owner_username: 统一渠道授权确定的业务归属用户名,None 时保留既有解析规则
|
||||
:return: 已匹配并处理回调时返回 True
|
||||
"""
|
||||
parsed = self.parse_callback(callback_data)
|
||||
if not parsed:
|
||||
@@ -232,6 +305,8 @@ class MediaInteractionChain(ChainBase):
|
||||
username=username,
|
||||
original_message_id=original_message_id,
|
||||
original_chat_id=original_chat_id,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -243,6 +318,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -254,6 +331,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -266,11 +345,22 @@ class MediaInteractionChain(ChainBase):
|
||||
userid: Union[str, int],
|
||||
username: str,
|
||||
text: str,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> bool:
|
||||
"""
|
||||
处理文本式交互。
|
||||
|
||||
有会话时优先处理数字选择和翻页;无会话时负责识别搜索/订阅类入口。
|
||||
|
||||
:param channel: 通知渠道
|
||||
:param source: 渠道实例标识
|
||||
:param userid: 渠道平台用户标识
|
||||
:param username: 渠道展示名称
|
||||
:param text: 用户输入的文本内容
|
||||
:param allowed_scopes: 受控普通成员的实时权限映射,None 表示不限制
|
||||
:param owner_username: 统一渠道授权确定的业务归属用户名,None 时保留既有解析规则
|
||||
:return: 已消费该文本时返回 True
|
||||
"""
|
||||
request = media_interaction_manager.get_by_user(userid)
|
||||
normalized = (text or "").strip()
|
||||
@@ -311,6 +401,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
elif request.phase == "torrent":
|
||||
self._handle_torrent_selection(
|
||||
@@ -320,6 +412,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
else:
|
||||
self._handle_media_selection(
|
||||
@@ -329,6 +423,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -403,6 +499,7 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -421,10 +518,20 @@ class MediaInteractionChain(ChainBase):
|
||||
source: str,
|
||||
userid: Union[str, int],
|
||||
username: str,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
根据用户输入搜索影视或音乐,并进入对应候选选择阶段。
|
||||
"""
|
||||
if not self._require_scope(
|
||||
allowed_scopes,
|
||||
self._action_required_scope(action),
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
):
|
||||
return
|
||||
meta: Optional[MetaBase]
|
||||
medias: List[MediaInfo | MusicInfo] = []
|
||||
if action.startswith("Music"):
|
||||
@@ -486,6 +593,8 @@ class MediaInteractionChain(ChainBase):
|
||||
username: str,
|
||||
original_message_id: Optional[Union[str, int]] = None,
|
||||
original_chat_id: Optional[str] = None,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
处理媒体选择阶段的序号输入。
|
||||
@@ -513,6 +622,15 @@ class MediaInteractionChain(ChainBase):
|
||||
request.current_media = mediainfo
|
||||
|
||||
if request.action in {"Search", "ReSearch", "MusicSearch", "MusicReSearch"}:
|
||||
if not self._require_scope(
|
||||
allowed_scopes,
|
||||
"search",
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
):
|
||||
return
|
||||
self._search_media_resources(
|
||||
request=request,
|
||||
mediainfo=mediainfo,
|
||||
@@ -522,6 +640,8 @@ class MediaInteractionChain(ChainBase):
|
||||
username=username,
|
||||
original_message_id=original_message_id,
|
||||
original_chat_id=original_chat_id,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -531,6 +651,15 @@ class MediaInteractionChain(ChainBase):
|
||||
"MusicSubscribe",
|
||||
"MusicReSubscribe",
|
||||
}:
|
||||
if not self._require_scope(
|
||||
allowed_scopes,
|
||||
"subscribe",
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
):
|
||||
return
|
||||
subscribe_media(
|
||||
host=self,
|
||||
request=request,
|
||||
@@ -539,6 +668,7 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
|
||||
def _search_media_resources(
|
||||
@@ -551,6 +681,8 @@ class MediaInteractionChain(ChainBase):
|
||||
username: str,
|
||||
original_message_id: Optional[Union[str, int]] = None,
|
||||
original_chat_id: Optional[str] = None,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
根据已选媒体搜索资源,并切换到资源选择阶段。
|
||||
@@ -626,7 +758,7 @@ class MediaInteractionChain(ChainBase):
|
||||
return
|
||||
|
||||
contexts = TorrentHelper().sort_torrents(contexts)
|
||||
if self._should_auto_download(userid):
|
||||
if self._should_auto_download(userid) and self._has_scope(allowed_scopes, "download"):
|
||||
logger.info("用户 %s 在自动下载用户中,开始自动择优下载 ...", userid)
|
||||
request.phase = "torrent"
|
||||
request.page = 0
|
||||
@@ -652,6 +784,8 @@ class MediaInteractionChain(ChainBase):
|
||||
userid=userid,
|
||||
username=username,
|
||||
no_exists=no_exists,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -676,6 +810,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source: str,
|
||||
userid: Union[str, int],
|
||||
username: str,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
处理资源选择阶段的下载操作。
|
||||
@@ -688,6 +824,15 @@ class MediaInteractionChain(ChainBase):
|
||||
username=username,
|
||||
)
|
||||
return
|
||||
if not self._require_scope(
|
||||
allowed_scopes,
|
||||
"download",
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
):
|
||||
return
|
||||
|
||||
if page_index == 0:
|
||||
if self._prompt_download_dir_selection(
|
||||
@@ -706,6 +851,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -741,7 +888,7 @@ class MediaInteractionChain(ChainBase):
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
username=owner_username or username,
|
||||
user_specified=True,
|
||||
)
|
||||
|
||||
@@ -793,6 +940,8 @@ class MediaInteractionChain(ChainBase):
|
||||
source: str,
|
||||
userid: Union[str, int],
|
||||
username: str,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
处理下载目录阶段的序号输入,并继续执行挂起的下载动作。
|
||||
@@ -805,6 +954,15 @@ class MediaInteractionChain(ChainBase):
|
||||
username=username,
|
||||
)
|
||||
return
|
||||
if not self._require_scope(
|
||||
allowed_scopes,
|
||||
"download",
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
):
|
||||
return
|
||||
|
||||
page_items, page, _ = self._page_items(
|
||||
items=request.download_dirs,
|
||||
@@ -830,6 +988,8 @@ class MediaInteractionChain(ChainBase):
|
||||
userid=userid,
|
||||
username=username,
|
||||
save_path=None,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -850,6 +1010,8 @@ class MediaInteractionChain(ChainBase):
|
||||
userid=userid,
|
||||
username=username,
|
||||
save_path=save_path,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
|
||||
def _execute_pending_download(
|
||||
@@ -860,6 +1022,8 @@ class MediaInteractionChain(ChainBase):
|
||||
userid: Union[str, int],
|
||||
username: str,
|
||||
save_path: Optional[str],
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
使用用户确认的下载目录执行单资源下载或自动择优下载。
|
||||
@@ -873,7 +1037,7 @@ class MediaInteractionChain(ChainBase):
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
username=owner_username or username,
|
||||
save_path=save_path,
|
||||
user_specified=True,
|
||||
)
|
||||
@@ -892,6 +1056,8 @@ class MediaInteractionChain(ChainBase):
|
||||
username=username,
|
||||
no_exists=no_exists,
|
||||
save_path=save_path,
|
||||
allowed_scopes=allowed_scopes,
|
||||
owner_username=owner_username,
|
||||
)
|
||||
return
|
||||
|
||||
@@ -927,6 +1093,8 @@ class MediaInteractionChain(ChainBase):
|
||||
username: str,
|
||||
no_exists: Optional[Dict[Union[int, str], Dict[int, NotExistMediaInfo]]] = None,
|
||||
save_path: Optional[str] = None,
|
||||
allowed_scopes: Optional[Mapping[str, Any]] = None,
|
||||
owner_username: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
自动择优下载当前资源列表,并在未完成时补建订阅。
|
||||
@@ -958,11 +1126,23 @@ class MediaInteractionChain(ChainBase):
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
username=owner_username or username,
|
||||
)
|
||||
if downloads and not lefts:
|
||||
logger.info("%s 下载完成", current_media.title_year)
|
||||
return
|
||||
if not self._has_scope(allowed_scopes, "subscribe"):
|
||||
self.post_message(
|
||||
Message(
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid=userid,
|
||||
username=username,
|
||||
title="当前渠道成员未获授权使用订阅能力,未自动添加缺失订阅",
|
||||
save_history=False,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
logger.info("%s 未下载未完整,添加订阅 ...", current_media.title_year)
|
||||
if downloads and current_media.type == MediaType.TV:
|
||||
@@ -975,11 +1155,14 @@ class MediaInteractionChain(ChainBase):
|
||||
note = None
|
||||
|
||||
mp_name = (
|
||||
self.user_repository.find_name_by_bindings(
|
||||
{f"{channel.name.lower()}_userid": userid}
|
||||
owner_username
|
||||
or (
|
||||
self.user_repository.find_name_by_bindings(
|
||||
{f"{channel.name.lower()}_userid": userid}
|
||||
)
|
||||
if channel
|
||||
else None
|
||||
)
|
||||
if channel
|
||||
else None
|
||||
)
|
||||
SubscribeChain().add(
|
||||
title=current_media.title or "",
|
||||
|
||||
@@ -16,7 +16,7 @@ from concurrent.futures import Future
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Protocol, Tuple, Union, cast
|
||||
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Protocol, Tuple, Union, cast
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from app.application.agent import (
|
||||
@@ -52,6 +52,9 @@ from app.schemas.message import IncomingMessage, Message
|
||||
from app.schemas.notification import ChannelCapabilityManager
|
||||
from app.schemas.types import EventType, MessageType, NotificationChannel
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.application.security.user import UserSnapshot
|
||||
|
||||
|
||||
class MessageResponsePort(Protocol):
|
||||
"""
|
||||
@@ -531,24 +534,213 @@ class MessageChain(ChainBase):
|
||||
},
|
||||
)
|
||||
|
||||
def _resolve_approved_channel_member(
|
||||
self, context: InteractionContext,
|
||||
) -> Tuple[bool, Optional["UserSnapshot"]]:
|
||||
"""
|
||||
实时解析已批准普通成员的能力与归属,区分未批准成员和失效授权。
|
||||
|
||||
:param context: 本次渠道消息上下文
|
||||
:return: (是否允许继续, 已批准成员快照);未申请或待审批返回 (True, None),授权失效已回复错误时返回 (False, None)
|
||||
"""
|
||||
authorization = get_channel_authorization()
|
||||
if authorization is None:
|
||||
return False, None
|
||||
try:
|
||||
member = authorization.find(context.channel.value, context.source or "", str(context.user_id))
|
||||
if member is None or member.status == "pending":
|
||||
return True, None
|
||||
return True, authorization.principal(member.id)
|
||||
except (PermissionError, ValueError) as error:
|
||||
self.post_message(Message(
|
||||
channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title=str(error), save_history=False,
|
||||
))
|
||||
return False, None
|
||||
|
||||
def _dispatch_member_media_text(
|
||||
self, context: InteractionContext, text: str, principal: "UserSnapshot",
|
||||
) -> bool:
|
||||
"""
|
||||
仅在传统媒体交互范围内处理已批准普通成员的文本输入,不进入旧管理会话。
|
||||
|
||||
:param context: 本次渠道消息上下文
|
||||
:param text: 去除 /noai 等控制前缀后的交互文本
|
||||
:param principal: 实时复核后的普通成员权限与归属快照
|
||||
:return: 已被传统媒体交互消费时返回 True
|
||||
"""
|
||||
if not text:
|
||||
return False
|
||||
status = self._mark_message_processing_started(
|
||||
channel=context.channel, source=context.source or "", userid=context.user_id,
|
||||
original_message_id=context.original_message_id, original_chat_id=context.original_chat_id, text=text,
|
||||
)
|
||||
try:
|
||||
return _MediaInteractionChain().handle_text_interaction(
|
||||
channel=context.channel,
|
||||
source=context.source or "",
|
||||
userid=context.user_id,
|
||||
username=context.username or str(context.user_id),
|
||||
text=text,
|
||||
allowed_scopes=principal.permissions,
|
||||
owner_username=principal.name,
|
||||
)
|
||||
finally:
|
||||
self._mark_message_processing_finished(
|
||||
channel=context.channel, source=context.source or "", userid=context.user_id, status=status,
|
||||
original_message_id=context.original_message_id, original_chat_id=context.original_chat_id,
|
||||
)
|
||||
|
||||
def _dispatch_member_media_callback(
|
||||
self, context: InteractionContext, callback_data: str, principal: "UserSnapshot",
|
||||
) -> bool:
|
||||
"""
|
||||
在成员实时能力范围内处理传统媒体交互按钮回调。
|
||||
|
||||
:param context: 本次渠道消息上下文
|
||||
:param callback_data: 已归一化的媒体交互回调载荷
|
||||
:param principal: 实时复核后的普通成员权限与归属快照
|
||||
:return: 回调不延后结束状态,固定返回 False
|
||||
"""
|
||||
if not ChannelCapabilityManager.supports_callbacks(context.channel):
|
||||
logger.warning("渠道 %s 不支持回调,但收到了回调消息:%s", context.channel.value, callback_data)
|
||||
return False
|
||||
status = self._mark_message_processing_started(
|
||||
channel=context.channel, source=context.source or "", userid=context.user_id,
|
||||
original_message_id=context.original_message_id, original_chat_id=context.original_chat_id,
|
||||
text=callback_data,
|
||||
)
|
||||
try:
|
||||
_MediaInteractionChain().handle_callback_interaction(
|
||||
callback_data=callback_data,
|
||||
channel=context.channel,
|
||||
source=context.source or "",
|
||||
userid=context.user_id,
|
||||
username=context.username or str(context.user_id),
|
||||
original_message_id=context.original_message_id,
|
||||
original_chat_id=context.original_chat_id,
|
||||
allowed_scopes=principal.permissions,
|
||||
owner_username=principal.name,
|
||||
)
|
||||
finally:
|
||||
self._mark_message_processing_finished(
|
||||
channel=context.channel, source=context.source or "", userid=context.user_id, status=status,
|
||||
original_message_id=context.original_message_id, original_chat_id=context.original_chat_id,
|
||||
)
|
||||
return False
|
||||
|
||||
def _handle_approved_channel_member_text(
|
||||
self, context: InteractionContext, text: str, principal: "UserSnapshot",
|
||||
images: Optional[List[IncomingMessage.MessageImage]], files: Optional[List[IncomingMessage.MessageAttachment]],
|
||||
has_audio_input: bool,
|
||||
) -> bool:
|
||||
"""
|
||||
路由已批准普通成员的文本消息:优先按配置分流受控 Agent 与受控传统媒体交互。
|
||||
|
||||
:param context: 平台消息上下文
|
||||
:param text: 转写后的用户输入文本
|
||||
:param principal: 实时复核后的普通成员权限与归属快照
|
||||
:param images: 归一化图片附件
|
||||
:param files: 文件附件
|
||||
:param has_audio_input: 是否已有语音输入
|
||||
:return: 是否延后结束处理中状态
|
||||
"""
|
||||
no_ai_requested, no_ai_text = self._strip_no_ai_prefix(text)
|
||||
if no_ai_requested:
|
||||
if not no_ai_text:
|
||||
self.post_message(Message(
|
||||
channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title="请输入要使用传统交互处理的内容", save_history=False,
|
||||
))
|
||||
return False
|
||||
self._dispatch_member_media_text(context, no_ai_text, principal)
|
||||
return False
|
||||
|
||||
if self._has_ai_prefix(text) or is_agent_learning_command(text):
|
||||
if not self.runtime_config.ai_agent_enable:
|
||||
self.post_message(Message(
|
||||
channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title="AI Agent 未启用,请联系管理员。", save_history=False,
|
||||
))
|
||||
return False
|
||||
return self._handle_ai_message(
|
||||
text=text, channel=context.channel, source=context.source or "", userid=context.user_id,
|
||||
username=context.username or "", is_channel_admin=False,
|
||||
original_message_id=context.original_message_id, original_chat_id=context.original_chat_id,
|
||||
images=images, files=files, has_audio_input=has_audio_input,
|
||||
)
|
||||
|
||||
media_attempted = False
|
||||
if media_interaction_manager.get_by_user(context.user_id) is not None:
|
||||
media_attempted = True
|
||||
if self._dispatch_member_media_text(context, text, principal):
|
||||
return False
|
||||
|
||||
if self.runtime_config.ai_agent_enable and (
|
||||
self.runtime_config.ai_agent_global or images or files or has_audio_input
|
||||
):
|
||||
return self._handle_ai_message(
|
||||
text=text, channel=context.channel, source=context.source or "", userid=context.user_id,
|
||||
username=context.username or "", is_channel_admin=False,
|
||||
original_message_id=context.original_message_id, original_chat_id=context.original_chat_id,
|
||||
images=images, files=files, has_audio_input=has_audio_input,
|
||||
)
|
||||
|
||||
if text and not media_attempted and self._dispatch_member_media_text(context, text, principal):
|
||||
return False
|
||||
|
||||
if self.runtime_config.ai_agent_enable:
|
||||
self.post_message(Message(
|
||||
channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title="请使用 /ai 加上要执行的操作。", save_history=False,
|
||||
))
|
||||
elif images or files or has_audio_input:
|
||||
self.post_message(Message(
|
||||
channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title="AI Agent 未启用,请联系管理员。", save_history=False,
|
||||
))
|
||||
return False
|
||||
|
||||
def _handle_channel_member_message(
|
||||
self, context: InteractionContext, text: str, callback_data: Optional[str],
|
||||
images: Optional[List[IncomingMessage.MessageImage]], files: Optional[List[IncomingMessage.MessageAttachment]],
|
||||
has_audio_input: bool,
|
||||
) -> Optional[bool]:
|
||||
"""
|
||||
普通及待审批成员只进入受控 Agent,旧管理会话不能在撤权后消费文本。
|
||||
受控处理普通及待审批成员消息,隔离旧管理会话并按配置分流 Agent 与传统媒体交互。
|
||||
|
||||
:param context: 平台消息上下文及刚复核的管理员标记
|
||||
:param text: 转写后的本次输入
|
||||
:param callback_data: 仅批准的 Agent 选项回调交给后续路由
|
||||
:param callback_data: 仅批准的 Agent 选项回调交给后续路由,媒体回调按成员能力执行
|
||||
:param images: 归一化图片附件
|
||||
:param files: 文件附件
|
||||
:param has_audio_input: 是否已有语音输入
|
||||
:return: None 表示继续原路由;布尔值表示本次已处理及是否延后结束状态
|
||||
"""
|
||||
if context.is_channel_admin or callback_data is not None:
|
||||
if context.is_channel_admin:
|
||||
return None
|
||||
if callback_data is not None:
|
||||
if parse_agent_choice_callback(callback_data) is not None:
|
||||
return None
|
||||
if _MediaInteractionChain.parse_callback(callback_data) is None:
|
||||
self.post_message(Message(
|
||||
channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title="此命令需要管理员授权。", save_history=False,
|
||||
))
|
||||
return False
|
||||
ok, principal = self._resolve_approved_channel_member(context)
|
||||
if not ok or principal is None:
|
||||
return False
|
||||
return self._dispatch_member_media_callback(context, callback_data, principal)
|
||||
|
||||
ok, principal = self._resolve_approved_channel_member(context)
|
||||
if not ok:
|
||||
return False
|
||||
if principal is not None:
|
||||
return self._handle_approved_channel_member_text(
|
||||
context, text, principal, images, files, has_audio_input,
|
||||
)
|
||||
|
||||
if not self.runtime_config.ai_agent_enable:
|
||||
self.post_message(Message(channel=context.channel, source=context.source, userid=context.user_id,
|
||||
title="AI Agent 未启用,请联系管理员。", save_history=False))
|
||||
@@ -622,8 +814,18 @@ class MessageChain(ChainBase):
|
||||
))
|
||||
return True
|
||||
principal = service.principal(member.id)
|
||||
traditional_command = value.startswith("/") and not self._has_ai_prefix(value) and not is_agent_learning_command(value)
|
||||
traditional_callback = bool(callback_data or text.startswith("CALLBACK:")) and parse_agent_choice_callback(value) is None
|
||||
no_ai_requested, _ = self._strip_no_ai_prefix(value)
|
||||
traditional_command = (
|
||||
value.startswith("/")
|
||||
and not self._has_ai_prefix(value)
|
||||
and not is_agent_learning_command(value)
|
||||
and not no_ai_requested
|
||||
)
|
||||
traditional_callback = (
|
||||
bool(callback_data or text.startswith("CALLBACK:"))
|
||||
and parse_agent_choice_callback(value) is None
|
||||
and _MediaInteractionChain.parse_callback(value) is None
|
||||
)
|
||||
if (traditional_command or traditional_callback) and not principal.is_superuser:
|
||||
self.post_message(Message(channel=channel, source=source, userid=userid, title="此命令需要管理员授权。", save_history=False))
|
||||
return True
|
||||
|
||||
@@ -47,9 +47,19 @@ def subscribe_media(
|
||||
source: str,
|
||||
userid: int | str,
|
||||
username: str,
|
||||
owner_username: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
为已选影视或音乐目标创建普通订阅或音质洗版订阅。
|
||||
|
||||
:param host: 提供用户绑定查询与渠道消息回复能力的宿主对象
|
||||
:param request: 当前媒体交互请求上下文
|
||||
:param mediainfo: 用户选定的影视或音乐目标
|
||||
:param channel: 发起交互的通知渠道
|
||||
:param source: 渠道实例标识
|
||||
:param userid: 渠道平台发送者标识
|
||||
:param username: 渠道展示昵称,未解析到业务归属时兜底使用
|
||||
:param owner_username: 统一渠道授权已确定的业务归属用户名;为空时回退按渠道绑定查询
|
||||
"""
|
||||
best_version = request.action in {"ReSubscribe", "MusicReSubscribe"}
|
||||
if not best_version:
|
||||
@@ -77,11 +87,14 @@ def subscribe_media(
|
||||
return
|
||||
|
||||
mp_name = (
|
||||
host.user_repository.find_name_by_bindings(
|
||||
{f"{channel.name.lower()}_userid": userid}
|
||||
owner_username
|
||||
or (
|
||||
host.user_repository.find_name_by_bindings(
|
||||
{f"{channel.name.lower()}_userid": userid}
|
||||
)
|
||||
if channel
|
||||
else None
|
||||
)
|
||||
if channel
|
||||
else None
|
||||
)
|
||||
SubscribeChain().add(
|
||||
title=mediainfo.title or "",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
用户在机器人中发送“申请使用”,或点击需要授权时显示的申请按钮。系统管理员在渠道授权弹窗批准后,机器人会向成员发送回执。批准不会自动重放之前的订阅或下载请求,用户需要重新发送要执行的操作。
|
||||
|
||||
普通成员通过受控 Agent 搜索、订阅和下载;定时任务另行开启。传统管理命令和旧式业务按钮仅渠道管理员可用,普通文本不再进入旧管理会话。管理员角色允许实例管理操作,设置时应单独核对。成员身份按通知实例和平台用户 ID 隔离,同一个人在不同机器人中分别授权。昵称、群组 ID 和机器人 ID 不能代替用户身份。
|
||||
普通成员在启用智能助手时可通过受控 Agent 搜索、订阅和下载(定时任务另行开启);未启用智能助手、未开启全局接管或显式使用 `/noai` 时,已批准的普通成员仍可在其已获授权的搜索、订阅、下载能力范围内使用传统媒体文本与按钮交互。传统管理命令、旧管理会话与管理按钮仍仅渠道管理员可用。管理员角色允许实例管理操作,设置时应单独核对。成员身份按通知实例和平台用户 ID 隔离,同一个人在不同机器人中分别授权。昵称、群组 ID 和机器人 ID 不能代替用户身份。
|
||||
|
||||
外部渠道中以标点或符号开头的纯文本(如 `#123456`、`?930441`)优先交给插件输入会话;没有匹配会话时,通过 `UserMessage` 事件交给插件处理,不进入 Agent 或普通消息历史。这类插件输入无需开启 Agent 或添加 `/ai` 前缀,尚未申请或待审批的成员也可发送,已停用或被拒绝的成员仍会被拦截。斜杠命令、按钮回调、带附件消息和网页聊天继续使用原有路由与权限检查。
|
||||
|
||||
|
||||
@@ -1114,3 +1114,235 @@ def test_channel_middleware_fails_closed_without_service(channel_authorization,
|
||||
))
|
||||
assert not accepted and "服务不可用" in result.content
|
||||
handler.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["你好 李焕英", "搜索 你好李焕英"])
|
||||
def test_approved_member_can_use_traditional_media_interaction_when_agent_disabled(
|
||||
channel_authorization, monkeypatch, text,
|
||||
):
|
||||
"""
|
||||
未启用 AI Agent 时,已批准普通成员发传统媒体文本应进入受控媒体交互,不报错 Agent 未启用且隔离旧管理会话。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
from app.application.messaging.site import site_interaction_manager
|
||||
|
||||
service, configs, _ = channel_authorization
|
||||
configs.append(NotificationConf(id="wechat-app", name="企微应用", type="wechat", enabled=True))
|
||||
member = service.request(NotificationChannel.Wechat.value, "企微应用", "wx_member", "微信成员")
|
||||
service.update(member.id, status="approved", role="member", scopes=("search", "subscribe", "download"), reviewer_id=1)
|
||||
principal = service.principal(member.id)
|
||||
|
||||
chain = MessageChain()
|
||||
monkeypatch.setattr(
|
||||
chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=False, ai_agent_global=False)
|
||||
)
|
||||
media_handle = Mock(return_value=True)
|
||||
site_handle = Mock(return_value=True)
|
||||
plugin_handler = Mock()
|
||||
post = Mock()
|
||||
monkeypatch.setattr("app.chain.interaction.MediaInteractionChain.handle_text_interaction", media_handle)
|
||||
monkeypatch.setattr("app.chain.site.SiteChain.handle_text_interaction", site_handle)
|
||||
monkeypatch.setattr(chain, "_plugin_input_interaction_handler", lambda: plugin_handler)
|
||||
monkeypatch.setattr(chain, "post_message", post)
|
||||
monkeypatch.setattr(chain, "_mark_message_processing_started", Mock(return_value=None))
|
||||
monkeypatch.setattr(chain, "_mark_message_processing_finished", Mock())
|
||||
|
||||
# 模拟该成员被降权前遗留的站点管理会话,普通成员回复不得再进入该管理会话。
|
||||
site_request = site_interaction_manager.create_or_replace(
|
||||
user_id="wx_member", command="/sites", channel=NotificationChannel.Wechat, source="企微应用", username="微信成员",
|
||||
)
|
||||
try:
|
||||
chain.handle_message(NotificationChannel.Wechat, "企微应用", "wx_member", "微信成员", text)
|
||||
media_handle.assert_called_once()
|
||||
kwargs = media_handle.call_args.kwargs
|
||||
assert kwargs["text"] == text
|
||||
assert kwargs["owner_username"] == principal.name
|
||||
assert kwargs["allowed_scopes"]["search"] is True
|
||||
assert kwargs["allowed_scopes"]["subscribe"] is True
|
||||
assert kwargs["allowed_scopes"]["download"] is True
|
||||
site_handle.assert_not_called()
|
||||
plugin_handler.handle_text.assert_not_called()
|
||||
post.assert_not_called()
|
||||
|
||||
# 显式 /ai 仍提示 AI Agent 未启用,而普通非媒体文本不误报未启用。
|
||||
chain.handle_message(NotificationChannel.Wechat, "企微应用", "wx_member", "微信成员", "/ai 查一下")
|
||||
assert post.call_count == 1
|
||||
assert "AI Agent 未启用" in post.call_args.args[0].title
|
||||
|
||||
post.reset_mock()
|
||||
media_handle.reset_mock()
|
||||
media_handle.return_value = False
|
||||
chain.handle_message(NotificationChannel.Wechat, "企微应用", "wx_member", "微信成员", "帮我推荐一部电影")
|
||||
media_handle.assert_called_once()
|
||||
post.assert_not_called()
|
||||
finally:
|
||||
site_interaction_manager.remove(site_request.request_id)
|
||||
|
||||
|
||||
def test_approved_member_media_callback_and_noai_routing_preserve_admin_boundary(
|
||||
channel_authorization, monkeypatch,
|
||||
):
|
||||
"""
|
||||
普通成员可使用传统媒体按钮回调、非全局模式及 /noai 传统交互,但管理回调与斜杠命令仍被拦截。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
from app.application.messaging.media import media_interaction_manager
|
||||
|
||||
service, _, _ = channel_authorization
|
||||
member = _approve(service, scopes=("search", "download"))
|
||||
principal = service.principal(member.id)
|
||||
|
||||
chain = MessageChain()
|
||||
monkeypatch.setattr(
|
||||
chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=False, ai_agent_global=False)
|
||||
)
|
||||
media_callback = Mock(return_value=True)
|
||||
media_text = Mock(return_value=True)
|
||||
agent = Mock(return_value=False)
|
||||
post = Mock()
|
||||
monkeypatch.setattr("app.chain.interaction.MediaInteractionChain.handle_callback_interaction", media_callback)
|
||||
monkeypatch.setattr("app.chain.interaction.MediaInteractionChain.handle_text_interaction", media_text)
|
||||
monkeypatch.setattr(chain, "_handle_ai_message", agent)
|
||||
monkeypatch.setattr(chain, "post_message", post)
|
||||
monkeypatch.setattr(chain, "_mark_message_processing_started", Mock(return_value=None))
|
||||
monkeypatch.setattr(chain, "_mark_message_processing_finished", Mock())
|
||||
|
||||
# 传统媒体按钮回调放行并携带实时权限和业务归属。
|
||||
chain.handle_message(
|
||||
NotificationChannel.Telegram, "机器人A", "42", "昵称", "", callback_data="media:req1:select:1"
|
||||
)
|
||||
media_callback.assert_called_once()
|
||||
assert media_callback.call_args.kwargs["callback_data"] == "media:req1:select:1"
|
||||
assert media_callback.call_args.kwargs["owner_username"] == principal.name
|
||||
assert media_callback.call_args.kwargs["allowed_scopes"]["download"] is True
|
||||
assert media_callback.call_args.kwargs["allowed_scopes"]["subscribe"] is False
|
||||
|
||||
# 管理类回调和传统斜杠命令仍仅管理员可用。
|
||||
chain.handle_message(
|
||||
NotificationChannel.Telegram, "机器人A", "42", "昵称", "", callback_data="sites:req1:refresh"
|
||||
)
|
||||
assert "管理员" in post.call_args.args[0].title
|
||||
post.reset_mock()
|
||||
chain.handle_message(NotificationChannel.Telegram, "机器人A", "42", "昵称", "/sites")
|
||||
assert "管理员" in post.call_args.args[0].title
|
||||
|
||||
# 全局 Agent 开启时,/noai 与已有活跃媒体会话的后续选择走受控传统媒体交互。
|
||||
monkeypatch.setattr(
|
||||
chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=True, ai_agent_global=True)
|
||||
)
|
||||
chain.handle_message(NotificationChannel.Telegram, "机器人A", "42", "昵称", "/noai 搜索 流浪地球")
|
||||
media_text.assert_called_once()
|
||||
assert media_text.call_args.kwargs["text"] == "搜索 流浪地球"
|
||||
agent.assert_not_called()
|
||||
|
||||
media_text.reset_mock()
|
||||
pending = media_interaction_manager.create_or_replace(
|
||||
user_id="42", channel=NotificationChannel.Telegram, source="机器人A", username="昵称",
|
||||
action="Search", keyword="流浪地球", title="流浪地球",
|
||||
)
|
||||
try:
|
||||
chain.handle_message(NotificationChannel.Telegram, "机器人A", "42", "昵称", "1")
|
||||
media_text.assert_called_once()
|
||||
assert media_text.call_args.kwargs["text"] == "1"
|
||||
agent.assert_not_called()
|
||||
finally:
|
||||
media_interaction_manager.remove(pending.request_id)
|
||||
|
||||
# 启用 Agent 但未开全局模式时,未命中媒体交互的普通闲聊提示使用 /ai。
|
||||
post.reset_mock()
|
||||
media_text.reset_mock()
|
||||
media_text.return_value = False
|
||||
monkeypatch.setattr(
|
||||
chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=True, ai_agent_global=False)
|
||||
)
|
||||
chain.handle_message(NotificationChannel.Telegram, "机器人A", "42", "昵称", "帮我推荐一部科幻片")
|
||||
assert "请使用 /ai" in post.call_args.args[0].title
|
||||
|
||||
|
||||
def test_traditional_media_interaction_enforces_member_scopes_and_owner_username(monkeypatch):
|
||||
"""
|
||||
受控传统媒体交互严格校验搜索、订阅、下载能力,并按授权归属记录下载与订阅用户名。
|
||||
"""
|
||||
from app.application.messaging.media import media_interaction_manager
|
||||
from app.chain.interaction import MediaInteractionChain
|
||||
from app.domain.context import Context, MediaInfo
|
||||
from app.domain.meta.metavideo import MetaVideo
|
||||
|
||||
interaction = MediaInteractionChain()
|
||||
post = Mock()
|
||||
media_search = Mock(return_value=(MetaVideo("你好李焕英"), [MediaInfo(title="你好,李焕英", year="2021")]))
|
||||
download_single = Mock()
|
||||
subscribe_add = Mock()
|
||||
monkeypatch.setattr(interaction, "post_message", post)
|
||||
monkeypatch.setattr("app.chain.interaction.MediaChain.search", media_search)
|
||||
monkeypatch.setattr("app.chain.interaction.DownloadChain.download_single", download_single)
|
||||
monkeypatch.setattr("app.chain.interaction.DownloadChain.get_no_exists_info", Mock(return_value=(False, {})))
|
||||
monkeypatch.setattr("app.chain.music_interaction.subscribe.SubscribeChain.add", subscribe_add)
|
||||
|
||||
# 缺少 search 能力时拒绝搜索。
|
||||
assert interaction.handle_text_interaction(
|
||||
channel=NotificationChannel.Wechat, source="企微应用", userid="u1", username="昵称",
|
||||
text="搜索 你好李焕英", allowed_scopes={"search": False, "subscribe": True, "download": False},
|
||||
owner_username="channel_owner",
|
||||
) is True
|
||||
media_search.assert_not_called()
|
||||
assert "搜索" in post.call_args.args[0].title
|
||||
|
||||
# 缺少 subscribe 能力时拒绝订阅。
|
||||
post.reset_mock()
|
||||
assert interaction.handle_text_interaction(
|
||||
channel=NotificationChannel.Wechat, source="企微应用", userid="u1", username="昵称",
|
||||
text="订阅 你好李焕英", allowed_scopes={"search": True, "subscribe": False, "download": False},
|
||||
owner_username="channel_owner",
|
||||
) is True
|
||||
media_search.assert_not_called()
|
||||
assert "订阅" in post.call_args.args[0].title
|
||||
|
||||
# 缺少 download 能力时阻止下载,具备 download 能力时使用授权归属用户名下载。
|
||||
post.reset_mock()
|
||||
torrent_ctx = Context(media_info=MediaInfo(title="你好,李焕英", year="2021"))
|
||||
request = media_interaction_manager.create_or_replace(
|
||||
user_id="u1", channel=NotificationChannel.Wechat, source="企微应用", username="昵称",
|
||||
action="Search", keyword="你好李焕英", title="你好,李焕英",
|
||||
meta=MetaVideo("你好李焕英"), items=[torrent_ctx],
|
||||
)
|
||||
request.phase = "torrent"
|
||||
monkeypatch.setattr(interaction, "_get_download_dirs", Mock(return_value=[]))
|
||||
try:
|
||||
assert interaction.handle_text_interaction(
|
||||
channel=NotificationChannel.Wechat, source="企微应用", userid="u1", username="昵称",
|
||||
text="1", allowed_scopes={"search": True, "subscribe": False, "download": False},
|
||||
owner_username="channel_owner",
|
||||
) is True
|
||||
download_single.assert_not_called()
|
||||
assert "下载" in post.call_args.args[0].title
|
||||
|
||||
assert interaction.handle_text_interaction(
|
||||
channel=NotificationChannel.Wechat, source="企微应用", userid="u1", username="昵称",
|
||||
text="1", allowed_scopes={"search": True, "subscribe": False, "download": True},
|
||||
owner_username="channel_owner",
|
||||
) is True
|
||||
download_single.assert_called_once()
|
||||
assert download_single.call_args.kwargs["username"] == "channel_owner"
|
||||
finally:
|
||||
media_interaction_manager.remove(request.request_id)
|
||||
|
||||
# 具备 subscribe 能力时,订阅归属记录为授权用户名而非平台昵称。
|
||||
media_item = MediaInfo(title="你好,李焕英", year="2021")
|
||||
sub_request = media_interaction_manager.create_or_replace(
|
||||
user_id="u1", channel=NotificationChannel.Wechat, source="企微应用", username="昵称",
|
||||
action="Subscribe", keyword="你好李焕英", title="你好,李焕英",
|
||||
meta=MetaVideo("你好李焕英"), items=[media_item],
|
||||
)
|
||||
try:
|
||||
assert interaction.handle_text_interaction(
|
||||
channel=NotificationChannel.Wechat, source="企微应用", userid="u1", username="昵称",
|
||||
text="1", allowed_scopes={"search": False, "subscribe": True, "download": False},
|
||||
owner_username="channel_owner",
|
||||
) is True
|
||||
subscribe_add.assert_called_once()
|
||||
assert subscribe_add.call_args.kwargs["username"] == "channel_owner"
|
||||
finally:
|
||||
media_interaction_manager.remove(sub_request.request_id)
|
||||
|
||||
Reference in New Issue
Block a user