mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 11:36:36 +08:00
1dbd73b30b
== New domain models (7) ==
- UserPermission: per-user feature toggles (13 booleans)
- StorageConfig: encrypted Alist/S3/WebDAV adapters
- LicenseKey + LicenseActivation: offline license issuance
- DownloadClient: multi-client downloader configs
- AssistantSession + AssistantMessage: multi-turn AI chat persistence
== New services (5) ==
- PermissionService: admin grants always-true; user defaults seeded
- StorageConfigService: AES-GCM encryption + per-type connection probe
- LicenseService: 24-char hyphenated key generation, activation/heartbeat
- DownloadClientService: qB/Aria2/Transmission CRUD + WebUI test
- AssistantService: chat history + execute/undo stubs (op_id tracking)
== Extended AIService.Chat ==
- Multi-turn LLM call with chat history; offline fallback reply
== New endpoints (60+) ==
Auth:
POST /auth/refresh, /auth/logout, /auth/change-password
PATCH /auth/profile
GET /auth/permissions, /auth/me
Permissions admin:
GET/PUT /admin/users/:id/permissions
POST /admin/users/:id/permissions/reset
Search:
GET /search, /search/advanced, /search/tmdb, /search/sites
System:
GET /system/config, /settings/schema, /system/events/ticket
POST /admin/system/scheduler/:name/trigger
Stats:
GET /stats/user/:id, /stats/top-users
POST /stats/play
Sites:
GET /sites/:id/resource, /sites/:id/userdata
Subscriptions:
PUT /subscriptions/:id, POST /subscriptions/:id/search
Playlists:
POST /playlists/:id/reorder
DELETE /playlists/:id/items/by-id/:item_id
DLNA per-renderer:
POST /dlna/:uuid/{play,pause,stop}, GET /dlna/:uuid/status
Media:
POST/DELETE /media/:id/favorite, GET /media/:id/favorite/status
POST /media/:id/ai-scrape, /media/scrape/test, /media/organize
GET /favorites (alias)
Playback:
GET /playback/:id/info, /playback/:id/external-players, /playback/:id/external-url
POST /playback/:id/progress
GET /playback/transcode/:job_id/status
Downloads:
POST /download/:id/{pause,resume,organize}
POST /download/{organize,sync,start-auto-sync}
GET /download/tasks
Admin: full CRUD on /admin/download/clients + /admin/download/aria2/stats
License:
POST /license/{activate,heartbeat}
GET /license/{status,heartbeat-status}
Admin: /admin/license/{generate,list,:id/activations,:id/revoke,activation/:id/unbind}
Storage:
GET /admin/storage/{status,:type}
PUT /admin/storage/:type, POST /admin/storage/:type/test
Assistant (multi-turn AI):
GET/POST /admin/assistant/sessions
GET/DELETE /admin/assistant/session/:id
POST /admin/assistant/{chat,execute}
POST /admin/assistant/undo/:op_id
GET /admin/assistant/history
== New React pages (4) ==
- AssistantChatPage (/assistant): full multi-turn chat UI with sessions
sidebar, optimistic user-turn append, live AI response.
- DownloadClientsPage (/download-clients): typed CRUD form for
qBittorrent / Aria2 / Transmission + per-row Test action.
- LicensePage (/license): generate keys, list activations, revoke,
unbind individual devices.
- StorageConfigPage (/storage-config): tabbed Alist/WebDAV/S3 form
with secret-aware redaction + connection probe.
== New API helpers (5) ==
- assistant, download_clients, license, permissions, storage_config
== Layout ==
- Sidebar gains 4 new admin links (AI 对话, 下载器, 外部存储, 许可证).
285 lines
7.9 KiB
Go
285 lines
7.9 KiB
Go
// Package service — DLNA / UPnP discovery.
|
|
//
|
|
// DLNAService scans the LAN for "MediaRenderer" UPnP devices via SSDP
|
|
// (multicast UDP 239.255.255.250:1900) and exposes a one-shot "cast"
|
|
// helper that POSTs a SOAP envelope to the renderer's AVTransport
|
|
// service to start playback of an HTTP URL.
|
|
//
|
|
// We do NOT mediate the renderer ↔ client traffic; the renderer pulls
|
|
// the bytes directly from MediaStationGo's /api/stream endpoint, so
|
|
// the cast call only ever transports a URL string.
|
|
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/xml"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// DLNAService discovers UPnP MediaRenderer devices and casts media to them.
|
|
type DLNAService struct {
|
|
log *zap.Logger
|
|
|
|
mu sync.Mutex
|
|
cache []DLNADevice
|
|
cachedAt time.Time
|
|
}
|
|
|
|
// NewDLNAService is the constructor.
|
|
func NewDLNAService(log *zap.Logger) *DLNAService {
|
|
return &DLNAService{log: log}
|
|
}
|
|
|
|
// DLNADevice is the public projection of a discovered renderer.
|
|
type DLNADevice struct {
|
|
UDN string `json:"udn"`
|
|
FriendlyName string `json:"friendly_name"`
|
|
Manufacturer string `json:"manufacturer"`
|
|
ModelName string `json:"model_name"`
|
|
Location string `json:"location"` // device description URL
|
|
ControlURL string `json:"control_url"` // AVTransport SOAP endpoint
|
|
IPAddress string `json:"ip_address"`
|
|
}
|
|
|
|
// ssdpDiscover sends an M-SEARCH and returns the LOCATION URLs of every
|
|
// device that replied within timeout.
|
|
func (d *DLNAService) ssdpDiscover(ctx context.Context, timeout time.Duration) ([]string, error) {
|
|
addr, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer conn.Close()
|
|
|
|
msg := strings.Join([]string{
|
|
"M-SEARCH * HTTP/1.1",
|
|
"HOST: 239.255.255.250:1900",
|
|
`MAN: "ssdp:discover"`,
|
|
"MX: 2",
|
|
"ST: urn:schemas-upnp-org:device:MediaRenderer:1",
|
|
"", "",
|
|
}, "\r\n")
|
|
if _, err := conn.WriteTo([]byte(msg), addr); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
deadline := time.Now().Add(timeout)
|
|
_ = conn.SetReadDeadline(deadline)
|
|
|
|
seen := map[string]struct{}{}
|
|
var locations []string
|
|
buf := make([]byte, 4096)
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return locations, nil
|
|
default:
|
|
}
|
|
n, _, err := conn.ReadFrom(buf)
|
|
if err != nil {
|
|
break
|
|
}
|
|
body := string(buf[:n])
|
|
for _, line := range strings.Split(body, "\r\n") {
|
|
if strings.HasPrefix(strings.ToUpper(line), "LOCATION:") {
|
|
loc := strings.TrimSpace(line[len("LOCATION:"):])
|
|
if _, ok := seen[loc]; ok {
|
|
continue
|
|
}
|
|
seen[loc] = struct{}{}
|
|
locations = append(locations, loc)
|
|
}
|
|
}
|
|
}
|
|
return locations, nil
|
|
}
|
|
|
|
// Discover returns every reachable MediaRenderer on the LAN. Results are
|
|
// cached for 30 seconds so the React UI's polling does not spam the
|
|
// network.
|
|
func (d *DLNAService) Discover(ctx context.Context, force bool) ([]DLNADevice, error) {
|
|
d.mu.Lock()
|
|
if !force && time.Since(d.cachedAt) < 30*time.Second && d.cache != nil {
|
|
out := append([]DLNADevice(nil), d.cache...)
|
|
d.mu.Unlock()
|
|
return out, nil
|
|
}
|
|
d.mu.Unlock()
|
|
|
|
locations, err := d.ssdpDiscover(ctx, 3*time.Second)
|
|
if err != nil {
|
|
// SSDP often fails on container networks; treat as "no devices"
|
|
// rather than 500 the API.
|
|
d.log.Debug("ssdp discover failed", zap.Error(err))
|
|
return nil, nil
|
|
}
|
|
devices := make([]DLNADevice, 0, len(locations))
|
|
for _, loc := range locations {
|
|
dev, err := d.fetchDescription(ctx, loc)
|
|
if err != nil {
|
|
d.log.Debug("desc fetch", zap.String("loc", loc), zap.Error(err))
|
|
continue
|
|
}
|
|
devices = append(devices, *dev)
|
|
}
|
|
|
|
d.mu.Lock()
|
|
d.cache = devices
|
|
d.cachedAt = time.Now()
|
|
d.mu.Unlock()
|
|
return devices, nil
|
|
}
|
|
|
|
// fetchDescription parses the device's UPnP XML descriptor and pulls out
|
|
// the AVTransport control URL.
|
|
func (d *DLNAService) fetchDescription(ctx context.Context, location string) (*DLNADevice, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, location, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
type service struct {
|
|
ServiceType string `xml:"serviceType"`
|
|
ControlURL string `xml:"controlURL"`
|
|
}
|
|
type device struct {
|
|
FriendlyName string `xml:"friendlyName"`
|
|
Manufacturer string `xml:"manufacturer"`
|
|
ModelName string `xml:"modelName"`
|
|
UDN string `xml:"UDN"`
|
|
ServiceList struct {
|
|
Services []service `xml:"service"`
|
|
} `xml:"serviceList"`
|
|
}
|
|
type root struct {
|
|
Device device `xml:"device"`
|
|
}
|
|
var r root
|
|
if err := xml.Unmarshal(body, &r); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
out := &DLNADevice{
|
|
UDN: r.Device.UDN,
|
|
FriendlyName: r.Device.FriendlyName,
|
|
Manufacturer: r.Device.Manufacturer,
|
|
ModelName: r.Device.ModelName,
|
|
Location: location,
|
|
}
|
|
if u, err := url.Parse(location); err == nil {
|
|
out.IPAddress = u.Hostname()
|
|
}
|
|
for _, svc := range r.Device.ServiceList.Services {
|
|
if strings.Contains(svc.ServiceType, "AVTransport") {
|
|
out.ControlURL = absoluteURL(location, svc.ControlURL)
|
|
break
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func absoluteURL(base, ref string) string {
|
|
bu, err := url.Parse(base)
|
|
if err != nil {
|
|
return ref
|
|
}
|
|
ru, err := url.Parse(ref)
|
|
if err != nil {
|
|
return ref
|
|
}
|
|
return bu.ResolveReference(ru).String()
|
|
}
|
|
|
|
// soapTemplate is the AVTransport SetAVTransportURI envelope.
|
|
const soapTemplate = `<?xml version="1.0"?>
|
|
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
|
|
<s:Body>
|
|
<u:SetAVTransportURI xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">
|
|
<InstanceID>0</InstanceID>
|
|
<CurrentURI>%s</CurrentURI>
|
|
<CurrentURIMetaData></CurrentURIMetaData>
|
|
</u:SetAVTransportURI>
|
|
</s:Body>
|
|
</s:Envelope>`
|
|
|
|
const playTemplate = `<?xml version="1.0"?>
|
|
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
|
|
<s:Body>
|
|
<u:Play xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">
|
|
<InstanceID>0</InstanceID>
|
|
<Speed>1</Speed>
|
|
</u:Play>
|
|
</s:Body>
|
|
</s:Envelope>`
|
|
|
|
// Cast tells the device at controlURL to start playing mediaURL. Returns
|
|
// the renderer's HTTP status for diagnostic purposes.
|
|
func (d *DLNAService) Cast(ctx context.Context, controlURL, mediaURL string) error {
|
|
if controlURL == "" {
|
|
return errors.New("device has no AVTransport control URL")
|
|
}
|
|
if err := d.soap(ctx, controlURL, "SetAVTransportURI",
|
|
fmt.Sprintf(soapTemplate, escapeXML(mediaURL))); err != nil {
|
|
return err
|
|
}
|
|
return d.soap(ctx, controlURL, "Play", playTemplate)
|
|
}
|
|
|
|
// 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)))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", `text/xml; charset="utf-8"`)
|
|
req.Header.Set("SOAPAction",
|
|
fmt.Sprintf(`"urn:schemas-upnp-org:service:AVTransport:1#%s"`, action))
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode >= 400 {
|
|
raw, _ := io.ReadAll(resp.Body)
|
|
return fmt.Errorf("dlna %s: %d: %s", action, resp.StatusCode, strings.TrimSpace(string(raw)))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func escapeXML(s string) string {
|
|
r := strings.NewReplacer("&", "&", "<", "<", ">", ">",
|
|
`"`, """, "'", "'")
|
|
return r.Replace(s)
|
|
}
|