mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-12-02 00:46:27 +08:00
fix(widget): 同步插件小组件架构门禁、开放模型与依赖快照
This commit is contained in:
@@ -68,7 +68,6 @@ from app.schemas.plugin import Plugin as _SchemaPlugin
|
||||
from app.schemas.plugin import PluginAgentPet as _SchemaPluginAgentPet
|
||||
from app.schemas.plugin import PluginDashboard as _SchemaPluginDashboard
|
||||
from app.schemas.plugin import PluginDashboardMetaItem as _SchemaPluginDashboardMetaItem
|
||||
from app.schemas.plugin import PluginWidgetMetaItem as _SchemaPluginWidgetMetaItem
|
||||
from app.schemas.plugin import PluginDataSummary as _SchemaPluginDataSummary
|
||||
from app.schemas.plugin import PluginDocumentation as _SchemaPluginDocumentation
|
||||
from app.schemas.plugin import PluginInstallOutcome as _SchemaPluginInstallOutcome
|
||||
@@ -90,6 +89,7 @@ from app.schemas.plugin import PluginSourceChangeRequest as _SchemaPluginSourceC
|
||||
from app.schemas.plugin import PluginSourceIdentity as _SchemaPluginSourceIdentity
|
||||
from app.schemas.plugin import PluginSourceInstallRequest as _SchemaPluginSourceInstallRequest
|
||||
from app.schemas.plugin import PluginSourceOptions as _SchemaPluginSourceOptions
|
||||
from app.schemas.plugin import PluginWidgetMetaItem as _SchemaPluginWidgetMetaItem
|
||||
from app.schemas.response import Response as _SchemaResponse
|
||||
from app.schemas.token import TokenPayload as _SchemaTokenPayload
|
||||
from app.schemas.types import SystemConfigKey
|
||||
@@ -779,12 +779,15 @@ def plugin_dashboard(
|
||||
)
|
||||
def plugin_widgets_meta(
|
||||
_: ApiPrincipal = Depends(get_current_active_superuser),
|
||||
page: CompatiblePageParam = None,
|
||||
count: CompatibleCountParam = None,
|
||||
) -> List[dict[str, Any]]:
|
||||
"""
|
||||
查询运行中插件声明的移动端桌面小组件目录及仪表板兜底入口。
|
||||
|
||||
:return: 已启用插件的小组件元信息列表
|
||||
"""
|
||||
del page, count
|
||||
return cast(List[dict[str, Any]], get_plugin_manager().get_plugin_widget_meta())
|
||||
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ async def widget_snapshot(
|
||||
response_model_exclude_none=True,
|
||||
openapi_extra={RAW_RESPONSE_OPENAPI_KEY: True},
|
||||
)
|
||||
async def widget_plugin_catalog(
|
||||
def widget_plugin_catalog(
|
||||
grant: WidgetGrant = Depends(get_widget_grant),
|
||||
service: WidgetSnapshotService = Depends(get_widget_snapshot_service),
|
||||
auth: WidgetAuthService = Depends(get_widget_auth_service),
|
||||
@@ -174,8 +174,8 @@ async def widget_plugin_catalog(
|
||||
:return: 不超过 32 KiB 的插件小组件目录模型
|
||||
"""
|
||||
try:
|
||||
result = await service.plugin_catalog(grant)
|
||||
await run_in_threadpool(auth.revalidate, grant)
|
||||
result = service.plugin_catalog(grant)
|
||||
auth.revalidate(grant)
|
||||
except WidgetAccessError as error:
|
||||
widget_http_error(error)
|
||||
except ValueError as error:
|
||||
@@ -190,7 +190,7 @@ async def widget_plugin_catalog(
|
||||
response_model_exclude_none=True,
|
||||
openapi_extra={RAW_RESPONSE_OPENAPI_KEY: True},
|
||||
)
|
||||
async def widget_plugin_snapshot(
|
||||
def widget_plugin_snapshot(
|
||||
plugin_id: str,
|
||||
key: str = "",
|
||||
grant: WidgetGrant = Depends(get_widget_grant),
|
||||
@@ -208,8 +208,8 @@ async def widget_plugin_snapshot(
|
||||
:return: 不超过 32 KiB 的单个插件小组件只读快照
|
||||
"""
|
||||
try:
|
||||
result = await service.plugin_snapshot(grant, plugin_id, key)
|
||||
await run_in_threadpool(auth.revalidate, grant)
|
||||
result = service.plugin_snapshot(grant, plugin_id, key)
|
||||
auth.revalidate(grant)
|
||||
except WidgetAccessError as error:
|
||||
widget_http_error(error)
|
||||
except ValueError as error:
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.application.security.widget import (
|
||||
from app.foundation.size import format_size
|
||||
from app.runtime.execution import run_in_threadpool
|
||||
from app.runtime.log import logger
|
||||
from app.schemas.common import JsonData, JsonObject
|
||||
from app.schemas.dashboard import DashboardMemoryInfo, DownloaderInfo
|
||||
from app.schemas.query import QueryPageRequest, SubscriptionFilter, SubscriptionSnapshot, TransferHistoryFilter
|
||||
from app.schemas.subscribe import Subscribe
|
||||
@@ -382,7 +383,7 @@ class WidgetSnapshotService:
|
||||
],
|
||||
)
|
||||
|
||||
async def plugin_catalog(self, grant: WidgetGrant) -> PluginWidgetCatalog:
|
||||
def plugin_catalog(self, grant: WidgetGrant) -> PluginWidgetCatalog:
|
||||
"""
|
||||
向拥有超级管理员权限的小组件授权返回可绑定的已启用插件小组件目录。
|
||||
|
||||
@@ -393,11 +394,7 @@ class WidgetSnapshotService:
|
||||
"""
|
||||
if not grant.user.is_superuser:
|
||||
raise WidgetAccessError(403, "当前账号无权读取插件小组件")
|
||||
raw_items = (
|
||||
await run_in_threadpool(self._plugin_widgets)
|
||||
if self._plugin_widgets is not None
|
||||
else []
|
||||
)
|
||||
raw_items = self._plugin_widgets() if self._plugin_widgets is not None else []
|
||||
descriptors: list[PluginWidgetDescriptor] = []
|
||||
for raw in (raw_items or [])[:64]:
|
||||
if not isinstance(raw, Mapping):
|
||||
@@ -410,8 +407,7 @@ class WidgetSnapshotService:
|
||||
wname = _text(str(raw.get("name") or pname), 120, pname)
|
||||
raw_desc = raw.get("description")
|
||||
desc = _text(str(raw_desc), 240) if isinstance(raw_desc, str) and raw_desc.strip() else None
|
||||
raw_kind = str(raw.get("kind") or "metrics").strip()
|
||||
kind: PluginWidgetKind = raw_kind if raw_kind in _ALLOWED_KINDS else "metrics" # type: ignore[assignment]
|
||||
kind = self._normalize_widget_kind(raw.get("kind"))
|
||||
source: Literal["widget", "dashboard"] = "dashboard" if raw.get("source") == "dashboard" else "widget"
|
||||
descriptors.append(
|
||||
PluginWidgetDescriptor(
|
||||
@@ -439,7 +435,7 @@ class WidgetSnapshotService:
|
||||
raise ValueError("插件小组件目录超过协议体积")
|
||||
return catalog
|
||||
|
||||
async def plugin_snapshot(
|
||||
def plugin_snapshot(
|
||||
self,
|
||||
grant: WidgetGrant,
|
||||
plugin_id: str,
|
||||
@@ -468,7 +464,7 @@ class WidgetSnapshotService:
|
||||
if self._plugin_widget_data is None:
|
||||
return self._unavailable_plugin_snapshot(grant, clean_pid, clean_key, generated_at, expires_at)
|
||||
try:
|
||||
raw = await run_in_threadpool(self._plugin_widget_data, clean_pid, clean_key)
|
||||
raw = self._plugin_widget_data(clean_pid, clean_key)
|
||||
except Exception as error:
|
||||
logger.warning(f"插件小组件 {clean_pid}/{clean_key} 读取失败({type(error).__name__})")
|
||||
return self._unavailable_plugin_snapshot(grant, clean_pid, clean_key, generated_at, expires_at)
|
||||
@@ -528,20 +524,20 @@ class WidgetSnapshotService:
|
||||
title = _text(str(raw.get("title") or pname), 240, pname)
|
||||
raw_sub = raw.get("subtitle")
|
||||
subtitle = _text(str(raw_sub), 240) if isinstance(raw_sub, str) and raw_sub.strip() else None
|
||||
raw_kind = str(raw.get("kind") or "metrics").strip()
|
||||
kind: PluginWidgetKind = raw_kind if raw_kind in _ALLOWED_KINDS else "metrics" # type: ignore[assignment]
|
||||
kind = self._normalize_widget_kind(raw.get("kind"))
|
||||
|
||||
metrics = self._sanitize_plugin_metrics(raw.get("metrics"))
|
||||
items = self._sanitize_plugin_items(raw.get("items"))
|
||||
layout = self._sanitize_layout_root(raw.get("layout"))
|
||||
raw_layout = self._sanitize_layout_root(raw.get("layout"))
|
||||
layout = JsonObject(raw_layout) if raw_layout is not None else None
|
||||
layouts_raw = raw.get("layouts")
|
||||
layouts: dict[str, dict[str, Any]] | None = None
|
||||
layouts: dict[str, JsonObject] | None = None
|
||||
if isinstance(layouts_raw, Mapping):
|
||||
cleaned_layouts: dict[str, dict[str, Any]] = {}
|
||||
cleaned_layouts: dict[str, JsonObject] = {}
|
||||
for size_key in ("small", "medium", "large"):
|
||||
sanitized_tree = self._sanitize_layout_root(layouts_raw.get(size_key))
|
||||
if sanitized_tree is not None:
|
||||
cleaned_layouts[size_key] = sanitized_tree
|
||||
cleaned_layouts[size_key] = JsonObject(sanitized_tree)
|
||||
if cleaned_layouts:
|
||||
layouts = cleaned_layouts
|
||||
|
||||
@@ -589,8 +585,7 @@ class WidgetSnapshotService:
|
||||
sub_val = _text(str(raw_sub), 120) if isinstance(raw_sub, str) and raw_sub.strip() else None
|
||||
raw_icon = entry.get("icon")
|
||||
icon = _text(str(raw_icon), 48) if isinstance(raw_icon, str) and raw_icon.strip() else None
|
||||
raw_tone = str(entry.get("tone") or "").strip()
|
||||
tone: PluginWidgetTone | None = raw_tone if raw_tone in _ALLOWED_TONES else None # type: ignore[assignment]
|
||||
tone = WidgetSnapshotService._normalize_widget_tone(entry.get("tone"))
|
||||
out.append(
|
||||
PluginWidgetMetricItem(
|
||||
id=mid,
|
||||
@@ -641,8 +636,48 @@ class WidgetSnapshotService:
|
||||
)
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _normalize_widget_kind(raw_kind: Any) -> PluginWidgetKind:
|
||||
"""
|
||||
将任意原始形态标识收敛为受支持的小组件形态字面量。
|
||||
"""
|
||||
candidate = str(raw_kind or "metrics").strip()
|
||||
if candidate == "list":
|
||||
return "list"
|
||||
if candidate == "poster":
|
||||
return "poster"
|
||||
if candidate == "nowPlaying":
|
||||
return "nowPlaying"
|
||||
if candidate == "custom":
|
||||
return "custom"
|
||||
return "metrics"
|
||||
|
||||
@staticmethod
|
||||
def _normalize_widget_tone(raw_tone: Any) -> PluginWidgetTone | None:
|
||||
"""
|
||||
将任意原始色调标识收敛为受支持的语义着色角色或空值。
|
||||
"""
|
||||
candidate = str(raw_tone or "").strip()
|
||||
if candidate == "default":
|
||||
return "default"
|
||||
if candidate == "primary":
|
||||
return "primary"
|
||||
if candidate == "secondary":
|
||||
return "secondary"
|
||||
if candidate == "muted":
|
||||
return "muted"
|
||||
if candidate == "accent":
|
||||
return "accent"
|
||||
if candidate == "success":
|
||||
return "success"
|
||||
if candidate == "warning":
|
||||
return "warning"
|
||||
if candidate == "danger":
|
||||
return "danger"
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _sanitize_layout_root(cls, raw_node: Any) -> dict[str, Any] | None:
|
||||
def _sanitize_layout_root(cls, raw_node: Any) -> dict[str, JsonData] | None:
|
||||
"""
|
||||
对声明式自定义小组件节点树执行深度不超过五层、总节点不超过四十个的白名单清洗。
|
||||
"""
|
||||
@@ -656,7 +691,7 @@ class WidgetSnapshotService:
|
||||
*,
|
||||
depth: int,
|
||||
budget: list[int],
|
||||
) -> dict[str, Any] | None:
|
||||
) -> dict[str, JsonData] | None:
|
||||
"""
|
||||
递归校验单个声明式布局节点,剔除未知属性、外部任意地址与越界数值。
|
||||
"""
|
||||
@@ -666,8 +701,22 @@ class WidgetSnapshotService:
|
||||
if node_type not in _ALLOWED_NODE_TYPES:
|
||||
return None
|
||||
budget[0] -= 1
|
||||
out: dict[str, Any] = {"type": node_type}
|
||||
out: dict[str, JsonData] = {"type": node_type}
|
||||
cls._copy_layout_scalars(raw_node, out)
|
||||
action = cls._sanitize_layout_action(raw_node.get("action"))
|
||||
if action is not None:
|
||||
out["action"] = action
|
||||
if node_type in {"column", "row", "stack", "box"} and depth < PLUGIN_WIDGET_MAX_DEPTH:
|
||||
children = cls._sanitize_layout_children(raw_node.get("children"), depth=depth + 1, budget=budget)
|
||||
if children is not None:
|
||||
out["children"] = children
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def _copy_layout_scalars(cls, raw_node: Mapping[str, Any], out: dict[str, JsonData]) -> None:
|
||||
"""
|
||||
提取并截断布局节点的文本、色调、有界数值、布尔开关与受控静态资源路径。
|
||||
"""
|
||||
for str_key, max_bytes in (
|
||||
("text", 240),
|
||||
("label", 120),
|
||||
@@ -681,13 +730,18 @@ class WidgetSnapshotService:
|
||||
val = raw_node.get(str_key)
|
||||
if isinstance(val, str) and val.strip():
|
||||
out[str_key] = _text(val, max_bytes)
|
||||
|
||||
raw_tone = raw_node.get("tone")
|
||||
if isinstance(raw_tone, str):
|
||||
clean_tone = raw_tone.strip()
|
||||
if clean_tone in _ALLOWED_TONES or _HEX_COLOR_RE.fullmatch(clean_tone):
|
||||
out["tone"] = clean_tone
|
||||
cls._copy_layout_numbers_and_assets(raw_node, out)
|
||||
|
||||
@classmethod
|
||||
def _copy_layout_numbers_and_assets(cls, raw_node: Mapping[str, Any], out: dict[str, JsonData]) -> None:
|
||||
"""
|
||||
拷贝布局节点中的有界数值、布尔标记与插件静态资源路径。
|
||||
"""
|
||||
for num_key, low, high in (
|
||||
("gap", 0.0, 32.0),
|
||||
("padding", 0.0, 32.0),
|
||||
@@ -703,43 +757,54 @@ class WidgetSnapshotService:
|
||||
if isinstance(num_val, (int, float)) and not isinstance(num_val, bool) and math.isfinite(float(num_val)):
|
||||
clamped = min(max(float(num_val), low), high)
|
||||
out[num_key] = int(clamped) if num_key == "maxLines" else clamped
|
||||
|
||||
if isinstance(raw_node.get("tabularNums"), bool):
|
||||
out["tabularNums"] = raw_node["tabularNums"]
|
||||
if isinstance(raw_node.get("scrim"), bool):
|
||||
out["scrim"] = raw_node["scrim"]
|
||||
|
||||
for bool_key in ("tabularNums", "scrim"):
|
||||
if isinstance(raw_node.get(bool_key), bool):
|
||||
out[bool_key] = raw_node[bool_key]
|
||||
for url_key in ("url", "backgroundUrl"):
|
||||
raw_url = raw_node.get(url_key)
|
||||
safe_url = cls._sanitize_plugin_asset_path(raw_url)
|
||||
safe_url = cls._sanitize_plugin_asset_path(raw_node.get(url_key))
|
||||
if safe_url:
|
||||
out[url_key] = safe_url
|
||||
|
||||
raw_action = raw_node.get("action")
|
||||
if isinstance(raw_action, Mapping):
|
||||
action_kind = str(raw_action.get("type") or "openPlugin").strip()
|
||||
if action_kind in {"openPlugin", "pluginAction"}:
|
||||
act_obj: dict[str, str] = {"type": action_kind}
|
||||
surface = str(raw_action.get("surface") or "data").strip()
|
||||
if surface in {"data", "config"}:
|
||||
act_obj["surface"] = surface
|
||||
act_id = raw_action.get("actionId")
|
||||
if isinstance(act_id, str) and _WIDGET_KEY_RE.fullmatch(act_id.strip()):
|
||||
act_obj["actionId"] = act_id.strip()
|
||||
out["action"] = act_obj
|
||||
@staticmethod
|
||||
def _sanitize_layout_action(raw_action: Any) -> dict[str, JsonData] | None:
|
||||
"""
|
||||
校验按钮或容器上的受控点击动作定义。
|
||||
"""
|
||||
if not isinstance(raw_action, Mapping):
|
||||
return None
|
||||
action_kind = str(raw_action.get("type") or "openPlugin").strip()
|
||||
if action_kind not in {"openPlugin", "pluginAction"}:
|
||||
return None
|
||||
act_obj: dict[str, JsonData] = {"type": action_kind}
|
||||
surface = str(raw_action.get("surface") or "data").strip()
|
||||
if surface in {"data", "config"}:
|
||||
act_obj["surface"] = surface
|
||||
act_id = raw_action.get("actionId")
|
||||
if isinstance(act_id, str) and _WIDGET_KEY_RE.fullmatch(act_id.strip()):
|
||||
act_obj["actionId"] = act_id.strip()
|
||||
return act_obj
|
||||
|
||||
if node_type in {"column", "row", "stack", "box"} and depth < PLUGIN_WIDGET_MAX_DEPTH:
|
||||
raw_children = raw_node.get("children")
|
||||
if isinstance(raw_children, list):
|
||||
children: list[dict[str, Any]] = []
|
||||
for child in raw_children[:16]:
|
||||
if budget[0] <= 0:
|
||||
break
|
||||
clean_child = cls._sanitize_layout_node(child, depth=depth + 1, budget=budget)
|
||||
if clean_child is not None:
|
||||
children.append(clean_child)
|
||||
out["children"] = children
|
||||
return out
|
||||
@classmethod
|
||||
def _sanitize_layout_children(
|
||||
cls,
|
||||
raw_children: Any,
|
||||
*,
|
||||
depth: int,
|
||||
budget: list[int],
|
||||
) -> list[JsonData] | None:
|
||||
"""
|
||||
按节点配额递归清洗容器子节点列表。
|
||||
"""
|
||||
if not isinstance(raw_children, list):
|
||||
return None
|
||||
children: list[JsonData] = []
|
||||
for child in raw_children[:16]:
|
||||
if budget[0] <= 0:
|
||||
break
|
||||
clean_child = cls._sanitize_layout_node(child, depth=depth, budget=budget)
|
||||
if clean_child is not None:
|
||||
children.append(clean_child)
|
||||
return children
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_plugin_asset_path(raw_url: Any) -> str | None:
|
||||
|
||||
@@ -669,72 +669,99 @@ class PluginProjection:
|
||||
has_page = bool(supports_plugin_hook(plugin, "get_page"))
|
||||
plugin_name = getattr(plugin, "plugin_name", None) or plugin_id
|
||||
if supports_plugin_hook(plugin, "get_widgets"):
|
||||
try:
|
||||
raw_list = plugin.get_widgets() or []
|
||||
except Exception as error:
|
||||
self._logger.error(f"获取插件[{plugin_id}]桌面小组件元信息出错:{error}")
|
||||
raw_list = []
|
||||
if isinstance(raw_list, list):
|
||||
for raw in raw_list:
|
||||
if not isinstance(raw, Mapping):
|
||||
continue
|
||||
raw_key = str(raw.get("key") or "").strip()
|
||||
if not _WIDGET_KEY_PATTERN.match(raw_key):
|
||||
self._logger.warning(
|
||||
f"插件[{plugin_id}]桌面小组件 key 无效,已跳过:{raw_key!r}"
|
||||
)
|
||||
continue
|
||||
if (plugin_id, raw_key) in declared_pairs:
|
||||
continue
|
||||
name = str(raw.get("name") or "").strip() or plugin_name
|
||||
kind = str(raw.get("kind") or "metrics").strip()
|
||||
if kind not in _WIDGET_KINDS:
|
||||
kind = "metrics"
|
||||
description = raw.get("description")
|
||||
desc_str = description.strip() if isinstance(description, str) and description.strip() else None
|
||||
declared_pairs.add((plugin_id, raw_key))
|
||||
items.append({
|
||||
"plugin_id": plugin_id,
|
||||
"plugin_name": plugin_name,
|
||||
"key": raw_key,
|
||||
"name": name,
|
||||
"description": desc_str,
|
||||
"kind": kind,
|
||||
"source": "widget",
|
||||
"has_page": has_page,
|
||||
})
|
||||
self._collect_declared_widgets(
|
||||
plugin_id, plugin, plugin_name, has_page, declared_pairs, items
|
||||
)
|
||||
if supports_plugin_hook(plugin, "get_dashboard"):
|
||||
try:
|
||||
dash_metas = (
|
||||
plugin.get_dashboard_meta()
|
||||
if supports_plugin_hook(plugin, "get_dashboard_meta")
|
||||
else None
|
||||
)
|
||||
except Exception as error:
|
||||
self._logger.error(f"获取插件[{plugin_id}]仪表盘兜底小组件元信息出错:{error}")
|
||||
continue
|
||||
entries = dash_metas if dash_metas else [{"key": "", "name": plugin_name}]
|
||||
for entry in entries:
|
||||
if not isinstance(entry, Mapping):
|
||||
continue
|
||||
dash_key = str(entry.get("key") or "").strip()
|
||||
if dash_key and not _WIDGET_KEY_PATTERN.match(dash_key):
|
||||
continue
|
||||
if (plugin_id, dash_key) in declared_pairs:
|
||||
continue
|
||||
declared_pairs.add((plugin_id, dash_key))
|
||||
items.append({
|
||||
"plugin_id": plugin_id,
|
||||
"plugin_name": plugin_name,
|
||||
"key": dash_key,
|
||||
"name": str(entry.get("name") or "").strip() or plugin_name,
|
||||
"description": None,
|
||||
"kind": "metrics",
|
||||
"source": "dashboard",
|
||||
"has_page": has_page,
|
||||
})
|
||||
self._collect_dashboard_fallback_widgets(
|
||||
plugin_id, plugin, plugin_name, has_page, declared_pairs, items
|
||||
)
|
||||
return items
|
||||
|
||||
def _collect_declared_widgets(
|
||||
self,
|
||||
plugin_id: str,
|
||||
plugin: Any,
|
||||
plugin_name: str,
|
||||
has_page: bool,
|
||||
declared_pairs: set[tuple[str, str]],
|
||||
items: list[dict[str, Any]],
|
||||
) -> None:
|
||||
"""
|
||||
收集单个插件通过 `get_widgets()` 显式声明的桌面小组件条目。
|
||||
"""
|
||||
try:
|
||||
raw_list = plugin.get_widgets() or []
|
||||
except Exception as error:
|
||||
self._logger.error(f"获取插件[{plugin_id}]桌面小组件元信息出错:{error}")
|
||||
return
|
||||
if not isinstance(raw_list, list):
|
||||
return
|
||||
for raw in raw_list:
|
||||
if not isinstance(raw, Mapping):
|
||||
continue
|
||||
raw_key = str(raw.get("key") or "").strip()
|
||||
if not _WIDGET_KEY_PATTERN.match(raw_key):
|
||||
self._logger.warning(f"插件[{plugin_id}]桌面小组件 key 无效,已跳过:{raw_key!r}")
|
||||
continue
|
||||
if (plugin_id, raw_key) in declared_pairs:
|
||||
continue
|
||||
kind = str(raw.get("kind") or "metrics").strip()
|
||||
description = raw.get("description")
|
||||
desc_str = description.strip() if isinstance(description, str) and description.strip() else None
|
||||
declared_pairs.add((plugin_id, raw_key))
|
||||
items.append({
|
||||
"plugin_id": plugin_id,
|
||||
"plugin_name": plugin_name,
|
||||
"key": raw_key,
|
||||
"name": str(raw.get("name") or "").strip() or plugin_name,
|
||||
"description": desc_str,
|
||||
"kind": kind if kind in _WIDGET_KINDS else "metrics",
|
||||
"source": "widget",
|
||||
"has_page": has_page,
|
||||
})
|
||||
|
||||
def _collect_dashboard_fallback_widgets(
|
||||
self,
|
||||
plugin_id: str,
|
||||
plugin: Any,
|
||||
plugin_name: str,
|
||||
has_page: bool,
|
||||
declared_pairs: set[tuple[str, str]],
|
||||
items: list[dict[str, Any]],
|
||||
) -> None:
|
||||
"""
|
||||
对未覆盖相同键名的仪表板条目补充桌面小组件兜底元信息。
|
||||
"""
|
||||
try:
|
||||
dash_metas = (
|
||||
plugin.get_dashboard_meta()
|
||||
if supports_plugin_hook(plugin, "get_dashboard_meta")
|
||||
else None
|
||||
)
|
||||
except Exception as error:
|
||||
self._logger.error(f"获取插件[{plugin_id}]仪表盘兜底小组件元信息出错:{error}")
|
||||
return
|
||||
for entry in (dash_metas or [{"key": "", "name": plugin_name}]):
|
||||
if not isinstance(entry, Mapping):
|
||||
continue
|
||||
dash_key = str(entry.get("key") or "").strip()
|
||||
if dash_key and not _WIDGET_KEY_PATTERN.match(dash_key):
|
||||
continue
|
||||
if (plugin_id, dash_key) in declared_pairs:
|
||||
continue
|
||||
declared_pairs.add((plugin_id, dash_key))
|
||||
items.append({
|
||||
"plugin_id": plugin_id,
|
||||
"plugin_name": plugin_name,
|
||||
"key": dash_key,
|
||||
"name": str(entry.get("name") or "").strip() or plugin_name,
|
||||
"description": None,
|
||||
"kind": "metrics",
|
||||
"source": "dashboard",
|
||||
"has_page": has_page,
|
||||
})
|
||||
|
||||
def widget_data(self, plugin_id: str, key: str = "") -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
读取插件专属桌面小组件快照;未实现专属方法时自动投影该插件的仪表板结构。
|
||||
@@ -847,69 +874,100 @@ class PluginProjection:
|
||||
if depth > 14 or (len(metrics) >= 8 and len(lines) >= 12):
|
||||
return
|
||||
if isinstance(node, str):
|
||||
cleaned = " ".join(node.split()).strip()
|
||||
if (
|
||||
cleaned
|
||||
and cleaned != "null"
|
||||
and not cleaned.startswith(("mdi-", "ri-", "#", "{", "."))
|
||||
and len(cleaned) <= 80
|
||||
):
|
||||
lines.append(cleaned)
|
||||
cls._append_clean_snippet(node, lines)
|
||||
return
|
||||
if isinstance(node, list):
|
||||
for child in node:
|
||||
cls._extract_vuetify_snippets(child, metrics, lines, depth + 1)
|
||||
return
|
||||
if not isinstance(node, Mapping):
|
||||
return
|
||||
comp = str(node.get("component") or "")
|
||||
if comp.lower() in {"style", "script", "vicon"}:
|
||||
if isinstance(node, Mapping):
|
||||
cls._extract_vuetify_mapping(node, metrics, lines, depth)
|
||||
|
||||
@staticmethod
|
||||
def _append_clean_snippet(raw: str, lines: list[str]) -> None:
|
||||
"""
|
||||
过滤图标类名、颜色值与脚本噪声后收集可读摘要文本。
|
||||
"""
|
||||
cleaned = " ".join(raw.split()).strip()
|
||||
if (
|
||||
cleaned
|
||||
and cleaned != "null"
|
||||
and not cleaned.startswith(("mdi-", "ri-", "#", "{", "."))
|
||||
and len(cleaned) <= 80
|
||||
):
|
||||
lines.append(cleaned)
|
||||
|
||||
@classmethod
|
||||
def _extract_vuetify_mapping(
|
||||
cls,
|
||||
node: Mapping[str, Any],
|
||||
metrics: list[dict[str, Any]],
|
||||
lines: list[str],
|
||||
depth: int,
|
||||
) -> None:
|
||||
"""
|
||||
解析单个 Vuetify 节点字典的属性指标与子元素内容。
|
||||
"""
|
||||
if str(node.get("component") or "").lower() in {"style", "script", "vicon"}:
|
||||
return
|
||||
props = node.get("props")
|
||||
if isinstance(props, Mapping):
|
||||
prop_title = str(props.get("title") or props.get("label") or "").strip()
|
||||
prop_value = str(props.get("value") or props.get("subtitle") or "").strip()
|
||||
if (
|
||||
prop_title
|
||||
and prop_value
|
||||
and len(prop_title) <= 24
|
||||
and len(prop_value) <= 32
|
||||
and not prop_title.startswith("mdi-")
|
||||
and not prop_value.startswith("mdi-")
|
||||
and len(metrics) < 8
|
||||
):
|
||||
metrics.append({
|
||||
"id": f"m-{len(metrics)}",
|
||||
"label": prop_title,
|
||||
"value": prop_value,
|
||||
})
|
||||
else:
|
||||
for field in ("title", "subtitle", "label", "text", "value"):
|
||||
val = props.get(field)
|
||||
if isinstance(val, str):
|
||||
cls._extract_vuetify_snippets(val, metrics, lines, depth + 1)
|
||||
cls._extract_vuetify_props(props, metrics, lines, depth)
|
||||
direct_text = node.get("text")
|
||||
if isinstance(direct_text, str):
|
||||
cls._extract_vuetify_snippets(direct_text, metrics, lines, depth + 1)
|
||||
cls._append_clean_snippet(direct_text, lines)
|
||||
content = node.get("content")
|
||||
if isinstance(content, list):
|
||||
local_lines: list[str] = []
|
||||
local_metrics: list[dict[str, Any]] = []
|
||||
for child in content:
|
||||
cls._extract_vuetify_snippets(child, local_metrics, local_lines, depth + 1)
|
||||
for item in local_metrics:
|
||||
if len(metrics) < 8:
|
||||
metrics.append(item)
|
||||
if (
|
||||
len(local_lines) == 2
|
||||
and len(local_lines[0]) <= 20
|
||||
and len(local_lines[1]) <= 28
|
||||
and len(metrics) < 8
|
||||
):
|
||||
metrics.append({
|
||||
"id": f"m-{len(metrics)}",
|
||||
"label": local_lines[0],
|
||||
"value": local_lines[1],
|
||||
})
|
||||
else:
|
||||
lines.extend(local_lines)
|
||||
cls._extract_vuetify_children(content, metrics, lines, depth)
|
||||
|
||||
@classmethod
|
||||
def _extract_vuetify_props(
|
||||
cls,
|
||||
props: Mapping[str, Any],
|
||||
metrics: list[dict[str, Any]],
|
||||
lines: list[str],
|
||||
depth: int,
|
||||
) -> None:
|
||||
"""
|
||||
提取 Vuetify 组件 props 中的成对键值指标或说明文本。
|
||||
"""
|
||||
prop_title = str(props.get("title") or props.get("label") or "").strip()
|
||||
prop_value = str(props.get("value") or props.get("subtitle") or "").strip()
|
||||
if (
|
||||
prop_title
|
||||
and prop_value
|
||||
and len(prop_title) <= 24
|
||||
and len(prop_value) <= 32
|
||||
and not prop_title.startswith("mdi-")
|
||||
and not prop_value.startswith("mdi-")
|
||||
and len(metrics) < 8
|
||||
):
|
||||
metrics.append({"id": f"m-{len(metrics)}", "label": prop_title, "value": prop_value})
|
||||
return
|
||||
for field in ("title", "subtitle", "label", "text", "value"):
|
||||
val = props.get(field)
|
||||
if isinstance(val, str):
|
||||
cls._extract_vuetify_snippets(val, metrics, lines, depth + 1)
|
||||
|
||||
@classmethod
|
||||
def _extract_vuetify_children(
|
||||
cls,
|
||||
content: list[Any],
|
||||
metrics: list[dict[str, Any]],
|
||||
lines: list[str],
|
||||
depth: int,
|
||||
) -> None:
|
||||
"""
|
||||
合并子节点提取结果,将紧凑的双行「标签+数值」自动归并为统计指标。
|
||||
"""
|
||||
local_lines: list[str] = []
|
||||
local_metrics: list[dict[str, Any]] = []
|
||||
for child in content:
|
||||
cls._extract_vuetify_snippets(child, local_metrics, local_lines, depth + 1)
|
||||
for item in local_metrics:
|
||||
if len(metrics) < 8:
|
||||
metrics.append(item)
|
||||
if len(local_lines) == 2 and len(local_lines[0]) <= 20 and len(local_lines[1]) <= 28 and len(metrics) < 8:
|
||||
metrics.append({"id": f"m-{len(metrics)}", "label": local_lines[0], "value": local_lines[1]})
|
||||
else:
|
||||
lines.extend(local_lines)
|
||||
|
||||
@@ -434,6 +434,7 @@ SCHEMA_EXPORTS = {
|
||||
'PluginSourceOptions': ('app.schemas.plugin', 'PluginSourceOptions'),
|
||||
'PluginTriggeredEventData': ('app.schemas.event', 'PluginTriggeredEventData'),
|
||||
'PluginUpdateCandidate': ('app.schemas.plugin', 'PluginUpdateCandidate'),
|
||||
'PluginWidgetMetaItem': ('app.schemas.plugin', 'PluginWidgetMetaItem'),
|
||||
'PluginWorkflowActionGroup': ('app.schemas.workflow', 'PluginWorkflowActionGroup'),
|
||||
'PrivateAttr': ('app.schemas.context', 'PrivateAttr'),
|
||||
'ProcessInfo': ('app.schemas.dashboard', 'ProcessInfo'),
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
小组件专用登记与有界只读快照协议;不包含业务命令或主登录凭据。
|
||||
"""
|
||||
|
||||
from typing import Any, Literal
|
||||
from typing import Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.schemas.common import JsonObject
|
||||
|
||||
WidgetContent = Literal[
|
||||
"overview", "downloads", "imports", "subscriptions", "movieSubscriptions", "tvSubscriptions", "musicSubscriptions"
|
||||
]
|
||||
@@ -180,8 +182,8 @@ class PluginWidgetSnapshot(BaseModel):
|
||||
subtitle: str | None = Field(default=None, max_length=240, description="卡片副标题")
|
||||
metrics: list[PluginWidgetMetricItem] = Field(default_factory=list, max_length=8, description="预设模板指标集合,最多八项")
|
||||
items: list[PluginWidgetListItem] = Field(default_factory=list, max_length=6, description="预设模板条目集合,最多六项")
|
||||
layout: dict[str, Any] | None = Field(default=None, description="通用声明式自定义布局根节点,已经过层级与字段清洗")
|
||||
layouts: dict[str, dict[str, Any]] | None = Field(
|
||||
layout: JsonObject | None = Field(default=None, description="通用声明式自定义布局根节点,已经过层级与字段清洗")
|
||||
layouts: dict[str, JsonObject] | None = Field(
|
||||
default=None,
|
||||
description="按 small、medium、large 尺寸分别声明的自定义布局根节点映射",
|
||||
)
|
||||
|
||||
@@ -851,7 +851,7 @@ flowchart LR
|
||||
| 指标 | 当前值 |
|
||||
|---|---:|
|
||||
| Python 模块 | 1200 |
|
||||
| 内部导入边 | 10,687 |
|
||||
| 内部导入边 | 10,692 |
|
||||
| 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) |
|
||||
| Application / Chain 具体 Adapter 直连 | 0 / 0 |
|
||||
| Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) |
|
||||
|
||||
@@ -980,8 +980,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 10687,
|
||||
"edge_sha256": "5395c7542852c2c45dbcd0325f522e49ff7c0c62ca8f9054d53449b743b47ce4",
|
||||
"edge_count": 10692,
|
||||
"edge_sha256": "4ac61cea5b1d5db7de36af43c353141d3669cacff213dd1080067c6891421ea4",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -2461,6 +2461,8 @@
|
||||
"app.api.dependencies.widget -> app.application",
|
||||
"app.api.dependencies.widget -> app.application.configuration",
|
||||
"app.api.dependencies.widget -> app.application.history",
|
||||
"app.api.dependencies.widget -> app.application.plugin",
|
||||
"app.api.dependencies.widget -> app.application.plugin.runtime",
|
||||
"app.api.dependencies.widget -> app.application.query",
|
||||
"app.api.dependencies.widget -> app.application.security",
|
||||
"app.api.dependencies.widget -> app.application.security.widget",
|
||||
@@ -4872,6 +4874,7 @@
|
||||
"app.application.widget -> app.runtime.execution",
|
||||
"app.application.widget -> app.runtime.log",
|
||||
"app.application.widget -> app.schemas",
|
||||
"app.application.widget -> app.schemas.common",
|
||||
"app.application.widget -> app.schemas.dashboard",
|
||||
"app.application.widget -> app.schemas.query",
|
||||
"app.application.widget -> app.schemas.subscribe",
|
||||
@@ -10381,6 +10384,8 @@
|
||||
"app.schemas.transfer -> app.schemas.types",
|
||||
"app.schemas.user -> app.schemas",
|
||||
"app.schemas.user -> app.schemas.common",
|
||||
"app.schemas.widget -> app.schemas",
|
||||
"app.schemas.widget -> app.schemas.common",
|
||||
"app.schemas.workflow -> app.schemas",
|
||||
"app.schemas.workflow -> app.schemas.common",
|
||||
"app.schemas.workflow -> app.schemas.context",
|
||||
|
||||
Reference in New Issue
Block a user