Files
MeBox/internal/service/stats.go
T
Kiro 7bd6bcfb1b feat: downloads, RSS, subtitles, Bangumi, watcher, stats, profile, audit
Backend
  - service/bangumi.go: Bangumi (bgm.tv) scraper for anime libraries.
  - service/episode_parser.go: SxxExx / NxE / EPxx / 第NN集 parser with
    unit tests; consumed by the scanner for tv/anime libraries.
  - service/scraper.go: provider chain orchestrator picks Bangumi for
    anime libraries (TMDb fallback), TMDb for everything else; emits
    'no_match' rows so we don't retry forever; AnyEnabled() for the
    scanner kick.
  - service/scanner.go: writes season/episode numbers for tv/anime libs
    and reports a 'probed' counter alongside 'added'.
  - service/transcoder.go (existing): unchanged, stays per-media.
  - service/subtitle.go: discovers external subtitles next to the source
    file (.srt/.vtt/.ass/.ssa) and converts SRT/ASS to WebVTT on the fly.
  - service/qbittorrent.go: thread-safe qBittorrent v2 Web UI client
    (login / add / list / delete) with cookie-jar reuse.
  - service/downloads.go: persists download tasks, reads runtime
    qbittorrent.* settings, polls /torrents/info every 5 s and pushes
    the result to WS subscribers ('download' topic).
  - service/subscription.go: 10-minute RSS poller with regex filter,
    GUID dedup persisted in the settings table, and 'subscription' WS
    events on enqueue.
  - service/watcher.go: fsnotify watcher with 5 s coalescing debouncer
    that triggers per-library rescans on create/rename/remove.
  - service/stats.go: dashboard snapshot — totals, recently added,
    gopsutil-driven CPU/mem/disk readings.
  - service/profile.go: non-credential profile patch + admin role mutator.
  - service/audit.go: best-effort writer for the access_logs table.
  - service/service.go: container wires every new service; Boot() spins
    up watcher / downloads poller / subscription scheduler; Close()
    tears them down on graceful shutdown.

Handlers
  - new files: downloads.go, subscriptions.go, subtitles.go, series.go,
    stats.go, profile.go, util.go.
  - handler.go: registers PATCH /me, /libraries/:id/seasons,
    /media/:id/subtitles, /subtitles/:id, /downloads*, /subscriptions*,
    /stats, /admin/users/:id/role.
  - auth.go / media.go: write audit rows for login + library CRUD and
    refresh the watcher when libraries change.

Frontend
  - api: new helpers for downloads, subscriptions, profile, series, stats,
    subtitles; library helper gained scrape().
  - hooks/useWebSocket.ts: shared connection with 3 s reconnect.
  - components/GlobalEvents.tsx: surfaces scan / scrape / subscription
    completion as toasts (mounted at app root).
  - pages: Library now switches to a season-grouped layout for tv/anime
    libraries; Player attaches WebVTT <track> elements; new pages for
    Downloads (live torrent table), Subscriptions, Profile, Stats.
  - components/Layout.tsx + App.tsx: sidebar groups (媒体库 / 自动化 /
    账号 / 管理) and routes for the new pages; /stats and /admin remain
    admin-only.
  - types/index.ts: new types — Subscription, DownloadTask, QBitTorrent,
    Hardware, StatsSnapshot.

Verified: go build, go vet, go test (incl. ParseEpisode + srtToVTT +
stripASSTags) all pass; tsc -b && vite build emits 17 route chunks plus
the deferred hls chunk; main bundle 247 KB / 83 KB gzipped.
2026-05-14 16:07:49 +00:00

114 lines
3.2 KiB
Go

// Package service — statistics aggregator.
//
// StatsService computes the dashboard numbers for the admin / home page:
// - total libraries, media items, users
// - total disk size and durations
// - top recently-watched media
// - process metadata (CPU / memory) via gopsutil
package service
import (
"context"
"runtime"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
"go.uber.org/zap"
"github.com/ShukeBta/MediaStationGo/internal/model"
"github.com/ShukeBta/MediaStationGo/internal/repository"
)
// StatsService computes aggregate stats.
type StatsService struct {
log *zap.Logger
repo *repository.Container
}
// NewStatsService is the constructor.
func NewStatsService(log *zap.Logger, repo *repository.Container) *StatsService {
return &StatsService{log: log, repo: repo}
}
// Snapshot is the JSON returned by /api/stats.
type Snapshot struct {
Libraries int64 `json:"libraries"`
MediaCount int64 `json:"media_count"`
UsersCount int64 `json:"users_count"`
TotalSizeBytes int64 `json:"total_size_bytes"`
TotalSeconds int64 `json:"total_seconds"`
RecentlyAdded []model.Media `json:"recently_added"`
Hardware Hardware `json:"hardware"`
GeneratedAt time.Time `json:"generated_at"`
}
// Hardware is the live CPU / memory / disk readings.
type Hardware struct {
CPUPercent float64 `json:"cpu_percent"`
MemoryUsed uint64 `json:"memory_used"`
MemoryTotal uint64 `json:"memory_total"`
DiskUsed uint64 `json:"disk_used"`
DiskTotal uint64 `json:"disk_total"`
GoVersion string `json:"go_version"`
Goroutines int `json:"goroutines"`
}
// Compute builds a fresh snapshot.
func (s *StatsService) Compute(ctx context.Context, dataDir string) (*Snapshot, error) {
snap := &Snapshot{GeneratedAt: time.Now()}
if err := s.repo.DB.Model(&model.Library{}).Count(&snap.Libraries).Error; err != nil {
return nil, err
}
if err := s.repo.DB.Model(&model.Media{}).Count(&snap.MediaCount).Error; err != nil {
return nil, err
}
if err := s.repo.DB.Model(&model.User{}).Count(&snap.UsersCount).Error; err != nil {
return nil, err
}
type sumRow struct {
Size int64
Seconds int64
}
var sum sumRow
if err := s.repo.DB.Model(&model.Media{}).
Select("COALESCE(SUM(size_bytes),0) as size, COALESCE(SUM(duration_sec),0) as seconds").
Scan(&sum).Error; err != nil {
return nil, err
}
snap.TotalSizeBytes = sum.Size
snap.TotalSeconds = sum.Seconds
if err := s.repo.DB.Model(&model.Media{}).
Order("created_at desc").Limit(12).
Find(&snap.RecentlyAdded).Error; err != nil {
return nil, err
}
snap.Hardware = readHardware(dataDir)
return snap, nil
}
func readHardware(dataDir string) Hardware {
hw := Hardware{
GoVersion: runtime.Version(),
Goroutines: runtime.NumGoroutine(),
}
if usage, err := cpu.Percent(0, false); err == nil && len(usage) > 0 {
hw.CPUPercent = usage[0]
}
if v, err := mem.VirtualMemory(); err == nil {
hw.MemoryUsed = v.Used
hw.MemoryTotal = v.Total
}
if dataDir == "" {
dataDir = "/"
}
if d, err := disk.Usage(dataDir); err == nil {
hw.DiskUsed = d.Used
hw.DiskTotal = d.Total
}
return hw
}