2026-07-05 10:03:11 +08:00
|
|
|
"""External plugin integration service."""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from typing import Any
|
|
|
|
|
from uuid import uuid4
|
|
|
|
|
|
|
|
|
|
from backend.dto.common import ApiError, ErrorCode
|
2026-07-06 03:55:47 +08:00
|
|
|
from backend.services.integration_token_service import IntegrationTokenService
|
2026-07-05 10:03:11 +08:00
|
|
|
from backend.services.wardrobe_service import WardrobeService
|
|
|
|
|
from core.identity import RequestContext
|
2026-07-06 03:55:47 +08:00
|
|
|
from core.secret_service import redact
|
2026-07-05 10:03:11 +08:00
|
|
|
from database.repositories.integration_repository import IntegrationRepository
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
PRIVATE_COMPANION = "astrbot_plugin_private_companion"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class IntegrationService:
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
wardrobe_service: WardrobeService,
|
|
|
|
|
integration_repository: IntegrationRepository,
|
2026-07-06 03:55:47 +08:00
|
|
|
token_service: IntegrationTokenService | None = None,
|
2026-07-05 10:03:11 +08:00
|
|
|
):
|
|
|
|
|
self.wardrobe_service = wardrobe_service
|
|
|
|
|
self.integration_repository = integration_repository
|
2026-07-06 03:55:47 +08:00
|
|
|
self.token_service = token_service
|
2026-07-05 10:03:11 +08:00
|
|
|
|
|
|
|
|
def daily_outfit(self, payload: dict[str, Any], ctx: RequestContext) -> dict[str, Any]:
|
|
|
|
|
source = str(payload.get("request_source") or PRIVATE_COMPANION)
|
|
|
|
|
if source != PRIVATE_COMPANION:
|
2026-07-05 15:28:28 +08:00
|
|
|
error = ApiError(
|
2026-07-05 10:03:11 +08:00
|
|
|
ErrorCode.INTEGRATION_TOKEN_INVALID,
|
|
|
|
|
"unsupported integration source",
|
|
|
|
|
{"request_source": source},
|
|
|
|
|
)
|
2026-07-05 15:28:28 +08:00
|
|
|
self._record_failure(source, payload, error)
|
|
|
|
|
raise error
|
2026-07-06 03:55:47 +08:00
|
|
|
if self.token_service:
|
|
|
|
|
try:
|
|
|
|
|
self.token_service.verify(source, _request_token(payload))
|
|
|
|
|
except ApiError as exc:
|
|
|
|
|
self._record_failure(source, payload, exc)
|
|
|
|
|
raise
|
2026-07-05 10:03:11 +08:00
|
|
|
profile_id = str(payload.get("profile_id") or "").strip()
|
|
|
|
|
if not profile_id:
|
2026-07-05 15:28:28 +08:00
|
|
|
error = ApiError(ErrorCode.VALIDATION_FAILED, "profile_id is required", {"field": "profile_id"})
|
|
|
|
|
self._record_failure(source, payload, error)
|
|
|
|
|
raise error
|
2026-07-05 10:03:11 +08:00
|
|
|
categories = payload.get("categories") or _categories_from_keywords(payload.get("keywords") or [])
|
2026-07-05 15:28:28 +08:00
|
|
|
try:
|
2026-07-06 03:48:39 +08:00
|
|
|
match = self.wardrobe_service.match(profile_id, _wardrobe_match_payload(payload, categories), ctx)
|
2026-07-05 15:28:28 +08:00
|
|
|
except Exception as exc:
|
|
|
|
|
self._record_failure(source, payload, exc)
|
|
|
|
|
raise
|
2026-07-06 03:48:39 +08:00
|
|
|
fallback_prompt = match.get("fallback_prompt") or _fallback_prompt(payload)
|
|
|
|
|
final_prompt = _final_prompt(match, fallback_prompt)
|
2026-07-05 10:03:11 +08:00
|
|
|
response = {
|
|
|
|
|
"matched": bool(match["selected_materials"]),
|
|
|
|
|
"selected_materials": match["selected_materials"],
|
|
|
|
|
"final_prompt": final_prompt,
|
|
|
|
|
"job_id": None,
|
|
|
|
|
"fallback_used": not bool(match["selected_materials"]),
|
2026-07-06 03:48:39 +08:00
|
|
|
"fallback_supplement_used": bool(match.get("fallback_supplement_used")),
|
|
|
|
|
"fallback_reason": match.get("fallback_reason"),
|
|
|
|
|
"fallback_prompt": fallback_prompt if match.get("fallback_reason") else None,
|
|
|
|
|
"fallback_strategy": match.get("fallback_strategy"),
|
|
|
|
|
"match_details": match.get("match_details"),
|
2026-07-05 10:03:11 +08:00
|
|
|
}
|
|
|
|
|
self.integration_repository.record(
|
|
|
|
|
{
|
|
|
|
|
"integration_log_id": new_integration_log_id(),
|
|
|
|
|
"integration_name": source,
|
|
|
|
|
"action": "daily_outfit",
|
|
|
|
|
"status": "succeeded",
|
2026-07-06 03:55:47 +08:00
|
|
|
"request": _redact_request(payload),
|
2026-07-05 10:03:11 +08:00
|
|
|
"response": response,
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
return response
|
|
|
|
|
|
2026-07-05 15:28:28 +08:00
|
|
|
def list_integration_logs(
|
|
|
|
|
self,
|
|
|
|
|
integration_name: str | None = None,
|
|
|
|
|
*,
|
|
|
|
|
action: str | None = None,
|
|
|
|
|
status: str | None = None,
|
|
|
|
|
) -> list[dict[str, Any]]:
|
|
|
|
|
return self.integration_repository.list(
|
|
|
|
|
integration_name=integration_name,
|
|
|
|
|
action=action,
|
|
|
|
|
status=status,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def _record_failure(self, source: str, payload: dict[str, Any], exc: Exception) -> None:
|
|
|
|
|
self.integration_repository.record(
|
|
|
|
|
{
|
|
|
|
|
"integration_log_id": new_integration_log_id(),
|
|
|
|
|
"integration_name": source,
|
|
|
|
|
"action": "daily_outfit",
|
|
|
|
|
"status": "failed",
|
2026-07-06 03:55:47 +08:00
|
|
|
"request": _redact_request(payload),
|
2026-07-05 15:28:28 +08:00
|
|
|
"response": {"error_code": _error_code(exc)},
|
|
|
|
|
"error_message": str(getattr(exc, "message", None) or exc),
|
|
|
|
|
}
|
|
|
|
|
)
|
2026-07-05 10:03:11 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def new_integration_log_id() -> str:
|
|
|
|
|
return f"intlog_{uuid4().hex}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _categories_from_keywords(keywords: list[Any]) -> list[str]:
|
|
|
|
|
lowered = {str(keyword).lower() for keyword in keywords}
|
|
|
|
|
categories = []
|
|
|
|
|
for category in ("top", "bottom", "dress", "shoes", "accessory"):
|
|
|
|
|
if category in lowered:
|
|
|
|
|
categories.append(category)
|
|
|
|
|
return categories or ["top", "bottom", "dress", "shoes", "accessory"]
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 03:48:39 +08:00
|
|
|
def _wardrobe_match_payload(payload: dict[str, Any], categories: list[str]) -> dict[str, Any]:
|
|
|
|
|
match_payload = {"categories": categories}
|
|
|
|
|
for key in ("keywords", "tags", "mood", "weather", "season", "style"):
|
|
|
|
|
if key in payload:
|
|
|
|
|
match_payload[key] = payload[key]
|
|
|
|
|
return match_payload
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 03:55:47 +08:00
|
|
|
def _request_token(payload: dict[str, Any]) -> str | None:
|
|
|
|
|
return str(payload.get("integration_token") or payload.get("token") or "").strip() or None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _redact_request(payload: dict[str, Any]) -> dict[str, Any]:
|
|
|
|
|
return redact(payload)
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 10:03:11 +08:00
|
|
|
def _fallback_prompt(payload: dict[str, Any]) -> str:
|
|
|
|
|
parts = ["daily outfit"]
|
|
|
|
|
for key in ("mood", "weather"):
|
|
|
|
|
value = payload.get(key)
|
|
|
|
|
if value:
|
|
|
|
|
parts.append(str(value))
|
|
|
|
|
keywords = payload.get("keywords") or []
|
|
|
|
|
parts.extend(str(keyword) for keyword in keywords)
|
|
|
|
|
return ", ".join(parts)
|
2026-07-05 15:28:28 +08:00
|
|
|
|
|
|
|
|
|
2026-07-06 03:48:39 +08:00
|
|
|
def _final_prompt(match: dict[str, Any], fallback_prompt: str) -> str:
|
|
|
|
|
outfit_prompt = str(match.get("outfit_prompt") or "").strip()
|
|
|
|
|
if match.get("fallback_supplement_used") and outfit_prompt and fallback_prompt:
|
|
|
|
|
return f"{outfit_prompt}, {fallback_prompt}"
|
|
|
|
|
return outfit_prompt or fallback_prompt
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 15:28:28 +08:00
|
|
|
def _error_code(exc: Exception) -> str:
|
|
|
|
|
code = getattr(exc, "error_code", None)
|
|
|
|
|
value = getattr(code, "value", None)
|
|
|
|
|
return str(value or code or exc.__class__.__name__)
|