media-preload: on-demand VPS cache warm-up API and agent

OpenAPI 3.0 contract (api/openapi.yaml) with oapi-codegen generated server,
client and models; preload-api (Jellyfin lookup, SQLite queue, bearer roles)
runs at home, preload-agent runs on the VPS and fills the rclone cache.
mise manages Go 1.27.3 and oapi-codegen 2.8.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GUebqghNwNssAZuWTxUq1y
This commit is contained in:
Claude committed 2026-11-04 17:49:06 -07:00
commit a18d45714e
18 files changed
+4970

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
bin/
*.db
*.db-*
+15
View File
@@ -0,0 +1,15 @@
# Build: podman build -t localhost/media-preload-api:latest -f Containerfile .
FROM docker.io/library/golang:1.27 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
ARG VERSION=dev
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/preload-api ./cmd/preload-api
FROM scratch
COPY --from=build /out/preload-api /preload-api
USER 65534:65534
EXPOSE 8125
VOLUME ["/data"]
ENTRYPOINT ["/preload-api"]
+74
View File
@@ -0,0 +1,74 @@
# media-preload
Warm the VPS media cache before someone watches something.
`webdav.godemperordoge.org` is served by the shared VPS, which keeps a 512 GB rclone cache of the Movies and TV
folders. The first play of a file streams over the home uplink. Once cached, it streams from the VPS. This service lets
a client, such as the planned Discord bot, say "I will watch X", so X is cached before anyone presses play.
```mermaid
graph LR
bot[Discord bot or any client] -->|"search, request (client token)"| api[preload-api on yveltal]
api -->|"items, episodes, next up"| jf[Jellyfin]
agent[preload-agent on the VPS] -->|"claim and report (agent token, over wg-home)"| api
agent -->|"GET whole file"| rc["rclone serve, read-only, 127.0.0.1:18124"]
rc -->|"cache miss: fetch over tunnel"| origin[rclone-webdav-vpscache on yveltal]
```
* **preload-api** (`cmd/preload-api`) runs at home next to Jellyfin. It resolves a movie, a season, chosen episodes or
"the next N unwatched episodes for user U" to file paths, and queues them in SQLite.
* **preload-agent** (`cmd/preload-agent`) runs on the VPS as the `rclone-media` user. It polls the API, skips files
already in the cache (it compares allocated blocks, since cache files are sparse), reads the rest at a capped rate,
and reports back. No inbound port is opened on the VPS: the agent dials home over the tunnel.
* Only `/media/Videos/Movies/` (which includes Arabic Shows), `/media2/Videos/tvshows/` and `/media2/Videos/mxtvshows/`
are cacheable. Anything else comes back as `not_cacheable`.
## API
The contract is [`api/openapi.yaml`](api/openapi.yaml) (OpenAPI 3.0). A running server also serves it at
`GET /openapi.json`. Generate a client for any language from it. For example, a Python bot:
```sh
uvx openapi-python-client generate --path api/openapi.yaml
```
Or a TypeScript or Go client with the OpenAPI generator or oapi-codegen. The Go server, client and models in
`internal/api/api.gen.go` are generated by `mise run generate`; never edit that file by hand.
Typical bot flow:
```sh
API=http://127.0.0.1:8125; TOKEN=... # PRELOAD_BOT_TOKEN in ziadpve ~/secrets.txt
curl -H "Authorization: Bearer $TOKEN" "$API/v1/search?q=dark%20matter&type=series"
curl -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -X POST "$API/v1/requests" \
-d '{"itemId":"<id from search>","season":2,"requestedBy":"discord:doge"}'
curl -H "Authorization: Bearer $TOKEN" "$API/v1/requests/1" # per-file progress
```
A series request takes either `season` (optionally with `episodes`) or `next` + `jellyfinUser`. It defaults to the
next 3 unwatched episodes. Limits: 40 files and 150 GB per request (`MAX_FILES`, `MAX_GB`).
Auth is `Authorization: Bearer <token>`. `CLIENT_TOKENS` may use search and requests, and `AGENT_TOKENS` may only use
`/v1/agent/*`. `/v1/health` and `/openapi.json` are open.
## Development
Tooling is managed by [mise](https://mise.jdx.dev/) (`mise.toml`: Go 1.27, oapi-codegen 2.8.2, `CGO_ENABLED=0`).
```sh
mise install # toolchain
mise run generate # regenerate internal/api from the spec
mise run build # bin/preload-api, bin/preload-agent
mise run test
```
## Deployment (as run on 2026-11-05)
| Piece | Where | Config |
|---|---|---|
| preload-api | yveltal, quadlet `deploy/media-preload-api.container`, image built from `Containerfile` | `/etc/media-preload/api.env` (600): `JELLYFIN_URL`, `JELLYFIN_API_KEY`, `CLIENT_TOKENS`, `AGENT_TOKENS`; data in volume `media-preload-data` |
| listen | 127.0.0.1:8125, 10.0.0.38:8125 (LAN), 10.77.0.2:8125 (tunnel) | yveltal's `wg_vps_guard` allows 8125 from 10.77.0.1 only |
| preload-agent | VPS `/usr/local/bin/preload-agent`, unit `deploy/preload-agent.service` | `/etc/preload-agent.env` (root:rclone-media 640): `PRELOAD_API_URL=http://10.77.0.2:8125`, `PRELOAD_AGENT_TOKEN` |
The nightly preload (`edge-preload.timer` on ziadpve, `~/handoffs/homelab/vps-edge/preload.py`) is separate and
still works on its own. It could later file its picks through this API instead.
+9
View File
@@ -0,0 +1,9 @@
# oapi-codegen v2 config: models, a net/http (Go 1.22 ServeMux) strict server, a typed client, and the embedded spec.
package: api
output: internal/api/api.gen.go
generate:
models: true
std-http-server: true
strict-server: true
client: true
embedded-spec: true
+268
View File
@@ -0,0 +1,268 @@
openapi: 3.0.3
info:
title: media-preload
version: 1.0.0
description: |
Warm the VPS media cache (webdav.godemperordoge.org) before someone watches something.
A client (for example the Discord bot) searches the Jellyfin library and files a request
("I will watch Dark Matter season 2"). The API resolves it to media files and queues them.
The preload agent on the VPS claims queued files and reads them through the local rclone
cache, so they stream from the VPS instead of over the home uplink.
Only Movies (including Arabic Shows) and the two TV libraries are cacheable; other files are
reported as `not_cacheable`.
Auth: `Authorization: Bearer <token>`. Client tokens may use the search and request endpoints;
agent tokens may only use `/v1/agent/*`.
servers:
- url: http://127.0.0.1:8125
description: on yveltal
- url: http://10.77.0.2:8125
description: from the VPS, over the wg-home tunnel
security:
- bearerAuth: []
tags:
- name: library
- name: requests
- name: agent
paths:
/v1/health:
get:
operationId: getHealth
summary: Liveness and version
security: []
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Health" }
/v1/search:
get:
operationId: searchLibrary
tags: [library]
summary: Search movies and series in Jellyfin
parameters:
- { name: q, in: query, required: true, schema: { type: string, minLength: 2 }, description: Title to search for }
- { name: type, in: query, required: false, schema: { $ref: "#/components/schemas/MediaType" } }
- { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 25, default: 10 } }
responses:
"200":
description: Matches, best first
content:
application/json:
schema:
type: array
items: { $ref: "#/components/schemas/MediaItem" }
"400": { $ref: "#/components/responses/Problem" }
"401": { $ref: "#/components/responses/Problem" }
/v1/requests:
post:
operationId: createRequest
tags: [requests]
summary: Ask for a movie or episodes to be cached
description: |
For a movie, `season`, `episodes` and `next` are ignored.
For a series, give exactly one of:
- `season` (whole season), optionally with `episodes` (those episode numbers of that season);
- `next` (the next N unwatched episodes for `jellyfinUser`).
With none of them, a series defaults to `next: 3` and then needs `jellyfinUser`.
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/CreateRequest" }
responses:
"201":
description: Queued (files already cached are marked `cached` right away by the agent)
content:
application/json:
schema: { $ref: "#/components/schemas/PreloadRequest" }
"400": { $ref: "#/components/responses/Problem" }
"401": { $ref: "#/components/responses/Problem" }
"404": { $ref: "#/components/responses/Problem" }
get:
operationId: listRequests
tags: [requests]
summary: Recent requests, newest first
parameters:
- { name: status, in: query, required: false, schema: { $ref: "#/components/schemas/RequestStatus" } }
- { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items: { $ref: "#/components/schemas/PreloadRequest" }
"401": { $ref: "#/components/responses/Problem" }
/v1/requests/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: integer, format: int64 } }
get:
operationId: getRequest
tags: [requests]
summary: One request with per-file progress
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/PreloadRequest" }
"401": { $ref: "#/components/responses/Problem" }
"404": { $ref: "#/components/responses/Problem" }
delete:
operationId: cancelRequest
tags: [requests]
summary: Cancel the files of a request that are still queued
responses:
"200":
description: Canceled (files already fetched stay cached)
content:
application/json:
schema: { $ref: "#/components/schemas/PreloadRequest" }
"401": { $ref: "#/components/responses/Problem" }
"404": { $ref: "#/components/responses/Problem" }
/v1/agent/claim:
post:
operationId: claimFile
tags: [agent]
summary: Agent takes the next queued file
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/ClaimRequest" }
responses:
"200":
description: A file to fetch
content:
application/json:
schema: { $ref: "#/components/schemas/AgentJob" }
"204":
description: Nothing queued
"401": { $ref: "#/components/responses/Problem" }
"403": { $ref: "#/components/responses/Problem" }
/v1/agent/files/{fileId}:
parameters:
- { name: fileId, in: path, required: true, schema: { type: integer, format: int64 } }
post:
operationId: reportFile
tags: [agent]
summary: Agent reports the result for a claimed file
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/FileReport" }
responses:
"204": { description: Recorded }
"401": { $ref: "#/components/responses/Problem" }
"403": { $ref: "#/components/responses/Problem" }
"404": { $ref: "#/components/responses/Problem" }
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
responses:
Problem:
description: Error
content:
application/json:
schema: { $ref: "#/components/schemas/Problem" }
schemas:
Problem:
type: object
required: [error]
properties:
error: { type: string, example: "series requests need jellyfinUser when using next" }
Health:
type: object
required: [status, version]
properties:
status: { type: string, example: ok }
version: { type: string }
MediaType:
type: string
enum: [movie, series]
MediaItem:
type: object
required: [id, name, type, cacheable]
properties:
id: { type: string, description: Jellyfin item id }
name: { type: string }
type: { $ref: "#/components/schemas/MediaType" }
year: { type: integer }
library: { type: string, description: "Jellyfin library path prefix, e.g. /media2/Videos/tvshows" }
seasonCount: { type: integer }
cacheable: { type: boolean, description: False when the item lives outside the cached folders }
CreateRequest:
type: object
required: [itemId, requestedBy]
properties:
itemId: { type: string, description: Jellyfin item id from /v1/search }
season: { type: integer, minimum: 0 }
episodes:
type: array
items: { type: integer, minimum: 0 }
description: Episode numbers within `season`
next: { type: integer, minimum: 1, maximum: 20, description: Next N unwatched episodes for jellyfinUser }
jellyfinUser: { type: string, description: Jellyfin user name whose watch progress decides "next" }
requestedBy: { type: string, maxLength: 100, description: Who asked, e.g. a Discord user name }
note: { type: string, maxLength: 500 }
RequestStatus:
type: string
enum: [queued, fetching, done, partial, failed, canceled]
FileStatus:
type: string
enum: [queued, fetching, cached, failed, canceled, not_cacheable]
PreloadFile:
type: object
required: [id, path, title, status, sizeBytes]
properties:
id: { type: integer, format: int64 }
path: { type: string, description: "Path as seen by Jellyfin and webdav, e.g. /media2/Videos/tvshows/..." }
title: { type: string, description: "e.g. Dark Matter S02E08" }
status: { $ref: "#/components/schemas/FileStatus" }
sizeBytes: { type: integer, format: int64 }
fetchedBytes: { type: integer, format: int64 }
error: { type: string }
updatedAt: { type: string, format: date-time }
PreloadRequest:
type: object
required: [id, itemId, title, requestedBy, status, createdAt, files]
properties:
id: { type: integer, format: int64 }
itemId: { type: string }
title: { type: string }
requestedBy: { type: string }
note: { type: string }
status: { $ref: "#/components/schemas/RequestStatus" }
createdAt: { type: string, format: date-time }
files:
type: array
items: { $ref: "#/components/schemas/PreloadFile" }
ClaimRequest:
type: object
required: [agentId]
properties:
agentId: { type: string, example: vps-dcruit2r }
AgentJob:
type: object
required: [fileId, path, sizeBytes]
properties:
fileId: { type: integer, format: int64 }
path: { type: string }
sizeBytes: { type: integer, format: int64 }
FileReport:
type: object
required: [result]
properties:
result:
type: string
enum: [cached, already_cached, failed]
bytes: { type: integer, format: int64, description: Bytes read from home for this file }
error: { type: string }
+193
View File
@@ -0,0 +1,193 @@
// preload-agent: runs on the VPS next to the rclone media cache. It claims queued files from preload-api (over the
// wg-home tunnel) and reads each one in full through the local read-only rclone server, which fills the VFS cache.
//
// Environment:
//
// PRELOAD_API_URL e.g. http://10.77.0.2:8125
// PRELOAD_AGENT_TOKEN bearer token (one of the API's AGENT_TOKENS)
// AGENT_ID default: hostname
// ORIGIN_URL local rclone serve webdav (default http://127.0.0.1:18124)
// CACHE_DIR rclone VFS cache root for that remote (default /var/cache/rclone-media/vfs/home-ro)
// RATE_MBPS read limit in megabytes per second (default 15, about 120 Mbit/s)
// POLL idle poll interval (default 30s)
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"golang.org/x/time/rate"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/api"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/service"
)
var version = "dev"
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
type agent struct {
api *api.ClientWithResponses
id string
origin string
cacheDir string
limiter *rate.Limiter
http *http.Client
log *slog.Logger
}
// cached reports whether the cache already holds (almost) the whole file. rclone's cache files are sparse, so
// allocated blocks, not the apparent size, tell how much is really there.
func (a *agent) cached(path string, size int64) bool {
st, err := os.Stat(a.cacheDir + path)
if err != nil || size <= 0 {
return false
}
if sys, ok := st.Sys().(*syscall.Stat_t); ok {
return float64(sys.Blocks*512) >= 0.98*float64(size)
}
return false
}
type limitedReader struct {
ctx context.Context
r io.Reader
l *rate.Limiter
}
func (lr limitedReader) Read(p []byte) (int, error) {
if len(p) > lr.l.Burst() {
p = p[:lr.l.Burst()]
}
n, err := lr.r.Read(p)
if n > 0 {
if werr := lr.l.WaitN(lr.ctx, n); werr != nil {
return n, werr
}
}
return n, err
}
// fetch reads the file through the local rclone server and returns the bytes read.
func (a *agent) fetch(ctx context.Context, path string) (int64, error) {
u := a.origin + (&url.URL{Path: path}).EscapedPath()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return 0, err
}
resp, err := a.http.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("origin HTTP %d", resp.StatusCode)
}
return io.Copy(io.Discard, limitedReader{ctx, resp.Body, a.limiter})
}
func (a *agent) report(ctx context.Context, id int64, res api.FileReportResult, n int64, ferr error) {
body := api.FileReport{Result: res, Bytes: &n}
if ferr != nil {
msg := ferr.Error()
body.Error = &msg
}
if _, err := a.api.ReportFileWithResponse(ctx, id, body); err != nil {
a.log.Error("report", "file", id, "err", err)
}
}
// once claims and processes one file; it returns false when nothing was queued.
func (a *agent) once(ctx context.Context) (bool, error) {
r, err := a.api.ClaimFileWithResponse(ctx, api.ClaimRequest{AgentId: a.id})
if err != nil {
return false, err
}
switch r.StatusCode() {
case http.StatusNoContent:
return false, nil
case http.StatusOK:
default:
return false, fmt.Errorf("claim: HTTP %d %s", r.StatusCode(), string(r.Body))
}
job := r.JSON200
log := a.log.With("file", job.FileId, "path", job.Path)
switch {
case !service.Cacheable(job.Path):
a.report(ctx, job.FileId, api.FileReportResultFailed, 0, errors.New("agent refused: outside cached folders"))
case a.cached(job.Path, job.SizeBytes):
log.Info("already cached")
a.report(ctx, job.FileId, api.FileReportResultAlreadyCached, 0, nil)
default:
start := time.Now()
n, ferr := a.fetch(ctx, job.Path)
if ferr != nil {
log.Error("fetch failed", "bytes", n, "err", ferr)
a.report(ctx, job.FileId, api.FileReportResultFailed, n, ferr)
} else {
mbps := float64(n) * 8 / 1e6 / time.Since(start).Seconds()
log.Info("cached", "bytes", n, "mbit_s", fmt.Sprintf("%.0f", mbps))
a.report(ctx, job.FileId, api.FileReportResultCached, n, nil)
}
}
return true, nil
}
func main() {
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
apiURL, token := os.Getenv("PRELOAD_API_URL"), os.Getenv("PRELOAD_AGENT_TOKEN")
if apiURL == "" || token == "" {
log.Error("PRELOAD_API_URL and PRELOAD_AGENT_TOKEN are required")
os.Exit(2)
}
host, _ := os.Hostname()
mbps, _ := strconv.ParseFloat(env("RATE_MBPS", "15"), 64)
poll, err := time.ParseDuration(env("POLL", "30s"))
if err != nil {
poll = 30 * time.Second
}
cl, err := api.NewClientWithResponses(apiURL, api.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
api.WithRequestEditorFn(func(ctx context.Context, req *http.Request) error {
req.Header.Set("Authorization", "Bearer "+token)
return nil
}))
if err != nil {
log.Error("client", "err", err)
os.Exit(2)
}
burst := 1 << 20
a := &agent{api: cl, id: env("AGENT_ID", host), origin: env("ORIGIN_URL", "http://127.0.0.1:18124"),
cacheDir: env("CACHE_DIR", "/var/cache/rclone-media/vfs/home-ro"),
limiter: rate.NewLimiter(rate.Limit(mbps*1e6), burst), http: &http.Client{}, log: log}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
log.Info("agent started", "id", a.id, "api", apiURL, "rate_MBps", mbps, "version", version)
for ctx.Err() == nil {
worked, err := a.once(ctx)
if err != nil {
log.Error("cycle", "err", err)
}
if !worked || err != nil {
select {
case <-ctx.Done():
case <-time.After(poll):
}
}
}
}
+167
View File
@@ -0,0 +1,167 @@
// preload-api: the media-preload control plane. Runs at home (yveltal), next to Jellyfin.
//
// Environment:
//
// LISTEN address to listen on (default :8125)
// DB_PATH SQLite file (default /data/preload.db)
// JELLYFIN_URL e.g. http://10.0.0.38:8096
// JELLYFIN_API_KEY Jellyfin API key
// CLIENT_TOKENS comma-separated bearer tokens for /v1/search and /v1/requests (e.g. the Discord bot)
// AGENT_TOKENS comma-separated bearer tokens for /v1/agent/* (the VPS preload agent)
// MAX_FILES per request (default 40)
// MAX_GB per request (default 150)
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/api"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/jellyfin"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/service"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/store"
)
var version = "dev" // set with -ldflags "-X main.version=..."
func env(k, def string) string {
if v := os.Getenv(k); v != "" {
return v
}
return def
}
func tokens(k string) [][]byte {
var out [][]byte
for _, t := range strings.Split(os.Getenv(k), ",") {
if t = strings.TrimSpace(t); t != "" {
out = append(out, []byte(t))
}
}
return out
}
func match(got string, list [][]byte) bool {
ok := false
for _, t := range list {
if subtle.ConstantTimeCompare([]byte(got), t) == 1 {
ok = true
}
}
return ok
}
func writeProblem(w http.ResponseWriter, code int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(api.Problem{Error: msg})
}
// auth enforces bearer tokens by role: agent tokens only for /v1/agent/*, client tokens for everything else.
// /v1/health and /openapi.json are open.
func auth(next http.Handler, clients, agents [][]byte) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/health" || r.URL.Path == "/openapi.json" {
next.ServeHTTP(w, r)
return
}
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || tok == "" {
writeProblem(w, http.StatusUnauthorized, "missing bearer token")
return
}
isAgentPath := strings.HasPrefix(r.URL.Path, "/v1/agent/")
switch {
case isAgentPath && match(tok, agents), !isAgentPath && match(tok, clients):
next.ServeHTTP(w, r)
case match(tok, agents) || match(tok, clients):
writeProblem(w, http.StatusForbidden, "this token may not use "+r.URL.Path)
default:
writeProblem(w, http.StatusUnauthorized, "invalid token")
}
})
}
func logRequests(next http.Handler, log *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, code: 200}
next.ServeHTTP(rec, r)
if r.URL.Path != "/v1/agent/claim" || rec.code != http.StatusNoContent { // idle polls are noise
log.Info("http", "method", r.Method, "path", r.URL.Path, "status", rec.code, "ms", time.Since(start).Milliseconds())
}
})
}
type statusRecorder struct {
http.ResponseWriter
code int
}
func (s *statusRecorder) WriteHeader(c int) { s.code = c; s.ResponseWriter.WriteHeader(c) }
func main() {
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
clients, agents := tokens("CLIENT_TOKENS"), tokens("AGENT_TOKENS")
if len(clients) == 0 || len(agents) == 0 || os.Getenv("JELLYFIN_API_KEY") == "" {
log.Error("CLIENT_TOKENS, AGENT_TOKENS and JELLYFIN_API_KEY are required")
os.Exit(2)
}
st, err := store.Open(env("DB_PATH", "/data/preload.db"))
if err != nil {
log.Error("open db", "err", err)
os.Exit(1)
}
defer st.Close()
maxFiles, _ := strconv.Atoi(env("MAX_FILES", "40"))
maxGB, _ := strconv.ParseFloat(env("MAX_GB", "150"), 64)
svc := &service.Service{Store: st, Jellyfin: jellyfin.New(env("JELLYFIN_URL", "http://10.0.0.38:8096"), os.Getenv("JELLYFIN_API_KEY")),
Version: version, MaxFiles: maxFiles, MaxBytes: int64(maxGB * 1e9), StaleClaim: 3 * time.Hour, Log: log}
mux := http.NewServeMux()
strict := api.NewStrictHandlerWithOptions(svc, nil, api.StrictHTTPServerOptions{
RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
writeProblem(w, http.StatusBadRequest, err.Error())
},
ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
log.Error("handler", "path", r.URL.Path, "err", err)
writeProblem(w, http.StatusBadGateway, "upstream error: "+err.Error())
},
})
api.HandlerWithOptions(strict, api.StdHTTPServerOptions{BaseRouter: mux,
ErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { writeProblem(w, http.StatusBadRequest, err.Error()) }})
mux.HandleFunc("GET /openapi.json", func(w http.ResponseWriter, r *http.Request) {
spec, err := api.GetSwagger()
if err != nil {
writeProblem(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(spec)
})
srv := &http.Server{Addr: env("LISTEN", ":8125"), Handler: logRequests(auth(mux, clients, agents), log),
ReadHeaderTimeout: 10 * time.Second}
go func() {
log.Info("listening", "addr", srv.Addr, "version", version)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Error("serve", "err", err)
os.Exit(1)
}
}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}
+20
View File
@@ -0,0 +1,20 @@
# Quadlet for yveltal: /etc/containers/systemd/media-preload-api.container
[Unit]
Description=media-preload API (VPS cache warm-up requests)
After=network-online.target wg-quick@wg-vps.service
[Container]
Image=localhost/media-preload-api:latest
ContainerName=media-preload-api
EnvironmentFile=/etc/media-preload/api.env
Volume=media-preload-data:/data:U
# localhost for a bot on yveltal, LAN for Kuma, the tunnel for the VPS agent (and a bot on the VPS)
PublishPort=127.0.0.1:8125:8125
PublishPort=10.0.0.38:8125:8125
PublishPort=10.77.0.2:8125:8125
[Service]
Restart=always
[Install]
WantedBy=default.target
+19
View File
@@ -0,0 +1,19 @@
# systemd unit for the VPS: /etc/systemd/system/preload-agent.service
[Unit]
Description=media-preload agent (fills the rclone media cache on request)
After=network-online.target wg-quick@wg-home.service rclone-media.service
Wants=rclone-media.service
[Service]
User=rclone-media
EnvironmentFile=/etc/preload-agent.env
ExecStart=/usr/local/bin/preload-agent
Restart=always
RestartSec=10
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
+30
View File
@@ -0,0 +1,30 @@
module gitea.godemperordoge.org/ziadarafat/media-preload
go 1.27.3
require (
github.com/getkin/kin-openapi v0.152.0
github.com/oapi-codegen/runtime v1.8.0
golang.org/x/time v0.14.0
modernc.org/sqlite v1.61.1
)
require (
github.com/apapsch/go-jsonmerge/v2 v2.0.0 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect
github.com/go-openapi/jsonpointer v0.22.5 // indirect
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.1.0 // indirect
github.com/oasdiff/yaml v0.1.1 // indirect
github.com/oasdiff/yaml3 v0.0.14 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.32.0 // indirect
modernc.org/libc v1.79.0 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
)
+101
View File
@@ -0,0 +1,101 @@
github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk=
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/getkin/kin-openapi v0.152.0 h1:XRVo77lMRyOGMHf1paMu9lxX3wzuQDZeprssZJnz/x8=
github.com/getkin/kin-openapi v0.152.0/go.mod h1:1+BHDzstro+P5CKtPy1X4PfofnFgmRe6uvMy9+r9fKY=
github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
github.com/go-openapi/jsonpointer v0.22.5/go.mod h1:gyUR3sCvGSWchA2sUBJGluYMbe1zazrYWIkWPjjMUY0=
github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3US3uUYSFhSo=
github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs=
github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/juju/gnuflag v0.0.0-20171113085948-2ce1bb71843d/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/3KntMs=
github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY=
github.com/oapi-codegen/runtime v1.8.0 h1:RJzEgQSJQADEPaG1cYuSCKYai/cCVRE2xnkrqhJs/3c=
github.com/oapi-codegen/runtime v1.8.0/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU=
github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY=
github.com/oasdiff/yaml v0.1.1/go.mod h1:EYJNoyktvWMJ0Hmhx+6qTaqMOsalUaRGT8Sj1hNcegU=
github.com/oasdiff/yaml3 v0.0.14 h1:aLJee3hxBK2H5wdXd9iPcIXb93Nty1Ge0pT171eHtkw=
github.com/oasdiff/yaml3 v0.0.14/go.mod h1:csto2xfDjYccdUn/yw/bPjj/cYTdp6HtFA0J4TWG+gg=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad/go.mod h1:qLr4V1qq6nMqFKkMo8ZTx3f+BZEkzsRUY10Xsm2mwU0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys=
modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4=
modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY=
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o=
modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8=
modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.61.1 h1:TBEE49wz7VlxS+qXRXMQiPUZYOXHJ4ku83daYv1fe04=
modernc.org/sqlite v1.61.1/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
File diff suppressed because it is too large. Load diff
+164
View File
@@ -0,0 +1,164 @@
// Package jellyfin is a minimal Jellyfin API client: just what media-preload needs to turn
// "I will watch X" into file paths.
package jellyfin
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// Client talks to Jellyfin with an API key.
type Client struct {
BaseURL string
APIKey string
HTTP *http.Client
}
// New returns a Client with a 30 s timeout.
func New(baseURL, apiKey string) *Client {
return &Client{BaseURL: strings.TrimRight(baseURL, "/"), APIKey: apiKey, HTTP: &http.Client{Timeout: 30 * time.Second}}
}
// Item is the subset of a Jellyfin BaseItemDto that media-preload uses.
type Item struct {
ID string `json:"Id"`
Name string `json:"Name"`
Type string `json:"Type"` // Movie, Series, Episode
ProductionYear int `json:"ProductionYear"`
Path string `json:"Path"`
ChildCount int `json:"ChildCount"`
IndexNumber int `json:"IndexNumber"`
ParentIndexNumber int `json:"ParentIndexNumber"`
SeriesName string `json:"SeriesName"`
SeriesID string `json:"SeriesId"`
MediaSources []MediaSource `json:"MediaSources"`
}
// MediaSource carries the file size.
type MediaSource struct {
Path string `json:"Path"`
Size int64 `json:"Size"`
}
// Size returns the size of the item's first media source, or 0.
func (i Item) Size() int64 {
if len(i.MediaSources) > 0 {
return i.MediaSources[0].Size
}
return 0
}
// EpisodeTitle renders "Series S01E02" for episodes and the plain name otherwise.
func (i Item) EpisodeTitle() string {
if i.Type == "Episode" {
return fmt.Sprintf("%s S%02dE%02d", i.SeriesName, i.ParentIndexNumber, i.IndexNumber)
}
return i.Name
}
type itemsResult struct {
Items []Item `json:"Items"`
}
// User is a Jellyfin user.
type User struct {
ID string `json:"Id"`
Name string `json:"Name"`
}
const fields = "Path,MediaSources,ProductionYear,ChildCount"
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error {
u := c.BaseURL + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", `MediaBrowser Token="`+c.APIKey+`"`)
resp, err := c.HTTP.Do(req)
if err != nil {
return fmt.Errorf("jellyfin %s: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("jellyfin %s: HTTP %d", path, resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(out)
}
// Search finds movies and/or series by title. types holds "Movie" and/or "Series".
func (c *Client) Search(ctx context.Context, term string, types []string, limit int) ([]Item, error) {
var r itemsResult
q := url.Values{"searchTerm": {term}, "IncludeItemTypes": {strings.Join(types, ",")}, "Recursive": {"true"},
"Limit": {strconv.Itoa(limit)}, "Fields": {fields}}
return r.Items, c.get(ctx, "/Items", q, &r)
}
// Item fetches one item by id; it returns (nil, nil) when it does not exist.
func (c *Client) Item(ctx context.Context, id string) (*Item, error) {
var r itemsResult
if err := c.get(ctx, "/Items", url.Values{"ids": {id}, "Fields": {fields}}, &r); err != nil {
return nil, err
}
if len(r.Items) == 0 {
return nil, nil
}
return &r.Items[0], nil
}
// Episodes lists a series' episodes. season < 0 means all seasons. With userID and startItemID it starts at that
// episode (inclusive) in watch order. limit <= 0 means no limit.
func (c *Client) Episodes(ctx context.Context, seriesID string, season int, userID, startItemID string, limit int) ([]Item, error) {
var r itemsResult
q := url.Values{"Fields": {fields}}
if season >= 0 {
q.Set("season", strconv.Itoa(season))
}
if userID != "" {
q.Set("userId", userID)
}
if startItemID != "" {
q.Set("startItemId", startItemID)
}
if limit > 0 {
q.Set("limit", strconv.Itoa(limit))
}
return r.Items, c.get(ctx, "/Shows/"+url.PathEscape(seriesID)+"/Episodes", q, &r)
}
// NextUp returns the next episode of a series for a user, or nil when they are caught up.
func (c *Client) NextUp(ctx context.Context, seriesID, userID string) (*Item, error) {
var r itemsResult
q := url.Values{"seriesId": {seriesID}, "userId": {userID}, "Fields": {fields}, "Limit": {"1"},
"enableResumable": {"true"}, "disableFirstEpisode": {"false"}}
if err := c.get(ctx, "/Shows/NextUp", q, &r); err != nil {
return nil, err
}
if len(r.Items) == 0 {
return nil, nil
}
return &r.Items[0], nil
}
// UserByName finds a user case-insensitively; it returns (nil, nil) when there is none.
func (c *Client) UserByName(ctx context.Context, name string) (*User, error) {
var users []User
if err := c.get(ctx, "/Users", nil, &users); err != nil {
return nil, err
}
for _, u := range users {
if strings.EqualFold(u.Name, name) {
return &u, nil
}
}
return nil, nil
}
+346
View File
@@ -0,0 +1,346 @@
// Package service implements the media-preload API (api.StrictServerInterface).
package service
import (
"context"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/api"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/jellyfin"
"gitea.godemperordoge.org/ziadarafat/media-preload/internal/store"
)
// CachedPrefixes are the folders the VPS cache serves (paths as Jellyfin and webdav see them).
var CachedPrefixes = []string{"/media/Videos/Movies/", "/media2/Videos/tvshows/", "/media2/Videos/mxtvshows/"}
// Cacheable reports whether a path is inside the cached folders.
func Cacheable(path string) bool {
if strings.Contains(path, "..") {
return false
}
for _, p := range CachedPrefixes {
if strings.HasPrefix(path, p) {
return true
}
}
return false
}
// Service holds the dependencies.
type Service struct {
Store *store.Store
Jellyfin *jellyfin.Client
Version string
MaxFiles int // per request
MaxBytes int64 // per request
StaleClaim time.Duration // a "fetching" file older than this is re-queued
Log *slog.Logger
}
var _ api.StrictServerInterface = (*Service)(nil)
func problem(msg string, a ...any) api.Problem { return api.Problem{Error: fmt.Sprintf(msg, a...)} }
func ptr[T any](v T) *T { return &v }
// GetHealth reports liveness.
func (s *Service) GetHealth(ctx context.Context, _ api.GetHealthRequestObject) (api.GetHealthResponseObject, error) {
return api.GetHealth200JSONResponse{Status: "ok", Version: s.Version}, nil
}
// SearchLibrary searches Jellyfin for movies and series.
func (s *Service) SearchLibrary(ctx context.Context, req api.SearchLibraryRequestObject) (api.SearchLibraryResponseObject, error) {
q := strings.TrimSpace(req.Params.Q)
if len(q) < 2 {
return api.SearchLibrary400JSONResponse{ProblemJSONResponse: api.ProblemJSONResponse(problem("q needs at least 2 characters"))}, nil
}
types := []string{"Movie", "Series"}
if req.Params.Type != nil {
types = map[api.MediaType][]string{api.Movie: {"Movie"}, api.Series: {"Series"}}[*req.Params.Type]
}
limit := 10
if req.Params.Limit != nil {
limit = *req.Params.Limit
}
items, err := s.Jellyfin.Search(ctx, q, types, limit)
if err != nil {
return nil, err
}
out := api.SearchLibrary200JSONResponse{}
for _, it := range items {
m := api.MediaItem{Id: it.ID, Name: it.Name, Type: api.Movie, Cacheable: Cacheable(withSlash(it.Path)), Library: ptr(library(it.Path))}
if it.Type == "Series" {
m.Type = api.Series
if it.ChildCount > 0 {
m.SeasonCount = ptr(it.ChildCount)
}
}
if it.ProductionYear > 0 {
m.Year = ptr(it.ProductionYear)
}
out = append(out, m)
}
return out, nil
}
// CreateRequest resolves a movie or episodes to files and queues them.
func (s *Service) CreateRequest(ctx context.Context, req api.CreateRequestRequestObject) (api.CreateRequestResponseObject, error) {
b := req.Body
bad := func(msg string, a ...any) (api.CreateRequestResponseObject, error) {
return api.CreateRequest400JSONResponse{ProblemJSONResponse: api.ProblemJSONResponse(problem(msg, a...))}, nil
}
if strings.TrimSpace(b.RequestedBy) == "" {
return bad("requestedBy is required")
}
item, err := s.Jellyfin.Item(ctx, b.ItemId)
if err != nil {
return nil, err
}
if item == nil {
return api.CreateRequest404JSONResponse(problem("no Jellyfin item %q", b.ItemId)), nil
}
var picked []jellyfin.Item
title := item.Name
switch item.Type {
case "Movie", "Episode":
picked = []jellyfin.Item{*item}
title = item.EpisodeTitle()
case "Series":
picked, title, err = s.pickEpisodes(ctx, item, b)
if err != nil {
var ue userError
if errors.As(err, &ue) {
return bad("%s", ue.Error())
}
return nil, err
}
default:
return bad("item %q is a %s; request a movie, a series or an episode", item.Name, item.Type)
}
if len(picked) == 0 {
return bad("nothing to cache for %s with those options", item.Name)
}
if len(picked) > s.MaxFiles {
return bad("that is %d files; the limit is %d per request", len(picked), s.MaxFiles)
}
r := store.Request{ItemID: item.ID, Title: title, RequestedBy: b.RequestedBy}
if b.Note != nil {
r.Note = *b.Note
}
var total int64
for _, ep := range picked {
f := store.File{Path: ep.Path, Title: ep.EpisodeTitle(), SizeBytes: ep.Size(), Status: store.Queued}
if !Cacheable(ep.Path) {
f.Status, f.Error = store.NotCacheable, "outside the cached folders"
} else {
total += f.SizeBytes
}
r.Files = append(r.Files, f)
}
if total > s.MaxBytes {
return bad("that is %.1f GB; the limit is %.0f GB per request", float64(total)/1e9, float64(s.MaxBytes)/1e9)
}
id, err := s.Store.CreateRequest(ctx, r)
if err != nil {
return nil, err
}
s.Log.Info("request queued", "id", id, "title", title, "files", len(r.Files), "bytes", total, "by", b.RequestedBy)
got, err := s.Store.GetRequest(ctx, id)
if err != nil {
return nil, err
}
return api.CreateRequest201JSONResponse(toAPI(got)), nil
}
type userError struct{ msg string }
func (e userError) Error() string { return e.msg }
func (s *Service) pickEpisodes(ctx context.Context, series *jellyfin.Item, b *api.CreateRequestJSONRequestBody) ([]jellyfin.Item, string, error) {
if b.Season != nil {
eps, err := s.Jellyfin.Episodes(ctx, series.ID, *b.Season, "", "", 0)
if err != nil {
return nil, "", err
}
if b.Episodes == nil || len(*b.Episodes) == 0 {
return eps, fmt.Sprintf("%s season %d", series.Name, *b.Season), nil
}
want := map[int]bool{}
for _, n := range *b.Episodes {
want[n] = true
}
var out []jellyfin.Item
for _, e := range eps {
if want[e.IndexNumber] {
out = append(out, e)
}
}
return out, fmt.Sprintf("%s season %d, %d episode(s)", series.Name, *b.Season, len(out)), nil
}
next := 3
if b.Next != nil {
next = *b.Next
}
if b.JellyfinUser == nil || *b.JellyfinUser == "" {
return nil, "", userError{"series requests need jellyfinUser (to find the next unwatched episode) or a season"}
}
u, err := s.Jellyfin.UserByName(ctx, *b.JellyfinUser)
if err != nil {
return nil, "", err
}
if u == nil {
return nil, "", userError{fmt.Sprintf("no Jellyfin user %q", *b.JellyfinUser)}
}
start, err := s.Jellyfin.NextUp(ctx, series.ID, u.ID)
if err != nil {
return nil, "", err
}
var eps []jellyfin.Item
if start == nil { // never started: from the first episode
eps, err = s.Jellyfin.Episodes(ctx, series.ID, -1, u.ID, "", next)
} else {
eps, err = s.Jellyfin.Episodes(ctx, series.ID, -1, u.ID, start.ID, next)
}
if err != nil {
return nil, "", err
}
return eps, fmt.Sprintf("%s, next %d for %s", series.Name, len(eps), u.Name), nil
}
// ListRequests returns recent requests.
func (s *Service) ListRequests(ctx context.Context, req api.ListRequestsRequestObject) (api.ListRequestsResponseObject, error) {
limit := 20
if req.Params.Limit != nil {
limit = *req.Params.Limit
}
fetch := limit
if req.Params.Status != nil {
fetch = 500 // status is derived, so filter after loading
}
ids, err := s.Store.ListRequestIDs(ctx, fetch)
if err != nil {
return nil, err
}
out := api.ListRequests200JSONResponse{}
for _, id := range ids {
r, err := s.Store.GetRequest(ctx, id)
if err != nil {
return nil, err
}
a := toAPI(r)
if req.Params.Status != nil && a.Status != *req.Params.Status {
continue
}
out = append(out, a)
if len(out) == limit {
break
}
}
return out, nil
}
// GetRequest returns one request.
func (s *Service) GetRequest(ctx context.Context, req api.GetRequestRequestObject) (api.GetRequestResponseObject, error) {
r, err := s.Store.GetRequest(ctx, req.Id)
if errors.Is(err, store.ErrNotFound) {
return api.GetRequest404JSONResponse(problem("no request %d", req.Id)), nil
} else if err != nil {
return nil, err
}
return api.GetRequest200JSONResponse(toAPI(r)), nil
}
// CancelRequest cancels a request's queued files.
func (s *Service) CancelRequest(ctx context.Context, req api.CancelRequestRequestObject) (api.CancelRequestResponseObject, error) {
if err := s.Store.Cancel(ctx, req.Id); errors.Is(err, store.ErrNotFound) {
return api.CancelRequest404JSONResponse(problem("no request %d", req.Id)), nil
} else if err != nil {
return nil, err
}
r, err := s.Store.GetRequest(ctx, req.Id)
if err != nil {
return nil, err
}
return api.CancelRequest200JSONResponse(toAPI(r)), nil
}
// ClaimFile hands the next queued file to an agent.
func (s *Service) ClaimFile(ctx context.Context, req api.ClaimFileRequestObject) (api.ClaimFileResponseObject, error) {
f, err := s.Store.Claim(ctx, req.Body.AgentId, s.StaleClaim)
if err != nil {
return nil, err
}
if f == nil {
return api.ClaimFile204Response{}, nil
}
s.Log.Info("claimed", "file", f.ID, "title", f.Title, "agent", req.Body.AgentId)
return api.ClaimFile200JSONResponse{FileId: f.ID, Path: f.Path, SizeBytes: f.SizeBytes}, nil
}
// ReportFile records an agent's result.
func (s *Service) ReportFile(ctx context.Context, req api.ReportFileRequestObject) (api.ReportFileResponseObject, error) {
status := store.Cached
if req.Body.Result == api.FileReportResultFailed {
status = store.Failed
}
var bytes int64
if req.Body.Bytes != nil {
bytes = *req.Body.Bytes
}
msg := ""
if req.Body.Error != nil {
msg = *req.Body.Error
}
if err := s.Store.Report(ctx, req.FileId, status, bytes, msg); errors.Is(err, store.ErrNotFound) {
return api.ReportFile404JSONResponse(problem("file %d is not being fetched", req.FileId)), nil
} else if err != nil {
return nil, err
}
s.Log.Info("reported", "file", req.FileId, "result", req.Body.Result, "bytes", bytes, "error", msg)
return api.ReportFile204Response{}, nil
}
func toAPI(r *store.Request) api.PreloadRequest {
a := api.PreloadRequest{Id: r.ID, ItemId: r.ItemID, Title: r.Title, RequestedBy: r.RequestedBy, CreatedAt: r.CreatedAt,
Status: api.RequestStatus(store.Status(r.Files)), Files: []api.PreloadFile{}}
if r.Note != "" {
a.Note = ptr(r.Note)
}
for _, f := range r.Files {
pf := api.PreloadFile{Id: f.ID, Path: f.Path, Title: f.Title, Status: api.FileStatus(f.Status), SizeBytes: f.SizeBytes,
UpdatedAt: ptr(f.UpdatedAt)}
if f.FetchedBytes > 0 {
pf.FetchedBytes = ptr(f.FetchedBytes)
}
if f.Error != "" {
pf.Error = ptr(f.Error)
}
a.Files = append(a.Files, pf)
}
return a
}
func withSlash(p string) string {
if strings.HasSuffix(p, "/") {
return p
}
return p + "/"
}
// library returns the cached-folder prefix a path sits under, or its first three components.
func library(p string) string {
for _, c := range CachedPrefixes {
if strings.HasPrefix(withSlash(p), c) {
return strings.TrimSuffix(c, "/")
}
}
parts := strings.SplitN(strings.TrimPrefix(p, "/"), "/", 4)
if len(parts) >= 3 {
return "/" + strings.Join(parts[:3], "/")
}
return p
}
+20
View File
@@ -0,0 +1,20 @@
package service
import "testing"
func TestCacheable(t *testing.T) {
for p, want := range map[string]bool{
"/media/Videos/Movies/Movies/Alien (1979)/a.mkv": true,
"/media/Videos/Movies/Arabic Shows/x/e1.mkv": true,
"/media2/Videos/tvshows/Dark Matter/S01E01.mkv": true,
"/media2/Videos/mxtvshows/x.mkv": true,
"/media2/Videos/movies/b.mkv": false,
"/media/Music/MyLibrary/song.flac": false,
"/media2/Videos/tvshows/../../../etc/passwd": false,
"/media2/Videos/tvshowsX/a.mkv": false,
} {
if got := Cacheable(p); got != want {
t.Errorf("Cacheable(%q) = %v, want %v", p, got, want)
}
}
}
+240
View File
@@ -0,0 +1,240 @@
// Package store keeps preload requests and their files in SQLite (pure Go driver, no cgo).
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
_ "modernc.org/sqlite"
)
// File statuses (mirror the OpenAPI FileStatus enum).
const (
Queued = "queued"
Fetching = "fetching"
Cached = "cached"
Failed = "failed"
Canceled = "canceled"
NotCacheable = "not_cacheable"
)
// ErrNotFound is returned when a request or file does not exist.
var ErrNotFound = errors.New("not found")
// Request is one "I will watch X" ask.
type Request struct {
ID int64
ItemID string
Title string
RequestedBy string
Note string
CreatedAt time.Time
Files []File
}
// File is one media file belonging to a request.
type File struct {
ID int64
RequestID int64
Path string
Title string
SizeBytes int64
Status string
FetchedBytes int64
Error string
UpdatedAt time.Time
}
// Store wraps the database.
type Store struct{ db *sql.DB }
const schema = `
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS requests (
id INTEGER PRIMARY KEY,
item_id TEXT NOT NULL,
title TEXT NOT NULL,
requested_by TEXT NOT NULL,
note TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY,
request_id INTEGER NOT NULL REFERENCES requests(id),
path TEXT NOT NULL,
title TEXT NOT NULL,
size_bytes INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL,
fetched_bytes INTEGER NOT NULL DEFAULT 0,
error TEXT NOT NULL DEFAULT '',
agent_id TEXT NOT NULL DEFAULT '',
claimed_at INTEGER NOT NULL DEFAULT 0,
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS files_status ON files(status, id);
CREATE INDEX IF NOT EXISTS files_request ON files(request_id);
`
// Open opens (and migrates) the database at path.
func Open(path string) (*Store, error) {
db, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)")
if err != nil {
return nil, err
}
db.SetMaxOpenConns(1) // SQLite: one writer; keeps claims race-free
if _, err := db.Exec(schema); err != nil {
return nil, fmt.Errorf("migrate: %w", err)
}
return &Store{db: db}, nil
}
// Close closes the database.
func (s *Store) Close() error { return s.db.Close() }
// CreateRequest stores a request and its files and returns the new request id.
func (s *Store) CreateRequest(ctx context.Context, r Request) (int64, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
now := time.Now().Unix()
res, err := tx.ExecContext(ctx, `INSERT INTO requests(item_id,title,requested_by,note,created_at) VALUES(?,?,?,?,?)`,
r.ItemID, r.Title, r.RequestedBy, r.Note, now)
if err != nil {
return 0, err
}
id, _ := res.LastInsertId()
for _, f := range r.Files {
if _, err := tx.ExecContext(ctx, `INSERT INTO files(request_id,path,title,size_bytes,status,error,updated_at) VALUES(?,?,?,?,?,?,?)`,
id, f.Path, f.Title, f.SizeBytes, f.Status, f.Error, now); err != nil {
return 0, err
}
}
return id, tx.Commit()
}
// GetRequest loads one request with its files.
func (s *Store) GetRequest(ctx context.Context, id int64) (*Request, error) {
r := Request{ID: id}
var created int64
err := s.db.QueryRowContext(ctx, `SELECT item_id,title,requested_by,note,created_at FROM requests WHERE id=?`, id).
Scan(&r.ItemID, &r.Title, &r.RequestedBy, &r.Note, &created)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
} else if err != nil {
return nil, err
}
r.CreatedAt = time.Unix(created, 0).UTC()
rows, err := s.db.QueryContext(ctx, `SELECT id,path,title,size_bytes,status,fetched_bytes,error,updated_at FROM files WHERE request_id=? ORDER BY id`, id)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
f := File{RequestID: id}
var upd int64
if err := rows.Scan(&f.ID, &f.Path, &f.Title, &f.SizeBytes, &f.Status, &f.FetchedBytes, &f.Error, &upd); err != nil {
return nil, err
}
f.UpdatedAt = time.Unix(upd, 0).UTC()
r.Files = append(r.Files, f)
}
return &r, rows.Err()
}
// ListRequestIDs returns the newest request ids.
func (s *Store) ListRequestIDs(ctx context.Context, limit int) ([]int64, error) {
rows, err := s.db.QueryContext(ctx, `SELECT id FROM requests ORDER BY id DESC LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
ids = append(ids, id)
}
return ids, rows.Err()
}
// Cancel marks a request's queued files canceled.
func (s *Store) Cancel(ctx context.Context, id int64) error {
if _, err := s.GetRequest(ctx, id); err != nil {
return err
}
_, err := s.db.ExecContext(ctx, `UPDATE files SET status=?, updated_at=? WHERE request_id=? AND status=?`,
Canceled, time.Now().Unix(), id, Queued)
return err
}
// Claim hands the oldest queued file to an agent. Files stuck in "fetching" longer than stale go back to the queue
// first, so a crashed agent does not strand them. It returns (nil, nil) when nothing is queued.
func (s *Store) Claim(ctx context.Context, agentID string, stale time.Duration) (*File, error) {
now := time.Now()
if _, err := s.db.ExecContext(ctx, `UPDATE files SET status=?, agent_id='' WHERE status=? AND claimed_at < ?`,
Queued, Fetching, now.Add(-stale).Unix()); err != nil {
return nil, err
}
f := File{}
err := s.db.QueryRowContext(ctx, `UPDATE files SET status=?, agent_id=?, claimed_at=?, updated_at=?
WHERE id = (SELECT id FROM files WHERE status=? ORDER BY id LIMIT 1)
RETURNING id, request_id, path, title, size_bytes`, Fetching, agentID, now.Unix(), now.Unix(), Queued).
Scan(&f.ID, &f.RequestID, &f.Path, &f.Title, &f.SizeBytes)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return &f, err
}
// Report records an agent's result for a claimed file.
func (s *Store) Report(ctx context.Context, fileID int64, status string, bytes int64, errMsg string) error {
res, err := s.db.ExecContext(ctx, `UPDATE files SET status=?, fetched_bytes=?, error=?, updated_at=? WHERE id=? AND status=?`,
status, bytes, errMsg, time.Now().Unix(), fileID, Fetching)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// Status derives a request's overall status from its files.
func Status(files []File) string {
var queued, fetching, cached, failed, canceled int
for _, f := range files {
switch f.Status {
case Queued:
queued++
case Fetching:
fetching++
case Cached:
cached++
case Canceled:
canceled++
default: // failed, not_cacheable
failed++
}
}
switch {
case fetching > 0 || (queued > 0 && cached+failed > 0):
return "fetching"
case queued > 0:
return "queued"
case cached > 0 && failed == 0:
return "done"
case cached > 0:
return "partial"
case canceled > 0 && failed == 0:
return "canceled"
default:
return "failed"
}
}
+80
View File
@@ -0,0 +1,80 @@
package store
import (
"context"
"path/filepath"
"testing"
"time"
)
func TestStatus(t *testing.T) {
f := func(s ...string) []File {
var out []File
for _, x := range s {
out = append(out, File{Status: x})
}
return out
}
cases := map[string][]File{
"queued": f(Queued, Queued),
"fetching": f(Cached, Queued),
"done": f(Cached, Cached, Canceled),
"partial": f(Cached, Failed),
"failed": f(NotCacheable),
"canceled": f(Canceled),
}
for want, files := range cases {
if got := Status(files); got != want {
t.Errorf("Status(%v) = %s, want %s", files, got, want)
}
}
}
func TestClaimReportCancel(t *testing.T) {
ctx := context.Background()
s, err := Open(filepath.Join(t.TempDir(), "t.db"))
if err != nil {
t.Fatal(err)
}
id, err := s.CreateRequest(ctx, Request{ItemID: "x", Title: "Show", RequestedBy: "test", Files: []File{
{Path: "/media2/Videos/tvshows/a.mkv", Title: "a", SizeBytes: 10, Status: Queued},
{Path: "/media2/Videos/tvshows/b.mkv", Title: "b", SizeBytes: 20, Status: Queued},
}})
if err != nil {
t.Fatal(err)
}
f, err := s.Claim(ctx, "agent", time.Hour)
if err != nil || f == nil || f.Title != "a" {
t.Fatalf("claim 1: %v %+v", err, f)
}
if err := s.Report(ctx, f.ID, Cached, 10, ""); err != nil {
t.Fatal(err)
}
if err := s.Report(ctx, f.ID, Cached, 10, ""); err != ErrNotFound {
t.Fatalf("second report on a finished file should be ErrNotFound, got %v", err)
}
if err := s.Cancel(ctx, id); err != nil {
t.Fatal(err)
}
if f, _ := s.Claim(ctx, "agent", time.Hour); f != nil {
t.Fatalf("canceled file was claimed: %+v", f)
}
r, _ := s.GetRequest(ctx, id)
if got := Status(r.Files); got != "done" {
t.Fatalf("status after cancel = %s, want done (1 cached, 1 canceled)", got)
}
}
func TestStaleClaimRequeued(t *testing.T) {
ctx := context.Background()
s, _ := Open(filepath.Join(t.TempDir(), "t.db"))
_, _ = s.CreateRequest(ctx, Request{ItemID: "x", Title: "M", RequestedBy: "t", Files: []File{{Path: "/media/Videos/Movies/m.mkv", Title: "m", Status: Queued}}})
f1, _ := s.Claim(ctx, "a1", time.Hour)
if f2, _ := s.Claim(ctx, "a2", time.Hour); f2 != nil {
t.Fatal("file claimed twice")
}
f3, _ := s.Claim(ctx, "a2", -time.Second) // everything counts as stale
if f3 == nil || f3.ID != f1.ID {
t.Fatalf("stale claim not requeued: %+v", f3)
}
}
+21
View File
@@ -0,0 +1,21 @@
[tools]
go = "1.27.3"
"go:github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen" = "2.8.2"
[env]
CGO_ENABLED = "0"
[tasks.generate]
description = "Generate Go server, client and models from api/openapi.yaml"
run = "oapi-codegen -config api/oapi-codegen.yaml api/openapi.yaml"
[tasks.build]
description = "Build both binaries into ./bin"
depends = ["generate"]
run = "go build -trimpath -ldflags='-s -w' -o bin/ ./cmd/..."
[tasks.test]
run = "go test ./..."
[tasks.vet]
run = "go vet ./..."