---
name: mediaproxy-plugin
description: Build, test and publish a MediaProxy source plugin (a Go binary that adds a website, API or feed as a source to a MediaProxy server). Use when asked to create, extend or fix a MediaProxy / mediaproxy2 plugin, provider, source or add-on, or to publish one to a plugin repository.
---

# Build a MediaProxy source plugin

A MediaProxy source plugin is **one Go binary** that the MediaProxy server runs as its own
process and talks to over gRPC (HashiCorp go-plugin, protocol version 1). It describes a
catalogue, lists items, searches, and turns an item into a playable stream. The server does
everything else: storage, TMDB matching, artwork, users, the web admin and every app.

Work inside a checkout of the **mediaproxy2** repository. It contains the SDK
(`pkg/sdk`), the generated contract (`pkg/pluginv1`, from
`proto/mediaproxy/plugin/v1/plugin.proto`), the test harness (`cmd/plugintest`) and the
repository tool (`cmd/mprepo`). Read `docs/PLUGIN_GUIDE.md` there for anything this file
does not cover; it is the source of truth.

A complete, tested example ships with this skill: `references/example-main.go`
(public-domain films from the Internet Archive). Start from it.

## Workflow

1. **Study the source.** Find the JSON API the site's own web app uses (network tab, page
   source). Prefer it over HTML scraping; fall back to HTML, then sitemap or RSS. Note which
   hostnames are involved, how listings page, how search works, and how a stream URL is
   obtained. Follow multi-stage URLs (JSON selector → manifest) to the real manifest.
2. **Scaffold.** Pick a lowercase slug id (`mysource`). Create
   `cmd/plugins/<id>/main.go` by copying `references/example-main.go` and renaming the type.
3. **Implement `sdk.Provider`** (see the contract below), then any optional interfaces.
4. **Build:** `go build -o bin/plugins/<id> ./cmd/plugins/<id>`
5. **Test until it passes:**
   ```bash
   go build -o bin/plugintest ./cmd/plugintest
   ./bin/plugintest -plugin bin/plugins/<id> describe
   ./bin/plugintest -plugin bin/plugins/<id> categories
   ./bin/plugintest -plugin bin/plugins/<id> items <categoryKey> 10
   ./bin/plugintest -plugin bin/plugins/<id> details <extId>
   ./bin/plugintest -plugin bin/plugins/<id> search <query>
   ./bin/plugintest -plugin bin/plugins/<id> resolve <extId>
   ./bin/plugintest -plugin bin/plugins/<id> validate      # must print ALL PASS
   ```
   Use `-config key=value,...` for settings, `-v` for plugin logs, and `-proxy <url>` when the
   site is geo-locked. Fix every `[FAIL]` and run `validate` again. Do not stop before
   `ALL PASS`.
6. **Report** what the plugin covers, what it cannot play and why, and the final
   `validate` output.
7. **Publish** only when asked (see "Publish to a repository").

## The contract

```go
type Provider interface {
	Manifest() *pluginv1.Manifest
	Configure(ctx context.Context, values map[string]string, host *sdk.Host) error
	TestConnection(ctx context.Context) error
	ListCategories(ctx context.Context) ([]*pluginv1.Category, error)
	ListItems(ctx context.Context, categoryKey, cursor string, limit int) (*pluginv1.ItemPage, error)
	GetDetails(ctx context.Context, extID string) (*pluginv1.Details, error)
	Search(ctx context.Context, query string, limit int) (*pluginv1.ItemPage, error)
	ResolvePlayback(ctx context.Context, extID string, maxHeight int) (*pluginv1.Playback, error)
}

func main() { sdk.Serve(&MySource{}) }
```

| Method | What it must do |
|---|---|
| `Manifest` | `Id` (lowercase slug, unique), `Name`, `Version`, `Description`, `Homepage`, `Capabilities`, `Constraints`, `ConfigSchema`, `Permissions`, `Countries`, `Languages`. `DefaultExit` (`"de"`, `"fr"`, `"uk"`, …) only for geo-locked sites. |
| `Configure` | Store `host` and read your settings. **No network calls.** App-wide settings arrive as `host.` keys (`host.tmdb_key`); never add your own field for those. May be called again later. |
| `TestConnection` | One cheap request that proves the source answers. |
| `ListCategories` | At least one category. Keys are stable (they end up in URLs). Set `Section` (`sdk.SectionMovies`, `SectionSeries`, `SectionDocumentaries`, …) when a row has one subject. |
| `ListItems` | Page with `cursor` (any string you define; `""` = first page). Return `NextCursor: ""` when done. Every item needs `ExtId`, `Type`, `Title`. |
| `GetDetails` | The item, plus `Episodes` for a `SHOW` (`Type: EPISODE`, `ParentExtId`, `Season`, `Episode`). A single video returns no episodes. |
| `Search` | Results, or an empty page if the source cannot search. Never an error for "no search". |
| `ResolvePlayback` | A `Playback` whose `Locator.Url` is a **real manifest** (`#EXTM3U`, `<MPD`) or direct media, never a JSON or HTML page. |

Optional interfaces (detected by type assertion): `sdk.EPGProvider` (programme guide),
`sdk.NowPlayingProvider` (song on a radio station; return an empty response when unknown and
set `RefreshSeconds`), `sdk.ImageFetcher` (images that are not URLs; wrap placeholders in
`sdk.StandInImage`), `sdk.Downloader`, `sdk.TestReporter`, `sdk.ConfigRewriter`,
`sdk.AuthFlows` (interactive login; list flow ids in `Manifest.AuthFlows`).

## Rules

**HTTP**
- All HTTP goes through `host.HTTP` (or `host.Stream` for large bodies). **Never build your
  own `http.Client`.** The host performs the request through the exit the operator chose, so
  resolve and playback leave from the same IP.
- Declare every hostname you fetch in `Permissions.Net` (`"api.example.com"`,
  `"*.example.com"`). Set `Lan: true` only when the operator points you at a LAN address.
  Blocked requests fail with an error starting `blocked:`.
- Store tokens and sessions in `host.State` (`Get`, `Set`, `Delete`), not in files.

**Items**
- Fill in everything the source gives you: `Description`, `Image`/`Backdrop` (16:9, at least
  1280 px wide), `Year` (production year, not upload date), `DurationSeconds`, `Lang`,
  `OriginalTitle`, `ExternalIds` (TMDB/IMDb ids make matching exact), `AudioLangs`,
  `SubtitleLangs`, `Genres`, `AgeRating` (as stated), `AvailableUntil`, `Country`, `Height`,
  `AirDate`, `WebUrl`. Anything else goes in `Meta`.
- Set `Type` honestly: `MOVIE`, `SHOW`, `EPISODE` or `LIVESTREAM`. Do not declare the
  Series/Movies/Live split yourself; the host does it.
- `Logo` is only the show's transparent title wordmark from the source. Never a channel logo,
  never a guessed URL.
- Report everything the source has. Do not add your own "exclude these" settings; the operator
  switches groups and channels on and off in the web admin.

**Playback**
- `Locator{Scheme: HLS | DASH | MP4 | MP3 | ICY, Url}`.
- `Headers`: every header the CDN needs for manifest and segments (`Referer`, `Origin`,
  `User-Agent`, `Cookie`, `Authorization`). Missing headers are the most common failure.
- Set `Live` for live streams, `TtlSeconds` for short-lived URLs, `IpBound` when a URL only
  plays from the resolving IP, `ProxyHint: REQUIRE_PROXY` when the CDN geo-blocks.
- Add `AudioTracks`, `Subtitles` and `Variants` when the source lists them separately.
- When an item exists but cannot be played (needs a login or subscription, expired), return a
  `Playback` with `UnavailableReason` set and no locator. That is a correct outcome, not an
  error. Mark such items when listing them with `sdk.Gate(item, sdk.AccessLogin)` or
  `sdk.Gate(item, sdk.AccessSubscription)`.
- Protected (DRM) streams: **describe only** (`Drm{System: …}`). Never fetch licences or
  decrypt. Prefer any clear stream the source offers.

**Robustness**
- Parse items one by one so a single broken item does not empty a category, but if a whole
  listing parses to zero items, return an error.
- Cache expensive listings in memory with a TTL and page the cached slice with the cursor.
- Keep a full sync of all categories in the low tens of seconds; run independent fetches
  concurrently, at most 6 in flight.
- Set `Constraints.CompleteCatalog = true` only if listing every category really returns the
  whole catalogue (the host then removes items that disappeared).

**Scope**
- Only build plugins for sources the user is allowed to use. Do not add code that bypasses
  DRM, paywalls, logins or geo-restrictions.

## Settings form

`ConfigSchema` fields render as the plugin's settings form in the web admin:

```go
ConfigSchema: []*pluginv1.ConfigField{
	{Key: "api_key", Label: "API key", Type: pluginv1.ConfigField_SECRET, Required: true,
		Help: "Create a free key at example.com/account."},
	{Key: "region", Label: "Region", Type: pluginv1.ConfigField_SELECT, Default: "eu",
		Options: []*pluginv1.SelectOption{{Value: "eu", Label: "Europe"}, {Value: "us", Label: "USA"}}},
},
```

Types: `TEXT`, `SECRET`, `INT`, `BOOL`, `SELECT`, `URL`, `TEXTAREA`, `DIR`, `DIRS`, `EXITS`.
Values arrive in `Configure` as strings keyed by `Key`.

## Install locally

Copy the binary into the server's plugin folder (`MP_PLUGIN_DIR`, default `bin/plugins`).
The server picks it up within a minute. In the web admin: Sources → Plugins → the plugin →
enable, press Test, then Sync now.

## Publish to a repository

```bash
go build -o mprepo ./cmd/mprepo
./mprepo keygen -key repo.key                      # once; keep repo.key secret and backed up
GOOS=linux GOARCH=amd64 go build -o bin/linux_amd64/<id> ./cmd/plugins/<id>
GOOS=linux GOARCH=arm64 go build -o bin/linux_arm64/<id> ./cmd/plugins/<id>
./mprepo add -key repo.key -repo ./repo -repo-name "My plugins" -publisher "Me" \
  -platform linux/amd64 -id <id> -version 1.0.0 bin/linux_amd64/<id>
./mprepo add -key repo.key -repo ./repo -platform linux/arm64 -id <id> -version 1.0.0 bin/linux_arm64/<id>
./mprepo verify -repo ./repo
```

Upload `./repo` to any static web server (GitHub Pages, S3, nginx) and share the URL.
Operators add it under Sources → Repositories; their server pins the signing key, verifies
checksums and rolls back failed updates. Set `Countries` and `Languages` in the manifest so
the repository filters show the plugin to the right people.

## Done means

- `./bin/plugintest -plugin bin/plugins/<id> validate` prints `ALL PASS`.
- Every fetched hostname is listed in `Permissions.Net`.
- No custom HTTP client, no network in `Configure`, no DRM circumvention.
- Unplayable items return `UnavailableReason`, not errors.
