wittyremote

package
v0.8.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Package wittyremote is the Remote Protocol: one WittyMedia client controlling another through the server. A client that can be controlled announces itself as a device, keeps a channel open for commands, and reports what it is playing. docs/REMOTE-PROTOCOL.md is the wire format; this file is its messages, and hub.go who is here and what is waiting.

Nothing here knows about HTTP, accounts' limits or the library: internal/server decides who may control what, and hands over only what is allowed.

Index

Constants

View Source
const (
	CodeOffline     = "offline"     // the device isn't here (any more)
	CodeBusy        = "busy"        // too many commands are already waiting for it
	CodeTimeout     = "timeout"     // it didn't answer in time
	CodeUnsupported = "unsupported" // it never said it could do this
	CodeRefused     = "refused"     // it answered, and said no
)

Codes a CommandError carries.

View Source
const (
	Version    = 1
	MinVersion = 1
)

Version is the protocol version this server speaks, and MinVersion the oldest it still accepts from a client. Within a version, messages only gain fields.

View Source
const (
	FeatureSeek      = "seek"
	FeatureVolume    = "volume"
	FeatureQueue     = "queue"
	FeatureAudio     = "audio"
	FeatureSubtitles = "subtitles"
	FeatureNavigate  = "navigate"
	FeatureRate      = "rate"
)

Features a device can say it has. One it doesn't name is never asked of it.

View Source
const (
	CmdPlay     = "play"
	CmdPause    = "pause"
	CmdResume   = "resume"
	CmdStop     = "stop"
	CmdSeek     = "seek"
	CmdNext     = "next"
	CmdPrevious = "previous"
	CmdVolume   = "volume"
	CmdMute     = "mute"
	CmdAudio    = "audio"
	CmdSubtitle = "subtitle"
	CmdRate     = "rate"
	CmdNavigate = "navigate"
	// CmdCast is only ever sent by a controller: the server turns it into a play for the
	// device it is sent to, and a stop for the one named in From.
	CmdCast = "cast"
)

Command types.

View Source
const (
	MaxNameLen    = 60
	MaxQueueItems = 200
	MaxTracks     = 64
)

What bounds a message. A device or a controller can't make the server hold more.

Variables

View Source
var (
	ErrNoDevice    = errors.New("no such device")
	ErrNotYours    = errors.New("that device belongs to another sign-in")
	ErrTooMany     = errors.New("too many devices are announced already")
	ErrTooManySubs = errors.New("too many controllers are watching already")
	ErrVersion     = errors.New("this app speaks an older Remote Protocol than the server accepts: update the app")
	ErrRate        = errors.New("too many messages: slow down")
	ErrNoCommand   = errors.New("no such command is waiting")
)

Features is every feature this version knows.

View Source
var Kinds = []string{"web", "tv", "phone", "tablet", "desktop", "other"}

Kinds of device. A client that is none of these says "other".

View Source
var MediaKinds = []string{"video", "audio", "dvd-iso", "dvd-folder", "bluray-iso", "bluray-folder", "cd-image", "book", "radio", "game", "photo"}

MediaKinds are the kinds of item a device can say it plays: the library's own item kinds.

View Source
var NavigateKeys = []string{"up", "down", "left", "right", "select", "back", "home", "menu", "playpause"}

NavigateKeys are the keys a TV interface is driven with.

View Source
var Statuses = []string{"idle", "playing", "paused", "buffering"}

Playback states a device reports.

Functions

func Clip

func Clip(s string, n int) string

Clip cuts s to at most n bytes without splitting a character, and drops what isn't text.

Types

type Announce

type Announce struct {
	UserID    int64
	UserName  string
	SessionID string // the sign-in it belongs to: auth.SessionID
	// DeviceID: the id it had before, to come back as the same device. "" for a new one.
	DeviceID string
	V        int
	Name     string
	Kind     string
	Caps     Capabilities
}

Announce is a client saying it can be controlled.

type Capabilities

type Capabilities struct {
	MediaKinds []string `json:"mediaKinds"`
	Features   []string `json:"features"`
}

Capabilities is what a device says it can do, and after Negotiate what the server will ask of it.

func (Capabilities) Has

func (c Capabilities) Has(feature string) bool

Has reports whether a feature was agreed.

func (Capabilities) Negotiate

func (c Capabilities) Negotiate() Capabilities

Negotiate keeps what both sides know. A newer client's features this server has never heard of are dropped, so nothing is ever sent that neither side can describe.

func (Capabilities) Plays

func (c Capabilities) Plays(kind string) bool

Plays reports whether a kind of item was agreed.

type Command

type Command struct {
	V    int    `json:"v"`
	ID   string `json:"id,omitempty"`
	Type string `json:"type"`

	// play
	ItemID     int64   `json:"itemId,omitempty"`
	Queue      []int64 `json:"queue,omitempty"`
	QueueIndex int     `json:"queueIndex,omitempty"`
	// play and seek: where, in seconds from the start.
	PositionSec *float64 `json:"positionSec,omitempty"`
	// seek: or this far from where it is now.
	BySec *float64 `json:"bySec,omitempty"`
	// play, audio, subtitle: a track's id as the device's own state lists it. "off" for no
	// subtitles.
	Audio    *string `json:"audio,omitempty"`
	Subtitle *string `json:"subtitle,omitempty"`
	// volume: 0 to 1. mute: on or off.
	Level *float64 `json:"level,omitempty"`
	Muted *bool    `json:"muted,omitempty"`
	// rate: 1 is normal speed.
	Rate *float64 `json:"rate,omitempty"`
	// navigate
	Key string `json:"key,omitempty"`
	// cast: the device to take over from.
	From string `json:"from,omitempty"`

	// Filled in by the server on the way to the device.
	Sender *Sender `json:"sender,omitempty"`
	SentAt int64   `json:"sentAt,omitempty"` // server time, ms
}

Command is one thing a device is asked to do. Which fields matter depends on Type; docs/REMOTE-PROTOCOL.md lists them. Pointers tell "not said" from zero.

func (*Command) Check

func (c *Command) Check() error

Check says what is wrong with a command a controller sent, or nil.

func (*Command) Items

func (c *Command) Items() []int64

Items is every item a play command names.

func (*Command) Needs

func (c *Command) Needs() string

Needs is the feature a device must have agreed for this command, "" for one every device obeys.

type CommandError

type CommandError struct {
	Code    string
	Message string
}

Why a command didn't happen. Code is for programs, Message for people.

func (*CommandError) Error

func (e *CommandError) Error() string

type Conn

type Conn struct {
	C chan Command
	// contains filtered or unexported fields
}

Conn is a device's open channel: the server's handler reads commands from C and writes them to the client, until Done closes.

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Done closes when the channel should end: the device was removed, announced itself again elsewhere, or went quiet.

func (*Conn) Why

func (c *Conn) Why() string

Why says what ended it, for the client's last message.

type Device

type Device struct {
	ID       string       `json:"id"`
	Name     string       `json:"name"`
	Kind     string       `json:"kind"`
	UserID   int64        `json:"userId"`
	UserName string       `json:"userName"`
	V        int          `json:"v"`
	Caps     Capabilities `json:"capabilities"`
	// Online: its channel is open, so a command can reach it.
	Online bool `json:"online"`
	// State is what it last reported, and StateAt when, in server milliseconds. A
	// controller works out where a playing device is now from the two.
	State   State `json:"state"`
	StateAt int64 `json:"stateAt"`

	SessionID string `json:"-"`
}

Device is one controllable client, as anyone allowed to control it sees it.

type Hub

type Hub struct {
	Limits Limits
	// OnDrop, when set, is told each device the hub forgets and why: "expired" (it never
	// opened its channel), "idle" (it went quiet), "removed" or "signed-out". It is called
	// with the hub's lock held, so it must not call the hub.
	OnDrop func(d Device, why string)
	// contains filtered or unexported fields
}

Hub is who is here. The zero value isn't usable: New makes one.

func New

func New(l Limits, now func() time.Time) *Hub

New makes a hub. now is the clock (nil: the real one), so tests can move time.

func (*Hub) Ack

func (h *Hub) Ack(id string, userID int64, session, commandID string, ok bool, why string) error

Ack is a device answering a command: done, or not and why.

func (*Hub) AllowCommand

func (h *Hub) AllowCommand(userID int64) bool

AllowCommand counts one command against an account's rate, and says whether it may go.

func (*Hub) Announce

func (h *Hub) Announce(a Announce) (Device, error)

Announce registers a device, or brings one back under the id it had. The device then has AnnounceGrace to open its channel.

func (*Hub) Attach

func (h *Hub) Attach(id string, userID int64, session string) (*Conn, Device, error)

Attach opens a device's channel. An earlier channel of the same device ends: the app reconnected, and one device has one channel.

func (*Hub) Counts

func (h *Hub) Counts() (devices, subs, pending int)

Counts is how much the hub is holding, for tests and the statistics.

func (*Hub) Detach

func (h *Hub) Detach(id string, c *Conn)

Detach is the channel's handler saying it has ended. The device is offline at once: nothing more can be sent to it, and whatever was waiting fails now, not after a timeout. It has AnnounceGrace to come back as the same device.

func (*Hub) Device

func (h *Hub) Device(id string) (Device, bool)

Device is one device, if it is here.

func (*Hub) Devices

func (h *Hub) Devices() []Device

Devices is everyone here, by name. The caller shows each account only what it may see.

func (*Hub) Remove

func (h *Hub) Remove(id string, userID int64, session string) error

Remove is a device saying goodbye, or its sign-in ending.

func (*Hub) RemoveSession

func (h *Hub) RemoveSession(session string)

RemoveSession forgets every device of a sign-in that has ended.

func (*Hub) RemoveUser

func (h *Hub) RemoveUser(userID int64, keep string)

RemoveUser forgets every device of an account, except those of the sign-in keep ("" for none): "sign out everywhere else", a new password, an account deleted.

func (*Hub) Report

func (h *Hub) Report(id string, userID int64, session string, st State) error

Report is a device saying what it is doing. It is also its heartbeat.

func (*Hub) Send

func (h *Hub) Send(ctx context.Context, id string, ownerID int64, cmd Command) error

Send gives a device a command and waits for its answer. It returns nil when the device said it did it, and a *CommandError otherwise. It never waits on a device that isn't here, and never leaves a command in a queue nobody is reading: a full queue is "busy", said at once. ownerID is whose device the caller was allowed to control; a device that has since become someone else's is "offline" to them.

func (*Hub) Subscribe

func (h *Hub) Subscribe(userID int64) (*Sub, error)

Subscribe starts watching for changes.

func (*Hub) Sweep

func (h *Hub) Sweep()

Sweep is sweep for whoever keeps a channel open and so has a clock ticking anyway.

type Limits

type Limits struct {
	MaxDevices            int // every account's together
	MaxDevicesPerUser     int
	MaxSubscribers        int // controllers watching, every account's together
	MaxSubscribersPerUser int
	// QueueLen: commands waiting to be written to one device. One more fails as "busy".
	QueueLen int
	// StateEvery: a device's reports closer together than this are refused, apart from a
	// short burst. CommandEvery: the same for one account's commands.
	StateEvery   time.Duration
	StateBurst   int
	CommandEvery time.Duration
	CommandBurst int
	// AnnounceGrace: how long a device that announced itself may take to open its channel,
	// and how long after its channel dropped it may come back as the same device.
	AnnounceGrace time.Duration
	// IdleAfter: a device whose channel is open but which has reported nothing for this
	// long is taken to be gone. HeartbeatEvery is what it is told to keep to.
	IdleAfter      time.Duration
	HeartbeatEvery time.Duration
	// AckTimeout: how long a command waits for the device to answer.
	AckTimeout time.Duration
}

Limits bound what the hub holds, so that a Raspberry Pi with a house full of devices, or one misbehaving app, costs a known amount of memory.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits suit a home: a handful of people, a few devices each.

type Sender

type Sender struct {
	UserName string `json:"userName"`
	DeviceID string `json:"deviceId,omitempty"`
}

Sender says who asked, for the device to show ("Sam is playing this on the TV").

type State

type State struct {
	V           int      `json:"v"`
	Status      string   `json:"status"`
	ItemID      int64    `json:"itemId,omitempty"`
	PositionSec float64  `json:"positionSec"`
	DurationSec float64  `json:"durationSec"`
	Rate        float64  `json:"rate"`
	Volume      *float64 `json:"volume,omitempty"`
	Muted       bool     `json:"muted"`
	Audio       string   `json:"audio,omitempty"`
	Subtitle    string   `json:"subtitle,omitempty"`
	AudioTracks []Track  `json:"audioTracks,omitempty"`
	SubTracks   []Track  `json:"subtitleTracks,omitempty"`
	Queue       []int64  `json:"queue,omitempty"`
	QueueIndex  int      `json:"queueIndex,omitempty"`
	// Screen: where in its interface the device is, when it isn't playing ("home", "player").
	Screen string `json:"screen,omitempty"`
}

State is what a device is doing, as it last said.

func (State) Clean

func (s State) Clean() State

Clean makes a state a device sent safe to keep and pass on: known status, finite numbers in range, short strings, bounded lists. A device is never refused for a slightly wrong report; it is tidied.

type Sub

type Sub struct {
	// contains filtered or unexported fields
}

Sub is a controller watching devices come, go and change. It is told only that something changed and which devices; it then reads what they are now. A slow controller therefore misses the steps in between, never the latest, and never makes anyone wait.

func (*Sub) C

func (s *Sub) C() <-chan struct{}

C says Take has something.

func (*Sub) Close

func (s *Sub) Close()

Close stops watching.

func (*Sub) Take

func (s *Sub) Take() []string

Take returns the ids of devices that changed since the last Take.

type Track

type Track struct {
	ID    string `json:"id"`
	Label string `json:"label,omitempty"`
	Lang  string `json:"lang,omitempty"`
}

Track is one sound or subtitle track a device offers for what it is playing.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL