Files
MeBox/internal/service/thetvdb.go
T
Kiro 8824638efb feat: hwaccel + Fanart/TheTVDB + AI + Discover + NFO + Tasks + Recycle bin
Backend
  - service/transcoder.go: encoder selector (software / nvenc / qsv /
    vaapi) with proper hwaccel + scale_* filters per encoder; configurable
    bitrate/preset/height/segment-seconds via transcoder.* config; new
    Active() snapshot + ActiveJob struct for the Tasks panel; unit-tested
    via buildFFmpegArgs(...).
  - service/thetvdb.go: TheTVDB v4 provider — login() caches the JWT for
    24h, SearchSeries() returns Match struct.
  - service/fanart.go: Fanart.tv provider — high-res movie artwork keyed
    by TMDb id; used to upgrade poster/backdrop after a successful match.
  - service/scraper.go: provider chain reworked — anime → Bangumi, tv →
    TheTVDB, default → TMDb, with optional Fanart upgrade post-match.
  - service/discover.go: TMDb /trending/movie/day + /movie/popular for
    the Discover rail.
  - service/ai.go: OpenAI-compatible client. SmartSearch() turns a free-
    form query into a structured SearchIntent JSON; Recommend() emits a
    short list of titles given the user's history. Disabled when
    ai.api_key is empty.
  - service/nfo.go: per-movie .nfo writer (Kodi/Jellyfin schema) +
    library-scope batch exporter.
  - service/media.go: SoftDelete / Restore / Purge / ListRecycleBin
    helpers backed by gorm Unscoped().
  - service/service.go: container wires Fanart, TheTVDB, Discover, AI,
    NFO; everything still tears down cleanly via Close().
  - config: new transcoder.* section (encoder, preset, video_bitrate,
    max_rate, buf_size, max_height, segment_seconds) with sensible
    defaults.

Handlers / routes
  - new files: discover.go, recycle.go, nfo.go, ai.go, tasks.go.
  - registers GET /tasks, /discover/{trending,popular},
    /ai/{status,search,recommend}; admin-only GET /recycle and
    DELETE/POST /media/:id (soft delete / restore / purge); admin-only
    POST /media/:id/nfo and /libraries/:id/nfo.

Frontend
  - new pages: DiscoverPage, TasksPage, RecycleBinPage; SearchPage gains
    an optional AI smart-search toggle that calls /api/ai/search.
  - MediaDetailPage gains admin actions for 导出 NFO and 移至回收站.
  - new api/ helpers: ai.ts, discover.ts, recycle.ts, tasks.ts.
  - App.tsx routes /discover, /tasks, /recycle (last two admin-only).
  - Layout sidebar groups now include Discover + Tasks + Recycle Bin.

Docker / config
  - Dockerfile: adds intel-media-driver / libva-utils / mesa-va-gallium
    so QSV + VAAPI work out of the box on Intel iGPUs.
  - docker-compose.yml: documents devices + group_add + nvidia runtime
    overrides for hardware transcoding.

Verified: go build, go vet, go test (incl. new TestBuildFFmpegArgs across
software / nvenc / qsv / vaapi encoder profiles); tsc -b && vite build
emits 22 route chunks plus the deferred hls chunk; main bundle 248 KB /
83 KB gzipped.
2026-05-14 16:22:08 +00:00

160 lines
4.0 KiB
Go

// Package service — TheTVDB v4 provider.
//
// TheTVDBProvider implements two methods used by the scraper for TV /
// anime libraries:
//
// Login() -> exchanges secrets.thetvdb_api_key for
// a JWT (cached for 24h).
// SearchSeries(query) -> /search?query=...&type=series
//
// The provider is enabled iff secrets.thetvdb_api_key is non-empty. When
// disabled every method returns nil, nil so the scraper orchestrator can
// gracefully fall through.
package service
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"sync"
"time"
"go.uber.org/zap"
"github.com/ShukeBta/MediaStationGo/internal/config"
)
// TheTVDBProvider talks to https://api4.thetvdb.com/v4.
type TheTVDBProvider struct {
cfg *config.Config
log *zap.Logger
client *http.Client
mu sync.Mutex
token string
tokenExp time.Time
}
// NewTheTVDBProvider is the constructor.
func NewTheTVDBProvider(cfg *config.Config, log *zap.Logger) *TheTVDBProvider {
return &TheTVDBProvider{
cfg: cfg,
log: log,
client: &http.Client{Timeout: 15 * time.Second},
}
}
// Enabled reports whether an API key is present.
func (t *TheTVDBProvider) Enabled() bool { return t.cfg.Secrets.TheTVDBAPIKey != "" }
// Login fetches a fresh JWT, cached for 24h.
func (t *TheTVDBProvider) Login(ctx context.Context) (string, error) {
t.mu.Lock()
defer t.mu.Unlock()
if time.Now().Before(t.tokenExp) && t.token != "" {
return t.token, nil
}
body, _ := json.Marshal(map[string]string{"apikey": t.cfg.Secrets.TheTVDBAPIKey})
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://api4.thetvdb.com/v4/login", bytes.NewReader(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := t.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return "", fmt.Errorf("thetvdb login: %d", resp.StatusCode)
}
var out struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return "", err
}
t.token = out.Data.Token
t.tokenExp = time.Now().Add(24 * time.Hour)
return t.token, nil
}
// SearchSeries returns the top match for a TV / anime query, or nil.
func (t *TheTVDBProvider) SearchSeries(ctx context.Context, query string) (*Match, error) {
if !t.Enabled() || query == "" {
return nil, nil
}
tok, err := t.Login(ctx)
if err != nil {
return nil, err
}
u := fmt.Sprintf("https://api4.thetvdb.com/v4/search?query=%s&type=series",
urlEscape(query))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+tok)
resp, err := t.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("thetvdb search: %d", resp.StatusCode)
}
type entry struct {
ID string `json:"id"`
Name string `json:"name"`
Overview string `json:"overview"`
Image string `json:"image_url"`
Year string `json:"year"`
}
type page struct {
Data []entry `json:"data"`
}
var p page
if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
return nil, err
}
if len(p.Data) == 0 {
return nil, nil
}
r := p.Data[0]
m := &Match{
Title: r.Name,
Overview: r.Overview,
PosterURL: r.Image,
}
if len(r.Year) >= 4 {
fmt.Sscanf(r.Year[:4], "%d", &m.Year)
}
return m, nil
}
// urlEscape is a tiny replacement for net/url.QueryEscape kept inline so
// the file does not pull a second import for one call.
func urlEscape(s string) string {
out := make([]byte, 0, len(s)*3)
for _, r := range []byte(s) {
switch {
case r >= '0' && r <= '9',
r >= 'A' && r <= 'Z',
r >= 'a' && r <= 'z',
r == '-', r == '_', r == '.', r == '~':
out = append(out, r)
default:
out = append(out, '%')
const hex = "0123456789ABCDEF"
out = append(out, hex[r>>4], hex[r&15])
}
}
return string(out)
}