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..fc12c7d 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -52,6 +52,14 @@ 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 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)). + `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..500fd41 --- /dev/null +++ b/docs/events.md @@ -0,0 +1,123 @@ +# 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.Session // nil when no server has a live record + // ... + } + return &pluginv1.HandleEventResponse{}, nil +} +``` + +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, 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 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 | +|---|---| +| `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 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. | +| `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. Provisional, see below. | + +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). + 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. `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. The one exception is `reason_flags.tmdb_id`, TMDB's + own numeric ID. + +## 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..c84cb2e --- /dev/null +++ b/pkg/pluginsdk/events/events.go @@ -0,0 +1,217 @@ +// 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 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 + // 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. + // + // 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" +) + +// 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 or artwork 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: the +// prefix, then a publisher plugin_id and an event name, both nonempty. +func IsPluginEvent(name string) bool { + 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 +// 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; 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") + } + 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..d30f158 --- /dev/null +++ b/pkg/pluginsdk/events/events_test.go @@ -0,0 +1,151 @@ +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, 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) + } + } +} + +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) + } + // 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 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","client_user_agent":"UA/1","routing_egress":"direct"}}`) + out, err := events.Project(events.SessionStarted, raw) + if err != nil { + t.Fatal(err) + } + 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) + } + 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) + } + 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 _, leaked := flags["internal_note"]; leaked { + t.Errorf("reason_flags carries a field NotificationReason doesn't declare: %v", flags) + } +} + +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{"next_up": 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 || n.ReasonFlags == nil || !n.ReasonFlags.NextUp { + 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..9ba98a2 --- /dev/null +++ b/pkg/pluginsdk/events/payloads.go @@ -0,0 +1,213 @@ +package events + +import "time" + +// LibraryChanged is the payload of catalog.library.changed. +type LibraryChanged struct { + LibraryID string `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 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. + 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. + // 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"` +} + +// 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"` + 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 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"` + 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 string `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 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"` + 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 string `json:"user_id"` + ProfileID string `json:"profile_id"` + LibraryID *string `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 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"` +} diff --git a/pkg/pluginsdk/manifest/subscriptions.go b/pkg/pluginsdk/manifest/subscriptions.go new file mode 100644 index 0000000..2a2ff09 --- /dev/null +++ b/pkg/pluginsdk/manifest/subscriptions.go @@ -0,0 +1,47 @@ +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" +) + +// 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 + } + 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{}{} + } + } + return problems +} diff --git a/pkg/pluginsdk/manifest/subscriptions_test.go b/pkg/pluginsdk/manifest/subscriptions_test.go new file mode 100644 index 0000000..d012618 --- /dev/null +++ b/pkg/pluginsdk/manifest/subscriptions_test.go @@ -0,0 +1,45 @@ +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 TestSubscriptionProblems(t *testing.T) { + for _, tc := range []struct { + name string + typ string + subscriptions []string + want string + }{ + {name: "catalog and plugin events", typ: "event_consumer.v1", subscriptions: []string{"session.started", "plugin.silo.pushover.sent"}}, + {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}}, + } + // 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 len(problems) == 0 || !strings.Contains(strings.Join(problems, "\n"), tc.want) { + t.Fatalf("SubscriptionProblems() = %v, want one containing %q", problems, tc.want) + } + }) + } +}