mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 11:36:36 +08:00
4b747c74ca
Audit-driven port from the original Python MediaStation. Eight major
subsystems that were absent from the Go rewrite are now in place,
each with its own service, handler, frontend page and smoke-test
assertions.
Backend services
- service/crypto.go: AES-256-GCM encrypt/decrypt for at-rest secrets
keyed off the JWT secret. Legacy plaintext rows pass through
unchanged for smooth upgrades. Unit-tested.
- service/api_config.go: third-party provider config (TMDb, Bangumi,
TheTVDB, Fanart, Douban, OpenAI). Seeds defaults on first run.
Encrypts api_key on write, returns masked 'abc1****wxyz' projection.
- service/duplicate.go: sparse-sample MD5 (head + middle + tail, 1MiB
each, plus file-size suffix) duplicate finder. Picks 'best' primary
(matched > size > id) and marks others is_duplicate=true.
- service/filemanager.go: server-side allow-listed file browser used
by the library-path picker. Strict path-traversal protection.
- service/dlna.go: real SSDP M-SEARCH discovery + AVTransport
SetAVTransportURI/Play SOAP cast. 30 s discovery cache.
- service/scheduler.go: 3 recurring background jobs (library_scan
60min, transcode_cleanup 24h, recycle_purge 24h with 30-day
cutoff). Status + run-now endpoints.
- service/cache_cleanup.go: walkAndPrune helper used by scheduler.
- service/storage.go: DB-only disk-usage breakdown by library and by
container format.
- service/emby_compat.go: read-only Emby/Jellyfin shim
(System/Info, Users, Users/x/Views, Items, PlaybackInfo) so Infuse
/ VidHub / Kodi can browse MediaStationGo libraries.
Model updates
- Media: new strm_url (302 redirect target), file_hash, is_duplicate,
duplicate_of fields.
- APIConfig: new table for encrypted provider secrets.
- AutoMigrate registers APIConfig.
Stream layer
- StreamService.ServeFile now redirects 302 to strm_url when set so
WebDAV / Alist / S3 / HTTP direct links work transparently.
Handlers + routes
- Authed: GET /files, GET /storage, GET /dlna/devices, POST /dlna/cast,
PUT/DELETE /media/:id/strm, POST /strm/import,
POST /duplicates/{scan,unmark}.
- Admin: GET/PUT/DELETE /admin/api-configs/:provider,
GET /admin/scheduler, POST /admin/scheduler/:name/run.
- New /emby/* group: System/Info, Users, Users/:userId/Views,
Users/:userId/Items, Items/:id/PlaybackInfo (auth-required).
Frontend pages (lazy-loaded, 7 new chunks)
- DlnaPage: device list + media picker + cast button.
- FileManagerPage: root selector + breadcrumb + sortable listing.
- APIConfigsPage: per-provider card with masked-key editor.
- StoragePage: usage tiles + per-library bars + per-container grid.
- DuplicatesPage: scan form + grouped report with primary highlight.
- SchedulerPage: live job table with run-now button (5s refresh).
- Sidebar reorganised: 自动化 group adds DLNA, 管理 group adds
存储 / 文件浏览 / 重复文件 / 定时任务 / API 配置.
Smoke test additions (all admin-only)
- api-configs seeded with 6 providers
- api-config encrypted in db (sqlite3 enc:v1: prefix check)
- storage breakdown
- file browser lists library root + rejects /etc (path traversal)
- dlna devices endpoint
- scheduler exposes 3 jobs + run library_scan
- emby /System/Info + /Users/{x}/Views
- strm set + stream 302 + strm clear
- duplicate scan
Verified: go build, go vet, go test (incl. new TestCrypto* suite + the
existing TestParseEpisode/TestCleanQuery/TestSrtToVTT/TestStripASSTags/
TestBuildFFmpegArgs); tsc -b && vite build emits 28 route chunks plus
the deferred hls chunk; main bundle 253 KB / 85 KB gzipped; smoke test
PASS=42 / FAIL=0.
116 lines
3.1 KiB
Go
116 lines
3.1 KiB
Go
// Package service — disk usage breakdown.
|
|
//
|
|
// StorageService aggregates "how much disk does each library use" for
|
|
// the React Storage tab. Numbers are computed from the in-DB
|
|
// media.size_bytes column so we never hit the disk on the hot path.
|
|
package service
|
|
|
|
import (
|
|
"context"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"github.com/ShukeBta/MediaStationGo/internal/repository"
|
|
)
|
|
|
|
// StorageService is the read-only aggregator.
|
|
type StorageService struct {
|
|
log *zap.Logger
|
|
repo *repository.Container
|
|
}
|
|
|
|
// NewStorageService is the constructor.
|
|
func NewStorageService(log *zap.Logger, repo *repository.Container) *StorageService {
|
|
return &StorageService{log: log, repo: repo}
|
|
}
|
|
|
|
// Breakdown is what /api/storage returns.
|
|
type Breakdown struct {
|
|
TotalBytes int64 `json:"total_bytes"`
|
|
TotalSeconds int64 `json:"total_seconds"`
|
|
ByLibrary []LibraryUsage `json:"by_library"`
|
|
ByContainer []ContainerStat `json:"by_container"`
|
|
}
|
|
|
|
// LibraryUsage is per-library disk + duration totals.
|
|
type LibraryUsage struct {
|
|
LibraryID string `json:"library_id"`
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Path string `json:"path"`
|
|
MediaCount int64 `json:"media_count"`
|
|
TotalBytes int64 `json:"total_bytes"`
|
|
TotalSeconds int64 `json:"total_seconds"`
|
|
}
|
|
|
|
// ContainerStat counts media items per container (mp4 / mkv / …).
|
|
type ContainerStat struct {
|
|
Container string `json:"container"`
|
|
Count int64 `json:"count"`
|
|
Bytes int64 `json:"bytes"`
|
|
}
|
|
|
|
// Compute returns the full breakdown.
|
|
func (s *StorageService) Compute(ctx context.Context) (*Breakdown, error) {
|
|
libs, err := s.repo.Library.List(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := &Breakdown{ByLibrary: make([]LibraryUsage, 0, len(libs))}
|
|
for _, l := range libs {
|
|
var usage LibraryUsage
|
|
usage.LibraryID = l.ID
|
|
usage.Name = l.Name
|
|
usage.Type = l.Type
|
|
usage.Path = l.Path
|
|
row := struct {
|
|
Count int64
|
|
Size int64
|
|
Seconds int64
|
|
}{}
|
|
err := s.repo.DB.WithContext(ctx).
|
|
Table("media").
|
|
Where("library_id = ? AND deleted_at IS NULL", l.ID).
|
|
Select("COUNT(*) as count, COALESCE(SUM(size_bytes),0) as size, COALESCE(SUM(duration_sec),0) as seconds").
|
|
Scan(&row).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
usage.MediaCount = row.Count
|
|
usage.TotalBytes = row.Size
|
|
usage.TotalSeconds = row.Seconds
|
|
out.TotalBytes += row.Size
|
|
out.TotalSeconds += row.Seconds
|
|
out.ByLibrary = append(out.ByLibrary, usage)
|
|
}
|
|
|
|
rows, err := s.containerStats(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out.ByContainer = rows
|
|
return out, nil
|
|
}
|
|
|
|
func (s *StorageService) containerStats(ctx context.Context) ([]ContainerStat, error) {
|
|
rows, err := s.repo.DB.WithContext(ctx).
|
|
Table("media").
|
|
Where("deleted_at IS NULL").
|
|
Select("COALESCE(NULLIF(container,''),'unknown') as container, COUNT(*) as count, COALESCE(SUM(size_bytes),0) as bytes").
|
|
Group("container").
|
|
Rows()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []ContainerStat{}
|
|
for rows.Next() {
|
|
var c ContainerStat
|
|
if err := rows.Scan(&c.Container, &c.Count, &c.Bytes); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, c)
|
|
}
|
|
return out, nil
|
|
}
|