mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-28 11:16:37 +08:00
1dbd73b30b
== New domain models (7) ==
- UserPermission: per-user feature toggles (13 booleans)
- StorageConfig: encrypted Alist/S3/WebDAV adapters
- LicenseKey + LicenseActivation: offline license issuance
- DownloadClient: multi-client downloader configs
- AssistantSession + AssistantMessage: multi-turn AI chat persistence
== New services (5) ==
- PermissionService: admin grants always-true; user defaults seeded
- StorageConfigService: AES-GCM encryption + per-type connection probe
- LicenseService: 24-char hyphenated key generation, activation/heartbeat
- DownloadClientService: qB/Aria2/Transmission CRUD + WebUI test
- AssistantService: chat history + execute/undo stubs (op_id tracking)
== Extended AIService.Chat ==
- Multi-turn LLM call with chat history; offline fallback reply
== New endpoints (60+) ==
Auth:
POST /auth/refresh, /auth/logout, /auth/change-password
PATCH /auth/profile
GET /auth/permissions, /auth/me
Permissions admin:
GET/PUT /admin/users/:id/permissions
POST /admin/users/:id/permissions/reset
Search:
GET /search, /search/advanced, /search/tmdb, /search/sites
System:
GET /system/config, /settings/schema, /system/events/ticket
POST /admin/system/scheduler/:name/trigger
Stats:
GET /stats/user/:id, /stats/top-users
POST /stats/play
Sites:
GET /sites/:id/resource, /sites/:id/userdata
Subscriptions:
PUT /subscriptions/:id, POST /subscriptions/:id/search
Playlists:
POST /playlists/:id/reorder
DELETE /playlists/:id/items/by-id/:item_id
DLNA per-renderer:
POST /dlna/:uuid/{play,pause,stop}, GET /dlna/:uuid/status
Media:
POST/DELETE /media/:id/favorite, GET /media/:id/favorite/status
POST /media/:id/ai-scrape, /media/scrape/test, /media/organize
GET /favorites (alias)
Playback:
GET /playback/:id/info, /playback/:id/external-players, /playback/:id/external-url
POST /playback/:id/progress
GET /playback/transcode/:job_id/status
Downloads:
POST /download/:id/{pause,resume,organize}
POST /download/{organize,sync,start-auto-sync}
GET /download/tasks
Admin: full CRUD on /admin/download/clients + /admin/download/aria2/stats
License:
POST /license/{activate,heartbeat}
GET /license/{status,heartbeat-status}
Admin: /admin/license/{generate,list,:id/activations,:id/revoke,activation/:id/unbind}
Storage:
GET /admin/storage/{status,:type}
PUT /admin/storage/:type, POST /admin/storage/:type/test
Assistant (multi-turn AI):
GET/POST /admin/assistant/sessions
GET/DELETE /admin/assistant/session/:id
POST /admin/assistant/{chat,execute}
POST /admin/assistant/undo/:op_id
GET /admin/assistant/history
== New React pages (4) ==
- AssistantChatPage (/assistant): full multi-turn chat UI with sessions
sidebar, optimistic user-turn append, live AI response.
- DownloadClientsPage (/download-clients): typed CRUD form for
qBittorrent / Aria2 / Transmission + per-row Test action.
- LicensePage (/license): generate keys, list activations, revoke,
unbind individual devices.
- StorageConfigPage (/storage-config): tabbed Alist/WebDAV/S3 form
with secret-aware redaction + connection probe.
== New API helpers (5) ==
- assistant, download_clients, license, permissions, storage_config
== Layout ==
- Sidebar gains 4 new admin links (AI 对话, 下载器, 外部存储, 许可证).
210 lines
6.6 KiB
Go
210 lines
6.6 KiB
Go
// Package service — multi-turn AI assistant chat.
|
|
//
|
|
// AssistantService persists chat sessions / messages and forwards user
|
|
// turns to AIService.Chat() for the actual LLM call. When the AI is
|
|
// disabled we still keep the transcript so the UI doesn't lose state;
|
|
// the assistant simply replies with a deterministic offline note.
|
|
//
|
|
// The "operation" / "undo" surface from the upstream Python project is
|
|
// stubbed out: we accept the request, log it, and return a unique op
|
|
// ID so the UI's Undo affordance still renders. Full action execution
|
|
// would need a typed schema and side-effects we don't ship here.
|
|
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/ShukeBta/MediaStationGo/internal/model"
|
|
"github.com/ShukeBta/MediaStationGo/internal/repository"
|
|
)
|
|
|
|
// AssistantService coordinates AssistantSession + AssistantMessage rows
|
|
// against the underlying AIService.
|
|
type AssistantService struct {
|
|
log *zap.Logger
|
|
repo *repository.Container
|
|
ai *AIService
|
|
}
|
|
|
|
// NewAssistantService is the constructor.
|
|
func NewAssistantService(log *zap.Logger, repo *repository.Container, ai *AIService) *AssistantService {
|
|
return &AssistantService{log: log, repo: repo, ai: ai}
|
|
}
|
|
|
|
// SessionView bundles the session header with its messages.
|
|
type SessionView struct {
|
|
Session model.AssistantSession `json:"session"`
|
|
Messages []model.AssistantMessage `json:"messages"`
|
|
}
|
|
|
|
// CreateSession opens a new chat thread.
|
|
func (s *AssistantService) CreateSession(ctx context.Context, userID, title string) (*model.AssistantSession, error) {
|
|
if title == "" {
|
|
title = "New chat"
|
|
}
|
|
sess := &model.AssistantSession{UserID: userID, Title: title}
|
|
if err := s.repo.Assistant.CreateSession(ctx, sess); err != nil {
|
|
return nil, err
|
|
}
|
|
return sess, nil
|
|
}
|
|
|
|
// ListSessions returns sessions for the user (or every session for
|
|
// admins when adminAll == true).
|
|
func (s *AssistantService) ListSessions(ctx context.Context, userID string, adminAll bool) ([]model.AssistantSession, error) {
|
|
if adminAll {
|
|
return s.repo.Assistant.ListSessions(ctx, "")
|
|
}
|
|
return s.repo.Assistant.ListSessions(ctx, userID)
|
|
}
|
|
|
|
// GetSession returns the full transcript for one session, after
|
|
// asserting ownership when the caller is not an admin.
|
|
func (s *AssistantService) GetSession(ctx context.Context, sessionID, userID string, isAdmin bool) (*SessionView, error) {
|
|
sess, err := s.repo.Assistant.FindSession(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if sess == nil {
|
|
return nil, errors.New("session not found")
|
|
}
|
|
if !isAdmin && sess.UserID != userID {
|
|
return nil, errors.New("forbidden")
|
|
}
|
|
msgs, err := s.repo.Assistant.ListMessages(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &SessionView{Session: *sess, Messages: msgs}, nil
|
|
}
|
|
|
|
// DeleteSession drops the session and its transcript.
|
|
func (s *AssistantService) DeleteSession(ctx context.Context, sessionID, userID string, isAdmin bool) error {
|
|
sess, err := s.repo.Assistant.FindSession(ctx, sessionID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if sess == nil {
|
|
return errors.New("session not found")
|
|
}
|
|
if !isAdmin && sess.UserID != userID {
|
|
return errors.New("forbidden")
|
|
}
|
|
return s.repo.Assistant.DeleteSession(ctx, sessionID)
|
|
}
|
|
|
|
// Chat appends a user turn, calls the AI, persists the assistant
|
|
// response, and returns both new messages.
|
|
func (s *AssistantService) Chat(ctx context.Context, sessionID, userID, content string, isAdmin bool) (*SessionView, error) {
|
|
if strings.TrimSpace(content) == "" {
|
|
return nil, errors.New("content required")
|
|
}
|
|
sess, err := s.repo.Assistant.FindSession(ctx, sessionID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if sess == nil {
|
|
return nil, errors.New("session not found")
|
|
}
|
|
if !isAdmin && sess.UserID != userID {
|
|
return nil, errors.New("forbidden")
|
|
}
|
|
|
|
// Append the user turn.
|
|
userMsg := &model.AssistantMessage{
|
|
SessionID: sessionID,
|
|
Role: "user",
|
|
Content: strings.TrimSpace(content),
|
|
}
|
|
if err := s.repo.Assistant.AppendMessage(ctx, userMsg); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Assemble history for the AI call.
|
|
prior, _ := s.repo.Assistant.ListMessages(ctx, sessionID)
|
|
history := make([]ChatTurn, 0, len(prior))
|
|
for _, m := range prior {
|
|
history = append(history, ChatTurn{Role: m.Role, Content: m.Content})
|
|
}
|
|
|
|
// Call the LLM (or fall back to a deterministic offline reply).
|
|
reply, err := s.ai.Chat(ctx, history)
|
|
if err != nil {
|
|
s.log.Warn("assistant chat failed", zap.Error(err))
|
|
reply = "(AI 暂未配置或调用失败,请稍后再试。)"
|
|
}
|
|
asstMsg := &model.AssistantMessage{
|
|
SessionID: sessionID,
|
|
Role: "assistant",
|
|
Content: reply,
|
|
}
|
|
if err := s.repo.Assistant.AppendMessage(ctx, asstMsg); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.GetSession(ctx, sessionID, userID, isAdmin)
|
|
}
|
|
|
|
// Execute is the operation-execute stub. We log the proposed action
|
|
// and return a synthetic OpID so the UI's Undo button has something to
|
|
// reference. Real execution would need a typed action schema we don't
|
|
// ship here.
|
|
func (s *AssistantService) Execute(ctx context.Context, sessionID, userID string, action map[string]any) (string, error) {
|
|
if sessionID == "" {
|
|
return "", errors.New("session_id required")
|
|
}
|
|
opID := uuid.NewString()
|
|
s.log.Info("assistant.execute (stub)",
|
|
zap.String("session_id", sessionID),
|
|
zap.String("user_id", userID),
|
|
zap.String("op_id", opID),
|
|
zap.Any("action", action),
|
|
)
|
|
// Record the action in the transcript so it shows up in History.
|
|
_ = s.repo.Assistant.AppendMessage(ctx, &model.AssistantMessage{
|
|
SessionID: sessionID,
|
|
Role: "system",
|
|
Content: "Action queued (no-op stub)",
|
|
OperationID: opID,
|
|
})
|
|
return opID, nil
|
|
}
|
|
|
|
// Undo is the inverse stub; we just record the request.
|
|
func (s *AssistantService) Undo(ctx context.Context, opID string) error {
|
|
s.log.Info("assistant.undo (stub)", zap.String("op_id", opID))
|
|
return nil
|
|
}
|
|
|
|
// History returns the operations issued by the user, by walking the
|
|
// transcripts and filtering on OperationID. This is bounded to recent
|
|
// rows so the admin History pane stays responsive.
|
|
func (s *AssistantService) History(ctx context.Context, userID string, isAdmin bool) ([]map[string]any, error) {
|
|
sessions, err := s.ListSessions(ctx, userID, isAdmin)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]map[string]any, 0)
|
|
cutoff := time.Now().AddDate(0, 0, -30)
|
|
for _, sess := range sessions {
|
|
msgs, _ := s.repo.Assistant.ListMessages(ctx, sess.ID)
|
|
for _, m := range msgs {
|
|
if m.OperationID == "" || m.CreatedAt.Before(cutoff) {
|
|
continue
|
|
}
|
|
out = append(out, map[string]any{
|
|
"op_id": m.OperationID,
|
|
"session": sess.ID,
|
|
"created_at": m.CreatedAt,
|
|
"content": m.Content,
|
|
})
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|