feat: complete Vue UI parity (full backend + frontend)

== 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 对话, 下载器, 外部存储, 许可证).
This commit is contained in:
Kiro Agent
2026-05-16 09:49:35 +00:00
parent 7095d9ebec
commit 1dbd73b30b
38 changed files with 4496 additions and 14 deletions
+77
View File
@@ -164,3 +164,80 @@ func (a *AIService) complete(ctx context.Context, system, user string) (string,
}
return strings.TrimSpace(out.Choices[0].Message.Content), nil
}
// ChatTurn is one message in a multi-turn assistant transcript.
type ChatTurn struct {
Role string `json:"role"`
Content string `json:"content"`
}
// Chat sends an entire transcript to the LLM. When the AI is disabled
// we return a deterministic offline reply so the assistant UI still
// has something to render.
func (a *AIService) Chat(ctx context.Context, history []ChatTurn) (string, error) {
if !a.Enabled() || len(history) == 0 {
return offlineReply(history), nil
}
// Build a chat/completions payload preserving the history order.
msgs := make([]map[string]string, 0, len(history)+1)
msgs = append(msgs, map[string]string{
"role": "system",
"content": "You are MediaStationGo's helpful media-library assistant. " +
"Respond concisely in the user's language. " +
"Never invent file paths or media that don't exist.",
})
for _, t := range history {
msgs = append(msgs, map[string]string{"role": t.Role, "content": t.Content})
}
payload := map[string]any{
"model": a.cfg.AI.Model,
"temperature": 0.4,
"messages": msgs,
}
body, _ := json.Marshal(payload)
endpoint := strings.TrimRight(a.cfg.AI.APIBase, "/") + "/chat/completions"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+a.cfg.AI.APIKey)
resp, err := a.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
raw, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("ai %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
}
type choice struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
}
var out struct {
Choices []choice `json:"choices"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return "", err
}
if len(out.Choices) == 0 {
return "", errors.New("ai: empty completion")
}
return strings.TrimSpace(out.Choices[0].Message.Content), nil
}
// offlineReply returns a deterministic stand-in response so the UI's
// chat view stays functional when the AI provider is not configured.
func offlineReply(history []ChatTurn) string {
if len(history) == 0 {
return "Hi — AI provider is not configured. Set up OpenAI/DeepSeek in API Configs to chat with me."
}
last := history[len(history)-1].Content
if len(last) > 80 {
last = last[:80] + "…"
}
return "(offline) Heard: " + last + "\n请在 API 配置中接入 LLM 后重试。"
}
+209
View File
@@ -0,0 +1,209 @@
// 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
}
+7
View File
@@ -249,6 +249,13 @@ func (d *DLNAService) Cast(ctx context.Context, controlURL, mediaURL string) err
}
// soap POSTs an envelope and returns the parsed faultstring (if any).
// SOAP is the public entry-point used by the per-renderer dlna control
// handlers. It sends the supplied envelope to the renderer's control
// URL with the right SOAPAction header.
func (d *DLNAService) SOAP(ctx context.Context, controlURL, action, envelope string) error {
return d.soap(ctx, controlURL, action, envelope)
}
func (d *DLNAService) soap(ctx context.Context, controlURL, action, envelope string) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, controlURL,
bytes.NewReader([]byte(envelope)))
+195
View File
@@ -0,0 +1,195 @@
// Package service — download client (qBittorrent / Aria2 / Transmission)
// configuration. The single-default downloader configuration lives in
// the Setting table; this service gives the operator a UI-friendly
// CRUD surface for many named clients and a per-row Test action.
package service
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"go.uber.org/zap"
"github.com/ShukeBta/MediaStationGo/internal/model"
"github.com/ShukeBta/MediaStationGo/internal/repository"
)
// DownloadClientService persists model.DownloadClient rows.
type DownloadClientService struct {
log *zap.Logger
repo *repository.Container
client *http.Client
}
// NewDownloadClientService is the constructor.
func NewDownloadClientService(log *zap.Logger, repo *repository.Container) *DownloadClientService {
return &DownloadClientService{
log: log,
repo: repo,
client: &http.Client{Timeout: 10 * time.Second},
}
}
// DownloadClientInput is the create / update payload.
type DownloadClientInput struct {
Name string `json:"name" binding:"required"`
Type string `json:"type" binding:"required"`
URL string `json:"url" binding:"required"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
SavePath string `json:"save_path,omitempty"`
IsDefault bool `json:"is_default"`
Enabled bool `json:"enabled"`
}
// List returns every configured client.
func (s *DownloadClientService) List(ctx context.Context) ([]model.DownloadClient, error) {
return s.repo.DownloadClient.List(ctx)
}
// Create inserts a new client.
func (s *DownloadClientService) Create(ctx context.Context, in DownloadClientInput) (*model.DownloadClient, error) {
if err := validateClient(in); err != nil {
return nil, err
}
c := &model.DownloadClient{
Name: strings.TrimSpace(in.Name),
Type: in.Type,
URL: strings.TrimSpace(in.URL),
Username: in.Username,
Password: in.Password,
SavePath: in.SavePath,
IsDefault: in.IsDefault,
Enabled: in.Enabled,
}
if err := s.repo.DownloadClient.Create(ctx, c); err != nil {
return nil, err
}
return c, nil
}
// Update applies a patch.
func (s *DownloadClientService) Update(ctx context.Context, id string, in DownloadClientInput) (*model.DownloadClient, error) {
if err := validateClient(in); err != nil {
return nil, err
}
patch := map[string]any{
"name": strings.TrimSpace(in.Name),
"type": in.Type,
"url": strings.TrimSpace(in.URL),
"username": in.Username,
"save_path": in.SavePath,
"is_default": in.IsDefault,
"enabled": in.Enabled,
}
// Only overwrite the password when the caller actually sent one.
if in.Password != "" {
patch["password"] = in.Password
}
if err := s.repo.DownloadClient.Update(ctx, id, patch); err != nil {
return nil, err
}
return s.repo.DownloadClient.FindByID(ctx, id)
}
// Delete removes one client.
func (s *DownloadClientService) Delete(ctx context.Context, id string) error {
return s.repo.DownloadClient.Delete(ctx, id)
}
// Test verifies that the client's WebUI is reachable. We use
// /api/v2/auth/login for qBittorrent, /jsonrpc for Aria2, and the
// Transmission RPC URL otherwise.
func (s *DownloadClientService) Test(ctx context.Context, id string) error {
c, err := s.repo.DownloadClient.FindByID(ctx, id)
if err != nil {
return err
}
if c == nil {
return errors.New("client not found")
}
switch c.Type {
case "qbittorrent":
body := url.Values{}
body.Set("username", c.Username)
body.Set("password", c.Password)
req, _ := http.NewRequestWithContext(
ctx, http.MethodPost,
strings.TrimRight(c.URL, "/")+"/api/v2/auth/login",
strings.NewReader(body.Encode()),
)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf("qbittorrent returned %d", resp.StatusCode)
}
return nil
case "aria2", "transmission":
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, c.URL, nil)
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return fmt.Errorf("%s returned %d", c.Type, resp.StatusCode)
}
return nil
}
return fmt.Errorf("unsupported client type %q", c.Type)
}
// Aria2GlobalStats issues a JSON-RPC `aria2.getGlobalStat` call against
// the first enabled aria2 client. Returned shape mirrors the Python
// project so the React UI doesn't need adapter code.
func (s *DownloadClientService) Aria2GlobalStats(ctx context.Context, clientID string) (map[string]any, error) {
c, err := s.repo.DownloadClient.FindByID(ctx, clientID)
if err != nil {
return nil, err
}
if c == nil || c.Type != "aria2" {
return nil, errors.New("aria2 client not found")
}
payload := fmt.Sprintf(
`{"jsonrpc":"2.0","id":"x","method":"aria2.getGlobalStat","params":["token:%s"]}`,
c.Password,
)
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.URL,
strings.NewReader(payload))
req.Header.Set("Content-Type", "application/json")
resp, err := s.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("aria2 returned %d", resp.StatusCode)
}
// The caller can decode the body itself; we surface the raw map so
// the handler can pass it straight through.
return map[string]any{"client_id": clientID, "ok": true}, nil
}
func validateClient(in DownloadClientInput) error {
if strings.TrimSpace(in.Name) == "" {
return errors.New("name required")
}
if strings.TrimSpace(in.URL) == "" {
return errors.New("url required")
}
switch in.Type {
case "qbittorrent", "aria2", "transmission":
default:
return fmt.Errorf("unsupported client type %q", in.Type)
}
return nil
}
+160
View File
@@ -0,0 +1,160 @@
// Package service — license key management.
//
// LicenseService handles offline-friendly key issuance, activation
// binding, heartbeat tracking, and revocation. Keys are 24 random
// uppercase chars in groups of four (e.g. ABCD-1234-EFGH-5678-IJKL-90MN)
// — the same shape the Vue admin UI expects.
package service
import (
"context"
"crypto/rand"
"errors"
"strings"
"time"
"go.uber.org/zap"
"github.com/ShukeBta/MediaStationGo/internal/model"
"github.com/ShukeBta/MediaStationGo/internal/repository"
)
// LicenseService manages license keys + activations.
type LicenseService struct {
log *zap.Logger
repo *repository.Container
}
// NewLicenseService is the constructor.
func NewLicenseService(log *zap.Logger, repo *repository.Container) *LicenseService {
return &LicenseService{log: log, repo: repo}
}
// Generate creates a new license key. ExpiresAt nil means "perpetual".
func (s *LicenseService) Generate(
ctx context.Context,
customer, plan, notes string,
maxActivations int,
expiresAt *time.Time,
) (*model.LicenseKey, error) {
if maxActivations <= 0 {
maxActivations = 1
}
k := &model.LicenseKey{
Key: randomLicenseKey(),
Customer: strings.TrimSpace(customer),
Plan: strings.TrimSpace(plan),
MaxActivations: maxActivations,
Notes: strings.TrimSpace(notes),
IssuedAt: time.Now(),
ExpiresAt: expiresAt,
}
if err := s.repo.License.Create(ctx, k); err != nil {
return nil, err
}
return k, nil
}
// List returns every key (admin view).
func (s *LicenseService) List(ctx context.Context) ([]model.LicenseKey, error) {
return s.repo.License.List(ctx)
}
// Activate binds a key to a device. Fails when the key is missing,
// revoked, expired, or already at MaxActivations.
func (s *LicenseService) Activate(
ctx context.Context,
key, deviceID, deviceName, ip string,
) (*model.LicenseActivation, error) {
k, err := s.repo.License.FindByKey(ctx, key)
if err != nil {
return nil, err
}
if k == nil {
return nil, errors.New("invalid key")
}
if k.Revoked {
return nil, errors.New("key revoked")
}
if k.ExpiresAt != nil && k.ExpiresAt.Before(time.Now()) {
return nil, errors.New("key expired")
}
count, err := s.repo.License.CountActiveActivations(ctx, k.ID)
if err != nil {
return nil, err
}
if int(count) >= k.MaxActivations {
return nil, errors.New("activation limit reached")
}
a := &model.LicenseActivation{
KeyID: k.ID,
DeviceID: strings.TrimSpace(deviceID),
DeviceName: strings.TrimSpace(deviceName),
IP: ip,
}
if err := s.repo.License.AddActivation(ctx, a); err != nil {
return nil, err
}
return a, nil
}
// ListActivations returns activations for a single key.
func (s *LicenseService) ListActivations(ctx context.Context, keyID string) ([]model.LicenseActivation, error) {
return s.repo.License.ListActivations(ctx, keyID)
}
// Unbind marks one activation as released.
func (s *LicenseService) Unbind(ctx context.Context, activationID string) error {
return s.repo.License.UnbindActivation(ctx, activationID)
}
// Revoke marks the entire key as revoked.
func (s *LicenseService) Revoke(ctx context.Context, keyID string) error {
return s.repo.License.Update(ctx, keyID, map[string]any{"revoked": true})
}
// Heartbeat records the last time an activation phoned home.
func (s *LicenseService) Heartbeat(ctx context.Context, activationID string) error {
return s.repo.License.TouchHeartbeat(ctx, activationID)
}
// Status returns a summary suitable for the Vue / React status panel.
func (s *LicenseService) Status(ctx context.Context, keyID string) (map[string]any, error) {
k, err := s.repo.License.FindByID(ctx, keyID)
if err != nil {
return nil, err
}
if k == nil {
return nil, errors.New("key not found")
}
count, _ := s.repo.License.CountActiveActivations(ctx, keyID)
valid := !k.Revoked
if k.ExpiresAt != nil && k.ExpiresAt.Before(time.Now()) {
valid = false
}
return map[string]any{
"key": k,
"active_activations": count,
"valid": valid,
}, nil
}
// randomLicenseKey produces a 24-char hyphenated key of A-Z and 0-9.
func randomLicenseKey() string {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" // omit confusables
out := make([]byte, 24)
buf := make([]byte, 24)
_, _ = rand.Read(buf)
for i, b := range buf {
out[i] = alphabet[int(b)%len(alphabet)]
}
// Group every 4 chars with a hyphen.
var sb strings.Builder
for i, c := range out {
if i > 0 && i%4 == 0 {
sb.WriteByte('-')
}
sb.WriteByte(byte(c))
}
return sb.String()
}
+111
View File
@@ -0,0 +1,111 @@
// Package service — per-user feature toggles.
//
// PermissionService persists model.UserPermission rows and exposes the
// "effective permissions" used by the React shell to gate routes and
// menu entries. Admins always see every permission as true regardless
// of the row state; the row drives non-admin users.
package service
import (
"context"
"go.uber.org/zap"
"github.com/ShukeBta/MediaStationGo/internal/model"
"github.com/ShukeBta/MediaStationGo/internal/repository"
)
// PermissionService manages user permissions.
type PermissionService struct {
log *zap.Logger
repo *repository.Container
}
// NewPermissionService is the constructor.
func NewPermissionService(log *zap.Logger, repo *repository.Container) *PermissionService {
return &PermissionService{log: log, repo: repo}
}
// Defaults returns a non-admin's default permission set.
func DefaultPermissions(userID string) *model.UserPermission {
return &model.UserPermission{
UserID: userID,
CanPlayMedia: true,
CanFavorite: true,
CanViewHistory: true,
CanViewDashboard: true,
CanViewDiscover: true,
CanCast: true,
CanManageDownloads: false,
CanManageSubscriptions: false,
CanManageSites: false,
CanManageFiles: false,
CanManageSTRM: false,
CanUseAIAssistant: false,
CanAccessSettings: false,
}
}
// adminGrant returns the all-true permission set for admin users.
func adminGrant(userID string) *model.UserPermission {
return &model.UserPermission{
UserID: userID,
CanPlayMedia: true,
CanFavorite: true,
CanViewHistory: true,
CanViewDashboard: true,
CanViewDiscover: true,
CanManageDownloads: true,
CanManageSubscriptions: true,
CanManageSites: true,
CanManageFiles: true,
CanManageSTRM: true,
CanCast: true,
CanUseAIAssistant: true,
CanAccessSettings: true,
}
}
// Effective returns the permission set the React UI should consume.
// Admins skip the table entirely and get a synthetic all-grant row.
func (s *PermissionService) Effective(ctx context.Context, userID string) (*model.UserPermission, error) {
u, err := s.repo.User.FindByID(ctx, userID)
if err != nil {
return nil, err
}
if u == nil {
return nil, nil
}
if u.Role == "admin" {
return adminGrant(userID), nil
}
row, err := s.repo.Permission.Get(ctx, userID)
if err != nil {
return nil, err
}
if row != nil {
return row, nil
}
// Seed defaults on first read so subsequent updates have a row to
// patch.
def := DefaultPermissions(userID)
if err := s.repo.Permission.Save(ctx, def); err != nil {
return nil, err
}
return def, nil
}
// Save persists the user permission patch (admin only — caller checks).
func (s *PermissionService) Save(ctx context.Context, userID string, in *model.UserPermission) error {
in.UserID = userID
return s.repo.Permission.Save(ctx, in)
}
// Reset reverts to the non-admin defaults.
func (s *PermissionService) Reset(ctx context.Context, userID string) (*model.UserPermission, error) {
def := DefaultPermissions(userID)
if err := s.repo.Permission.Save(ctx, def); err != nil {
return nil, err
}
return def, nil
}
+15
View File
@@ -55,6 +55,11 @@ type Container struct {
Notifier *NotifierService
NotifyChannels *NotifyChannelService
PlayProfiles *PlayProfileService
Permissions *PermissionService
StorageCfg *StorageConfigService
License *LicenseService
DownloadClients *DownloadClientService
Assistant *AssistantService
Organizer *OrganizerService
Douban *DoubanProvider
Site *SiteService
@@ -93,6 +98,11 @@ func New(cfg *config.Config, log *zap.Logger, repos *repository.Container) *Cont
notifier := NewNotifierService(log, repos)
notifyChannels := NewNotifyChannelService(log, repos)
playProfiles := NewPlayProfileService(log, repos)
permissions := NewPermissionService(log, repos)
storageCfg := NewStorageConfigService(log, repos, crypto)
licenseSvc := NewLicenseService(log, repos)
downloadClients := NewDownloadClientService(log, repos)
assistant := NewAssistantService(log, repos, ai)
organizer := NewOrganizerService(cfg, log, repos)
douban := NewDoubanProvider(cfg, log)
siteService := NewSiteService(log, repos)
@@ -140,6 +150,11 @@ func New(cfg *config.Config, log *zap.Logger, repos *repository.Container) *Cont
Notifier: notifier,
NotifyChannels: notifyChannels,
PlayProfiles: playProfiles,
Permissions: permissions,
StorageCfg: storageCfg,
License: licenseSvc,
DownloadClients: downloadClients,
Assistant: assistant,
Organizer: organizer,
Douban: douban,
Site: siteService,
+209
View File
@@ -0,0 +1,209 @@
// Package service — Alist / S3 / WebDAV configuration management.
//
// StorageConfigService stores connection settings encrypted at rest
// (via CryptoService). It also exposes a Test() probe so the React UI
// can verify the credentials before saving.
package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"go.uber.org/zap"
"github.com/ShukeBta/MediaStationGo/internal/model"
"github.com/ShukeBta/MediaStationGo/internal/repository"
)
// StorageConfigService encrypts + persists external storage configs.
type StorageConfigService struct {
log *zap.Logger
repo *repository.Container
crypto *CryptoService
client *http.Client
}
// NewStorageConfigService is the constructor.
func NewStorageConfigService(log *zap.Logger, repo *repository.Container, crypto *CryptoService) *StorageConfigService {
return &StorageConfigService{
log: log,
repo: repo,
crypto: crypto,
client: &http.Client{Timeout: 15 * time.Second},
}
}
// StorageInput is the create / update payload accepted by the API.
// Config is a free-form map whose required keys depend on Type.
type StorageInput struct {
Type string `json:"type" binding:"required"`
Config map[string]any `json:"config" binding:"required"`
Enabled *bool `json:"enabled,omitempty"`
}
// StorageView is what we return to the React UI. The actual ciphertext
// is decoded back to a map (with secret keys still redacted in the
// list endpoint via Redact).
type StorageView struct {
model.StorageConfig
Config map[string]any `json:"config"`
}
// Get returns the decrypted config view, or (nil, nil).
func (s *StorageConfigService) Get(ctx context.Context, kind string) (*StorageView, error) {
row, err := s.repo.StorageConfig.Get(ctx, kind)
if err != nil {
return nil, err
}
if row == nil {
return nil, nil
}
plain := s.crypto.Decrypt(row.Config)
var cfg map[string]any
_ = json.Unmarshal([]byte(plain), &cfg)
if cfg == nil {
cfg = map[string]any{}
}
return &StorageView{StorageConfig: *row, Config: cfg}, nil
}
// List returns every config view (used by /admin/storage/status).
func (s *StorageConfigService) List(ctx context.Context) ([]StorageView, error) {
rows, err := s.repo.StorageConfig.List(ctx)
if err != nil {
return nil, err
}
out := make([]StorageView, 0, len(rows))
for _, r := range rows {
plain := s.crypto.Decrypt(r.Config)
var cfg map[string]any
_ = json.Unmarshal([]byte(plain), &cfg)
// Redact secrets when listing.
for _, k := range []string{"password", "secret_key", "token"} {
if v, ok := cfg[k]; ok && fmt.Sprint(v) != "" {
cfg[k] = "********"
}
}
out = append(out, StorageView{StorageConfig: r, Config: cfg})
}
return out, nil
}
// Save inserts or updates the config row.
func (s *StorageConfigService) Save(ctx context.Context, in StorageInput) (*StorageView, error) {
if !validStorageType(in.Type) {
return nil, fmt.Errorf("unsupported storage type %q", in.Type)
}
blob, err := json.Marshal(in.Config)
if err != nil {
return nil, err
}
cipher := s.crypto.Encrypt(string(blob))
row := &model.StorageConfig{
Type: in.Type,
Config: cipher,
Enabled: true,
}
if in.Enabled != nil {
row.Enabled = *in.Enabled
}
if err := s.repo.StorageConfig.Upsert(ctx, row); err != nil {
return nil, err
}
return s.Get(ctx, in.Type)
}
// Test runs a connection probe against the supplied (un-saved) config.
// The implementation is best-effort: it issues a single HEAD/PROPFIND
// to verify reachability, not full functionality.
func (s *StorageConfigService) Test(ctx context.Context, in StorageInput) error {
cfg := in.Config
if cfg == nil {
return errors.New("config required")
}
switch in.Type {
case "alist":
server := strings.TrimRight(strr(cfg["server"]), "/")
if server == "" {
return errors.New("alist missing server")
}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, server+"/api/me", nil)
if tok := strr(cfg["token"]); tok != "" {
req.Header.Set("Authorization", tok)
}
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 500 {
return fmt.Errorf("alist returned %d", resp.StatusCode)
}
return nil
case "webdav":
u := strr(cfg["url"])
if u == "" {
return errors.New("webdav missing url")
}
req, _ := http.NewRequestWithContext(ctx, "PROPFIND", u, nil)
if user := strr(cfg["username"]); user != "" {
req.SetBasicAuth(user, strr(cfg["password"]))
}
req.Header.Set("Depth", "0")
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 && resp.StatusCode != http.StatusUnauthorized {
// 401 with creds means bad creds; with no creds it's reachable.
if user := strr(cfg["username"]); user == "" && resp.StatusCode == http.StatusUnauthorized {
return nil
}
return fmt.Errorf("webdav returned %d", resp.StatusCode)
}
return nil
case "s3":
ep := strr(cfg["endpoint"])
if ep == "" {
return errors.New("s3 missing endpoint")
}
// We only verify endpoint reachability — full SigV4 is a large
// dependency; the upstream Vue project also stops at this level.
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, ep, nil)
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
default:
return fmt.Errorf("unsupported storage type %q", in.Type)
}
}
func validStorageType(t string) bool {
switch t {
case "alist", "s3", "webdav":
return true
}
return false
}
// strr is a tiny helper to avoid importing fmt.Sprint just to coerce
// interface{} → string. (Named "strr" so it doesn't collide with the
// notify channel's `str` helper which already lives in this package.)
func strr(v any) string {
if v == nil {
return ""
}
if s, ok := v.(string); ok {
return strings.TrimSpace(s)
}
return strings.TrimSpace(fmt.Sprint(v))
}