From 9c0dc32455918cac6478d94881d07e8ca417e32f Mon Sep 17 00:00:00 2001 From: Quick104 <31828688+Quick104@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:57:15 -0500 Subject: [PATCH 1/6] feat(events): publish the host event catalog with typed payloads Add pkg/pluginsdk/events: the event names a host delivers to event_consumer.v1 capabilities, the access class of each (public, admin, user_data), Go payload types, Decode for plugins, and Project, which hosts use to rewrite a payload into its public shape. The manifest validator now checks subscriptions: event_consumer.v1 only, well-formed names, no repeats. Unknown names stay valid so a plugin built against a newer SDK loads on an older host. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/compatibility.md | 7 + docs/events.md | 97 +++++++++ docs/runtime-host.md | 4 +- pkg/pluginsdk/events/events.go | 209 ++++++++++++++++++ pkg/pluginsdk/events/events_test.go | 122 +++++++++++ pkg/pluginsdk/events/payloads.go | 216 +++++++++++++++++++ pkg/pluginsdk/manifest/manifest.go | 3 + pkg/pluginsdk/manifest/subscriptions.go | 33 +++ pkg/pluginsdk/manifest/subscriptions_test.go | 43 ++++ 10 files changed, 734 insertions(+), 1 deletion(-) create mode 100644 docs/events.md create mode 100644 pkg/pluginsdk/events/events.go create mode 100644 pkg/pluginsdk/events/events_test.go create mode 100644 pkg/pluginsdk/events/payloads.go create mode 100644 pkg/pluginsdk/manifest/subscriptions.go create mode 100644 pkg/pluginsdk/manifest/subscriptions_test.go diff --git a/README.md b/README.md index 0a6bc06..38fe53c 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ release builds resolve the SDK from a published module tag. - `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/capability` — stable capability type constants for manifests and peer discovery. - `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/config` — config-schema helpers. - `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/convert` — type conversions. +- `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events` — the host event catalog: event names, access classes, and typed payloads (see [docs/events.md](docs/events.md)). - `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/httpclient` — credentialed JSON-over-HTTP client with bounded responses and typed status errors. - `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/imagevariant` — canonical image-size variant strings. - `github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest` — manifest loading/rendering. diff --git a/docs/compatibility.md b/docs/compatibility.md index eac9fce..f2e5428 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -52,6 +52,13 @@ with a `default` arm rather than an exhaustive match, and do not assume the constants shipped in any given SDK tag are the complete set. The same rule applies to any future open vocabulary added to `v1`. +Event subscriptions are open too. The manifest validator checks the shape of +each name in `subscriptions`, not whether this SDK knows it, so a plugin built +against a newer SDK still loads on an older host, which ignores an event it +doesn't deliver. The catalog and its payload types in `pkg/pluginsdk/events` +change additively: an event or a payload field is never renamed or removed +(see [events.md](events.md)). + `FetchMarkersRequest.episode_numbering` and `SubmitMarkerRequest.episode_numbering` are open too. Hosts send an external ID key, today `tvdb` or `tmdb`, or leave the field empty when they cannot tell. A marker provider treats a value it does not diff --git a/docs/events.md b/docs/events.md new file mode 100644 index 0000000..ea1141b --- /dev/null +++ b/docs/events.md @@ -0,0 +1,97 @@ +# Host events + +An `event_consumer.v1` capability lists event names in its manifest +`subscriptions`, and the host calls `EventConsumer.HandleEvent` for each one +(see [runtime-host.md](runtime-host.md#receiving-events) for delivery +guarantees). This page lists the events a host delivers and their payloads. +The Go names and payload types are in +[`pkg/pluginsdk/events`](../pkg/pluginsdk/events). + +A host delivers two kinds of events: + +- **Catalog events**, listed below. +- **Plugin events**, named `plugin..`. The host + stamps the prefix when a plugin calls `PublishEvent`, so no plugin can + publish a catalog event. + +The host delivers no other event name. A subscription to one is ignored. + +## Decoding payloads + +`HandleEventRequest.payload` is a JSON object. Decode it into the event's +payload type: + +```go +import "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events" + +func (s *server) HandleEvent(ctx context.Context, req *pluginv1.HandleEventRequest) (*pluginv1.HandleEventResponse, error) { + switch req.GetEventName() { + case events.SessionStarted: + var event events.SessionEvent + if err := events.Decode(req.GetPayload(), &event); err != nil { + return &pluginv1.HandleEventResponse{}, nil // malformed: ignore, don't retry + } + session, _ := event.DecodeSession() + // ... + } + return &pluginv1.HandleEventResponse{}, nil +} +``` + +Payloads change additively. A field is never renamed, removed, or given a new +meaning, and a host can add fields at any time, so ignore fields you don't +know. Vocabularies such as a job's `job_type` or a notification's `type` are +open: treat an unknown value as something you don't handle. + +## Access + +Each catalog event has an access class, which says whose data the payload +carries. A host shows the classes a plugin subscribes to when an administrator +installs it, and an upgrade that subscribes to a new class waits for an +administrator to approve it. + +| Access | Carries | +|---|---| +| `public` | The catalog and libraries. Never names an account or profile. Plugin events are `public`. | +| `admin` | Server operations: playback activity, scans and jobs. Can name accounts, profiles, devices and network addresses, as the admin activity views do. | +| `user_data` | One profile's personal data, such as the notifications in its inbox. | + +## Catalog + +| Event | Access | Payload | When | +|---|---|---|---| +| `catalog.library.changed` | public | `LibraryChanged` | A scan or refresh changed a library. | +| `catalog.item.changed` | public | `ItemChanged` | A catalog item's metadata, artwork or files changed. | +| `session.started` | admin | `SessionEvent` | A playback session started. | +| `session.paused` | admin | `SessionEvent` | A playback session paused. | +| `session.resumed` | admin | `SessionEvent` | A paused session resumed. | +| `session.stopped` | admin | `SessionEvent` | A playback session ended. | +| `scan.started` | admin | `ScanEvent` | A library scan started. | +| `scan.completed` | admin | `ScanEvent` | A library scan finished. | +| `scan.failed` | admin | `ScanEvent` | A library scan failed. | +| `scan.cancelled` | admin | `ScanEvent` | A library scan was cancelled. | +| `job.created` | admin | `JobEvent` | An admin job was queued. | +| `job.completed` | admin | `JobEvent` | An admin job finished. | +| `job.failed` | admin | `JobEvent` | An admin job failed. | +| `job.cancelled` | admin | `JobEvent` | An admin job was cancelled. | +| `notification.created` | user_data | `Notification` | Silo added a notification to a profile's inbox. | + +Notes on specific payloads: + +- **`SessionEvent`** carries the live session (`session`, on started, paused + and resumed) or the history entry the end recorded (`history`, on stopped). + These are the `/api/v2` `AdminPlaybackSession` and + `AdminPlaybackHistoryEntry` objects, with every field that schema defines. + `DecodeSession` and `DecodeHistory` read the common ones. A session's + events can arrive out of order; `seq` orders them. +- **`Notification`** identifies its recipient by `user_id` and `profile_id` + together. Profile IDs repeat across accounts. +- IDs at the top level of a payload are JSON numbers (`library_id`, + `user_id`) or strings (`content_id`, `profile_id`) as listed. Objects taken + from `/api/v2` use that API's string IDs. + +## Hosts + +A host delivers only the events above and plugin events, after +`events.Project` rewrites each payload into its public shape. Adding an event +to the catalog, or a field to a payload type, is an additive SDK change. diff --git a/docs/runtime-host.md b/docs/runtime-host.md index 2ccad0c..124f7be 100644 --- a/docs/runtime-host.md +++ b/docs/runtime-host.md @@ -193,7 +193,9 @@ events. An `event_consumer.v1` capability lists the event names it wants in its manifest `subscriptions`, and the host calls `EventConsumer.HandleEvent` for -each matching event. Once Silo has stored an event, it delivers it to each +each matching event. The host delivers the catalog events in +[events.md](events.md), which also documents their payloads, and plugin +events; it ignores a subscription to any other name. Once Silo has stored an event, it delivers it to each subscribing installation at least once, however many Silo servers run, unless every attempt fails: diff --git a/pkg/pluginsdk/events/events.go b/pkg/pluginsdk/events/events.go new file mode 100644 index 0000000..01a1cf3 --- /dev/null +++ b/pkg/pluginsdk/events/events.go @@ -0,0 +1,209 @@ +// Package events is the catalog of host events an event_consumer.v1 +// capability can subscribe to: their names, who their payloads are about, and +// the Go types their payloads decode into. +// +// The catalog is the public contract. A host delivers only the events listed +// here, and plugin events (names starting with PluginEventPrefix). Payloads +// change additively: a field is never renamed, removed, or given a new +// meaning, so decoding into the types in this package keeps working as hosts +// add fields. See docs/events.md. +package events + +import ( + "encoding/json" + "fmt" + "regexp" + "slices" + "strings" + + "google.golang.org/protobuf/types/known/structpb" +) + +// Access says who an event's payload is about, and so what an administrator +// approves before the host delivers it to a plugin. +type Access string + +const ( + // AccessPublic events describe the catalog and libraries, or come from + // plugins. They never name an account or profile. + AccessPublic Access = "public" + // AccessAdmin events describe server operations, such as playback + // activity, scans and jobs. They can name accounts, profiles, devices and + // network addresses, the way the admin activity views do. + AccessAdmin Access = "admin" + // AccessUserData events carry one profile's personal data, such as the + // notifications Silo adds to its inbox. + AccessUserData Access = "user_data" +) + +// Valid reports whether a is one of the access classes this SDK knows. +func (a Access) Valid() bool { + switch a { + case AccessPublic, AccessAdmin, AccessUserData: + return true + } + return false +} + +// Event names in the catalog. +const ( + // CatalogLibraryChanged: a scan or refresh changed a library. Payload + // LibraryChanged. + CatalogLibraryChanged = "catalog.library.changed" + // CatalogItemChanged: one catalog item's metadata, artwork or files + // changed. Payload ItemChanged. + CatalogItemChanged = "catalog.item.changed" + + // SessionStarted, SessionPaused, SessionResumed and SessionStopped follow + // a playback session. Payload SessionEvent. + SessionStarted = "session.started" + SessionPaused = "session.paused" + SessionResumed = "session.resumed" + SessionStopped = "session.stopped" + + // ScanStarted, ScanCompleted, ScanFailed and ScanCancelled follow a + // library scan. Payload ScanEvent. + ScanStarted = "scan.started" + ScanCompleted = "scan.completed" + ScanFailed = "scan.failed" + ScanCancelled = "scan.cancelled" + + // JobCreated, JobCompleted, JobFailed and JobCancelled follow an admin + // job, such as a refresh or an export. Payload JobEvent. + JobCreated = "job.created" + JobCompleted = "job.completed" + JobFailed = "job.failed" + JobCancelled = "job.cancelled" + + // NotificationCreated: Silo added a notification to a profile's inbox, + // such as a new episode or a request update. Payload Notification. + NotificationCreated = "notification.created" +) + +// PluginEventPrefix starts the name of every event a plugin publishes. The +// host stamps it as plugin.., so a plugin cannot +// publish a host event. Plugin events are AccessPublic. +const PluginEventPrefix = "plugin." + +// Definition describes one catalog event. +type Definition struct { + Name string + Access Access + Description string + newPayload func() any +} + +// NewPayload returns a pointer to a new value of the event's payload type, +// for json.Unmarshal or Decode. +func (d Definition) NewPayload() any { return d.newPayload() } + +func define[T any](name string, access Access, description string) Definition { + return Definition{Name: name, Access: access, Description: description, newPayload: func() any { return new(T) }} +} + +var catalog = []Definition{ + define[LibraryChanged](CatalogLibraryChanged, AccessPublic, "A scan or refresh changed a library."), + define[ItemChanged](CatalogItemChanged, AccessPublic, "A catalog item's metadata, artwork or files changed."), + + define[SessionEvent](SessionStarted, AccessAdmin, "A playback session started."), + define[SessionEvent](SessionPaused, AccessAdmin, "A playback session paused."), + define[SessionEvent](SessionResumed, AccessAdmin, "A paused playback session resumed."), + define[SessionEvent](SessionStopped, AccessAdmin, "A playback session ended."), + + define[ScanEvent](ScanStarted, AccessAdmin, "A library scan started."), + define[ScanEvent](ScanCompleted, AccessAdmin, "A library scan finished."), + define[ScanEvent](ScanFailed, AccessAdmin, "A library scan failed."), + define[ScanEvent](ScanCancelled, AccessAdmin, "A library scan was cancelled."), + + define[JobEvent](JobCreated, AccessAdmin, "An admin job was queued."), + define[JobEvent](JobCompleted, AccessAdmin, "An admin job finished."), + define[JobEvent](JobFailed, AccessAdmin, "An admin job failed."), + define[JobEvent](JobCancelled, AccessAdmin, "An admin job was cancelled."), + + define[Notification](NotificationCreated, AccessUserData, "Silo added a notification to a profile's inbox."), +} + +var byName = func() map[string]Definition { + out := make(map[string]Definition, len(catalog)) + for _, d := range catalog { + out[d.Name] = d + } + return out +}() + +// Catalog returns every catalog event, in a stable order. +func Catalog() []Definition { return slices.Clone(catalog) } + +// Lookup returns the catalog event named name. Plugin events aren't in the +// catalog; use AccessOf for them. +func Lookup(name string) (Definition, bool) { + d, ok := byName[name] + return d, ok +} + +// IsPluginEvent reports whether name is an event a plugin published. +func IsPluginEvent(name string) bool { + return strings.HasPrefix(name, PluginEventPrefix) && len(name) > len(PluginEventPrefix) +} + +// AccessOf returns the access class of a catalog or plugin event. It reports +// false for any other name: the host doesn't deliver it. +func AccessOf(name string) (Access, bool) { + if d, ok := byName[name]; ok { + return d.Access, true + } + if IsPluginEvent(name) { + return AccessPublic, true + } + return "", false +} + +// namePattern is the shape of an event name: dot-separated lowercase +// segments. Plugin IDs may contain hyphens, so segments may too. +var namePattern = regexp.MustCompile(`^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$`) + +// ValidName reports whether name has the shape of an event name. It does +// not check the catalog: a plugin built against a newer SDK may subscribe to +// an event an older host doesn't know, and that host ignores the name. +func ValidName(name string) bool { + return len(name) <= 256 && namePattern.MatchString(name) +} + +// Decode decodes an event payload, as HandleEventRequest carries it, into +// out, which is usually a pointer to one of this package's payload types. +func Decode(payload *structpb.Struct, out any) error { + if payload == nil { + return fmt.Errorf("events: payload is empty") + } + raw, err := json.Marshal(payload.AsMap()) + if err != nil { + return fmt.Errorf("events: encode payload: %w", err) + } + if err := json.Unmarshal(raw, out); err != nil { + return fmt.Errorf("events: decode payload: %w", err) + } + return nil +} + +// Project rewrites a catalog event's JSON payload into its public shape: the +// fields of the event's payload type, and nothing else. Hosts call it before +// delivering an event so internal fields don't reach plugins. Plugin events +// pass through unchanged. Any other name is an error. +func Project(name string, raw []byte) ([]byte, error) { + if IsPluginEvent(name) { + return raw, nil + } + d, ok := byName[name] + if !ok { + return nil, fmt.Errorf("events: %q is not a catalog event", name) + } + payload := d.NewPayload() + if err := json.Unmarshal(raw, payload); err != nil { + return nil, fmt.Errorf("events: decode %s payload: %w", name, err) + } + out, err := json.Marshal(payload) + if err != nil { + return nil, fmt.Errorf("events: encode %s payload: %w", name, err) + } + return out, nil +} diff --git a/pkg/pluginsdk/events/events_test.go b/pkg/pluginsdk/events/events_test.go new file mode 100644 index 0000000..3a7d50d --- /dev/null +++ b/pkg/pluginsdk/events/events_test.go @@ -0,0 +1,122 @@ +package events_test + +import ( + "encoding/json" + "testing" + + "google.golang.org/protobuf/types/known/structpb" + + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events" +) + +func TestCatalogEntriesAreWellFormed(t *testing.T) { + seen := map[string]bool{} + for _, d := range events.Catalog() { + if !events.ValidName(d.Name) || seen[d.Name] { + t.Errorf("catalog name %q is malformed or repeated", d.Name) + } + seen[d.Name] = true + if !d.Access.Valid() { + t.Errorf("%s: access %q", d.Name, d.Access) + } + if err := json.Unmarshal([]byte(`{}`), d.NewPayload()); err != nil { + t.Errorf("%s: payload type doesn't decode: %v", d.Name, err) + } + } +} + +func TestAccessOf(t *testing.T) { + for name, want := range map[string]events.Access{ + events.CatalogItemChanged: events.AccessPublic, + events.SessionStarted: events.AccessAdmin, + events.NotificationCreated: events.AccessUserData, + "plugin.silo.pushover.sent": events.AccessPublic, + } { + if got, ok := events.AccessOf(name); !ok || got != want { + t.Errorf("AccessOf(%q) = %q, %v; want %q", name, got, ok, want) + } + } + // Internal names and a bare prefix are not deliverable. + for _, name := range []string{"user_state.changed", "scan_complete", "plugin."} { + if _, ok := events.AccessOf(name); ok { + t.Errorf("AccessOf(%q) reported a deliverable event", name) + } + } +} + +func TestProjectKeepsOnlyPublicFields(t *testing.T) { + raw := []byte(`{"id":"j1","job_type":"library_refresh","status":"failed", + "request_payload":{"secret":"x"},"result_payload":{"internal":1}, + "requested_at":"2026-11-04T10:00:00Z","updated_at":"2026-11-04T10:01:00Z"}`) + out, err := events.Project(events.JobFailed, raw) + if err != nil { + t.Fatal(err) + } + var got map[string]any + if err := json.Unmarshal(out, &got); err != nil { + t.Fatal(err) + } + if _, leaked := got["request_payload"]; leaked { + t.Fatalf("internal field reached the public payload: %s", out) + } + if got["job_type"] != "library_refresh" || got["status"] != "failed" { + t.Fatalf("public fields lost: %s", out) + } +} + +func TestProjectKeepsNestedAPIObjects(t *testing.T) { + // session is an /api/v2 object governed by that contract: every field + // passes through, not only the ones PlaybackSession reads. + raw := []byte(`{"session_id":"s1","seq":3,"at":"2026-11-04T10:00:00.123Z","state":"playing", + "session":{"session_id":"s1","user_id":"7","media_title":"Heat","routing_egress":"direct"}}`) + out, err := events.Project(events.SessionStarted, raw) + if err != nil { + t.Fatal(err) + } + var event events.SessionEvent + if err := json.Unmarshal(out, &event); err != nil { + t.Fatal(err) + } + var session map[string]any + if err := json.Unmarshal(event.Session, &session); err != nil || session["routing_egress"] != "direct" { + t.Fatalf("nested session = %s, %v", event.Session, err) + } + typed, err := event.DecodeSession() + if err != nil || typed.UserID != "7" || typed.MediaTitle != "Heat" { + t.Fatalf("DecodeSession() = %+v, %v", typed, err) + } + if history, err := event.DecodeHistory(); history != nil || err != nil { + t.Fatalf("DecodeHistory() = %+v, %v; want nil for a started event", history, err) + } +} + +func TestProjectRejectsNamesOutsideTheCatalog(t *testing.T) { + if _, err := events.Project("user_state.changed", []byte(`{}`)); err == nil { + t.Fatal("Project accepted an internal event") + } + raw := []byte(`{"anything":true}`) + if out, err := events.Project("plugin.silo.test.ping", raw); err != nil || string(out) != string(raw) { + t.Fatalf("plugin event changed: %s, %v", out, err) + } +} + +func TestDecode(t *testing.T) { + payload, err := structpb.NewStruct(map[string]any{ + "id": "d1", "type": "episode.available", "user_id": 7, "profile_id": "p1", + "season_number": 2, "reason_flags": map[string]any{"favorite": true}, + "created_at": "2026-11-04T10:00:00Z", + }) + if err != nil { + t.Fatal(err) + } + var n events.Notification + if err := events.Decode(payload, &n); err != nil { + t.Fatal(err) + } + if n.UserID != 7 || n.ProfileID != "p1" || n.SeasonNumber == nil || *n.SeasonNumber != 2 || string(n.ReasonFlags) != `{"favorite":true}` { + t.Fatalf("Decode() = %+v", n) + } + if err := events.Decode(nil, &n); err == nil { + t.Fatal("Decode(nil) succeeded") + } +} diff --git a/pkg/pluginsdk/events/payloads.go b/pkg/pluginsdk/events/payloads.go new file mode 100644 index 0000000..4657ced --- /dev/null +++ b/pkg/pluginsdk/events/payloads.go @@ -0,0 +1,216 @@ +package events + +import ( + "encoding/json" + "time" +) + +// LibraryChanged is the payload of catalog.library.changed. +type LibraryChanged struct { + LibraryID int `json:"library_id"` + // Reason is what changed the library, such as "scan". + Reason string `json:"reason"` + New int `json:"new"` + Updated int `json:"updated"` + Missing int `json:"missing"` + MatchedFiles int `json:"matched_files"` + RetriedItems int `json:"retried_items"` + StillUnmatchedWarnings int `json:"still_unmatched_warnings"` +} + +// ItemChanged is the payload of catalog.item.changed. +type ItemChanged struct { + LibraryID int `json:"library_id"` + ContentID string `json:"content_id"` + // Change names what changed, such as "metadata_updated". The vocabulary + // is open; treat an unknown value as a general change. + Change string `json:"change"` +} + +// SessionEvent is the payload of session.started, session.paused, +// session.resumed and session.stopped. +type SessionEvent struct { + SessionID string `json:"session_id"` + // Seq orders one session's events: a higher number is newer. Events can + // arrive out of order. + Seq int64 `json:"seq"` + At time.Time `json:"at"` + // State is the session's state after the event: playing, paused or + // stopped. + State string `json:"state"` + // EndReason is why a stopped session ended. + EndReason string `json:"end_reason,omitempty"` + // Session is the live session on a started, paused or resumed event, as + // the /api/v2 AdminPlaybackSession schema describes it. Absent when no + // server has a live record of it. DecodeSession reads common fields. + Session json.RawMessage `json:"session,omitempty"` + // History is the history entry a stopped event recorded, as the /api/v2 + // AdminPlaybackHistoryEntry schema describes it. DecodeHistory reads + // common fields. + History json.RawMessage `json:"history,omitempty"` +} + +// DecodeSession decodes the live session. It returns nil when the event has +// none. +func (e SessionEvent) DecodeSession() (*PlaybackSession, error) { + return decodeOptional[PlaybackSession](e.Session) +} + +// DecodeHistory decodes the history entry. It returns nil when the event has +// none. +func (e SessionEvent) DecodeHistory() (*PlaybackHistoryEntry, error) { + return decodeOptional[PlaybackHistoryEntry](e.History) +} + +func decodeOptional[T any](raw json.RawMessage) (*T, error) { + if len(raw) == 0 || string(raw) == "null" { + return nil, nil + } + out := new(T) + if err := json.Unmarshal(raw, out); err != nil { + return nil, err + } + return out, nil +} + +// PlaybackSession is a subset of the /api/v2 AdminPlaybackSession schema. As +// in /api/v2, IDs are strings. +type PlaybackSession struct { + SessionID string `json:"session_id"` + UserID string `json:"user_id"` + Username string `json:"username"` + ProfileID string `json:"profile_id"` + ProfileName string `json:"profile_name,omitempty"` + ContentID string `json:"content_id,omitempty"` + MediaTitle string `json:"media_title"` + MediaType string `json:"media_type"` + SeriesName string `json:"series_name,omitempty"` + EpisodeName string `json:"episode_name,omitempty"` + SeasonNumber *int `json:"season_number,omitempty"` + EpisodeNumber *int `json:"episode_number,omitempty"` + PosterURL string `json:"poster_url,omitempty"` + PlayMethod string `json:"play_method"` + EffectivePlayMethod string `json:"effective_play_method,omitempty"` + StartedAt time.Time `json:"started_at"` + PositionSeconds float64 `json:"position_seconds"` + IsPaused bool `json:"is_paused"` + ClientIP string `json:"client_ip,omitempty"` + // StreamLocation is "local" or "remote". + StreamLocation string `json:"stream_location"` + ClientName string `json:"client_name,omitempty"` + ClientVersion string `json:"client_version,omitempty"` + DeviceID string `json:"device_id,omitempty"` + DevicePlatform string `json:"device_platform,omitempty"` + StreamBitrateKbps *int `json:"stream_bitrate_kbps"` +} + +// PlaybackHistoryEntry is a subset of the /api/v2 AdminPlaybackHistoryEntry +// schema. As in /api/v2, IDs are strings. +type PlaybackHistoryEntry struct { + SessionID string `json:"session_id"` + UserID string `json:"user_id"` + Username string `json:"username"` + ProfileID string `json:"profile_id"` + ProfileName string `json:"profile_name"` + MediaItemID string `json:"media_item_id"` + MediaTitle string `json:"media_title"` + MediaType string `json:"media_type"` + PlayMethod string `json:"play_method"` + StartedAt time.Time `json:"started_at"` + EndedAt time.Time `json:"ended_at"` + WatchedSeconds float64 `json:"watched_seconds"` + DurationSeconds *float64 `json:"duration_seconds"` + Completed bool `json:"completed"` + SeriesTitle string `json:"series_title"` + SeasonNumber *int `json:"season_number"` + EpisodeNumber *int `json:"episode_number"` + ClientIP *string `json:"client_ip"` + DeviceID *string `json:"device_id"` + DevicePlatform *string `json:"device_platform"` + ClientName *string `json:"client_name"` + EndReason *string `json:"end_reason"` +} + +// ScanEvent is the payload of scan.started, scan.completed, scan.failed and +// scan.cancelled. +type ScanEvent struct { + ID string `json:"id"` + LibraryID int `json:"library_id"` + // Mode and Trigger say how the scan runs and what started it. Their + // vocabularies are open. + Mode string `json:"mode"` + // Path is set when the scan covers one folder of the library. + Path string `json:"path,omitempty"` + Trigger string `json:"trigger"` + Status string `json:"status"` + StartedAt *time.Time `json:"started_at,omitempty"` + CompletedAt *time.Time `json:"completed_at,omitempty"` + ErrorMessage string `json:"error_message,omitempty"` + Result *ScanResult `json:"result,omitempty"` +} + +// ScanResult counts what a scan found. +type ScanResult struct { + New int `json:"new"` + Updated int `json:"updated"` + Unchanged int `json:"unchanged"` + Missing int `json:"missing"` + // MissingSkippedProtected counts files the scan didn't mark missing + // because their storage was offline or unreadable. + MissingSkippedProtected int `json:"missing_skipped_protected"` + FilesDeleted int `json:"files_deleted"` + ItemsDeleted int `json:"items_deleted"` + MatchedFiles int `json:"matched_files"` + StillUnmatchedWarnings int `json:"still_unmatched_warnings"` + Errors int `json:"errors"` +} + +// JobEvent is the payload of job.created, job.completed, job.failed and +// job.cancelled. +type JobEvent struct { + ID string `json:"id"` + // JobType names the job, such as "library_refresh". The vocabulary is + // open. + JobType string `json:"job_type"` + Status string `json:"status"` + CreatedByUserID int `json:"created_by_user_id"` + Message string `json:"message"` + ErrorMessage string `json:"error_message,omitempty"` + ProgressCurrent int `json:"progress_current"` + ProgressTotal int `json:"progress_total"` + RequestedAt time.Time `json:"requested_at"` + StartedAt *time.Time `json:"started_at,omitempty"` + CompletedAt *time.Time `json:"completed_at,omitempty"` + UpdatedAt time.Time `json:"updated_at"` +} + +// Notification is the payload of notification.created: one delivery +// to one profile's inbox. +type Notification struct { + ID string `json:"id"` + // Type is the delivery type, such as "episode.available", + // "request.approved", "request.declined" or "request.fulfilled". The + // vocabulary is open. + Type string `json:"type"` + // UserID is the account that owns the profile. Profile IDs repeat across + // accounts, so identify a recipient by UserID and ProfileID together. + UserID int `json:"user_id"` + ProfileID string `json:"profile_id"` + LibraryID *int `json:"library_id,omitempty"` + SeriesID *string `json:"series_id,omitempty"` + EpisodeID *string `json:"episode_id,omitempty"` + SeriesTitle string `json:"series_title,omitempty"` + EpisodeTitle string `json:"episode_title,omitempty"` + SeasonNumber *int `json:"season_number,omitempty"` + EpisodeNumber *int `json:"episode_number,omitempty"` + // PosterPath is a catalog image path. Resolve it to a URL with the + // host's ResolveCatalogImageURLs. + PosterPath string `json:"poster_path,omitempty"` + // PosterURL is a poster URL when the host has one ready. It can expire. + PosterURL string `json:"poster_url,omitempty"` + // ReasonFlags is a JSON object whose shape depends on Type: why an + // episode was announced (favorite, watchlist, continue_watching, + // next_up) or which request changed. + ReasonFlags json.RawMessage `json:"reason_flags,omitempty"` + CreatedAt time.Time `json:"created_at"` +} diff --git a/pkg/pluginsdk/manifest/manifest.go b/pkg/pluginsdk/manifest/manifest.go index 5d7291c..ae3f852 100644 --- a/pkg/pluginsdk/manifest/manifest.go +++ b/pkg/pluginsdk/manifest/manifest.go @@ -153,6 +153,9 @@ func Validate(manifest *pluginv1.PluginManifest) error { if err := validateAuthProviderCapability(capability); err != nil { return err } + if err := validateSubscriptions(capability); err != nil { + return err + } } if err := validateNetworkAuthPairing(manifest); err != nil { return err diff --git a/pkg/pluginsdk/manifest/subscriptions.go b/pkg/pluginsdk/manifest/subscriptions.go new file mode 100644 index 0000000..c442ac5 --- /dev/null +++ b/pkg/pluginsdk/manifest/subscriptions.go @@ -0,0 +1,33 @@ +package manifest + +import ( + "fmt" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/capability" + "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events" +) + +// validateSubscriptions checks an event_consumer.v1 capability's event names. +// It checks their shape, not the catalog: a host ignores a name it doesn't +// deliver, so a plugin built against a newer SDK still loads on an older host. +func validateSubscriptions(descriptor *pluginv1.CapabilityDescriptor) error { + subscriptions := descriptor.GetSubscriptions() + if len(subscriptions) == 0 { + return nil + } + if descriptor.GetType() != capability.EventConsumer { + return fmt.Errorf("plugin capability %q: subscriptions require type %q", descriptor.GetId(), capability.EventConsumer) + } + seen := make(map[string]struct{}, len(subscriptions)) + for _, name := range subscriptions { + if !events.ValidName(name) { + return fmt.Errorf("plugin capability %q: subscription %q is not an event name", descriptor.GetId(), name) + } + if _, dup := seen[name]; dup { + return fmt.Errorf("plugin capability %q: subscription %q is listed twice", descriptor.GetId(), name) + } + seen[name] = struct{}{} + } + return nil +} diff --git a/pkg/pluginsdk/manifest/subscriptions_test.go b/pkg/pluginsdk/manifest/subscriptions_test.go new file mode 100644 index 0000000..73a8d8d --- /dev/null +++ b/pkg/pluginsdk/manifest/subscriptions_test.go @@ -0,0 +1,43 @@ +package manifest_test + +import ( + "strings" + "testing" + + pluginv1 "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginproto/silo/plugin/v1" + publicmanifest "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest" +) + +func TestValidateSubscriptions(t *testing.T) { + for _, tc := range []struct { + name string + typ string + subscriptions []string + wantErr string + }{ + {name: "catalog and plugin events", typ: "event_consumer.v1", subscriptions: []string{"session.started", "plugin.silo.pushover.sent"}}, + // A newer SDK's event loads on an older host, which ignores it. + {name: "event this SDK doesn't know", typ: "event_consumer.v1", subscriptions: []string{"media.added_someday"}}, + {name: "duplicate", typ: "event_consumer.v1", subscriptions: []string{"scan.failed", "scan.failed"}, wantErr: "listed twice"}, + {name: "not an event name", typ: "event_consumer.v1", subscriptions: []string{"Session Started"}, wantErr: "not an event name"}, + {name: "single segment", typ: "event_consumer.v1", subscriptions: []string{"scan"}, wantErr: "not an event name"}, + {name: "wrong capability type", typ: "scheduled_task.v1", subscriptions: []string{"scan.failed"}, wantErr: "require type"}, + } { + t.Run(tc.name, func(t *testing.T) { + manifest := &pluginv1.PluginManifest{ + PluginId: "silo.test", Version: "1.0.0", + Capabilities: []*pluginv1.CapabilityDescriptor{{Type: tc.typ, Id: "events", Subscriptions: tc.subscriptions}}, + } + err := publicmanifest.Validate(manifest) + if tc.wantErr == "" { + if err != nil { + t.Fatalf("Validate() = %v, want nil", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("Validate() = %v, want error containing %q", err, tc.wantErr) + } + }) + } +} From b475b816226d2e2bcad874195980f1503a2d92ec Mon Sep 17 00:00:00 2001 From: Quick104 <31828688+Quick104@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:47:18 -0500 Subject: [PATCH 2/6] feat(events): add media request lifecycle events to the catalog request.submitted, request.approved, request.declined and request.fulfilled carry a RequestEvent payload with admin access, so a plugin can alert administrators to new requests. Co-Authored-By: Claude Opus 5.5 --- docs/events.md | 4 ++++ pkg/pluginsdk/events/events.go | 12 ++++++++++++ pkg/pluginsdk/events/payloads.go | 27 +++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/docs/events.md b/docs/events.md index ea1141b..783e10b 100644 --- a/docs/events.md +++ b/docs/events.md @@ -74,6 +74,10 @@ administrator to approve it. | `job.completed` | admin | `JobEvent` | An admin job finished. | | `job.failed` | admin | `JobEvent` | An admin job failed. | | `job.cancelled` | admin | `JobEvent` | An admin job was cancelled. | +| `request.submitted` | admin | `RequestEvent` | Someone requested a movie or series. | +| `request.approved` | admin | `RequestEvent` | A media request was approved. | +| `request.declined` | admin | `RequestEvent` | A media request was declined. | +| `request.fulfilled` | admin | `RequestEvent` | A requested title arrived in a library. | | `notification.created` | user_data | `Notification` | Silo added a notification to a profile's inbox. | Notes on specific payloads: diff --git a/pkg/pluginsdk/events/events.go b/pkg/pluginsdk/events/events.go index 01a1cf3..f9345a0 100644 --- a/pkg/pluginsdk/events/events.go +++ b/pkg/pluginsdk/events/events.go @@ -75,6 +75,13 @@ const ( JobFailed = "job.failed" JobCancelled = "job.cancelled" + // RequestSubmitted, RequestApproved, RequestDeclined and RequestFulfilled + // follow a media request. Payload RequestEvent. + RequestSubmitted = "request.submitted" + RequestApproved = "request.approved" + RequestDeclined = "request.declined" + RequestFulfilled = "request.fulfilled" + // NotificationCreated: Silo added a notification to a profile's inbox, // such as a new episode or a request update. Payload Notification. NotificationCreated = "notification.created" @@ -120,6 +127,11 @@ var catalog = []Definition{ define[JobEvent](JobFailed, AccessAdmin, "An admin job failed."), define[JobEvent](JobCancelled, AccessAdmin, "An admin job was cancelled."), + define[RequestEvent](RequestSubmitted, AccessAdmin, "Someone requested a movie or series."), + define[RequestEvent](RequestApproved, AccessAdmin, "A media request was approved."), + define[RequestEvent](RequestDeclined, AccessAdmin, "A media request was declined."), + define[RequestEvent](RequestFulfilled, AccessAdmin, "A requested title arrived in a library."), + define[Notification](NotificationCreated, AccessUserData, "Silo added a notification to a profile's inbox."), } diff --git a/pkg/pluginsdk/events/payloads.go b/pkg/pluginsdk/events/payloads.go index 4657ced..6944e5b 100644 --- a/pkg/pluginsdk/events/payloads.go +++ b/pkg/pluginsdk/events/payloads.go @@ -184,6 +184,33 @@ type JobEvent struct { UpdatedAt time.Time `json:"updated_at"` } +// RequestEvent is the payload of request.submitted, request.approved, +// request.declined and request.fulfilled. +type RequestEvent struct { + ID string `json:"id"` + // MediaType is "movie" or "series". The vocabulary is open. + MediaType string `json:"media_type"` + Title string `json:"title"` + Year *int `json:"year,omitempty"` + TMDBID int `json:"tmdb_id,omitempty"` + TVDBID *int `json:"tvdb_id,omitempty"` + IMDbID string `json:"imdb_id,omitempty"` + // PosterPath is a TMDB image path, such as "/abc.jpg". + PosterPath string `json:"poster_path,omitempty"` + // Status is the request's state after the event. The vocabulary is open. + Status string `json:"status"` + // RequestedByUserID and RequestedByProfileID identify the requester; + // both are empty for a request no profile made, such as an import. + RequestedByUserID int `json:"requested_by_user_id,omitempty"` + RequestedByProfileID string `json:"requested_by_profile_id,omitempty"` + RequesterName string `json:"requester_name,omitempty"` + // Reason is why a request was declined, when one was given. + Reason string `json:"reason,omitempty"` + // LibraryContentID is the catalog item a fulfilled request matched. + LibraryContentID string `json:"library_content_id,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + // Notification is the payload of notification.created: one delivery // to one profile's inbox. type Notification struct { From da2ba5e95007d7e48c02a2723efa48f12e10678a Mon Sep 17 00:00:00 2001 From: Quick104 <31828688+Quick104@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:35:54 -0500 Subject: [PATCH 3/6] fix(manifest): keep loading manifests whose subscriptions predate the catalog Validate rejected duplicate and single-segment subscriptions, which manifests already installed on hosts may carry, so a host upgrading the SDK could refuse an unchanged plugin. Validate no longer checks subscriptions; manifest.SubscriptionProblems reports them for a plugin's own tests, including names no host delivers. Document that payload integers fit in 53 bits. Co-Authored-By: Claude Opus 5.5 --- docs/compatibility.md | 9 ++-- docs/events.md | 6 +++ pkg/pluginsdk/events/events.go | 4 +- pkg/pluginsdk/manifest/manifest.go | 3 -- pkg/pluginsdk/manifest/subscriptions.go | 52 +++++++++++++------- pkg/pluginsdk/manifest/subscriptions_test.go | 30 +++++------ 6 files changed, 62 insertions(+), 42 deletions(-) diff --git a/docs/compatibility.md b/docs/compatibility.md index f2e5428..fc12c7d 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -52,10 +52,11 @@ with a `default` arm rather than an exhaustive match, and do not assume the constants shipped in any given SDK tag are the complete set. The same rule applies to any future open vocabulary added to `v1`. -Event subscriptions are open too. The manifest validator checks the shape of -each name in `subscriptions`, not whether this SDK knows it, so a plugin built -against a newer SDK still loads on an older host, which ignores an event it -doesn't deliver. The catalog and its payload types in `pkg/pluginsdk/events` +Event subscriptions are open too. The manifest validator doesn't check them, +so manifests that predate the event catalog keep loading, and a plugin built +against a newer SDK loads on an older host, which ignores an event it doesn't +deliver. `manifest.SubscriptionProblems` reports names no host delivers, for a +plugin's own tests. The catalog and its payload types in `pkg/pluginsdk/events` change additively: an event or a payload field is never renamed or removed (see [events.md](events.md)). diff --git a/docs/events.md b/docs/events.md index 783e10b..290dafc 100644 --- a/docs/events.md +++ b/docs/events.md @@ -38,6 +38,12 @@ func (s *server) HandleEvent(ctx context.Context, req *pluginv1.HandleEventReque } ``` +Integers in payloads fit in 53 bits, the range a JSON number and a +`google.protobuf.Value` hold exactly. Larger identifiers are strings. + +To check that every subscription names an event a host delivers, call +`manifest.SubscriptionProblems` from the plugin's tests. + Payloads change additively. A field is never renamed, removed, or given a new meaning, and a host can add fields at any time, so ignore fields you don't know. Vocabularies such as a job's `job_type` or a notification's `type` are diff --git a/pkg/pluginsdk/events/events.go b/pkg/pluginsdk/events/events.go index f9345a0..d5f1ff7 100644 --- a/pkg/pluginsdk/events/events.go +++ b/pkg/pluginsdk/events/events.go @@ -175,14 +175,14 @@ func AccessOf(name string) (Access, bool) { var namePattern = regexp.MustCompile(`^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$`) // ValidName reports whether name has the shape of an event name. It does -// not check the catalog: a plugin built against a newer SDK may subscribe to -// an event an older host doesn't know, and that host ignores the name. +// not check the catalog; AccessOf does. func ValidName(name string) bool { return len(name) <= 256 && namePattern.MatchString(name) } // Decode decodes an event payload, as HandleEventRequest carries it, into // out, which is usually a pointer to one of this package's payload types. +// Payload integers fit in 53 bits, which a protobuf Value holds exactly. func Decode(payload *structpb.Struct, out any) error { if payload == nil { return fmt.Errorf("events: payload is empty") diff --git a/pkg/pluginsdk/manifest/manifest.go b/pkg/pluginsdk/manifest/manifest.go index ae3f852..5d7291c 100644 --- a/pkg/pluginsdk/manifest/manifest.go +++ b/pkg/pluginsdk/manifest/manifest.go @@ -153,9 +153,6 @@ func Validate(manifest *pluginv1.PluginManifest) error { if err := validateAuthProviderCapability(capability); err != nil { return err } - if err := validateSubscriptions(capability); err != nil { - return err - } } if err := validateNetworkAuthPairing(manifest); err != nil { return err diff --git a/pkg/pluginsdk/manifest/subscriptions.go b/pkg/pluginsdk/manifest/subscriptions.go index c442ac5..2a2ff09 100644 --- a/pkg/pluginsdk/manifest/subscriptions.go +++ b/pkg/pluginsdk/manifest/subscriptions.go @@ -8,26 +8,40 @@ import ( "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/events" ) -// validateSubscriptions checks an event_consumer.v1 capability's event names. -// It checks their shape, not the catalog: a host ignores a name it doesn't -// deliver, so a plugin built against a newer SDK still loads on an older host. -func validateSubscriptions(descriptor *pluginv1.CapabilityDescriptor) error { - subscriptions := descriptor.GetSubscriptions() - if len(subscriptions) == 0 { - return nil - } - if descriptor.GetType() != capability.EventConsumer { - return fmt.Errorf("plugin capability %q: subscriptions require type %q", descriptor.GetId(), capability.EventConsumer) - } - seen := make(map[string]struct{}, len(subscriptions)) - for _, name := range subscriptions { - if !events.ValidName(name) { - return fmt.Errorf("plugin capability %q: subscription %q is not an event name", descriptor.GetId(), name) +// SubscriptionProblems lists what is wrong with a manifest's event +// subscriptions: a subscription on a capability other than +// event_consumer.v1, a name that isn't an event name, a name listed twice, or +// a name that is neither a catalog event nor a plugin event, which no host +// delivers. +// +// Validate doesn't apply these checks, because manifests that predate the +// event catalog load without them and a host must keep loading installed +// plugins. Call it from a plugin's own tests to catch a subscription that +// will never fire. +func SubscriptionProblems(manifest *pluginv1.PluginManifest) []string { + var problems []string + for _, descriptor := range manifest.GetCapabilities() { + subscriptions := descriptor.GetSubscriptions() + if len(subscriptions) == 0 { + continue + } + if descriptor.GetType() != capability.EventConsumer { + problems = append(problems, fmt.Sprintf("capability %q: subscriptions need type %q", descriptor.GetId(), capability.EventConsumer)) + continue } - if _, dup := seen[name]; dup { - return fmt.Errorf("plugin capability %q: subscription %q is listed twice", descriptor.GetId(), name) + seen := make(map[string]struct{}, len(subscriptions)) + for _, name := range subscriptions { + switch _, known := events.AccessOf(name); { + case !events.ValidName(name): + problems = append(problems, fmt.Sprintf("capability %q: %q is not an event name", descriptor.GetId(), name)) + case !known: + problems = append(problems, fmt.Sprintf("capability %q: %q is not in the event catalog, so no host delivers it", descriptor.GetId(), name)) + } + if _, dup := seen[name]; dup { + problems = append(problems, fmt.Sprintf("capability %q: %q is listed twice", descriptor.GetId(), name)) + } + seen[name] = struct{}{} } - seen[name] = struct{}{} } - return nil + return problems } diff --git a/pkg/pluginsdk/manifest/subscriptions_test.go b/pkg/pluginsdk/manifest/subscriptions_test.go index 73a8d8d..d012618 100644 --- a/pkg/pluginsdk/manifest/subscriptions_test.go +++ b/pkg/pluginsdk/manifest/subscriptions_test.go @@ -8,35 +8,37 @@ import ( publicmanifest "github.com/Silo-Server/silo-plugin-sdk/pkg/pluginsdk/manifest" ) -func TestValidateSubscriptions(t *testing.T) { +func TestSubscriptionProblems(t *testing.T) { for _, tc := range []struct { name string typ string subscriptions []string - wantErr string + want string }{ {name: "catalog and plugin events", typ: "event_consumer.v1", subscriptions: []string{"session.started", "plugin.silo.pushover.sent"}}, - // A newer SDK's event loads on an older host, which ignores it. - {name: "event this SDK doesn't know", typ: "event_consumer.v1", subscriptions: []string{"media.added_someday"}}, - {name: "duplicate", typ: "event_consumer.v1", subscriptions: []string{"scan.failed", "scan.failed"}, wantErr: "listed twice"}, - {name: "not an event name", typ: "event_consumer.v1", subscriptions: []string{"Session Started"}, wantErr: "not an event name"}, - {name: "single segment", typ: "event_consumer.v1", subscriptions: []string{"scan"}, wantErr: "not an event name"}, - {name: "wrong capability type", typ: "scheduled_task.v1", subscriptions: []string{"scan.failed"}, wantErr: "require type"}, + {name: "duplicate", typ: "event_consumer.v1", subscriptions: []string{"scan.failed", "scan.failed"}, want: "listed twice"}, + {name: "internal name", typ: "event_consumer.v1", subscriptions: []string{"scan_complete"}, want: "not an event name"}, + {name: "not in the catalog", typ: "event_consumer.v1", subscriptions: []string{"user_state.changed"}, want: "not in the event catalog"}, + {name: "wrong capability type", typ: "scheduled_task.v1", subscriptions: []string{"scan.failed"}, want: "need type"}, } { t.Run(tc.name, func(t *testing.T) { manifest := &pluginv1.PluginManifest{ PluginId: "silo.test", Version: "1.0.0", Capabilities: []*pluginv1.CapabilityDescriptor{{Type: tc.typ, Id: "events", Subscriptions: tc.subscriptions}}, } - err := publicmanifest.Validate(manifest) - if tc.wantErr == "" { - if err != nil { - t.Fatalf("Validate() = %v, want nil", err) + // Validate keeps accepting what it accepted before the catalog. + if err := publicmanifest.Validate(manifest); err != nil { + t.Fatalf("Validate() = %v; subscriptions must not stop a manifest from loading", err) + } + problems := publicmanifest.SubscriptionProblems(manifest) + if tc.want == "" { + if len(problems) != 0 { + t.Fatalf("SubscriptionProblems() = %v, want none", problems) } return } - if err == nil || !strings.Contains(err.Error(), tc.wantErr) { - t.Fatalf("Validate() = %v, want error containing %q", err, tc.wantErr) + if len(problems) == 0 || !strings.Contains(strings.Join(problems, "\n"), tc.want) { + t.Fatalf("SubscriptionProblems() = %v, want one containing %q", problems, tc.want) } }) } From 7f7f2b2546ec1907798e51efac31d1d9030abb67 Mon Sep 17 00:00:00 2001 From: Quick104 <31828688+Quick104@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:23:03 -0500 Subject: [PATCH 4/6] fix(events): require a publisher and an event name in plugin event names A plugin event is stamped plugin.., and a published name can't be empty, so plugin.foo can never fire. IsPluginEvent accepted it, so AccessOf and SubscriptionProblems treated it as deliverable. Co-Authored-By: Claude Opus 5.5 --- pkg/pluginsdk/events/events.go | 7 +++++-- pkg/pluginsdk/events/events_test.go | 5 +++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/pkg/pluginsdk/events/events.go b/pkg/pluginsdk/events/events.go index d5f1ff7..b15217c 100644 --- a/pkg/pluginsdk/events/events.go +++ b/pkg/pluginsdk/events/events.go @@ -153,9 +153,12 @@ func Lookup(name string) (Definition, bool) { return d, ok } -// IsPluginEvent reports whether name is an event a plugin published. +// IsPluginEvent reports whether name is an event a plugin published: the +// prefix, then a publisher plugin_id and an event name, both nonempty. func IsPluginEvent(name string) bool { - return strings.HasPrefix(name, PluginEventPrefix) && len(name) > len(PluginEventPrefix) + rest, ok := strings.CutPrefix(name, PluginEventPrefix) + i := strings.LastIndexByte(rest, '.') + return ok && i > 0 && i < len(rest)-1 } // AccessOf returns the access class of a catalog or plugin event. It reports diff --git a/pkg/pluginsdk/events/events_test.go b/pkg/pluginsdk/events/events_test.go index 3a7d50d..f9f3dcd 100644 --- a/pkg/pluginsdk/events/events_test.go +++ b/pkg/pluginsdk/events/events_test.go @@ -36,8 +36,9 @@ func TestAccessOf(t *testing.T) { t.Errorf("AccessOf(%q) = %q, %v; want %q", name, got, ok, want) } } - // Internal names and a bare prefix are not deliverable. - for _, name := range []string{"user_state.changed", "scan_complete", "plugin."} { + // Internal names, a bare prefix, and a plugin name without both a + // publisher and an event name are not deliverable. + for _, name := range []string{"user_state.changed", "scan_complete", "plugin.", "plugin.foo", "plugin.foo."} { if _, ok := events.AccessOf(name); ok { t.Errorf("AccessOf(%q) reported a deliverable event", name) } From c5b17fc91e9ea836cb7836cda2f7ab999f7c6c08 Mon Sep 17 00:00:00 2001 From: Quick <31828688+Quick104@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:45:33 +0000 Subject: [PATCH 5/6] fix(events): use string IDs, mark optional fields, drop request events Every identifier in a payload is now a JSON string, as in /api/v2, and a field the host can leave out is a pointer, so absent never reads as zero. The request.* events had no consumer and leave the catalog. notification.created stays but is marked provisional in favor of notification_channel.v1 destinations. docs/events.md gains the versioning rule and no longer promises install-time approval of access classes. Co-Authored-By: Claude Opus 5.5 --- docs/events.md | 45 ++++++++++++++++++----------- pkg/pluginsdk/events/events.go | 16 +++------- pkg/pluginsdk/events/events_test.go | 9 ++++-- pkg/pluginsdk/events/payloads.go | 45 +++++++---------------------- 4 files changed, 49 insertions(+), 66 deletions(-) diff --git a/docs/events.md b/docs/events.md index 290dafc..69f55ef 100644 --- a/docs/events.md +++ b/docs/events.md @@ -38,23 +38,34 @@ func (s *server) HandleEvent(ctx context.Context, req *pluginv1.HandleEventReque } ``` -Integers in payloads fit in 53 bits, the range a JSON number and a -`google.protobuf.Value` hold exactly. Larger identifiers are strings. +Integers in payloads, such as counts and season numbers, fit in 53 bits, the +range a JSON number and a `google.protobuf.Value` hold exactly. Identifiers +are always strings. To check that every subscription names an event a host delivers, call `manifest.SubscriptionProblems` from the plugin's tests. -Payloads change additively. A field is never renamed, removed, or given a new -meaning, and a host can add fields at any time, so ignore fields you don't -know. Vocabularies such as a job's `job_type` or a notification's `type` are -open: treat an unknown value as something you don't handle. +Payloads change additively: + +- A field is never renamed, removed, retyped or given a new meaning. New fields + arrive only with an SDK release that adds them to the payload type, since a + host projects every payload through `events.Project`. Ignore fields you + don't know. +- A change that can't be made additively ships as a new event name; the old + event keeps its shape. +- An event never moves to a different access class. +- A field the host can leave out is a pointer (or an `omitempty` string), so + "absent" never reads as a zero ID, `0` or the zero time. + +Vocabularies such as a job's `job_type` or a notification's `type` are open: +treat an unknown value as something you don't handle. ## Access Each catalog event has an access class, which says whose data the payload -carries. A host shows the classes a plugin subscribes to when an administrator -installs it, and an upgrade that subscribes to a new class waits for an -administrator to approve it. +carries. A host may, in a later release, ask an administrator to approve the +`admin` and `user_data` classes before it delivers them, so subscribe only to +the events the plugin uses. | Access | Carries | |---|---| @@ -80,11 +91,7 @@ administrator to approve it. | `job.completed` | admin | `JobEvent` | An admin job finished. | | `job.failed` | admin | `JobEvent` | An admin job failed. | | `job.cancelled` | admin | `JobEvent` | An admin job was cancelled. | -| `request.submitted` | admin | `RequestEvent` | Someone requested a movie or series. | -| `request.approved` | admin | `RequestEvent` | A media request was approved. | -| `request.declined` | admin | `RequestEvent` | A media request was declined. | -| `request.fulfilled` | admin | `RequestEvent` | A requested title arrived in a library. | -| `notification.created` | user_data | `Notification` | Silo added a notification to a profile's inbox. | +| `notification.created` | user_data | `Notification` | Silo added a notification to a profile's inbox. Provisional, see below. | Notes on specific payloads: @@ -96,9 +103,13 @@ Notes on specific payloads: events can arrive out of order; `seq` orders them. - **`Notification`** identifies its recipient by `user_id` and `profile_id` together. Profile IDs repeat across accounts. -- IDs at the top level of a payload are JSON numbers (`library_id`, - `user_id`) or strings (`content_id`, `profile_id`) as listed. Objects taken - from `/api/v2` use that API's string IDs. +- **`notification.created` is provisional.** A plugin that sends a profile's + notifications somewhere else (Pushover, ntfy and the like) should provide a + `notification_channel.v1` destination, which gets the host's preferences, + queue and retries. This event may leave the catalog before SDK 1.0. +- Every identifier is a JSON string, as in `/api/v2`: `library_id`, + `user_id`, `created_by_user_id`, `content_id`, `profile_id`. Don't parse or + compare them as numbers. ## Hosts diff --git a/pkg/pluginsdk/events/events.go b/pkg/pluginsdk/events/events.go index b15217c..db99ef2 100644 --- a/pkg/pluginsdk/events/events.go +++ b/pkg/pluginsdk/events/events.go @@ -75,15 +75,12 @@ const ( JobFailed = "job.failed" JobCancelled = "job.cancelled" - // RequestSubmitted, RequestApproved, RequestDeclined and RequestFulfilled - // follow a media request. Payload RequestEvent. - RequestSubmitted = "request.submitted" - RequestApproved = "request.approved" - RequestDeclined = "request.declined" - RequestFulfilled = "request.fulfilled" - // NotificationCreated: Silo added a notification to a profile's inbox, // such as a new episode or a request update. Payload Notification. + // + // Provisional: a plugin that delivers notifications should provide a + // notification_channel.v1 destination instead. This event may leave the + // catalog before SDK 1.0. NotificationCreated = "notification.created" ) @@ -127,11 +124,6 @@ var catalog = []Definition{ define[JobEvent](JobFailed, AccessAdmin, "An admin job failed."), define[JobEvent](JobCancelled, AccessAdmin, "An admin job was cancelled."), - define[RequestEvent](RequestSubmitted, AccessAdmin, "Someone requested a movie or series."), - define[RequestEvent](RequestApproved, AccessAdmin, "A media request was approved."), - define[RequestEvent](RequestDeclined, AccessAdmin, "A media request was declined."), - define[RequestEvent](RequestFulfilled, AccessAdmin, "A requested title arrived in a library."), - define[Notification](NotificationCreated, AccessUserData, "Silo added a notification to a profile's inbox."), } diff --git a/pkg/pluginsdk/events/events_test.go b/pkg/pluginsdk/events/events_test.go index f9f3dcd..ae6eccf 100644 --- a/pkg/pluginsdk/events/events_test.go +++ b/pkg/pluginsdk/events/events_test.go @@ -63,6 +63,11 @@ func TestProjectKeepsOnlyPublicFields(t *testing.T) { if got["job_type"] != "library_refresh" || got["status"] != "failed" { t.Fatalf("public fields lost: %s", out) } + // A job the server queued itself has no creator: the field is absent, + // not a zero ID. + if _, present := got["created_by_user_id"]; present { + t.Fatalf("absent creator encoded as a value: %s", out) + } } func TestProjectKeepsNestedAPIObjects(t *testing.T) { @@ -103,7 +108,7 @@ func TestProjectRejectsNamesOutsideTheCatalog(t *testing.T) { func TestDecode(t *testing.T) { payload, err := structpb.NewStruct(map[string]any{ - "id": "d1", "type": "episode.available", "user_id": 7, "profile_id": "p1", + "id": "d1", "type": "episode.available", "user_id": "7", "profile_id": "p1", "season_number": 2, "reason_flags": map[string]any{"favorite": true}, "created_at": "2026-11-04T10:00:00Z", }) @@ -114,7 +119,7 @@ func TestDecode(t *testing.T) { if err := events.Decode(payload, &n); err != nil { t.Fatal(err) } - if n.UserID != 7 || n.ProfileID != "p1" || n.SeasonNumber == nil || *n.SeasonNumber != 2 || string(n.ReasonFlags) != `{"favorite":true}` { + if n.UserID != "7" || n.ProfileID != "p1" || n.SeasonNumber == nil || *n.SeasonNumber != 2 || string(n.ReasonFlags) != `{"favorite":true}` { t.Fatalf("Decode() = %+v", n) } if err := events.Decode(nil, &n); err == nil { diff --git a/pkg/pluginsdk/events/payloads.go b/pkg/pluginsdk/events/payloads.go index 6944e5b..20b5d82 100644 --- a/pkg/pluginsdk/events/payloads.go +++ b/pkg/pluginsdk/events/payloads.go @@ -7,7 +7,7 @@ import ( // LibraryChanged is the payload of catalog.library.changed. type LibraryChanged struct { - LibraryID int `json:"library_id"` + LibraryID string `json:"library_id"` // Reason is what changed the library, such as "scan". Reason string `json:"reason"` New int `json:"new"` @@ -20,7 +20,7 @@ type LibraryChanged struct { // ItemChanged is the payload of catalog.item.changed. type ItemChanged struct { - LibraryID int `json:"library_id"` + LibraryID string `json:"library_id"` ContentID string `json:"content_id"` // Change names what changed, such as "metadata_updated". The vocabulary // is open; treat an unknown value as a general change. @@ -135,7 +135,7 @@ type PlaybackHistoryEntry struct { // scan.cancelled. type ScanEvent struct { ID string `json:"id"` - LibraryID int `json:"library_id"` + LibraryID string `json:"library_id"` // Mode and Trigger say how the scan runs and what started it. Their // vocabularies are open. Mode string `json:"mode"` @@ -171,9 +171,11 @@ type JobEvent struct { ID string `json:"id"` // JobType names the job, such as "library_refresh". The vocabulary is // open. - JobType string `json:"job_type"` - Status string `json:"status"` - CreatedByUserID int `json:"created_by_user_id"` + JobType string `json:"job_type"` + Status string `json:"status"` + // CreatedByUserID is the account that queued the job. Absent for a job + // the server queued itself. + CreatedByUserID *string `json:"created_by_user_id,omitempty"` Message string `json:"message"` ErrorMessage string `json:"error_message,omitempty"` ProgressCurrent int `json:"progress_current"` @@ -184,33 +186,6 @@ type JobEvent struct { UpdatedAt time.Time `json:"updated_at"` } -// RequestEvent is the payload of request.submitted, request.approved, -// request.declined and request.fulfilled. -type RequestEvent struct { - ID string `json:"id"` - // MediaType is "movie" or "series". The vocabulary is open. - MediaType string `json:"media_type"` - Title string `json:"title"` - Year *int `json:"year,omitempty"` - TMDBID int `json:"tmdb_id,omitempty"` - TVDBID *int `json:"tvdb_id,omitempty"` - IMDbID string `json:"imdb_id,omitempty"` - // PosterPath is a TMDB image path, such as "/abc.jpg". - PosterPath string `json:"poster_path,omitempty"` - // Status is the request's state after the event. The vocabulary is open. - Status string `json:"status"` - // RequestedByUserID and RequestedByProfileID identify the requester; - // both are empty for a request no profile made, such as an import. - RequestedByUserID int `json:"requested_by_user_id,omitempty"` - RequestedByProfileID string `json:"requested_by_profile_id,omitempty"` - RequesterName string `json:"requester_name,omitempty"` - // Reason is why a request was declined, when one was given. - Reason string `json:"reason,omitempty"` - // LibraryContentID is the catalog item a fulfilled request matched. - LibraryContentID string `json:"library_content_id,omitempty"` - CreatedAt time.Time `json:"created_at"` -} - // Notification is the payload of notification.created: one delivery // to one profile's inbox. type Notification struct { @@ -221,9 +196,9 @@ type Notification struct { Type string `json:"type"` // UserID is the account that owns the profile. Profile IDs repeat across // accounts, so identify a recipient by UserID and ProfileID together. - UserID int `json:"user_id"` + UserID string `json:"user_id"` ProfileID string `json:"profile_id"` - LibraryID *int `json:"library_id,omitempty"` + LibraryID *string `json:"library_id,omitempty"` SeriesID *string `json:"series_id,omitempty"` EpisodeID *string `json:"episode_id,omitempty"` SeriesTitle string `json:"series_title,omitempty"` From 3d7111dbcebbc2e6ad4106636946a839025f39e9 Mon Sep 17 00:00:00 2001 From: Quick <31828688+Quick104@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:58:13 +0000 Subject: [PATCH 6/6] fix(events): project nested session, history and reason objects to declared fields SessionEvent carried the host's whole admin session and history objects, and Notification its reason_flags, as raw JSON, so a field the host added reached plugins without an SDK release. They are typed now, and Project keeps only the declared fields. catalog.item.changed no longer claims to report file changes, which hosts don't deliver to plugins. Co-Authored-By: Claude Fable 5.2 --- docs/events.md | 21 +++++--- pkg/pluginsdk/events/events.go | 7 +-- pkg/pluginsdk/events/events_test.go | 53 ++++++++++++------ pkg/pluginsdk/events/payloads.go | 83 ++++++++++++++--------------- 4 files changed, 94 insertions(+), 70 deletions(-) diff --git a/docs/events.md b/docs/events.md index 69f55ef..500fd41 100644 --- a/docs/events.md +++ b/docs/events.md @@ -31,7 +31,7 @@ func (s *server) HandleEvent(ctx context.Context, req *pluginv1.HandleEventReque if err := events.Decode(req.GetPayload(), &event); err != nil { return &pluginv1.HandleEventResponse{}, nil // malformed: ignore, don't retry } - session, _ := event.DecodeSession() + session := event.Session // nil when no server has a live record // ... } return &pluginv1.HandleEventResponse{}, nil @@ -78,7 +78,7 @@ the events the plugin uses. | Event | Access | Payload | When | |---|---|---|---| | `catalog.library.changed` | public | `LibraryChanged` | A scan or refresh changed a library. | -| `catalog.item.changed` | public | `ItemChanged` | A catalog item's metadata, artwork or files changed. | +| `catalog.item.changed` | public | `ItemChanged` | A catalog item's metadata or artwork changed. | | `session.started` | admin | `SessionEvent` | A playback session started. | | `session.paused` | admin | `SessionEvent` | A playback session paused. | | `session.resumed` | admin | `SessionEvent` | A paused session resumed. | @@ -97,19 +97,24 @@ Notes on specific payloads: - **`SessionEvent`** carries the live session (`session`, on started, paused and resumed) or the history entry the end recorded (`history`, on stopped). - These are the `/api/v2` `AdminPlaybackSession` and - `AdminPlaybackHistoryEntry` objects, with every field that schema defines. - `DecodeSession` and `DecodeHistory` read the common ones. A session's - events can arrive out of order; `seq` orders them. + They carry the fields of `PlaybackSession` and `PlaybackHistoryEntry` and + no others: a field the host adds to its `/api/v2` `AdminPlaybackSession` + or `AdminPlaybackHistoryEntry` schema reaches plugins only when an SDK + release adds it to these types. A session's events can arrive out of + order; `seq` orders them. - **`Notification`** identifies its recipient by `user_id` and `profile_id` - together. Profile IDs repeat across accounts. + together. Profile IDs repeat across accounts. `reason_flags` carries the + fields of `NotificationReason`: `next_up` on a new episode, and the title + (`request_id`, `tmdb_id`, `media_type`, `title`, `year`, the decline + `reason`, `follower`) on a request or watchlist notification. - **`notification.created` is provisional.** A plugin that sends a profile's notifications somewhere else (Pushover, ntfy and the like) should provide a `notification_channel.v1` destination, which gets the host's preferences, queue and retries. This event may leave the catalog before SDK 1.0. - Every identifier is a JSON string, as in `/api/v2`: `library_id`, `user_id`, `created_by_user_id`, `content_id`, `profile_id`. Don't parse or - compare them as numbers. + compare them as numbers. The one exception is `reason_flags.tmdb_id`, TMDB's + own numeric ID. ## Hosts diff --git a/pkg/pluginsdk/events/events.go b/pkg/pluginsdk/events/events.go index db99ef2..c84cb2e 100644 --- a/pkg/pluginsdk/events/events.go +++ b/pkg/pluginsdk/events/events.go @@ -50,8 +50,9 @@ const ( // CatalogLibraryChanged: a scan or refresh changed a library. Payload // LibraryChanged. CatalogLibraryChanged = "catalog.library.changed" - // CatalogItemChanged: one catalog item's metadata, artwork or files - // changed. Payload ItemChanged. + // CatalogItemChanged: one catalog item's metadata or artwork changed. + // Items a scan adds, removes or re-files are reported by + // CatalogLibraryChanged, not one by one. Payload ItemChanged. CatalogItemChanged = "catalog.item.changed" // SessionStarted, SessionPaused, SessionResumed and SessionStopped follow @@ -107,7 +108,7 @@ func define[T any](name string, access Access, description string) Definition { var catalog = []Definition{ define[LibraryChanged](CatalogLibraryChanged, AccessPublic, "A scan or refresh changed a library."), - define[ItemChanged](CatalogItemChanged, AccessPublic, "A catalog item's metadata, artwork or files changed."), + define[ItemChanged](CatalogItemChanged, AccessPublic, "A catalog item's metadata or artwork changed."), define[SessionEvent](SessionStarted, AccessAdmin, "A playback session started."), define[SessionEvent](SessionPaused, AccessAdmin, "A playback session paused."), diff --git a/pkg/pluginsdk/events/events_test.go b/pkg/pluginsdk/events/events_test.go index ae6eccf..d30f158 100644 --- a/pkg/pluginsdk/events/events_test.go +++ b/pkg/pluginsdk/events/events_test.go @@ -70,29 +70,52 @@ func TestProjectKeepsOnlyPublicFields(t *testing.T) { } } -func TestProjectKeepsNestedAPIObjects(t *testing.T) { - // session is an /api/v2 object governed by that contract: every field - // passes through, not only the ones PlaybackSession reads. +func TestProjectKeepsOnlyCatalogFieldsOfNestedObjects(t *testing.T) { + // A nested object is allowlisted like the payload itself: a field the + // host's own schema has and the catalog type lacks doesn't reach plugins. raw := []byte(`{"session_id":"s1","seq":3,"at":"2026-11-04T10:00:00.123Z","state":"playing", - "session":{"session_id":"s1","user_id":"7","media_title":"Heat","routing_egress":"direct"}}`) + "session":{"session_id":"s1","user_id":"7","media_title":"Heat","client_user_agent":"UA/1","routing_egress":"direct"}}`) out, err := events.Project(events.SessionStarted, raw) if err != nil { t.Fatal(err) } - var event events.SessionEvent + var event struct { + Session map[string]any `json:"session"` + History map[string]any `json:"history"` + } if err := json.Unmarshal(out, &event); err != nil { t.Fatal(err) } - var session map[string]any - if err := json.Unmarshal(event.Session, &session); err != nil || session["routing_egress"] != "direct" { - t.Fatalf("nested session = %s, %v", event.Session, err) + if event.Session["user_id"] != "7" || event.Session["media_title"] != "Heat" { + t.Fatalf("session = %v, want its catalog fields", event.Session) + } + for _, internal := range []string{"client_user_agent", "routing_egress"} { + if _, leaked := event.Session[internal]; leaked { + t.Errorf("session carries %q, which PlaybackSession doesn't declare", internal) + } + } + if event.History != nil { + t.Fatalf("history = %v, want none on a started event", event.History) + } + + raw = []byte(`{"id":"d1","type":"request.declined","user_id":"7","profile_id":"p1","created_at":"2026-11-04T10:00:00Z", + "reason_flags":{"request_id":"r1","tmdb_id":603,"media_type":"movie","reason":"Not available","internal_note":"x"}}`) + out, err = events.Project(events.NotificationCreated, raw) + if err != nil { + t.Fatal(err) + } + var notification struct { + ReasonFlags map[string]any `json:"reason_flags"` + } + if err := json.Unmarshal(out, ¬ification); err != nil { + t.Fatal(err) } - typed, err := event.DecodeSession() - if err != nil || typed.UserID != "7" || typed.MediaTitle != "Heat" { - t.Fatalf("DecodeSession() = %+v, %v", typed, err) + flags := notification.ReasonFlags + if flags["request_id"] != "r1" || flags["tmdb_id"] != float64(603) || flags["reason"] != "Not available" { + t.Fatalf("reason_flags = %v, want the request's catalog fields", flags) } - if history, err := event.DecodeHistory(); history != nil || err != nil { - t.Fatalf("DecodeHistory() = %+v, %v; want nil for a started event", history, err) + if _, leaked := flags["internal_note"]; leaked { + t.Errorf("reason_flags carries a field NotificationReason doesn't declare: %v", flags) } } @@ -109,7 +132,7 @@ func TestProjectRejectsNamesOutsideTheCatalog(t *testing.T) { func TestDecode(t *testing.T) { payload, err := structpb.NewStruct(map[string]any{ "id": "d1", "type": "episode.available", "user_id": "7", "profile_id": "p1", - "season_number": 2, "reason_flags": map[string]any{"favorite": true}, + "season_number": 2, "reason_flags": map[string]any{"next_up": true}, "created_at": "2026-11-04T10:00:00Z", }) if err != nil { @@ -119,7 +142,7 @@ func TestDecode(t *testing.T) { if err := events.Decode(payload, &n); err != nil { t.Fatal(err) } - if n.UserID != "7" || n.ProfileID != "p1" || n.SeasonNumber == nil || *n.SeasonNumber != 2 || string(n.ReasonFlags) != `{"favorite":true}` { + if n.UserID != "7" || n.ProfileID != "p1" || n.SeasonNumber == nil || *n.SeasonNumber != 2 || n.ReasonFlags == nil || !n.ReasonFlags.NextUp { t.Fatalf("Decode() = %+v", n) } if err := events.Decode(nil, &n); err == nil { diff --git a/pkg/pluginsdk/events/payloads.go b/pkg/pluginsdk/events/payloads.go index 20b5d82..9ba98a2 100644 --- a/pkg/pluginsdk/events/payloads.go +++ b/pkg/pluginsdk/events/payloads.go @@ -1,9 +1,6 @@ package events -import ( - "encoding/json" - "time" -) +import "time" // LibraryChanged is the payload of catalog.library.changed. type LibraryChanged struct { @@ -40,41 +37,17 @@ type SessionEvent struct { State string `json:"state"` // EndReason is why a stopped session ended. EndReason string `json:"end_reason,omitempty"` - // Session is the live session on a started, paused or resumed event, as - // the /api/v2 AdminPlaybackSession schema describes it. Absent when no - // server has a live record of it. DecodeSession reads common fields. - Session json.RawMessage `json:"session,omitempty"` - // History is the history entry a stopped event recorded, as the /api/v2 - // AdminPlaybackHistoryEntry schema describes it. DecodeHistory reads - // common fields. - History json.RawMessage `json:"history,omitempty"` + // Session is the live session on a started, paused or resumed event. + // Absent when no server has a live record of it. + Session *PlaybackSession `json:"session,omitempty"` + // History is the history entry a stopped event recorded. + History *PlaybackHistoryEntry `json:"history,omitempty"` } -// DecodeSession decodes the live session. It returns nil when the event has -// none. -func (e SessionEvent) DecodeSession() (*PlaybackSession, error) { - return decodeOptional[PlaybackSession](e.Session) -} - -// DecodeHistory decodes the history entry. It returns nil when the event has -// none. -func (e SessionEvent) DecodeHistory() (*PlaybackHistoryEntry, error) { - return decodeOptional[PlaybackHistoryEntry](e.History) -} - -func decodeOptional[T any](raw json.RawMessage) (*T, error) { - if len(raw) == 0 || string(raw) == "null" { - return nil, nil - } - out := new(T) - if err := json.Unmarshal(raw, out); err != nil { - return nil, err - } - return out, nil -} - -// PlaybackSession is a subset of the /api/v2 AdminPlaybackSession schema. As -// in /api/v2, IDs are strings. +// PlaybackSession is a playback session as plugins see it: these fields of +// the /api/v2 AdminPlaybackSession schema and no others. As in /api/v2, IDs +// are strings. A field the host adds to that schema reaches plugins only when +// an SDK release adds it here. type PlaybackSession struct { SessionID string `json:"session_id"` UserID string `json:"user_id"` @@ -104,8 +77,9 @@ type PlaybackSession struct { StreamBitrateKbps *int `json:"stream_bitrate_kbps"` } -// PlaybackHistoryEntry is a subset of the /api/v2 AdminPlaybackHistoryEntry -// schema. As in /api/v2, IDs are strings. +// PlaybackHistoryEntry is a finished session as plugins see it: these fields +// of the /api/v2 AdminPlaybackHistoryEntry schema and no others. As in +// /api/v2, IDs are strings. type PlaybackHistoryEntry struct { SessionID string `json:"session_id"` UserID string `json:"user_id"` @@ -210,9 +184,30 @@ type Notification struct { PosterPath string `json:"poster_path,omitempty"` // PosterURL is a poster URL when the host has one ready. It can expire. PosterURL string `json:"poster_url,omitempty"` - // ReasonFlags is a JSON object whose shape depends on Type: why an - // episode was announced (favorite, watchlist, continue_watching, - // next_up) or which request changed. - ReasonFlags json.RawMessage `json:"reason_flags,omitempty"` - CreatedAt time.Time `json:"created_at"` + // ReasonFlags says why the notification was sent. Which fields are set + // depends on Type. + ReasonFlags *NotificationReason `json:"reason_flags,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +// NotificationReason is a notification's reason_flags. A new-episode +// notification sets NextUp. A request or watchlist notification names the +// title. Other types set nothing. +type NotificationReason struct { + // NextUp: the episode is the next one after what the profile watched. + NextUp bool `json:"next_up,omitempty"` + // RequestID is the media request a request.* notification is about. + RequestID string `json:"request_id,omitempty"` + // TMDBID is the title's ID at TMDB, which is a number there. It is the + // one identifier in the catalog that isn't a string. + TMDBID int64 `json:"tmdb_id,omitempty"` + // MediaType is "movie" or "series". + MediaType string `json:"media_type,omitempty"` + Title string `json:"title,omitempty"` + Year int `json:"year,omitempty"` + // Reason is the message an administrator gave when declining a request. + Reason string `json:"reason,omitempty"` + // Follower marks a request.fulfilled notification sent to a profile that + // followed the title and did not request it. + Follower bool `json:"follower,omitempty"` }