mediaproxy

Bau deine eigene Quelle

Eine Quelle ist ein kleines Go-Programm. Beschreib deinen Katalog, liefere abspielbare Streams, und der Server kümmert sich um Zuordnung, Artwork, Nutzer und jede App.

  1. 1

    Schreiben

    Implementiere mit dem SDK sechs Methoden: beschreiben, Kategorien auflisten, Einträge auflisten, Details, Suche und Wiedergabe auflösen.

  2. 2

    Testen

    plugintest lässt die Abnahmetests gegen die echte Website laufen, bis ALL PASS erscheint.

  3. 3

    Veröffentlichen

    mprepo signiert ein Repository, das du auf GitHub Pages, S3 oder jedem Webserver hosten kannst.

Beispiel herunterladen

Ein vollständiges Quell-Plugin für gemeinfreie Filme aus dem Internet Archive. Es besteht die plugintest-Abnahmesuite gegen die Live-Seite.

Getestet mit plugintest: ALL PASS

Lass deinen KI-Coding-Agenten bauen

Gib Claude Code, Codex oder einem anderen Coding-Agenten unseren Plugin-Skill. Er kennt den Vertrag, die Regeln und die Testschleife und hört erst auf, wenn plugintest ALL PASS meldet.

Füge das in deinen Agenten ein, in einem Checkout von mediaproxy2:

Lies /downloads/mediaproxy-plugin-skill/SKILL.md und baue danach ein MediaProxy-Plugin für <deine Quelle>.

Für eine dauerhafte Installation entpackst du den Ordner in das Skills-Verzeichnis deines Agenten, bei Claude Code ~/.claude/skills/.

Arten von Plugins

Jedes Plugin ist ein Go-Binary, das der Server als eigenen Prozess startet. Was es tut, entscheidet, wie es bereitgestellt wird und wo es im Web-Admin erscheint.

Wie der Server ein Plugin ausführt

  1. 1

    Start

    Der Server startet das Binary und beide Seiten prüfen den Handshake (Protokollversion 1). Ab dann sprechen sie gRPC.

  2. 2

    Beschreiben

    Der Server liest Manifest und baut aus ConfigSchema das Einstellungsformular im Web-Admin.

  3. 3

    Konfigurieren

    Gespeicherte Einstellungen und die Host-Dienste kommen in Configure an. Der Test-Button ruft TestConnection auf.

  4. 4

    Synchronisieren

    Nach Zeitplan ruft der Server ListCategories auf, blättert durch ListItems und GetDetails, speichert alles und ordnet Titel TMDB zu.

  5. 5

    Abspielen

    Wenn jemand auf Play drückt, ruft der Server ResolvePlayback auf und streamt das Ergebnis an die App.

Das Interface

Eine Inhaltsquelle implementiert sdk.Provider. Die Typen sind die generierten Protobuf-Nachrichten, damit Plugin und Server dasselbe Vokabular teilen.

type Provider interface {
	Manifest() *pluginv1.Manifest
	// Configure receives the operator's values for the fields declared in
	// Manifest().ConfigSchema plus the Host services to use for HTTP/state.
	Configure(ctx context.Context, values map[string]string, host *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{}) }

Optional

Implementiere zusätzlich beliebige davon und deklariere sie in Capabilities:

Das Manifest

Manifest sagt dem Server, wer das Plugin ist, was es kann und was es erreichen darf. Die wichtigsten Felder:

Id
Slug in Kleinbuchstaben, eindeutig über alle Plugin-Arten hinweg.
Name, Version, Description, Homepage
Wird im Web-Admin und in Repositories angezeigt.
Capabilities
Was du implementierst: catalog, search, details, live, epg, now_playing, download und mehr.
Constraints
needs_exit für geogesperrte Inhalte, ip_bound und url_ttl_seconds für kurzlebige URLs, complete_catalog, damit der Server verschwundene Titel entfernen darf.
ConfigSchema
Das Einstellungsformular mit den Feldtypen text, secret, int, bool, select, url, textarea, Ordnern und Exit-Listen.
Permissions
Die Hostnamen, die das Plugin abrufen darf, ob es ins LAN darf und welche Ordner es nutzen darf.
Countries, Languages
Für die Länder- und Sprachfilter in Repositories.
Content
catalog (Filme und Serien, TMDB zugeordnet), clips, live oder music.
SearchKinds
Was Search liefert: Filme, Serien, Musik oder Live.
DefaultExit
Das Exit-Land, das du vorschlägst. Der Betreiber entscheidet.

Einträge und Wiedergabe

pluginv1.ItemFülle alles aus, was die Seite hergibt. Je mehr ein Item aussagt, desto besser die Zuordnung und desto reichhaltiger die Apps.

ExtId
Deine eigene stabile ID für den Eintrag.
Type
SHOW, MOVIE, EPISODE oder LIVESTREAM.
Title, OriginalTitle, Description
So, wie die Seite sie angibt.
Image, Backdrop, Logo
Artwork als ImageRef: eine URL mit optionalen Headern.
Year, AirDate, DurationSeconds
Für die TMDB-Zuordnung und die Sortierung.
ParentExtId, Season, Episode
Wie Episoden zu einer Serie gehören.
ExternalIds
TMDB- oder IMDb-IDs, wenn die Seite sie hat.
AudioLangs, SubtitleLangs, Genres, AgeRating
Werden in den Apps angezeigt und von Filtern genutzt.
Section
movies, series, documentaries, shows, news, sport, kids oder culture.

pluginv1.PlaybackResolvePlayback gibt ein Playback zurück:

Locator
Schema (HLS, DASH, MP4, MP3, ICY) und die abzuspielende URL.
Headers
Header, die das CDN für Manifest und Segmente braucht.
Live
True für Live-Sender und Radio.
TtlSeconds, IpBound
Wie lange die URL gültig bleibt und ob sie nur von der auflösenden IP abspielbar ist.
AudioTracks, Subtitles, Variants
Zusätzliche Spuren und Qualitäten, wenn die Seite sie auflistet.
UnavailableReason
Wird statt eines Locators gesetzt, wenn ein Eintrag nicht abspielbar ist, mit einem Grund, den die Apps anzeigen.

Was der Server deinem Plugin bietet

  • HTTP über den Host

    Jede Anfrage geht über den Ausgang raus, den der Betreiber für deine Quelle gewählt hat.

  • Speicher

    Ein Key-Value-Speicher für Sitzungen und Tokens, der Neustarts übersteht.

  • Medienwerkzeuge

    ffmpeg, ffprobe und yt-dlp, vom Server aktuell gehalten.

  • Leitplanken

    Eine Netzwerk-Allowlist aus deinem Manifest, kein LAN-Zugriff ohne Angabe und ein Speicherlimit.

type Host struct {
	HTTP      *http.Client // every request leaves through the operator's exit
	Stream    *http.Client // the same, for big bodies with no size cap
	State     State        // persistent key/value store for this plugin
	Media     Media        // ffmpeg, ffprobe and yt-dlp
	Music     Music        // covers, artist photos and tracks
	Lists     Lists        // feeds of the enabled "lists" plugins
	Solver    Solver       // pages behind a browser challenge
	// … see pkg/sdk/host.go
}

Das vollständige Beispiel

Jede Zeile des herunterladbaren Plugins. Es listet zwei Reihen, blättert mit einem Cursor, sucht live und löst das beste MP4 auf.

Beispiel mit README (.zip)
// Archive Films: a complete example MediaProxy source plugin.
//
// It lists public-domain feature films from the Internet Archive
// (archive.org), searches them, and resolves each one to a playable MP4.
// Everything here is the real plugin contract: build it inside the
// mediaproxy2 repository and drop the binary into the plugin folder.
//
//	mkdir -p cmd/plugins/archivefilms && cp main.go cmd/plugins/archivefilms/
//	go build -o bin/plugins/archivefilms ./cmd/plugins/archivefilms
//	./bin/plugintest -plugin bin/plugins/archivefilms validate
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"sync"

	pluginv1 "mediaproxy2/pkg/pluginv1"
	"mediaproxy2/pkg/sdk"
)

const (
	searchURL = "https://archive.org/advancedsearch.php"
	pageSize  = 50
)

// ArchiveFilms implements sdk.Provider.
type ArchiveFilms struct {
	mu         sync.Mutex
	host       *sdk.Host
	collection string
}

// Manifest describes the plugin to the host: identity, what it can do,
// which hosts it may reach, and the settings form shown in the web admin.
func (a *ArchiveFilms) Manifest() *pluginv1.Manifest {
	return &pluginv1.Manifest{
		Id:          "archivefilms",
		Name:        "Archive Films",
		Version:     "1.0.0",
		Description: "Public-domain feature films from the Internet Archive.",
		Homepage:    "https://archive.org/details/feature_films",
		Capabilities: &pluginv1.Capabilities{
			Catalog: true, // ListCategories + ListItems
			Search:  true, // Search
			Details: true, // GetDetails
		},
		Constraints: &pluginv1.Constraints{
			CompleteCatalog: false, // we page through a slice, not everything
		},
		// The host only lets the plugin fetch these hostnames.
		Permissions: &pluginv1.Permissions{Net: []string{"archive.org", "*.archive.org"}},
		Countries:   []string{"global"},
		Languages:   []string{"en"},
		ConfigSchema: []*pluginv1.ConfigField{{
			Key:     "collection",
			Label:   "Collection",
			Type:    pluginv1.ConfigField_TEXT,
			Default: "feature_films",
			Help:    "Which archive.org collection to list, for example feature_films or silent_films.",
		}},
	}
}

// Configure receives the operator's settings and the host services.
// All HTTP must go through host.HTTP so it leaves via the operator's exit.
func (a *ArchiveFilms) Configure(_ context.Context, values map[string]string, host *sdk.Host) error {
	a.mu.Lock()
	defer a.mu.Unlock()
	a.host = host
	a.collection = strings.TrimSpace(values["collection"])
	if a.collection == "" {
		a.collection = "feature_films"
	}
	return nil
}

// TestConnection drives the Test button in the web admin.
func (a *ArchiveFilms) TestConnection(ctx context.Context) error {
	_, err := a.search(ctx, a.query(""), 1, 1)
	return err
}

// ListCategories returns the rows this source offers.
func (a *ArchiveFilms) ListCategories(context.Context) ([]*pluginv1.Category, error) {
	return []*pluginv1.Category{
		{Key: "popular", Name: "Most watched", Sort: 0, Section: sdk.SectionMovies},
		{Key: "recent", Name: "Recently added", Sort: 1, Section: sdk.SectionMovies},
	}, nil
}

// ListItems pages through one category. The cursor is ours to define:
// here it is the next archive.org page number.
func (a *ArchiveFilms) ListItems(ctx context.Context, categoryKey, cursor string, limit int) (*pluginv1.ItemPage, error) {
	page, _ := strconv.Atoi(cursor)
	if page < 1 {
		page = 1
	}
	if limit <= 0 || limit > pageSize {
		limit = pageSize
	}
	sort := "downloads desc"
	if categoryKey == "recent" {
		sort = "addeddate desc"
	}
	docs, err := a.searchSorted(ctx, a.query(""), sort, page, limit)
	if err != nil {
		return nil, err
	}
	out := &pluginv1.ItemPage{}
	for _, d := range docs {
		out.Items = append(out.Items, d.item(categoryKey))
	}
	if len(docs) == limit && page < 4 { // keep the example catalogue small
		out.NextCursor = strconv.Itoa(page + 1)
	}
	return out, nil
}

// GetDetails returns one title. Films have no episodes, so Episodes stays empty.
func (a *ArchiveFilms) GetDetails(ctx context.Context, extID string) (*pluginv1.Details, error) {
	docs, err := a.search(ctx, "identifier:"+quote(extID), 1, 1)
	if err != nil {
		return nil, err
	}
	if len(docs) == 0 {
		return nil, fmt.Errorf("%s: not found", extID)
	}
	return &pluginv1.Details{Item: docs[0].item("")}, nil
}

// Search answers the app's search box live.
func (a *ArchiveFilms) Search(ctx context.Context, query string, limit int) (*pluginv1.ItemPage, error) {
	if limit <= 0 || limit > pageSize {
		limit = pageSize
	}
	docs, err := a.search(ctx, a.query(query), 1, limit)
	if err != nil {
		return nil, err
	}
	out := &pluginv1.ItemPage{}
	for _, d := range docs {
		out.Items = append(out.Items, d.item(""))
	}
	return out, nil
}

// ResolvePlayback turns an item into something playable: here the best
// MP4 file of the archive.org item. The host proxies it to every app.
func (a *ArchiveFilms) ResolvePlayback(ctx context.Context, extID string, maxHeight int) (*pluginv1.Playback, error) {
	var meta struct {
		Files []struct {
			Name   string `json:"name"`
			Format string `json:"format"`
			Height string `json:"height"`
		} `json:"files"`
	}
	if err := a.getJSON(ctx, "https://archive.org/metadata/"+url.PathEscape(extID), &meta); err != nil {
		return nil, err
	}
	best, bestHeight := "", 0
	for _, f := range meta.Files {
		if !strings.HasSuffix(strings.ToLower(f.Name), ".mp4") {
			continue
		}
		h, _ := strconv.Atoi(f.Height)
		if maxHeight > 0 && h > maxHeight {
			continue
		}
		if best == "" || h > bestHeight {
			best, bestHeight = f.Name, h
		}
	}
	if best == "" {
		// A described outcome, not an error: the apps show the reason.
		return &pluginv1.Playback{UnavailableReason: "This item has no MP4 file."}, nil
	}
	return &pluginv1.Playback{
		Locator: &pluginv1.Locator{
			Scheme: pluginv1.Scheme_MP4,
			Url:    "https://archive.org/download/" + url.PathEscape(extID) + "/" + url.PathEscape(best),
		},
		Height: uint32(bestHeight),
		Lang:   "en",
	}, nil
}

// --- archive.org helpers -------------------------------------------------

type doc struct {
	Identifier  string `json:"identifier"`
	Title       string `json:"title"`
	Description any    `json:"description"` // a string or a list of strings
	Year        any    `json:"year"`
}

func (d doc) item(category string) *pluginv1.Item {
	year, _ := strconv.Atoi(fmt.Sprint(d.Year))
	return &pluginv1.Item{
		ExtId:       d.Identifier,
		Type:        pluginv1.ItemType_MOVIE,
		Title:       d.Title,
		Description: text(d.Description),
		Year:        int32(year),
		CategoryKey: category,
		Image:       &pluginv1.ImageRef{Url: "https://archive.org/services/img/" + d.Identifier},
		WebUrl:      "https://archive.org/details/" + d.Identifier,
		Lang:        "en",
	}
}

func (a *ArchiveFilms) query(words string) string {
	a.mu.Lock()
	q := "collection:" + quote(a.collection) + " AND mediatype:movies"
	a.mu.Unlock()
	if words = strings.TrimSpace(words); words != "" {
		q += " AND title:(" + words + ")"
	}
	return q
}

func (a *ArchiveFilms) search(ctx context.Context, q string, page, rows int) ([]doc, error) {
	return a.searchSorted(ctx, q, "downloads desc", page, rows)
}

func (a *ArchiveFilms) searchSorted(ctx context.Context, q, sort string, page, rows int) ([]doc, error) {
	v := url.Values{}
	v.Set("q", q)
	for _, f := range []string{"identifier", "title", "description", "year"} {
		v.Add("fl[]", f)
	}
	v.Set("sort[]", sort)
	v.Set("rows", strconv.Itoa(rows))
	v.Set("page", strconv.Itoa(page))
	v.Set("output", "json")
	var res struct {
		Response struct {
			Docs []doc `json:"docs"`
		} `json:"response"`
	}
	if err := a.getJSON(ctx, searchURL+"?"+v.Encode(), &res); err != nil {
		return nil, err
	}
	return res.Response.Docs, nil
}

func (a *ArchiveFilms) getJSON(ctx context.Context, u string, into any) error {
	a.mu.Lock()
	host := a.host
	a.mu.Unlock()
	if host == nil {
		return errors.New("not configured")
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
	if err != nil {
		return err
	}
	resp, err := host.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("archive.org answered %s", resp.Status)
	}
	return json.NewDecoder(resp.Body).Decode(into)
}

func quote(s string) string { return `"` + strings.ReplaceAll(s, `"`, ``) + `"` }

func text(v any) string {
	switch t := v.(type) {
	case string:
		return t
	case []any:
		if len(t) > 0 {
			return fmt.Sprint(t[0])
		}
	}
	return ""
}

func main() { sdk.Serve(&ArchiveFilms{}) }

Gegen die echte Website testen

plugintest beschreibt, listet, sucht und löst Streams auf. validate ist die Abnahmesuite: mindestens eine Kategorie, überall gültige Einträge, Details für zwei Serien und drei funktionierende Wiedergabeproben.

go build -o bin/plugintest ./cmd/plugintest
./bin/plugintest -plugin bin/plugins/archivefilms validate

[PASS] manifest                 archivefilms v1.0.0
[PASS] test_connection          ok
[PASS] categories               2 categories
[PASS] items:popular            50 items, 0 invalid
[PASS] items:recent             50 items, 0 invalid
[PASS] resolve:sex_madness      media bytes (video/mp4) (MP4)
ALL PASS

Signiertes Repository veröffentlichen

mprepo erstellt deinen Signaturschlüssel, fügt Builds für jede Plattform hinzu und prüft den Ordner. Lade ihn auf GitHub Pages, S3 oder einen beliebigen Webserver hoch und teile die URL.

go build -o mprepo ./cmd/mprepo
./mprepo keygen -key repo.key
GOOS=linux GOARCH=arm64 go build -o bin/linux_arm64/archivefilms ./cmd/plugins/archivefilms
./mprepo add -key repo.key -repo ./repo -platform linux/arm64 \
  -id archivefilms -version 1.0.0 bin/linux_arm64/archivefilms
./mprepo verify -repo ./repo

Der vollständige Plugin-Leitfaden behandelt Einstellungsformulare, Nutzerkonten, Programmführer, Musik, Podcasts und die Scraping-Regeln, die wir auf die harte Tour gelernt haben.