From a18d45714e4bdb89c59f954cd75550868b30a52a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 17:49:06 -0700 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01GUebqghNwNssAZuWTxUq1y --- .gitignore | 3 + Containerfile | 15 + README.md | 74 + api/oapi-codegen.yaml | 9 + api/openapi.yaml | 268 +++ cmd/preload-agent/main.go | 193 ++ cmd/preload-api/main.go | 167 ++ deploy/media-preload-api.container | 20 + deploy/preload-agent.service | 19 + go.mod | 30 + go.sum | 101 + internal/api/api.gen.go | 3200 ++++++++++++++++++++++++++++ internal/jellyfin/client.go | 164 ++ internal/service/service.go | 346 +++ internal/service/service_test.go | 20 + internal/store/store.go | 240 +++ internal/store/store_test.go | 80 + mise.toml | 21 + 18 files changed, 4970 insertions(+) create mode 100644 .gitignore create mode 100644 Containerfile create mode 100644 README.md create mode 100644 api/oapi-codegen.yaml create mode 100644 api/openapi.yaml create mode 100644 cmd/preload-agent/main.go create mode 100644 cmd/preload-api/main.go create mode 100644 deploy/media-preload-api.container create mode 100644 deploy/preload-agent.service create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/api/api.gen.go create mode 100644 internal/jellyfin/client.go create mode 100644 internal/service/service.go create mode 100644 internal/service/service_test.go create mode 100644 internal/store/store.go create mode 100644 internal/store/store_test.go create mode 100644 mise.toml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bd28439 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +bin/ +*.db +*.db-* diff --git a/Containerfile b/Containerfile new file mode 100644 index 0000000..2c67d1f --- /dev/null +++ b/Containerfile @@ -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"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..206f309 --- /dev/null +++ b/README.md @@ -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":"","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 `. `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. diff --git a/api/oapi-codegen.yaml b/api/oapi-codegen.yaml new file mode 100644 index 0000000..8a6f89b --- /dev/null +++ b/api/oapi-codegen.yaml @@ -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 diff --git a/api/openapi.yaml b/api/openapi.yaml new file mode 100644 index 0000000..4103fdd --- /dev/null +++ b/api/openapi.yaml @@ -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 `. 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 } diff --git a/cmd/preload-agent/main.go b/cmd/preload-agent/main.go new file mode 100644 index 0000000..173e1ef --- /dev/null +++ b/cmd/preload-agent/main.go @@ -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): + } + } + } +} diff --git a/cmd/preload-api/main.go b/cmd/preload-api/main.go new file mode 100644 index 0000000..ebb013a --- /dev/null +++ b/cmd/preload-api/main.go @@ -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) +} diff --git a/deploy/media-preload-api.container b/deploy/media-preload-api.container new file mode 100644 index 0000000..763afb9 --- /dev/null +++ b/deploy/media-preload-api.container @@ -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 diff --git a/deploy/preload-agent.service b/deploy/preload-agent.service new file mode 100644 index 0000000..8d6e672 --- /dev/null +++ b/deploy/preload-agent.service @@ -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 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b70e789 --- /dev/null +++ b/go.mod @@ -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 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5422cc0 --- /dev/null +++ b/go.sum @@ -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= diff --git a/internal/api/api.gen.go b/internal/api/api.gen.go new file mode 100644 index 0000000..2c50258 --- /dev/null +++ b/internal/api/api.gen.go @@ -0,0 +1,3200 @@ +//go:build go1.22 + +// Package api provides primitives to interact with the openapi HTTP API. +// +// Code generated by github.com/oapi-codegen/oapi-codegen/v2 version v2.8.2 DO NOT EDIT. +package api + +import ( + "bytes" + "compress/flate" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "path" + "strings" + "time" + + "github.com/getkin/kin-openapi/openapi3" + "github.com/oapi-codegen/runtime" +) + +// Defines values for FileReportResult. +const ( + FileReportResultAlreadyCached FileReportResult = "already_cached" + FileReportResultCached FileReportResult = "cached" + FileReportResultFailed FileReportResult = "failed" +) + +// Valid indicates whether the value is a known member of the FileReportResult enum. +func (e FileReportResult) Valid() bool { + switch e { + case FileReportResultAlreadyCached: + return true + case FileReportResultCached: + return true + case FileReportResultFailed: + return true + default: + return false + } +} + +// Defines values for FileStatus. +const ( + FileStatusCached FileStatus = "cached" + FileStatusCanceled FileStatus = "canceled" + FileStatusFailed FileStatus = "failed" + FileStatusFetching FileStatus = "fetching" + FileStatusNotCacheable FileStatus = "not_cacheable" + FileStatusQueued FileStatus = "queued" +) + +// Valid indicates whether the value is a known member of the FileStatus enum. +func (e FileStatus) Valid() bool { + switch e { + case FileStatusCached: + return true + case FileStatusCanceled: + return true + case FileStatusFailed: + return true + case FileStatusFetching: + return true + case FileStatusNotCacheable: + return true + case FileStatusQueued: + return true + default: + return false + } +} + +// Defines values for MediaType. +const ( + Movie MediaType = "movie" + Series MediaType = "series" +) + +// Valid indicates whether the value is a known member of the MediaType enum. +func (e MediaType) Valid() bool { + switch e { + case Movie: + return true + case Series: + return true + default: + return false + } +} + +// Defines values for RequestStatus. +const ( + RequestStatusCanceled RequestStatus = "canceled" + RequestStatusDone RequestStatus = "done" + RequestStatusFailed RequestStatus = "failed" + RequestStatusFetching RequestStatus = "fetching" + RequestStatusPartial RequestStatus = "partial" + RequestStatusQueued RequestStatus = "queued" +) + +// Valid indicates whether the value is a known member of the RequestStatus enum. +func (e RequestStatus) Valid() bool { + switch e { + case RequestStatusCanceled: + return true + case RequestStatusDone: + return true + case RequestStatusFailed: + return true + case RequestStatusFetching: + return true + case RequestStatusPartial: + return true + case RequestStatusQueued: + return true + default: + return false + } +} + +// AgentJob defines model for AgentJob. +type AgentJob struct { + FileId int64 `json:"fileId"` + Path string `json:"path"` + SizeBytes int64 `json:"sizeBytes"` +} + +// ClaimRequest defines model for ClaimRequest. +type ClaimRequest struct { + // AgentId Example: vps-dcruit2r + AgentId string `json:"agentId"` +} + +// CreateRequest defines model for CreateRequest. +type CreateRequest struct { + // Episodes Episode numbers within `season` + Episodes *[]int `json:"episodes,omitempty"` + + // ItemId Jellyfin item id from /v1/search + ItemId string `json:"itemId"` + + // JellyfinUser Jellyfin user name whose watch progress decides "next" + JellyfinUser *string `json:"jellyfinUser,omitempty"` + + // Next Next N unwatched episodes for jellyfinUser + Next *int `json:"next,omitempty"` + Note *string `json:"note,omitempty"` + + // RequestedBy Who asked + RequestedBy string `json:"requestedBy"` + Season *int `json:"season,omitempty"` +} + +// FileReport defines model for FileReport. +type FileReport struct { + // Bytes Bytes read from home for this file + Bytes *int64 `json:"bytes,omitempty"` + Error *string `json:"error,omitempty"` + Result FileReportResult `json:"result"` +} + +// FileReportResult defines model for FileReport.Result. +type FileReportResult string + +// FileStatus defines model for FileStatus. +type FileStatus string + +// Health defines model for Health. +type Health struct { + // Status Example: ok + Status string `json:"status"` + Version string `json:"version"` +} + +// MediaItem defines model for MediaItem. +type MediaItem struct { + // Cacheable False when the item lives outside the cached folders + Cacheable bool `json:"cacheable"` + + // Id Jellyfin item id + Id string `json:"id"` + + // Library Jellyfin library path prefix, e.g. /media2/Videos/tvshows + Library *string `json:"library,omitempty"` + Name string `json:"name"` + SeasonCount *int `json:"seasonCount,omitempty"` + Type MediaType `json:"type"` + Year *int `json:"year,omitempty"` +} + +// MediaType defines model for MediaType. +type MediaType string + +// PreloadFile defines model for PreloadFile. +type PreloadFile struct { + Error *string `json:"error,omitempty"` + FetchedBytes *int64 `json:"fetchedBytes,omitempty"` + Id int64 `json:"id"` + + // Path Path as seen by Jellyfin and webdav, e.g. /media2/Videos/tvshows/... + Path string `json:"path"` + SizeBytes int64 `json:"sizeBytes"` + Status FileStatus `json:"status"` + + // Title e.g. Dark Matter S02E08 + Title string `json:"title"` + UpdatedAt *time.Time `json:"updatedAt,omitempty"` +} + +// PreloadRequest defines model for PreloadRequest. +type PreloadRequest struct { + CreatedAt time.Time `json:"createdAt"` + Files []PreloadFile `json:"files"` + Id int64 `json:"id"` + ItemId string `json:"itemId"` + Note *string `json:"note,omitempty"` + RequestedBy string `json:"requestedBy"` + Status RequestStatus `json:"status"` + Title string `json:"title"` +} + +// Problem defines model for Problem. +type Problem struct { + // Error Example: series requests need jellyfinUser when using next + Error string `json:"error"` +} + +// RequestStatus defines model for RequestStatus. +type RequestStatus string + +// ListRequestsParams defines parameters for ListRequests. +type ListRequestsParams struct { + Status *RequestStatus `form:"status,omitempty" json:"status,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// SearchLibraryParams defines parameters for SearchLibrary. +type SearchLibraryParams struct { + // Q Title to search for + Q string `form:"q" json:"q"` + Type *MediaType `form:"type,omitempty" json:"type,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + +// ClaimFileJSONRequestBody defines body for ClaimFile for application/json ContentType. +type ClaimFileJSONRequestBody = ClaimRequest + +// ReportFileJSONRequestBody defines body for ReportFile for application/json ContentType. +type ReportFileJSONRequestBody = FileReport + +// CreateRequestJSONRequestBody defines body for CreateRequest for application/json ContentType. +type CreateRequestJSONRequestBody = CreateRequest + +// RequestEditorFn is the function signature for the RequestEditor callback function +type RequestEditorFn func(ctx context.Context, req *http.Request) error + +// Doer performs HTTP requests. +// +// The standard http.Client implements this interface. +type HttpRequestDoer interface { + Do(req *http.Request) (*http.Response, error) +} + +// Client which conforms to the OpenAPI3 specification for this service. +type Client struct { + // The endpoint of the server conforming to this interface, with scheme, + // https://api.deepmap.com for example. This can contain a path relative + // to the server, such as https://api.deepmap.com/dev-test, and all the + // paths in the swagger spec will be appended to the server. + Server string + + // Doer for performing requests, typically a *http.Client with any + // customized settings, such as certificate chains. + Client HttpRequestDoer + + // A list of callbacks for modifying requests which are generated before sending over + // the network. + RequestEditors []RequestEditorFn +} + +// ClientOption allows setting custom parameters during construction +type ClientOption func(*Client) error + +// Creates a new Client, with reasonable defaults +func NewClient(server string, opts ...ClientOption) (*Client, error) { + // create a client with sane default values + client := Client{ + Server: server, + } + // mutate client and add all optional params + for _, o := range opts { + if err := o(&client); err != nil { + return nil, err + } + } + // ensure the server URL always has a trailing slash + if !strings.HasSuffix(client.Server, "/") { + client.Server += "/" + } + // create httpClient, if not already present + if client.Client == nil { + client.Client = &http.Client{} + } + return &client, nil +} + +// WithHTTPClient allows overriding the default Doer, which is +// automatically created using http.Client. This is useful for tests. +func WithHTTPClient(doer HttpRequestDoer) ClientOption { + return func(c *Client) error { + c.Client = doer + return nil + } +} + +// WithRequestEditorFn allows setting up a callback function, which will be +// called right before sending the request. This can be used to mutate the request. +func WithRequestEditorFn(fn RequestEditorFn) ClientOption { + return func(c *Client) error { + c.RequestEditors = append(c.RequestEditors, fn) + return nil + } +} + +// The interface specification for the client above. +type ClientInterface interface { + + // ClaimFileWithBody Agent takes the next queued file + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). + ClaimFileWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ClaimFile Agent takes the next queued file + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). + ClaimFile(ctx context.Context, body ClaimFileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ReportFileWithBody Agent reports the result for a claimed file + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). + ReportFileWithBody(ctx context.Context, fileId int64, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ReportFile Agent reports the result for a claimed file + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). + ReportFile(ctx context.Context, fileId int64, body ReportFileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetHealth Liveness and version + // + // Corresponds with GET /v1/health (the `GetHealth` operationId). + GetHealth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + + // ListRequests Recent requests, newest first + // + // Corresponds with GET /v1/requests (the `ListRequests` operationId). + ListRequests(ctx context.Context, params *ListRequestsParams, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateRequestWithBody Ask for a movie or episodes to be cached + // + // 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`. + // + // Takes any type of body and a specified content type. + // + // Corresponds with POST /v1/requests (the `CreateRequest` operationId). + CreateRequestWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CreateRequest Ask for a movie or episodes to be cached + // + // 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`. + // + // Takes a body of the `application/json` content type. + // + // Corresponds with POST /v1/requests (the `CreateRequest` operationId). + CreateRequest(ctx context.Context, body CreateRequestJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + + // CancelRequest Cancel the files of a request that are still queued + // + // Corresponds with DELETE /v1/requests/{id} (the `CancelRequest` operationId). + CancelRequest(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*http.Response, error) + + // GetRequest One request with per-file progress + // + // Corresponds with GET /v1/requests/{id} (the `GetRequest` operationId). + GetRequest(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*http.Response, error) + + // SearchLibrary Search movies and series in Jellyfin + // + // Corresponds with GET /v1/search (the `SearchLibrary` operationId). + SearchLibrary(ctx context.Context, params *SearchLibraryParams, reqEditors ...RequestEditorFn) (*http.Response, error) +} + +// ClaimFileWithBody Agent takes the next queued file +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). +func (c *Client) ClaimFileWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewClaimFileRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ClaimFile Agent takes the next queued file +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). +func (c *Client) ClaimFile(ctx context.Context, body ClaimFileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewClaimFileRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ReportFileWithBody Agent reports the result for a claimed file +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). +func (c *Client) ReportFileWithBody(ctx context.Context, fileId int64, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewReportFileRequestWithBody(c.Server, fileId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ReportFile Agent reports the result for a claimed file +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). +func (c *Client) ReportFile(ctx context.Context, fileId int64, body ReportFileJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewReportFileRequest(c.Server, fileId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// GetHealth Liveness and version +// +// Corresponds with GET /v1/health (the `GetHealth` operationId). +func (c *Client) GetHealth(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetHealthRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// ListRequests Recent requests, newest first +// +// Corresponds with GET /v1/requests (the `ListRequests` operationId). +func (c *Client) ListRequests(ctx context.Context, params *ListRequestsParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewListRequestsRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// CreateRequestWithBody Ask for a movie or episodes to be cached +// +// 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`. +// +// Takes any type of body and a specified content type. +// +// Corresponds with POST /v1/requests (the `CreateRequest` operationId). +func (c *Client) CreateRequestWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateRequestRequestWithBody(c.Server, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// CreateRequest Ask for a movie or episodes to be cached +// +// 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`. +// +// Takes a body of the `application/json` content type. +// +// Corresponds with POST /v1/requests (the `CreateRequest` operationId). +func (c *Client) CreateRequest(ctx context.Context, body CreateRequestJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateRequestRequest(c.Server, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// CancelRequest Cancel the files of a request that are still queued +// +// Corresponds with DELETE /v1/requests/{id} (the `CancelRequest` operationId). +func (c *Client) CancelRequest(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCancelRequestRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// GetRequest One request with per-file progress +// +// Corresponds with GET /v1/requests/{id} (the `GetRequest` operationId). +func (c *Client) GetRequest(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetRequestRequest(c.Server, id) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// SearchLibrary Search movies and series in Jellyfin +// +// Corresponds with GET /v1/search (the `SearchLibrary` operationId). +func (c *Client) SearchLibrary(ctx context.Context, params *SearchLibraryParams, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewSearchLibraryRequest(c.Server, params) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +// NewClaimFileRequest calls the generic ClaimFile builder with application/json body +func NewClaimFileRequest(server string, body ClaimFileJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewClaimFileRequestWithBody(server, "application/json", bodyReader) +} + +// NewClaimFileRequestWithBody constructs an http.Request for the ClaimFile method, with any body, and a specified content type +func NewClaimFileRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/agent/claim") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewReportFileRequest calls the generic ReportFile builder with application/json body +func NewReportFileRequest(server string, fileId int64, body ReportFileJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewReportFileRequestWithBody(server, fileId, "application/json", bodyReader) +} + +// NewReportFileRequestWithBody constructs an http.Request for the ReportFile method, with any body, and a specified content type +func NewReportFileRequestWithBody(server string, fileId int64, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "fileId", fileId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int64"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/agent/files/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewGetHealthRequest constructs an http.Request for the GetHealth method +func NewGetHealthRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/health") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewListRequestsRequest constructs an http.Request for the ListRequests method +func NewListRequestsRequest(server string, params *ListRequestsParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/requests") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if params.Status != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "status", *params.Status, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewCreateRequestRequest calls the generic CreateRequest builder with application/json body +func NewCreateRequestRequest(server string, body CreateRequestJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewCreateRequestRequestWithBody(server, "application/json", bodyReader) +} + +// NewCreateRequestRequestWithBody constructs an http.Request for the CreateRequest method, with any body, and a specified content type +func NewCreateRequestRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/requests") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + +// NewCancelRequestRequest constructs an http.Request for the CancelRequest method +func NewCancelRequestRequest(server string, id int64) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int64"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/requests/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodDelete, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewGetRequestRequest constructs an http.Request for the GetRequest method +func NewGetRequestRequest(server string, id int64) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: "int64"}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/requests/%s", pathParam0) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +// NewSearchLibraryRequest constructs an http.Request for the SearchLibrary method +func NewSearchLibraryRequest(server string, params *SearchLibraryParams) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/v1/search") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + if params != nil { + // queryValues collects non-styled parameters (passthrough, JSON) + // that are safe to round-trip through url.Values.Encode(). + queryValues := queryURL.Query() + // rawQueryFragments collects pre-encoded query fragments from + // styled parameters, preserving literal commas as delimiters + // per the OpenAPI spec (e.g. "color=blue,black,brown"). + var rawQueryFragments []string + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "q", params.Q, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + if params.Type != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "type", *params.Type, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if encoded := queryValues.Encode(); encoded != "" { + rawQueryFragments = append(rawQueryFragments, encoded) + } + queryURL.RawQuery = strings.Join(rawQueryFragments, "&") + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + +func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error { + for _, r := range c.RequestEditors { + if err := r(ctx, req); err != nil { + return err + } + } + for _, r := range additionalEditors { + if err := r(ctx, req); err != nil { + return err + } + } + return nil +} + +// ClientWithResponses builds on ClientInterface to offer response payloads +type ClientWithResponses struct { + ClientInterface +} + +// NewClientWithResponses creates a new ClientWithResponses, which wraps +// Client with return type handling +func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) { + client, err := NewClient(server, opts...) + if err != nil { + return nil, err + } + return &ClientWithResponses{client}, nil +} + +// WithBaseURL overrides the baseURL. +func WithBaseURL(baseURL string) ClientOption { + return func(c *Client) error { + newBaseURL, err := url.Parse(baseURL) + if err != nil { + return err + } + c.Server = newBaseURL.String() + return nil + } +} + +// ClientWithResponsesInterface is the interface specification for the client with responses above. +type ClientWithResponsesInterface interface { + + // ClaimFileWithBodyWithResponse Agent takes the next queued file + // + // Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). + ClaimFileWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ClaimFileResponse, error) + + // ClaimFileWithResponse Agent takes the next queued file + // + // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). + ClaimFileWithResponse(ctx context.Context, body ClaimFileJSONRequestBody, reqEditors ...RequestEditorFn) (*ClaimFileResponse, error) + + // ReportFileWithBodyWithResponse Agent reports the result for a claimed file + // + // Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). + ReportFileWithBodyWithResponse(ctx context.Context, fileId int64, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ReportFileResponse, error) + + // ReportFileWithResponse Agent reports the result for a claimed file + // + // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). + ReportFileWithResponse(ctx context.Context, fileId int64, body ReportFileJSONRequestBody, reqEditors ...RequestEditorFn) (*ReportFileResponse, error) + + // GetHealthWithResponse Liveness and version + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with GET /v1/health (the `GetHealth` operationId). + GetHealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetHealthResponse, error) + + // ListRequestsWithResponse Recent requests, newest first + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with GET /v1/requests (the `ListRequests` operationId). + ListRequestsWithResponse(ctx context.Context, params *ListRequestsParams, reqEditors ...RequestEditorFn) (*ListRequestsResponse, error) + + // CreateRequestWithBodyWithResponse Ask for a movie or episodes to be cached + // + // 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`. + // + // Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/requests (the `CreateRequest` operationId). + CreateRequestWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateRequestResponse, error) + + // CreateRequestWithResponse Ask for a movie or episodes to be cached + // + // 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`. + // + // Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). + // + // Corresponds with POST /v1/requests (the `CreateRequest` operationId). + CreateRequestWithResponse(ctx context.Context, body CreateRequestJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateRequestResponse, error) + + // CancelRequestWithResponse Cancel the files of a request that are still queued + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with DELETE /v1/requests/{id} (the `CancelRequest` operationId). + CancelRequestWithResponse(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*CancelRequestResponse, error) + + // GetRequestWithResponse One request with per-file progress + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with GET /v1/requests/{id} (the `GetRequest` operationId). + GetRequestWithResponse(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*GetRequestResponse, error) + + // SearchLibraryWithResponse Search movies and series in Jellyfin + // + // Returns a wrapper object for the known response body format(s). + // + // Corresponds with GET /v1/search (the `SearchLibrary` operationId). + SearchLibraryWithResponse(ctx context.Context, params *SearchLibraryParams, reqEditors ...RequestEditorFn) (*SearchLibraryResponse, error) +} + +type ClaimFileResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *AgentJob + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem + // JSON403 the response for an HTTP 403 `application/json` response + JSON403 *Problem +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r ClaimFileResponse) GetJSON200() *AgentJob { + return r.JSON200 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r ClaimFileResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetJSON403 returns the response for an HTTP 403 `application/json` response +func (r ClaimFileResponse) GetJSON403() *Problem { + return r.JSON403 +} + +// GetBody returns the raw response body bytes +func (r ClaimFileResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r ClaimFileResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ClaimFileResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ClaimFileResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ReportFileResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem + // JSON403 the response for an HTTP 403 `application/json` response + JSON403 *Problem + // JSON404 the response for an HTTP 404 `application/json` response + JSON404 *Problem +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r ReportFileResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetJSON403 returns the response for an HTTP 403 `application/json` response +func (r ReportFileResponse) GetJSON403() *Problem { + return r.JSON403 +} + +// GetJSON404 returns the response for an HTTP 404 `application/json` response +func (r ReportFileResponse) GetJSON404() *Problem { + return r.JSON404 +} + +// GetBody returns the raw response body bytes +func (r ReportFileResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r ReportFileResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ReportFileResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ReportFileResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetHealthResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *Health +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r GetHealthResponse) GetJSON200() *Health { + return r.JSON200 +} + +// GetBody returns the raw response body bytes +func (r GetHealthResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r GetHealthResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetHealthResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetHealthResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type ListRequestsResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *[]PreloadRequest + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r ListRequestsResponse) GetJSON200() *[]PreloadRequest { + return r.JSON200 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r ListRequestsResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetBody returns the raw response body bytes +func (r ListRequestsResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r ListRequestsResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r ListRequestsResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r ListRequestsResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CreateRequestResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON201 the response for an HTTP 201 `application/json` response + JSON201 *PreloadRequest + // JSON400 the response for an HTTP 400 `application/json` response + JSON400 *Problem + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem + // JSON404 the response for an HTTP 404 `application/json` response + JSON404 *Problem +} + +// GetJSON201 returns the response for an HTTP 201 `application/json` response +func (r CreateRequestResponse) GetJSON201() *PreloadRequest { + return r.JSON201 +} + +// GetJSON400 returns the response for an HTTP 400 `application/json` response +func (r CreateRequestResponse) GetJSON400() *Problem { + return r.JSON400 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r CreateRequestResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetJSON404 returns the response for an HTTP 404 `application/json` response +func (r CreateRequestResponse) GetJSON404() *Problem { + return r.JSON404 +} + +// GetBody returns the raw response body bytes +func (r CreateRequestResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r CreateRequestResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CreateRequestResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CreateRequestResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type CancelRequestResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *PreloadRequest + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem + // JSON404 the response for an HTTP 404 `application/json` response + JSON404 *Problem +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r CancelRequestResponse) GetJSON200() *PreloadRequest { + return r.JSON200 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r CancelRequestResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetJSON404 returns the response for an HTTP 404 `application/json` response +func (r CancelRequestResponse) GetJSON404() *Problem { + return r.JSON404 +} + +// GetBody returns the raw response body bytes +func (r CancelRequestResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r CancelRequestResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r CancelRequestResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r CancelRequestResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type GetRequestResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *PreloadRequest + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem + // JSON404 the response for an HTTP 404 `application/json` response + JSON404 *Problem +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r GetRequestResponse) GetJSON200() *PreloadRequest { + return r.JSON200 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r GetRequestResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetJSON404 returns the response for an HTTP 404 `application/json` response +func (r GetRequestResponse) GetJSON404() *Problem { + return r.JSON404 +} + +// GetBody returns the raw response body bytes +func (r GetRequestResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r GetRequestResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r GetRequestResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r GetRequestResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +type SearchLibraryResponse struct { + Body []byte + HTTPResponse *http.Response + // JSON200 the response for an HTTP 200 `application/json` response + JSON200 *[]MediaItem + // JSON400 the response for an HTTP 400 `application/json` response + JSON400 *Problem + // JSON401 the response for an HTTP 401 `application/json` response + JSON401 *Problem +} + +// GetJSON200 returns the response for an HTTP 200 `application/json` response +func (r SearchLibraryResponse) GetJSON200() *[]MediaItem { + return r.JSON200 +} + +// GetJSON400 returns the response for an HTTP 400 `application/json` response +func (r SearchLibraryResponse) GetJSON400() *Problem { + return r.JSON400 +} + +// GetJSON401 returns the response for an HTTP 401 `application/json` response +func (r SearchLibraryResponse) GetJSON401() *Problem { + return r.JSON401 +} + +// GetBody returns the raw response body bytes +func (r SearchLibraryResponse) GetBody() []byte { + return r.Body +} + +// Status returns HTTPResponse.Status +func (r SearchLibraryResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r SearchLibraryResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r SearchLibraryResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + +// ClaimFileWithBodyWithResponse Agent takes the next queued file +// +// Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). +func (c *ClientWithResponses) ClaimFileWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ClaimFileResponse, error) { + rsp, err := c.ClaimFileWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseClaimFileResponse(rsp) +} + +// ClaimFileWithResponse Agent takes the next queued file +// +// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/agent/claim (the `ClaimFile` operationId). +func (c *ClientWithResponses) ClaimFileWithResponse(ctx context.Context, body ClaimFileJSONRequestBody, reqEditors ...RequestEditorFn) (*ClaimFileResponse, error) { + rsp, err := c.ClaimFile(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseClaimFileResponse(rsp) +} + +// ReportFileWithBodyWithResponse Agent reports the result for a claimed file +// +// Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). +func (c *ClientWithResponses) ReportFileWithBodyWithResponse(ctx context.Context, fileId int64, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ReportFileResponse, error) { + rsp, err := c.ReportFileWithBody(ctx, fileId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseReportFileResponse(rsp) +} + +// ReportFileWithResponse Agent reports the result for a claimed file +// +// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/agent/files/{fileId} (the `ReportFile` operationId). +func (c *ClientWithResponses) ReportFileWithResponse(ctx context.Context, fileId int64, body ReportFileJSONRequestBody, reqEditors ...RequestEditorFn) (*ReportFileResponse, error) { + rsp, err := c.ReportFile(ctx, fileId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseReportFileResponse(rsp) +} + +// GetHealthWithResponse Liveness and version +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with GET /v1/health (the `GetHealth` operationId). +func (c *ClientWithResponses) GetHealthWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*GetHealthResponse, error) { + rsp, err := c.GetHealth(ctx, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetHealthResponse(rsp) +} + +// ListRequestsWithResponse Recent requests, newest first +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with GET /v1/requests (the `ListRequests` operationId). +func (c *ClientWithResponses) ListRequestsWithResponse(ctx context.Context, params *ListRequestsParams, reqEditors ...RequestEditorFn) (*ListRequestsResponse, error) { + rsp, err := c.ListRequests(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseListRequestsResponse(rsp) +} + +// CreateRequestWithBodyWithResponse Ask for a movie or episodes to be cached +// +// 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`. +// +// Takes any type of body and a specified content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/requests (the `CreateRequest` operationId). +func (c *ClientWithResponses) CreateRequestWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateRequestResponse, error) { + rsp, err := c.CreateRequestWithBody(ctx, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateRequestResponse(rsp) +} + +// CreateRequestWithResponse Ask for a movie or episodes to be cached +// +// 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`. +// +// Takes a body of the `application/json` content type, and returns a wrapper object for the known response body format(s). +// +// Corresponds with POST /v1/requests (the `CreateRequest` operationId). +func (c *ClientWithResponses) CreateRequestWithResponse(ctx context.Context, body CreateRequestJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateRequestResponse, error) { + rsp, err := c.CreateRequest(ctx, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseCreateRequestResponse(rsp) +} + +// CancelRequestWithResponse Cancel the files of a request that are still queued +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with DELETE /v1/requests/{id} (the `CancelRequest` operationId). +func (c *ClientWithResponses) CancelRequestWithResponse(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*CancelRequestResponse, error) { + rsp, err := c.CancelRequest(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseCancelRequestResponse(rsp) +} + +// GetRequestWithResponse One request with per-file progress +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with GET /v1/requests/{id} (the `GetRequest` operationId). +func (c *ClientWithResponses) GetRequestWithResponse(ctx context.Context, id int64, reqEditors ...RequestEditorFn) (*GetRequestResponse, error) { + rsp, err := c.GetRequest(ctx, id, reqEditors...) + if err != nil { + return nil, err + } + return ParseGetRequestResponse(rsp) +} + +// SearchLibraryWithResponse Search movies and series in Jellyfin +// +// Returns a wrapper object for the known response body format(s). +// +// Corresponds with GET /v1/search (the `SearchLibrary` operationId). +func (c *ClientWithResponses) SearchLibraryWithResponse(ctx context.Context, params *SearchLibraryParams, reqEditors ...RequestEditorFn) (*SearchLibraryResponse, error) { + rsp, err := c.SearchLibrary(ctx, params, reqEditors...) + if err != nil { + return nil, err + } + return ParseSearchLibraryResponse(rsp) +} + +// ParseClaimFileResponse parses an HTTP response from a ClaimFileWithResponse call +func ParseClaimFileResponse(rsp *http.Response) (*ClaimFileResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ClaimFileResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest AgentJob + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + } + + return response, nil +} + +// ParseReportFileResponse parses an HTTP response from a ReportFileWithResponse call +func ParseReportFileResponse(rsp *http.Response) (*ReportFileResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ReportFileResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case rsp.StatusCode == 204: + break // No content-type + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetHealthResponse parses an HTTP response from a GetHealthWithResponse call +func ParseGetHealthResponse(rsp *http.Response) (*GetHealthResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetHealthResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest Health + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + } + + return response, nil +} + +// ParseListRequestsResponse parses an HTTP response from a ListRequestsWithResponse call +func ParseListRequestsResponse(rsp *http.Response) (*ListRequestsResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &ListRequestsResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []PreloadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + } + + return response, nil +} + +// ParseCreateRequestResponse parses an HTTP response from a CreateRequestWithResponse call +func ParseCreateRequestResponse(rsp *http.Response) (*CreateRequestResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CreateRequestResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 201: + var dest PreloadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON201 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseCancelRequestResponse parses an HTTP response from a CancelRequestWithResponse call +func ParseCancelRequestResponse(rsp *http.Response) (*CancelRequestResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &CancelRequestResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PreloadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseGetRequestResponse parses an HTTP response from a GetRequestWithResponse call +func ParseGetRequestResponse(rsp *http.Response) (*GetRequestResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &GetRequestResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest PreloadRequest + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + } + + return response, nil +} + +// ParseSearchLibraryResponse parses an HTTP response from a SearchLibraryWithResponse call +func ParseSearchLibraryResponse(rsp *http.Response) (*SearchLibraryResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &SearchLibraryResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest []MediaItem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: + var dest Problem + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON401 = &dest + + } + + return response, nil +} + +// ServerInterface represents all server handlers. +type ServerInterface interface { + // ClaimFile Agent takes the next queued file + // (POST /v1/agent/claim) + ClaimFile(w http.ResponseWriter, r *http.Request) + // ReportFile Agent reports the result for a claimed file + // (POST /v1/agent/files/{fileId}) + ReportFile(w http.ResponseWriter, r *http.Request, fileId int64) + // GetHealth Liveness and version + // (GET /v1/health) + GetHealth(w http.ResponseWriter, r *http.Request) + // ListRequests Recent requests, newest first + // (GET /v1/requests) + ListRequests(w http.ResponseWriter, r *http.Request, params ListRequestsParams) + // CreateRequest Ask for a movie or episodes to be cached + // (POST /v1/requests) + CreateRequest(w http.ResponseWriter, r *http.Request) + // CancelRequest Cancel the files of a request that are still queued + // (DELETE /v1/requests/{id}) + CancelRequest(w http.ResponseWriter, r *http.Request, id int64) + // GetRequest One request with per-file progress + // (GET /v1/requests/{id}) + GetRequest(w http.ResponseWriter, r *http.Request, id int64) + // SearchLibrary Search movies and series in Jellyfin + // (GET /v1/search) + SearchLibrary(w http.ResponseWriter, r *http.Request, params SearchLibraryParams) +} + +// ServerInterfaceWrapper converts contexts to parameters. +type ServerInterfaceWrapper struct { + Handler ServerInterface + HandlerMiddlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +type MiddlewareFunc func(http.Handler) http.Handler + +// ClaimFile operation middleware +func (siw *ServerInterfaceWrapper) ClaimFile(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ClaimFile(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// ReportFile operation middleware +func (siw *ServerInterfaceWrapper) ReportFile(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // ------------- Path parameter "fileId" ------------- + var fileId int64 + + err = runtime.BindStyledParameterWithOptions("simple", "fileId", r.PathValue("fileId"), &fileId, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int64", ValueIsUnescaped: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "fileId", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ReportFile(w, r, fileId) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// GetHealth operation middleware +func (siw *ServerInterfaceWrapper) GetHealth(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetHealth(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// ListRequests operation middleware +func (siw *ServerInterfaceWrapper) ListRequests(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // Parameter object where we will unmarshal all parameters from the context + var params ListRequestsParams + + // ------------- Optional query parameter "status" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "status", r.URL.Query(), ¶ms.Status, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + var requiredError *runtime.RequiredParameterError + if errors.As(err, &requiredError) { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "status"}) + } else { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "status", Err: err}) + } + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + var requiredError *runtime.RequiredParameterError + if errors.As(err, &requiredError) { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "limit"}) + } else { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + } + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.ListRequests(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// CreateRequest operation middleware +func (siw *ServerInterfaceWrapper) CreateRequest(w http.ResponseWriter, r *http.Request) { + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CreateRequest(w, r) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// CancelRequest operation middleware +func (siw *ServerInterfaceWrapper) CancelRequest(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // ------------- Path parameter "id" ------------- + var id int64 + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int64", ValueIsUnescaped: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.CancelRequest(w, r, id) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// GetRequest operation middleware +func (siw *ServerInterfaceWrapper) GetRequest(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // ------------- Path parameter "id" ------------- + var id int64 + + err = runtime.BindStyledParameterWithOptions("simple", "id", r.PathValue("id"), &id, runtime.BindStyledParameterOptions{ParamLocation: runtime.ParamLocationPath, Explode: false, Required: true, Type: "integer", Format: "int64", ValueIsUnescaped: true}) + if err != nil { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "id", Err: err}) + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.GetRequest(w, r, id) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +// SearchLibrary operation middleware +func (siw *ServerInterfaceWrapper) SearchLibrary(w http.ResponseWriter, r *http.Request) { + + var err error + _ = err + + // Parameter object where we will unmarshal all parameters from the context + var params SearchLibraryParams + + // ------------- Required query parameter "q" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, true, "q", r.URL.Query(), ¶ms.Q, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + var requiredError *runtime.RequiredParameterError + if errors.As(err, &requiredError) { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "q"}) + } else { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "q", Err: err}) + } + return + } + + // ------------- Optional query parameter "type" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "type", r.URL.Query(), ¶ms.Type, runtime.BindQueryParameterOptions{Type: "string", Format: ""}) + if err != nil { + var requiredError *runtime.RequiredParameterError + if errors.As(err, &requiredError) { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "type"}) + } else { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "type", Err: err}) + } + return + } + + // ------------- Optional query parameter "limit" ------------- + + err = runtime.BindQueryParameterWithOptions("form", true, false, "limit", r.URL.Query(), ¶ms.Limit, runtime.BindQueryParameterOptions{Type: "integer", Format: ""}) + if err != nil { + var requiredError *runtime.RequiredParameterError + if errors.As(err, &requiredError) { + siw.ErrorHandlerFunc(w, r, &RequiredParamError{ParamName: "limit"}) + } else { + siw.ErrorHandlerFunc(w, r, &InvalidParamFormatError{ParamName: "limit", Err: err}) + } + return + } + + handler := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + siw.Handler.SearchLibrary(w, r, params) + })) + + for _, middleware := range siw.HandlerMiddlewares { + handler = middleware(handler) + } + + handler.ServeHTTP(w, r) +} + +type UnescapedCookieParamError struct { + ParamName string + Err error +} + +func (e *UnescapedCookieParamError) Error() string { + return fmt.Sprintf("error unescaping cookie parameter '%s'", e.ParamName) +} + +func (e *UnescapedCookieParamError) Unwrap() error { + return e.Err +} + +type UnmarshalingParamError struct { + ParamName string + Err error +} + +func (e *UnmarshalingParamError) Error() string { + return fmt.Sprintf("Error unmarshaling parameter %s as JSON: %s", e.ParamName, e.Err.Error()) +} + +func (e *UnmarshalingParamError) Unwrap() error { + return e.Err +} + +type RequiredParamError struct { + ParamName string +} + +func (e *RequiredParamError) Error() string { + return fmt.Sprintf("Query argument %s is required, but not found", e.ParamName) +} + +type RequiredHeaderError struct { + ParamName string + Err error +} + +func (e *RequiredHeaderError) Error() string { + return fmt.Sprintf("Header parameter %s is required, but not found", e.ParamName) +} + +func (e *RequiredHeaderError) Unwrap() error { + return e.Err +} + +type InvalidParamFormatError struct { + ParamName string + Err error +} + +func (e *InvalidParamFormatError) Error() string { + return fmt.Sprintf("Invalid format for parameter %s: %s", e.ParamName, e.Err.Error()) +} + +func (e *InvalidParamFormatError) Unwrap() error { + return e.Err +} + +type TooManyValuesForParamError struct { + ParamName string + Count int +} + +func (e *TooManyValuesForParamError) Error() string { + return fmt.Sprintf("Expected one value for %s, got %d", e.ParamName, e.Count) +} + +// Handler creates http.Handler with routing matching OpenAPI spec. +func Handler(si ServerInterface) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{}) +} + +// ServeMux is an abstraction of [http.ServeMux]. +type ServeMux interface { + HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) + http.Handler +} + +type StdHTTPServerOptions struct { + BaseURL string + BaseRouter ServeMux + Middlewares []MiddlewareFunc + ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +// HandlerFromMux creates http.Handler with routing matching OpenAPI spec based on the provided mux. +func HandlerFromMux(si ServerInterface, m ServeMux) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{ + BaseRouter: m, + }) +} + +func HandlerFromMuxWithBaseURL(si ServerInterface, m ServeMux, baseURL string) http.Handler { + return HandlerWithOptions(si, StdHTTPServerOptions{ + BaseURL: baseURL, + BaseRouter: m, + }) +} + +// HandlerWithOptions creates http.Handler with additional options +func HandlerWithOptions(si ServerInterface, options StdHTTPServerOptions) http.Handler { + m := options.BaseRouter + + if m == nil { + m = http.NewServeMux() + } + if options.ErrorHandlerFunc == nil { + options.ErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } + + wrapper := ServerInterfaceWrapper{ + Handler: si, + HandlerMiddlewares: options.Middlewares, + ErrorHandlerFunc: options.ErrorHandlerFunc, + } + + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/v1/health", wrapper.GetHealth) + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/v1/search", wrapper.SearchLibrary) + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/v1/requests", wrapper.ListRequests) + m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/v1/requests", wrapper.CreateRequest) + m.HandleFunc(http.MethodDelete+" "+options.BaseURL+"/v1/requests/{id}", wrapper.CancelRequest) + m.HandleFunc(http.MethodGet+" "+options.BaseURL+"/v1/requests/{id}", wrapper.GetRequest) + m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/v1/agent/claim", wrapper.ClaimFile) + m.HandleFunc(http.MethodPost+" "+options.BaseURL+"/v1/agent/files/{fileId}", wrapper.ReportFile) + + return m +} + +type ProblemJSONResponse Problem + +type ClaimFileRequestObject struct { + Body *ClaimFileJSONRequestBody +} + +type ClaimFileResponseObject interface { + VisitClaimFileResponse(w http.ResponseWriter) error +} + +type ClaimFile200JSONResponse AgentJob + +func (response ClaimFile200JSONResponse) VisitClaimFileResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type ClaimFile204Response struct { +} + +func (response ClaimFile204Response) VisitClaimFileResponse(w http.ResponseWriter) error { + w.WriteHeader(204) + return nil +} + +type ClaimFile401JSONResponse struct{ ProblemJSONResponse } + +func (response ClaimFile401JSONResponse) VisitClaimFileResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +type ClaimFile403JSONResponse Problem + +func (response ClaimFile403JSONResponse) VisitClaimFileResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + _, err := buf.WriteTo(w) + return err +} + +type ReportFileRequestObject struct { + FileId int64 `json:"fileId"` + Body *ReportFileJSONRequestBody +} + +type ReportFileResponseObject interface { + VisitReportFileResponse(w http.ResponseWriter) error +} + +type ReportFile204Response struct { +} + +func (response ReportFile204Response) VisitReportFileResponse(w http.ResponseWriter) error { + w.WriteHeader(204) + return nil +} + +type ReportFile401JSONResponse struct{ ProblemJSONResponse } + +func (response ReportFile401JSONResponse) VisitReportFileResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +type ReportFile403JSONResponse Problem + +func (response ReportFile403JSONResponse) VisitReportFileResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(403) + _, err := buf.WriteTo(w) + return err +} + +type ReportFile404JSONResponse Problem + +func (response ReportFile404JSONResponse) VisitReportFileResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + _, err := buf.WriteTo(w) + return err +} + +type GetHealthRequestObject struct { +} + +type GetHealthResponseObject interface { + VisitGetHealthResponse(w http.ResponseWriter) error +} + +type GetHealth200JSONResponse Health + +func (response GetHealth200JSONResponse) VisitGetHealthResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type ListRequestsRequestObject struct { + Params ListRequestsParams +} + +type ListRequestsResponseObject interface { + VisitListRequestsResponse(w http.ResponseWriter) error +} + +type ListRequests200JSONResponse []PreloadRequest + +func (response ListRequests200JSONResponse) VisitListRequestsResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type ListRequests401JSONResponse struct{ ProblemJSONResponse } + +func (response ListRequests401JSONResponse) VisitListRequestsResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +type CreateRequestRequestObject struct { + Body *CreateRequestJSONRequestBody +} + +type CreateRequestResponseObject interface { + VisitCreateRequestResponse(w http.ResponseWriter) error +} + +type CreateRequest201JSONResponse PreloadRequest + +func (response CreateRequest201JSONResponse) VisitCreateRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(201) + _, err := buf.WriteTo(w) + return err +} + +type CreateRequest400JSONResponse struct{ ProblemJSONResponse } + +func (response CreateRequest400JSONResponse) VisitCreateRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + _, err := buf.WriteTo(w) + return err +} + +type CreateRequest401JSONResponse Problem + +func (response CreateRequest401JSONResponse) VisitCreateRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +type CreateRequest404JSONResponse Problem + +func (response CreateRequest404JSONResponse) VisitCreateRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + _, err := buf.WriteTo(w) + return err +} + +type CancelRequestRequestObject struct { + Id int64 `json:"id"` +} + +type CancelRequestResponseObject interface { + VisitCancelRequestResponse(w http.ResponseWriter) error +} + +type CancelRequest200JSONResponse PreloadRequest + +func (response CancelRequest200JSONResponse) VisitCancelRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type CancelRequest401JSONResponse struct{ ProblemJSONResponse } + +func (response CancelRequest401JSONResponse) VisitCancelRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +type CancelRequest404JSONResponse Problem + +func (response CancelRequest404JSONResponse) VisitCancelRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + _, err := buf.WriteTo(w) + return err +} + +type GetRequestRequestObject struct { + Id int64 `json:"id"` +} + +type GetRequestResponseObject interface { + VisitGetRequestResponse(w http.ResponseWriter) error +} + +type GetRequest200JSONResponse PreloadRequest + +func (response GetRequest200JSONResponse) VisitGetRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type GetRequest401JSONResponse struct{ ProblemJSONResponse } + +func (response GetRequest401JSONResponse) VisitGetRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +type GetRequest404JSONResponse Problem + +func (response GetRequest404JSONResponse) VisitGetRequestResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(404) + _, err := buf.WriteTo(w) + return err +} + +type SearchLibraryRequestObject struct { + Params SearchLibraryParams +} + +type SearchLibraryResponseObject interface { + VisitSearchLibraryResponse(w http.ResponseWriter) error +} + +type SearchLibrary200JSONResponse []MediaItem + +func (response SearchLibrary200JSONResponse) VisitSearchLibraryResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + _, err := buf.WriteTo(w) + return err +} + +type SearchLibrary400JSONResponse struct{ ProblemJSONResponse } + +func (response SearchLibrary400JSONResponse) VisitSearchLibraryResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(400) + _, err := buf.WriteTo(w) + return err +} + +type SearchLibrary401JSONResponse Problem + +func (response SearchLibrary401JSONResponse) VisitSearchLibraryResponse(w http.ResponseWriter) error { + + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(response); err != nil { + return err + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(401) + _, err := buf.WriteTo(w) + return err +} + +// StrictServerInterface represents all server handlers. +type StrictServerInterface interface { + // ClaimFile Agent takes the next queued file + // (POST /v1/agent/claim) + ClaimFile(ctx context.Context, request ClaimFileRequestObject) (ClaimFileResponseObject, error) + // ReportFile Agent reports the result for a claimed file + // (POST /v1/agent/files/{fileId}) + ReportFile(ctx context.Context, request ReportFileRequestObject) (ReportFileResponseObject, error) + // GetHealth Liveness and version + // (GET /v1/health) + GetHealth(ctx context.Context, request GetHealthRequestObject) (GetHealthResponseObject, error) + // ListRequests Recent requests, newest first + // (GET /v1/requests) + ListRequests(ctx context.Context, request ListRequestsRequestObject) (ListRequestsResponseObject, error) + // CreateRequest Ask for a movie or episodes to be cached + // (POST /v1/requests) + CreateRequest(ctx context.Context, request CreateRequestRequestObject) (CreateRequestResponseObject, error) + // CancelRequest Cancel the files of a request that are still queued + // (DELETE /v1/requests/{id}) + CancelRequest(ctx context.Context, request CancelRequestRequestObject) (CancelRequestResponseObject, error) + // GetRequest One request with per-file progress + // (GET /v1/requests/{id}) + GetRequest(ctx context.Context, request GetRequestRequestObject) (GetRequestResponseObject, error) + // SearchLibrary Search movies and series in Jellyfin + // (GET /v1/search) + SearchLibrary(ctx context.Context, request SearchLibraryRequestObject) (SearchLibraryResponseObject, error) +} + +type StrictHandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, request any) (any, error) +type StrictMiddlewareFunc func(f StrictHandlerFunc, operationID string) StrictHandlerFunc + +type StrictHTTPServerOptions struct { + RequestErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) + ResponseErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, err error) +} + +func NewStrictHandler(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc) ServerInterface { + return &strictHandler{ssi: ssi, middlewares: middlewares, options: StrictHTTPServerOptions{ + RequestErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + }, + ResponseErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusInternalServerError) + }, + }} +} + +func NewStrictHandlerWithOptions(ssi StrictServerInterface, middlewares []StrictMiddlewareFunc, options StrictHTTPServerOptions) ServerInterface { + if options.RequestErrorHandlerFunc == nil { + options.RequestErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusBadRequest) + } + } + if options.ResponseErrorHandlerFunc == nil { + options.ResponseErrorHandlerFunc = func(w http.ResponseWriter, r *http.Request, err error) { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + } + return &strictHandler{ssi: ssi, middlewares: middlewares, options: options} +} + +type strictHandler struct { + ssi StrictServerInterface + middlewares []StrictMiddlewareFunc + options StrictHTTPServerOptions +} + +// ClaimFile operation middleware +func (sh *strictHandler) ClaimFile(w http.ResponseWriter, r *http.Request) { + var request ClaimFileRequestObject + + var body ClaimFileJSONRequestBody + if err := runtime.BindJSONBody(r, &body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.ClaimFile(ctx, request.(ClaimFileRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "ClaimFile") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(ClaimFileResponseObject); ok { + if err := validResponse.VisitClaimFileResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// ReportFile operation middleware +func (sh *strictHandler) ReportFile(w http.ResponseWriter, r *http.Request, fileId int64) { + var request ReportFileRequestObject + + request.FileId = fileId + + var body ReportFileJSONRequestBody + if err := runtime.BindJSONBody(r, &body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.ReportFile(ctx, request.(ReportFileRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "ReportFile") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(ReportFileResponseObject); ok { + if err := validResponse.VisitReportFileResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetHealth operation middleware +func (sh *strictHandler) GetHealth(w http.ResponseWriter, r *http.Request) { + var request GetHealthRequestObject + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetHealth(ctx, request.(GetHealthRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetHealth") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetHealthResponseObject); ok { + if err := validResponse.VisitGetHealthResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// ListRequests operation middleware +func (sh *strictHandler) ListRequests(w http.ResponseWriter, r *http.Request, params ListRequestsParams) { + var request ListRequestsRequestObject + + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.ListRequests(ctx, request.(ListRequestsRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "ListRequests") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(ListRequestsResponseObject); ok { + if err := validResponse.VisitListRequestsResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// CreateRequest operation middleware +func (sh *strictHandler) CreateRequest(w http.ResponseWriter, r *http.Request) { + var request CreateRequestRequestObject + + var body CreateRequestJSONRequestBody + if err := runtime.BindJSONBody(r, &body); err != nil { + sh.options.RequestErrorHandlerFunc(w, r, fmt.Errorf("can't decode JSON body: %w", err)) + return + } + request.Body = &body + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.CreateRequest(ctx, request.(CreateRequestRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "CreateRequest") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(CreateRequestResponseObject); ok { + if err := validResponse.VisitCreateRequestResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// CancelRequest operation middleware +func (sh *strictHandler) CancelRequest(w http.ResponseWriter, r *http.Request, id int64) { + var request CancelRequestRequestObject + + request.Id = id + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.CancelRequest(ctx, request.(CancelRequestRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "CancelRequest") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(CancelRequestResponseObject); ok { + if err := validResponse.VisitCancelRequestResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// GetRequest operation middleware +func (sh *strictHandler) GetRequest(w http.ResponseWriter, r *http.Request, id int64) { + var request GetRequestRequestObject + + request.Id = id + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.GetRequest(ctx, request.(GetRequestRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "GetRequest") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(GetRequestResponseObject); ok { + if err := validResponse.VisitGetRequestResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// SearchLibrary operation middleware +func (sh *strictHandler) SearchLibrary(w http.ResponseWriter, r *http.Request, params SearchLibraryParams) { + var request SearchLibraryRequestObject + + request.Params = params + + handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, request interface{}) (interface{}, error) { + return sh.ssi.SearchLibrary(ctx, request.(SearchLibraryRequestObject)) + } + for _, middleware := range sh.middlewares { + handler = middleware(handler, "SearchLibrary") + } + + response, err := handler(r.Context(), w, r, request) + + if err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } else if validResponse, ok := response.(SearchLibraryResponseObject); ok { + if err := validResponse.VisitSearchLibraryResponse(w); err != nil { + sh.options.ResponseErrorHandlerFunc(w, r, err) + } + } else if response != nil { + sh.options.ResponseErrorHandlerFunc(w, r, fmt.Errorf("unexpected response type: %T", response)) + } +} + +// Base64 encoded, compressed with deflate, json marshaled OpenAPI spec. +// Stored as a slice of fixed-width chunks rather than one concatenated +// const string: with thousands of chunks the chained `+` fold is several +// times slower for the Go compiler than parsing a slice literal. +var swaggerSpec = []string{ + "zFlfc9s4Dv8qGN49JDeK7bjt7Y77lHa3d91tt72m132oM2dagi02EqmSlB1vxt/9BiT1z5YTZ/tn9ikK", + "JYIg8APwA3zLYpUXSqK0hk1umUZTKGnQ/fNWq3mGOT3GSlqUlh55UWQi5lYoOfxklKQ1E6eYc3r6u8YF", + "m7C/DRu5Q//WDCt52+02YgmaWIuCxLAJ+1lrpRmth49J1sUSpf1Fzem50KpAbYXXbCEyfJm4J6VzbtmE", + "CWn/+ZhFzG4K9P/iEjXbRqzgNqVPwxtjtZBLemHEH/hsY9EcJWgbMY2fS6ExYZOPlQpBfFvYVb1XzT9h", + "bOmo5xkX+Tv8XKKx+9fhdFF/H7zheZHR5lVhzpJYl8KONYt2td/RppLQe7ZGbvHg4VgIoxL/vOMU/wZk", + "mc9RG1gLmwoJM4PcKDljERMWc7cxF1LkZc4moz4PhBWuNd+wrd/2Mtk/8BfMss1CSKAPQCSw0CqH4ep8", + "aJDrON03Q8Q+hT3/NajvkFga1CB5jrBOlUFYcxunUGi11GgMJBiLBA1MmcQbO2V9J9Gb/RN+wxsLv0Ep", + "nURMoLInLJSGjnYRy/mNN9N4FDU2O++zmVQWnWX5zSuUS4Lwk9GoRy3tHYvJs82+dr+nCri5RgIqDpYD", + "4PCTMLHSSWMRNpFllkXtk857T/J+v8/dO8gMvu7q2QfTFyLDd1go3YPReRWl3du5eAONPCAlVTk6s9tU", + "GKAIZdExGQJd9ulLERpNmTmFUNJ9P7KYk5dZxHhGB2/+Vy8suMiwHYIHYjXIPGSDS8ttadpHfi6x9Ceg", + "jVMSGbHdU2lFxugfpbJeLT7PsEehiP0beWbTfUOb5vA6EanrvmhYoTbCo+Hu6waRzY6+i7/GRPCXFvN9", + "lZqL7Pn/Bc8olFOUYFP0WSMTKzSgSmtEgm7ZmwoWKktQm+Yuc6Uy5NIlpCOSUZ8RMjHXXG/u2By+AKoS", + "UGhciJsIXCQOc7rzePhBJKjM0K5MqtamN/G4IL09FJDPVSlt6/1e4r27KjvTv6cPtxHbINd9onaDOmFB", + "rXBGxPrwtuPf90GbCte5WgnaalCLTt1sbvhWY6Z4QnHRU7kOhq0LFMo0xxb3CgIPoBNdh78l/3IDBlHC", + "fAM1ALhMYI3zhK/u9PtwMBj0+f5hHCVqBfBdPm/lGUKJsH3R5bT9ietreM2tRQ2Xo/HPox/7tCyLhFtM", + "LmxHS1o7syLH/S19eApEymsTNXnjbmYVEHKQ3sQaH6Za5Kid21vTm7tZbQPRPq5zLK4aUrSfAAIXuK/2", + "770/Dg3Bdj2AOMJrdX2v/NbWqeXFxg+Vgfu9WbccB2K9qUs+bUA4z4BETDqEy1eG0gi5BEfe7oOhP6RP", + "r66J7qnNiZLo8Kyt4Flvje4lCQbjUgu7uSS/BOKDXKO+KH3KcQ5zpcstN/dJrS18WyXkQvXQQK5zVws/", + "vL0El398VYQTn5oGS5VgXqBWOlFLHCi9PIU5LpRGMCpHJQNjRuP+pz5gOZjKqbyAOBMoLZwQ7wrOcUdV", + "PHOu7Cl4/o7GvdkrjpQjHSaAV+6cypMpewlrkWX+5E4m8oUPxlN2OoD3KcLF25eg0aiMir+wYFW4ZhAr", + "E3Cecgrkg6mkTYWPXHDNEyhZWyimbs34HUlLBBE+LwFsqlW5TN2WTMU8Ax1nSuJUOsNGYBS924CxGnnu", + "+WklX0hjibSqBagVarfuuGtZZEJeO8O+kdkGXlOFNHAiZJyVCeH4QvO5iOGSasapU4o227WC9x+CPWkH", + "1wh1RX4Kyqaoq4tonErtiDYmVLJmHbo4824tbTqBGf1RWvzhuv0JPHOwg2k5Gj2KrbpG6R5xNoDnHgVu", + "0UDON9RfON2864P9nG8BZVIoIa15OpV8ubNPycxvnlHj514P/0Fa1Tlmwpxvz4L/WtRyws4Ho8GIIlYV", + "KHkh2IQ9GowGj0J9cUHVyHWOpqVC+dpBKcddljKx79pfiHZae6aSzVcbiHSmAttuNrK6xG3UHciMR6Ov", + "dnY9XOmZxlw4qFAQuaxG5hyPHvf0vsolghAo9Nnj0fmhg+ubNHMg+v7RA76nHFnmuWPcfjoEll+HrEIZ", + "vh2yLGKWL009HWFXtL/xPX1jhrd+jrN1IOCa52hR06ZbJuiKgZR4Ct4Mfbp+ilo2v3+OdBUdgJvvfr8h", + "3lot9lFo63H5O6Sk/j2cTd8//jJw+Czn4eG7bjcd4D7B34uTtG6Sl9jjrn+hDW30NwzTcEJPkL75tUMa", + "2OTjVdsCr8QKJRpfuKr8WN2s4kwH7/ZKGPuu+ijqjYzPJepNExoNXT/qXjuccxv1S81ELmxHaIIL7kYy", + "41FrnuYGVncN1LZXX+ikh/QCdUrfbQf6vfjQSOog/R3GHureWRFIXKOxsBDa2Ba2qw/Y1bbJPzvjFBcb", + "riuP6ilvBLNqojlzWJpRop05hiGWUmlMBlPpt3pGHsFSrJC4YGwzqucIajGZyrNaJpysU5VhoHGnESin", + "As+yjRsyt488sW5eizuzaLUAm3JbiXjqxHvNTupqcHAsO2u3CbPTwVT+TsdKr6tjeFF9HwiQM1QQ3RkT", + "eDSruJd0fYfZEenpyg6b6MzhvxGj6JxxVJI//4q/73TRv4/2//jyfBKYqJ+gVgM6QlTO9TUmMPNLM9Bi", + "mVrga76hoQo51uXoUx80oweWk/PvVn7MNSyaaAKlG/xZBfNqKNkfnztJengrPD9JMEM/CNgBlusq28D6", + "RsXofgc/Dw3urovDQA6M5ZW/T7+zT7xqDkNeN7Vo2k2fTAiBxlLLWbf1venzEB34S7jgza/f2bBvJNZm", + "dNm7QH3mGojq57WDZehewi2+mGyHYAo/IB7iO5fu9aswzt/TrGvh99SFUhx7oRTpLOqlL5/v1D4XsvrB", + "bdwzD+pnRGHcfhxaWrP9P8GwztsMa/zkr0Cwmt+JjuBWr/3EKoJ5Q4i+ed3ohIaHlS8CnokHSiFkPQVr", + "BUf1c9LVdofZdweBH6/I2Ab1qh+fSsJmhZl1s8dSZ2FAOBkOz8c/0HxkcD758Xz8hG2j3a3tMVXUDKfW", + "yzM3n7KllLgvdTT4geSOg9Sr+ka3Dcr8zbZRvVRngtaab8C2V9v/DwA=", +} + +// decodeSpec returns the embedded OpenAPI spec as raw JSON bytes, +// after base64-decoding and flate-decompressing the embedded blob. +func decodeSpec() ([]byte, error) { + encoded := strings.Join(swaggerSpec, "") + compressed, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, fmt.Errorf("error base64 decoding spec: %w", err) + } + zr := flate.NewReader(bytes.NewReader(compressed)) + var buf bytes.Buffer + if _, err := buf.ReadFrom(zr); err != nil { + return nil, fmt.Errorf("read flate: %w", err) + } + if err := zr.Close(); err != nil { + return nil, fmt.Errorf("close flate reader: %w", err) + } + + return buf.Bytes(), nil +} + +var rawSpec = decodeSpecCached() + +// a naive cache of the decoded OpenAPI spec +func decodeSpecCached() func() ([]byte, error) { + data, err := decodeSpec() + return func() ([]byte, error) { + return data, err + } +} + +// Constructs a synthetic filesystem for resolving external references when loading openapi specifications. +func PathToRawSpec(pathToFile string) map[string]func() ([]byte, error) { + res := make(map[string]func() ([]byte, error)) + if len(pathToFile) > 0 { + res[pathToFile] = rawSpec + } + + return res +} + +// GetSpec returns the OpenAPI specification corresponding to the generated +// code in this file. External references in the spec are resolved through +// PathToRawSpec; externally-referenced files must be embedded in their +// corresponding Go packages (via the import-mapping feature). URL-based +// external refs are not supported. +func GetSpec() (swagger *openapi3.T, err error) { + resolvePath := PathToRawSpec("") + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + loader.ReadFromURIFunc = func(loader *openapi3.Loader, url *url.URL) ([]byte, error) { + pathToFile := url.String() + pathToFile = path.Clean(pathToFile) + getSpec, ok := resolvePath[pathToFile] + if !ok { + err1 := fmt.Errorf("path not found: %s", pathToFile) + return nil, err1 + } + return getSpec() + } + var specData []byte + specData, err = rawSpec() + if err != nil { + return + } + swagger, err = loader.LoadFromData(specData) + if err != nil { + return + } + return +} + +// GetSpecJSON returns the raw JSON bytes of the embedded OpenAPI +// specification: decompressed but not unmarshaled. External references +// are not resolved here; the bytes are the spec exactly as embedded by +// codegen. The result is cached at package init time, so repeated calls +// are cheap. +func GetSpecJSON() ([]byte, error) { + return rawSpec() +} + +// GetSwagger returns the OpenAPI specification corresponding to the +// generated code in this file. +// +// Deprecated: GetSwagger predates kin-openapi renaming openapi3.Swagger +// to openapi3.T. Use [GetSpec] instead. This wrapper is retained for +// backwards compatibility. +func GetSwagger() (*openapi3.T, error) { + return GetSpec() +} diff --git a/internal/jellyfin/client.go b/internal/jellyfin/client.go new file mode 100644 index 0000000..3ad585f --- /dev/null +++ b/internal/jellyfin/client.go @@ -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 +} diff --git a/internal/service/service.go b/internal/service/service.go new file mode 100644 index 0000000..918e35f --- /dev/null +++ b/internal/service/service.go @@ -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 +} diff --git a/internal/service/service_test.go b/internal/service/service_test.go new file mode 100644 index 0000000..d190e1d --- /dev/null +++ b/internal/service/service_test.go @@ -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) + } + } +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..da7f674 --- /dev/null +++ b/internal/store/store.go @@ -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" + } +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go new file mode 100644 index 0000000..1a4792d --- /dev/null +++ b/internal/store/store_test.go @@ -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) + } +} diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..e476aa9 --- /dev/null +++ b/mise.toml @@ -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 ./..."