Crea tu propia fuente
Una fuente es un pequeño programa en Go. Describe tu catálogo, devuelve streams reproducibles y el servidor se encarga de la asociación, las imágenes, los usuarios y todas las apps.
- 1
Escríbela
Implementa seis métodos con el SDK: describir, listar categorías, listar elementos, detalles, buscar y resolver la reproducción.
- 2
Pruébala
plugintest ejecuta la batería de pruebas de aceptación contra el sitio real hasta que muestra ALL PASS.
- 3
Publícala
mprepo firma un repositorio que puedes alojar en GitHub Pages, S3 o cualquier servidor web.
Descarga el ejemplo
Un plugin de fuente completo para películas de dominio público de Internet Archive. Supera la batería de pruebas de aceptación plugintest contra el sitio real.
Probado con plugintest: ALL PASS
Que lo programe tu agente de IA
Dale nuestro skill de plugins a Claude Code, Codex o cualquier agente de programación. Conoce el contrato, las reglas y el ciclo de pruebas, y no para hasta que plugintest muestra ALL PASS.
Pega esto en tu agente, dentro de una copia de mediaproxy2:
Lee /downloads/mediaproxy-plugin-skill/SKILL.md y síguelo para crear un plugin de MediaProxy para <tu fuente>.Para instalarlo de forma permanente, descomprime la carpeta en el directorio de skills de tu agente; en Claude Code, ~/.claude/skills/.
Tipos de plugins
Cada plugin es un binario de Go que el servidor arranca como un proceso propio. Lo que hace determina cómo se sirve y dónde aparece en la administración web.
Fuente de contenido
sdk.ServeLista películas, series, canales en directo, radio, música o pódcasts y los convierte en streams. La mayoría de los plugins son de este tipo.
Listas
Types: "lists"Listados de títulos, como rankings o listas de seguimiento, que el servidor convierte en filas en todas las apps.
Salvapantallas
Types: "screensaver"Diapositivas para el salvapantallas de la tele: carteles, fotos o un canal en directo.
Directorio musical
Types: "musicdir"Responde a las búsquedas de música de todo el servidor: portadas, fotos de artistas y pistas.
Solo búsqueda
Types: "search"No sincroniza un catálogo propio y solo responde a búsquedas.
Salida de red
sdk.ServeExitOfrece salidas VPN o smart DNS por las que el operador puede enrutar las fuentes.
Proxy de streams
sdk.ServeProxyPluginSe sitúa entre un stream y las apps cuando un formato necesita procesarse antes.
Cómo ejecuta el servidor un plugin
- 1
Arranque
El servidor lanza el binario y ambas partes comprueban el handshake (versión de protocolo 1). A partir de ahí se comunican por gRPC.
- 2
Descripción
El servidor lee Manifest y genera el formulario de ajustes de la administración web a partir de ConfigSchema.
- 3
Configuración
Los ajustes guardados y los servicios del host llegan en Configure. El botón Probar llama a TestConnection.
- 4
Sincronización
Según una programación, el servidor llama a ListCategories, recorre las páginas de ListItems y GetDetails, lo guarda todo y empareja los títulos con TMDB.
- 5
Reproducción
Cuando alguien pulsa reproducir, el servidor llama a ResolvePlayback y envía el resultado a la app.
La interfaz
Una fuente de contenido implementa sdk.Provider. Los tipos son los mensajes protobuf generados, así que plugin y servidor comparten un mismo vocabulario.
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{}) }Opcional
Implementa también cualquiera de estas y decláralas en Capabilities:
EPGProviderQué hay ahora y más tarde en tus canales en directo.
GetEPG(ctx context.Context, extIDs []string, from, to time.Time) ([]*pluginv1.Programme, time.Time, error)NowPlayingProviderLa canción que está sonando ahora mismo en una emisora de radio.
NowPlaying(ctx context.Context, extID string) (*pluginv1.NowPlayingResponse, error)ImageFetcherImágenes que no son simples URL, o un monograma de sustitución.
FetchImage(ctx context.Context, ref string) (contentType string, data []byte, err error)DownloaderGuardar elementos en disco tú mismo, con tu propia estructura.
Download(ctx context.Context, extID string) ([]*pluginv1.DownloadJob, error)TestReporterUn mensaje útil tras una prueba correcta, como la fecha de caducidad de una cuenta.
TestDetail() stringConfigRewriterAjustes que se derivan de otros ajustes, que se vuelven a escribir para que el operador los vea.
RewriteConfig(ctx context.Context, values map[string]string, host *Host) (map[string]string, error)
El manifiesto
Manifest le dice al servidor quién es el plugin, qué puede hacer y a qué puede acceder. Campos principales:
Id- Slug en minúsculas, único entre todos los tipos de plugin.
Name, Version, Description, Homepage- Se muestran en la administración web y en los repositorios.
Capabilities- Lo que implementas: catalog, search, details, live, epg, now_playing, download y más.
Constraints- needs_exit para contenido con bloqueo geográfico, ip_bound y url_ttl_seconds para URL de corta duración, complete_catalog para que el servidor pueda eliminar los títulos que han desaparecido.
ConfigSchema- El formulario de ajustes: text, secret, int, bool, select, url, textarea, carpetas y listas de salidas.
Permissions- Los nombres de host a los que el plugin puede acceder, si puede llegar a la red local y qué carpetas puede usar.
Countries, Languages- Los usan los filtros de país e idioma de los repositorios.
Content- catalog (películas y series, emparejadas con TMDB), clips, live o music.
SearchKinds- Lo que devuelve Search: películas, series, música o directo.
DefaultExit- El país de salida que sugieres. Decide el operador.
Elementos y reproducción
pluginv1.ItemRellena todo lo que te dé el sitio. Cuanto más diga un Item, mejor será el emparejamiento y más completas las apps.
ExtId- Tu propio id estable para el elemento.
Type- SHOW, MOVIE, EPISODE o LIVESTREAM.
Title, OriginalTitle, Description- Tal como los indica el sitio.
Image, Backdrop, Logo- Imágenes como ImageRef: una URL con cabeceras opcionales.
Year, AirDate, DurationSeconds- Se usan para el emparejamiento con TMDB y para ordenar.
ParentExtId, Season, Episode- Cómo pertenecen los episodios a una serie.
ExternalIds- Ids de TMDB o IMDb cuando el sitio los tiene.
AudioLangs, SubtitleLangs, Genres, AgeRating- Se muestran en las apps y los usan los filtros.
Section- movies, series, documentaries, shows, news, sport, kids o culture.
pluginv1.PlaybackResolvePlayback devuelve un Playback:
Locator- Esquema (HLS, DASH, MP4, MP3, ICY) y la URL que se reproduce.
Headers- Las cabeceras que necesita la CDN para el manifiesto y los segmentos.
Live- True para canales en directo y radio.
TtlSeconds, IpBound- Cuánto tiempo sigue siendo válida la URL y si solo se reproduce desde la IP que la resolvió.
AudioTracks, Subtitles, Variants- Pistas y calidades adicionales cuando el sitio las indica.
UnavailableReason- Se rellena en lugar de un localizador cuando un elemento no se puede reproducir, con un motivo que muestran las apps.
Lo que el servidor le da a tu plugin
HTTP a través del host
Cada petición sale por la salida que el operador eligió para tu fuente.
Almacenamiento
Un almacén clave-valor para sesiones y tokens que sobrevive a los reinicios.
Herramientas multimedia
ffmpeg, ffprobe y yt-dlp, que el servidor mantiene actualizados.
Medidas de protección
Una lista de red permitida a partir de tu manifiesto, sin acceso a la red local salvo que lo declares, y un límite de memoria.
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
}El ejemplo completo
Cada línea del plugin descargable. Lista dos filas, pagina con un cursor, busca en directo y resuelve el mejor MP4.
// 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{}) }Prueba contra el sitio real
plugintest describe, lista, busca y resuelve streams. validate es la batería de pruebas de aceptación: al menos una categoría, elementos válidos en todas partes, detalles de dos series y tres pruebas de reproducción que funcionen.
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 PASSPublica un repositorio firmado
mprepo crea tu clave de firma, añade compilaciones para cada plataforma y revisa la carpeta. Súbela a GitHub Pages, S3 o cualquier servidor web y comparte la 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 ./repoLa guía completa de plugins cubre formularios de ajustes, cuentas de usuario, guías de programación, música, pódcasts y las reglas de scraping que aprendimos a base de errores.