mirror of
https://github.com/truewhile/MeBox.git
synced 2026-10-05 04:56:37 +08:00
Resolve merge conflicts: merge all Go backend and React frontend changes
This commit is contained in:
@@ -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 后重试。"
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -46,6 +46,13 @@ func (d *DiscoverService) Popular(ctx context.Context) ([]Match, error) {
|
||||
// fetch is the shared helper that paginates page=1 only — that's all the
|
||||
// home page needs and it keeps us under TMDb's 50 rps limit.
|
||||
func (d *DiscoverService) fetch(ctx context.Context, path string) ([]Match, error) {
|
||||
return d.Fetch(ctx, path)
|
||||
}
|
||||
|
||||
// Fetch is the public entry point used by the multi-section handler.
|
||||
// It paginates page=1 only — that's all the home page needs and it
|
||||
// keeps us under TMDb's 50 rps limit.
|
||||
func (d *DiscoverService) Fetch(ctx context.Context, path string) ([]Match, error) {
|
||||
if d.tmdb == nil || !d.tmdb.Enabled() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -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)))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
// Package service — notification channel CRUD + multi-channel dispatch.
|
||||
//
|
||||
// The original NotifierService reads a single set of keys from the
|
||||
// settings table. NotifyChannelService persists *named* channels in
|
||||
// their own table so the operator can add multiple Telegram bots, Bark
|
||||
// servers, etc. and pick which events flow to which channel.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/model"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/repository"
|
||||
)
|
||||
|
||||
// NotifyChannelService manages notify channels and dispatches messages.
|
||||
type NotifyChannelService struct {
|
||||
log *zap.Logger
|
||||
repo *repository.Container
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewNotifyChannelService is the constructor.
|
||||
func NewNotifyChannelService(log *zap.Logger, repo *repository.Container) *NotifyChannelService {
|
||||
return &NotifyChannelService{
|
||||
log: log,
|
||||
repo: repo,
|
||||
client: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// ChannelInput is the shape accepted by Create / Update. Config is a
|
||||
// generic map; it gets serialised to JSON before being persisted.
|
||||
type ChannelInput struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
ChannelType string `json:"channel_type" binding:"required"`
|
||||
Config map[string]any `json:"config"`
|
||||
Events []string `json:"events"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
}
|
||||
|
||||
// channelView is the public shape — Config is decoded back to a map so
|
||||
// the React form can edit it directly without unwrapping JSON twice.
|
||||
type channelView struct {
|
||||
model.NotifyChannel
|
||||
Config map[string]any `json:"config"`
|
||||
Events []string `json:"events"`
|
||||
}
|
||||
|
||||
// toView decodes Config + Events from their persisted JSON strings.
|
||||
func toView(n model.NotifyChannel) channelView {
|
||||
v := channelView{NotifyChannel: n}
|
||||
if n.Config != "" {
|
||||
_ = json.Unmarshal([]byte(n.Config), &v.Config)
|
||||
}
|
||||
if v.Config == nil {
|
||||
v.Config = map[string]any{}
|
||||
}
|
||||
if n.Events != "" {
|
||||
_ = json.Unmarshal([]byte(n.Events), &v.Events)
|
||||
}
|
||||
if v.Events == nil {
|
||||
v.Events = []string{}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// List returns every channel as a decoded view.
|
||||
func (s *NotifyChannelService) List(ctx context.Context) ([]channelView, error) {
|
||||
rows, err := s.repo.NotifyChannel.List(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]channelView, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, toView(r))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Create persists a new channel.
|
||||
func (s *NotifyChannelService) Create(ctx context.Context, in ChannelInput) (*channelView, error) {
|
||||
if err := validateChannel(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfgBlob, _ := json.Marshal(in.Config)
|
||||
evBlob, _ := json.Marshal(in.Events)
|
||||
n := &model.NotifyChannel{
|
||||
Name: strings.TrimSpace(in.Name),
|
||||
ChannelType: in.ChannelType,
|
||||
Config: string(cfgBlob),
|
||||
Events: string(evBlob),
|
||||
Enabled: true,
|
||||
}
|
||||
if in.Enabled != nil {
|
||||
n.Enabled = *in.Enabled
|
||||
}
|
||||
if err := s.repo.NotifyChannel.Create(ctx, n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := toView(*n)
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// Update applies a partial patch to an existing channel.
|
||||
func (s *NotifyChannelService) Update(ctx context.Context, id string, in ChannelInput) (*channelView, error) {
|
||||
if err := validateChannel(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfgBlob, _ := json.Marshal(in.Config)
|
||||
evBlob, _ := json.Marshal(in.Events)
|
||||
patch := map[string]any{
|
||||
"name": strings.TrimSpace(in.Name),
|
||||
"channel_type": in.ChannelType,
|
||||
"config": string(cfgBlob),
|
||||
"events": string(evBlob),
|
||||
}
|
||||
if in.Enabled != nil {
|
||||
patch["enabled"] = *in.Enabled
|
||||
}
|
||||
if err := s.repo.NotifyChannel.Update(ctx, id, patch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row, err := s.repo.NotifyChannel.FindByID(ctx, id)
|
||||
if err != nil || row == nil {
|
||||
return nil, err
|
||||
}
|
||||
v := toView(*row)
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// Delete removes the channel.
|
||||
func (s *NotifyChannelService) Delete(ctx context.Context, id string) error {
|
||||
return s.repo.NotifyChannel.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// Test sends a "测试通知" through a single channel.
|
||||
func (s *NotifyChannelService) Test(ctx context.Context, id string) error {
|
||||
row, err := s.repo.NotifyChannel.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if row == nil {
|
||||
return errors.New("channel not found")
|
||||
}
|
||||
return s.dispatchOne(ctx, *row, "MediaStationGo 测试通知", "如果你看到这条消息,说明该通道工作正常。")
|
||||
}
|
||||
|
||||
// Broadcast sends a message to every enabled channel that subscribes to
|
||||
// `event` (an empty Events slice means "all events"). Failures are
|
||||
// logged and never abort the loop.
|
||||
func (s *NotifyChannelService) Broadcast(ctx context.Context, title, body, event string) {
|
||||
rows, err := s.repo.NotifyChannel.ListEnabled(ctx)
|
||||
if err != nil {
|
||||
s.log.Warn("notify list failed", zap.Error(err))
|
||||
return
|
||||
}
|
||||
for _, r := range rows {
|
||||
if !channelSubscribes(r, event) {
|
||||
continue
|
||||
}
|
||||
if err := s.dispatchOne(ctx, r, title, body); err != nil {
|
||||
s.log.Warn("notify dispatch failed", zap.String("channel", r.Name), zap.Error(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// channelSubscribes returns true when the channel's Events list is
|
||||
// empty (= all events) or contains `event`.
|
||||
func channelSubscribes(n model.NotifyChannel, event string) bool {
|
||||
if event == "" || n.Events == "" || n.Events == "[]" {
|
||||
return true
|
||||
}
|
||||
var ev []string
|
||||
if err := json.Unmarshal([]byte(n.Events), &ev); err != nil {
|
||||
return true
|
||||
}
|
||||
if len(ev) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, e := range ev {
|
||||
if e == event {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// dispatchOne is the inner dispatcher; the channel type drives which
|
||||
// HTTP request gets built.
|
||||
func (s *NotifyChannelService) dispatchOne(ctx context.Context, n model.NotifyChannel, title, body string) error {
|
||||
cfg := map[string]any{}
|
||||
_ = json.Unmarshal([]byte(n.Config), &cfg)
|
||||
|
||||
switch n.ChannelType {
|
||||
case "telegram":
|
||||
token := str(cfg["bot_token"])
|
||||
chat := str(cfg["chat_id"])
|
||||
if token == "" || chat == "" {
|
||||
return errors.New("telegram missing bot_token / chat_id")
|
||||
}
|
||||
text := fmt.Sprintf("<b>%s</b>\n\n%s", escapeHTML(title), escapeHTML(body))
|
||||
u := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token)
|
||||
form := url.Values{}
|
||||
form.Set("chat_id", chat)
|
||||
form.Set("text", text)
|
||||
form.Set("parse_mode", "HTML")
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
return s.do(req)
|
||||
|
||||
case "bark":
|
||||
key := str(cfg["device_key"])
|
||||
if key == "" {
|
||||
return errors.New("bark missing device_key")
|
||||
}
|
||||
server := str(cfg["server"])
|
||||
if server == "" {
|
||||
server = "https://api.day.app"
|
||||
}
|
||||
u := fmt.Sprintf("%s/%s/%s/%s",
|
||||
strings.TrimRight(server, "/"),
|
||||
url.PathEscape(key),
|
||||
url.PathEscape(title),
|
||||
url.PathEscape(body),
|
||||
)
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
return s.do(req)
|
||||
|
||||
case "wechat":
|
||||
key := str(cfg["sendkey"])
|
||||
if key == "" {
|
||||
return errors.New("wechat missing sendkey")
|
||||
}
|
||||
u := fmt.Sprintf("https://sctapi.ftqq.com/%s.send", url.PathEscape(key))
|
||||
form := url.Values{}
|
||||
form.Set("title", title)
|
||||
form.Set("desp", body)
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, u, strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
return s.do(req)
|
||||
|
||||
case "webhook":
|
||||
urlS := str(cfg["url"])
|
||||
if urlS == "" {
|
||||
return errors.New("webhook missing url")
|
||||
}
|
||||
method := strings.ToUpper(str(cfg["method"]))
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
// Substitute {{title}} / {{message}} in the body template.
|
||||
bodyTpl := str(cfg["body_template"])
|
||||
if bodyTpl == "" {
|
||||
bodyTpl = `{"title":"{{title}}","message":"{{message}}"}`
|
||||
}
|
||||
bodyStr := strings.NewReplacer("{{title}}", title, "{{message}}", body).Replace(bodyTpl)
|
||||
req, _ := http.NewRequestWithContext(ctx, method, urlS, strings.NewReader(bodyStr))
|
||||
// Apply custom headers (encoded as JSON in the config).
|
||||
if hdrRaw := str(cfg["headers"]); hdrRaw != "" {
|
||||
var hdr map[string]string
|
||||
if err := json.Unmarshal([]byte(hdrRaw), &hdr); err == nil {
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
if req.Header.Get("Content-Type") == "" && method != http.MethodGet {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
return s.do(req)
|
||||
}
|
||||
return fmt.Errorf("unknown channel type %q", n.ChannelType)
|
||||
}
|
||||
|
||||
func (s *NotifyChannelService) do(req *http.Request) error {
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("upstream returned %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateChannel rejects obviously-malformed inputs early so the API
|
||||
// returns a useful 400 rather than a database constraint error.
|
||||
func validateChannel(in ChannelInput) error {
|
||||
if strings.TrimSpace(in.Name) == "" {
|
||||
return errors.New("name required")
|
||||
}
|
||||
switch in.ChannelType {
|
||||
case "telegram", "wechat", "bark", "webhook":
|
||||
default:
|
||||
return fmt.Errorf("unsupported channel type %q", in.ChannelType)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// str safely extracts a string from an interface{} loaded from JSON.
|
||||
func str(v any) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
if s, ok := v.(string); ok {
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
return strings.TrimSpace(fmt.Sprint(v))
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// Package service — multi-persona play profiles.
|
||||
//
|
||||
// PlayProfileService persists per-user "viewing personas" so the same
|
||||
// account can switch between, e.g., a child-safe profile and an adult
|
||||
// one without changing credentials. Profiles drive content rating
|
||||
// gates, library access, and player defaults; the upstream Vue project
|
||||
// shipped the form but never wired the backend, so we implement the
|
||||
// data model here.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/model"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/repository"
|
||||
)
|
||||
|
||||
// PlayProfileService manages PlayProfile rows.
|
||||
type PlayProfileService struct {
|
||||
log *zap.Logger
|
||||
repo *repository.Container
|
||||
}
|
||||
|
||||
// NewPlayProfileService is the constructor.
|
||||
func NewPlayProfileService(log *zap.Logger, repo *repository.Container) *PlayProfileService {
|
||||
return &PlayProfileService{log: log, repo: repo}
|
||||
}
|
||||
|
||||
// PlayProfileInput is the create/update payload accepted by the API.
|
||||
// PIN is hashed only when non-empty so omitting it preserves the
|
||||
// existing PIN on update.
|
||||
type PlayProfileInput struct {
|
||||
UserID string `json:"user_id"`
|
||||
Name string `json:"name"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
ContentRatingLimit string `json:"content_rating_limit"`
|
||||
AllowAdult bool `json:"allow_adult"`
|
||||
RequirePIN bool `json:"require_pin"`
|
||||
PIN string `json:"pin,omitempty"`
|
||||
PreferredSubtitleLang string `json:"preferred_subtitle_lang"`
|
||||
PreferredAudioLang string `json:"preferred_audio_lang"`
|
||||
AutoplayNext bool `json:"autoplay_next"`
|
||||
SkipIntro bool `json:"skip_intro"`
|
||||
AllowedLibraryIDs []string `json:"allowed_library_ids"`
|
||||
}
|
||||
|
||||
// ProfileView is the public shape — AllowedLibraryIDs is decoded back
|
||||
// to a slice so the React form can bind to it directly.
|
||||
type ProfileView struct {
|
||||
model.PlayProfile
|
||||
AllowedLibraryIDs []string `json:"allowed_library_ids"`
|
||||
}
|
||||
|
||||
func toProfileView(p model.PlayProfile) ProfileView {
|
||||
v := ProfileView{PlayProfile: p}
|
||||
if p.AllowedLibraryIDs != "" {
|
||||
_ = json.Unmarshal([]byte(p.AllowedLibraryIDs), &v.AllowedLibraryIDs)
|
||||
}
|
||||
if v.AllowedLibraryIDs == nil {
|
||||
v.AllowedLibraryIDs = []string{}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// List returns every profile (admin view).
|
||||
func (s *PlayProfileService) List(ctx context.Context) ([]ProfileView, error) {
|
||||
rows, err := s.repo.PlayProfile.List(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ProfileView, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, toProfileView(r))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListByUser returns the profiles owned by the user.
|
||||
func (s *PlayProfileService) ListByUser(ctx context.Context, userID string) ([]ProfileView, error) {
|
||||
rows, err := s.repo.PlayProfile.ListByUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]ProfileView, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, toProfileView(r))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Create inserts a new play profile. When IsDefault is true we clear
|
||||
// every other default for the user inside the same transaction.
|
||||
func (s *PlayProfileService) Create(ctx context.Context, in PlayProfileInput) (*ProfileView, error) {
|
||||
if err := validateProfileInput(in, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
libsBlob, _ := json.Marshal(in.AllowedLibraryIDs)
|
||||
p := &model.PlayProfile{
|
||||
UserID: in.UserID,
|
||||
Name: strings.TrimSpace(in.Name),
|
||||
IsDefault: in.IsDefault,
|
||||
ContentRatingLimit: in.ContentRatingLimit,
|
||||
AllowAdult: in.AllowAdult,
|
||||
RequirePIN: in.RequirePIN,
|
||||
PreferredSubtitleLang: in.PreferredSubtitleLang,
|
||||
PreferredAudioLang: in.PreferredAudioLang,
|
||||
AutoplayNext: in.AutoplayNext,
|
||||
SkipIntro: in.SkipIntro,
|
||||
AllowedLibraryIDs: string(libsBlob),
|
||||
}
|
||||
if in.RequirePIN && in.PIN != "" {
|
||||
p.PINHash = hashPIN(in.PIN)
|
||||
}
|
||||
if in.IsDefault {
|
||||
if err := s.repo.PlayProfile.ClearDefaultsFor(ctx, in.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := s.repo.PlayProfile.Create(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := toProfileView(*p)
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// Update applies a patch to an existing profile.
|
||||
func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfileInput) (*ProfileView, error) {
|
||||
row, err := s.repo.PlayProfile.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if row == nil {
|
||||
return nil, errors.New("profile not found")
|
||||
}
|
||||
if err := validateProfileInput(in, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
libsBlob, _ := json.Marshal(in.AllowedLibraryIDs)
|
||||
patch := map[string]any{
|
||||
"name": strings.TrimSpace(in.Name),
|
||||
"is_default": in.IsDefault,
|
||||
"content_rating_limit": in.ContentRatingLimit,
|
||||
"allow_adult": in.AllowAdult,
|
||||
"require_pin": in.RequirePIN,
|
||||
"preferred_subtitle_lang": in.PreferredSubtitleLang,
|
||||
"preferred_audio_lang": in.PreferredAudioLang,
|
||||
"autoplay_next": in.AutoplayNext,
|
||||
"skip_intro": in.SkipIntro,
|
||||
"allowed_library_ids": string(libsBlob),
|
||||
}
|
||||
if in.RequirePIN && in.PIN != "" {
|
||||
patch["pin_hash"] = hashPIN(in.PIN)
|
||||
}
|
||||
if !in.RequirePIN {
|
||||
patch["pin_hash"] = ""
|
||||
}
|
||||
if in.IsDefault {
|
||||
if err := s.repo.PlayProfile.ClearDefaultsFor(ctx, row.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := s.repo.PlayProfile.Update(ctx, id, patch); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
row, err = s.repo.PlayProfile.FindByID(ctx, id)
|
||||
if err != nil || row == nil {
|
||||
return nil, err
|
||||
}
|
||||
v := toProfileView(*row)
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// Delete removes a profile.
|
||||
func (s *PlayProfileService) Delete(ctx context.Context, id string) error {
|
||||
return s.repo.PlayProfile.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// TouchActive bumps the LastActiveAt timestamp; called by the player
|
||||
// when a profile is selected.
|
||||
func (s *PlayProfileService) TouchActive(ctx context.Context, id string) error {
|
||||
now := time.Now()
|
||||
return s.repo.PlayProfile.Update(ctx, id, map[string]any{
|
||||
"last_active_at": &now,
|
||||
})
|
||||
}
|
||||
|
||||
// validateProfileInput rejects malformed payloads. On create we require
|
||||
// user_id; on update we allow it to be empty (caller supplies it via URL).
|
||||
func validateProfileInput(in PlayProfileInput, requireUser bool) error {
|
||||
if strings.TrimSpace(in.Name) == "" {
|
||||
return errors.New("name required")
|
||||
}
|
||||
if requireUser && strings.TrimSpace(in.UserID) == "" {
|
||||
return errors.New("user_id required")
|
||||
}
|
||||
if in.RequirePIN && in.PIN != "" {
|
||||
if len(in.PIN) < 4 || len(in.PIN) > 8 {
|
||||
return errors.New("pin must be 4-8 characters")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hashPIN is a deterministic SHA-256 (PINs are short numeric secrets;
|
||||
// bcrypt is overkill for this use case).
|
||||
func hashPIN(pin string) string {
|
||||
sum := sha256.Sum256([]byte(pin))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -53,9 +53,15 @@ type Container struct {
|
||||
Emby *EmbyService
|
||||
Backup *BackupService
|
||||
Notifier *NotifierService
|
||||
NotifyChannels *NotifyChannelService
|
||||
PlayProfiles *PlayProfileService
|
||||
Permissions *PermissionService
|
||||
StorageCfg *StorageConfigService
|
||||
License *LicenseService
|
||||
DownloadClients *DownloadClientService
|
||||
Assistant *AssistantService
|
||||
Organizer *OrganizerService
|
||||
Douban *DoubanProvider
|
||||
Permission *PermissionService
|
||||
Token *TokenService
|
||||
ApiConfig *ApiConfigService
|
||||
DownloadMgr *DownloadManager
|
||||
@@ -98,8 +104,16 @@ func New(cfg *config.Config, log *zap.Logger, repos *repository.Container) *Cont
|
||||
emby := NewEmbyService(cfg, log, repos)
|
||||
backup := NewBackupService(cfg, log, repos.DB)
|
||||
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)
|
||||
scheduler := NewSchedulerService(log, repos, scanner, transcoder, hub, cfg.Cache.CacheDir)
|
||||
|
||||
// 初始化认证相关服务
|
||||
@@ -151,9 +165,15 @@ func New(cfg *config.Config, log *zap.Logger, repos *repository.Container) *Cont
|
||||
Emby: emby,
|
||||
Backup: backup,
|
||||
Notifier: notifier,
|
||||
NotifyChannels: notifyChannels,
|
||||
PlayProfiles: playProfiles,
|
||||
Permissions: permissions,
|
||||
StorageCfg: storageCfg,
|
||||
License: licenseSvc,
|
||||
DownloadClients: downloadClients,
|
||||
Assistant: assistant,
|
||||
Organizer: organizer,
|
||||
Douban: douban,
|
||||
Permission: permissionSvc,
|
||||
Token: tokenSvc,
|
||||
ApiConfig: apiConfigSvc,
|
||||
DownloadMgr: downloadMgr,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
// Package service — site management (PT/BT tracker CRUD + connection test).
|
||||
//
|
||||
// SiteService owns the lifecycle of Site rows and exposes a cross-site
|
||||
// search dispatcher that fans out a keyword query to every enabled site's
|
||||
// adapter, collects results and returns them merged + sorted.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/ShukeBta/MediaStationGo/internal/model"
|
||||
"github.com/ShukeBta/MediaStationGo/internal/repository"
|
||||
)
|
||||
|
||||
// SiteService manages PT/BT site configurations.
|
||||
type SiteService struct {
|
||||
log *zap.Logger
|
||||
repo *repository.Container
|
||||
}
|
||||
|
||||
// NewSiteService is the constructor.
|
||||
func NewSiteService(log *zap.Logger, repo *repository.Container) *SiteService {
|
||||
return &SiteService{log: log, repo: repo}
|
||||
}
|
||||
|
||||
// Create persists a new site.
|
||||
func (s *SiteService) Create(ctx context.Context, site *model.Site) error {
|
||||
if strings.TrimSpace(site.Name) == "" || strings.TrimSpace(site.BaseURL) == "" {
|
||||
return errors.New("name and base_url required")
|
||||
}
|
||||
site.BaseURL = strings.TrimRight(site.BaseURL, "/")
|
||||
if site.SiteType == "" {
|
||||
site.SiteType = "nexusphp"
|
||||
}
|
||||
if site.AuthType == "" {
|
||||
site.AuthType = "cookie"
|
||||
}
|
||||
if site.Timeout <= 0 {
|
||||
site.Timeout = 15
|
||||
}
|
||||
return s.repo.DB.WithContext(ctx).Create(site).Error
|
||||
}
|
||||
|
||||
// List returns every site ordered by priority (lower = higher priority).
|
||||
func (s *SiteService) List(ctx context.Context) ([]model.Site, error) {
|
||||
var sites []model.Site
|
||||
err := s.repo.DB.WithContext(ctx).Order("priority asc, created_at asc").Find(&sites).Error
|
||||
return sites, err
|
||||
}
|
||||
|
||||
// FindByID returns a single site or nil.
|
||||
func (s *SiteService) FindByID(ctx context.Context, id string) (*model.Site, error) {
|
||||
var site model.Site
|
||||
err := s.repo.DB.WithContext(ctx).Where("id = ?", id).First(&site).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return &site, err
|
||||
}
|
||||
|
||||
// Update applies a partial patch to an existing site.
|
||||
func (s *SiteService) Update(ctx context.Context, id string, updates map[string]any) error {
|
||||
return s.repo.DB.WithContext(ctx).Model(&model.Site{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
|
||||
// Delete removes a site.
|
||||
func (s *SiteService) Delete(ctx context.Context, id string) error {
|
||||
return s.repo.DB.WithContext(ctx).Where("id = ?", id).Delete(&model.Site{}).Error
|
||||
}
|
||||
|
||||
// TestConnection tries to reach the site's base URL with the configured
|
||||
// credentials and reports success/failure.
|
||||
func (s *SiteService) TestConnection(ctx context.Context, id string) (bool, string, error) {
|
||||
site, err := s.FindByID(ctx, id)
|
||||
if err != nil || site == nil {
|
||||
return false, "site not found", err
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: time.Duration(site.Timeout) * time.Second}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, site.BaseURL, nil)
|
||||
if err != nil {
|
||||
return false, err.Error(), nil
|
||||
}
|
||||
|
||||
// Apply auth headers.
|
||||
req.Header.Set("User-Agent", effectiveUA(site))
|
||||
switch site.AuthType {
|
||||
case "cookie":
|
||||
if site.Cookie != "" {
|
||||
req.Header.Set("Cookie", site.Cookie)
|
||||
}
|
||||
case "api_key":
|
||||
if site.APIKey != "" {
|
||||
req.Header.Set("x-api-key", site.APIKey)
|
||||
}
|
||||
case "authorization":
|
||||
if site.AuthHeader != "" {
|
||||
req.Header.Set("Authorization", site.AuthHeader)
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
status := "fail"
|
||||
_ = s.repo.DB.WithContext(ctx).Model(&model.Site{}).Where("id = ?", id).
|
||||
Update("login_status", status).Error
|
||||
return false, err.Error(), nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var ok bool
|
||||
var msg string
|
||||
switch {
|
||||
case resp.StatusCode == 200:
|
||||
ok, msg = true, "连接成功"
|
||||
case resp.StatusCode == 403:
|
||||
ok, msg = false, "认证失败 (HTTP 403)"
|
||||
case resp.StatusCode == 401:
|
||||
ok, msg = false, "未授权 (HTTP 401)"
|
||||
default:
|
||||
ok, msg = resp.StatusCode < 400, "HTTP "+resp.Status
|
||||
}
|
||||
|
||||
loginStatus := "ok"
|
||||
if !ok {
|
||||
loginStatus = "fail"
|
||||
}
|
||||
_ = s.repo.DB.WithContext(ctx).Model(&model.Site{}).Where("id = ?", id).
|
||||
Updates(map[string]any{"login_status": loginStatus, "last_check": time.Now()}).Error
|
||||
return ok, msg, nil
|
||||
}
|
||||
|
||||
// SearchResult is one torrent returned by a site adapter search.
|
||||
type SearchResult struct {
|
||||
SiteName string `json:"site_name"`
|
||||
SiteID string `json:"site_id"`
|
||||
Title string `json:"title"`
|
||||
TorrentURL string `json:"torrent_url"`
|
||||
DownloadURL string `json:"download_url"`
|
||||
Size int64 `json:"size"`
|
||||
Seeders int `json:"seeders"`
|
||||
Leechers int `json:"leechers"`
|
||||
Free bool `json:"free"`
|
||||
}
|
||||
|
||||
// Search fans out a keyword query to every enabled site and returns
|
||||
// merged results sorted by seeders descending.
|
||||
func (s *SiteService) Search(ctx context.Context, keyword string) ([]SearchResult, error) {
|
||||
if strings.TrimSpace(keyword) == "" {
|
||||
return nil, errors.New("keyword required")
|
||||
}
|
||||
sites, err := s.List(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var results []SearchResult
|
||||
for i := range sites {
|
||||
if !sites[i].Enabled {
|
||||
continue
|
||||
}
|
||||
adapter := NewSiteAdapter(&sites[i])
|
||||
if adapter == nil {
|
||||
continue
|
||||
}
|
||||
items, err := adapter.Search(ctx, keyword)
|
||||
if err != nil {
|
||||
s.log.Debug("site search failed",
|
||||
zap.String("site", sites[i].Name), zap.Error(err))
|
||||
continue
|
||||
}
|
||||
for _, item := range items {
|
||||
results = append(results, SearchResult{
|
||||
SiteName: sites[i].Name,
|
||||
SiteID: sites[i].ID,
|
||||
Title: item.Title,
|
||||
TorrentURL: item.TorrentURL,
|
||||
DownloadURL: item.DownloadURL,
|
||||
Size: item.Size,
|
||||
Seeders: item.Seeders,
|
||||
Leechers: item.Leechers,
|
||||
Free: item.Free,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by seeders desc.
|
||||
for i := 0; i < len(results); i++ {
|
||||
for j := i + 1; j < len(results); j++ {
|
||||
if results[j].Seeders > results[i].Seeders {
|
||||
results[i], results[j] = results[j], results[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func effectiveUA(site *model.Site) string {
|
||||
if site.UserAgent != "" {
|
||||
return site.UserAgent
|
||||
}
|
||||
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
Reference in New Issue
Block a user