Skip to main content

spoolframe_protocol/
messages.rs

1//! The messages of `spoolframe/client/1`.
2//!
3//! Every enum is internally tagged: `{"type": "ping"}`,
4//! `{"type": "item", "id": "plex:movie:1"}`. Peers ignore fields they do
5//! not know, and an error or event type they do not know decodes as
6//! `Unknown`, so a newer peer can add both without breaking an older one.
7//! A request type the server does not know is answered with
8//! [`Error::Unsupported`].
9
10use std::fmt;
11
12use serde::{Deserialize, Serialize};
13use spoolframe_types::{
14    ClientCapabilities, DisplayCapabilities, Item, Library, LibraryId, Marker, MediaId,
15    MediaTracks, PersonId, Platform, Role, SubtitleFormat, TrackPreferences,
16};
17
18use crate::invite_admin::{CreateInvite, InviteCreated, InviteSummary};
19use crate::media::PlaybackHandle;
20use crate::pairing::{PairingAnswer, PairingOffer, RelayCode};
21use crate::passkeys::{
22    FinishPasskeyRegistration, FinishPasskeySignIn, PasskeyInfo, PasskeyRegistrationBegun,
23    PasskeySignInBegun,
24};
25use crate::playback::{BitmapSubtitles, ChosenTracks, PlaybackPlan, Quality, Selection};
26use crate::playlists::{
27    Kinds, PinNote, PlaylistEdit, PlaylistPage, PlaylistRef, PlaylistSummary, Visibility,
28};
29use crate::plex::PlexLink;
30use crate::portable::{
31    IdentityRecord, PortableIdentityState, PortableUserId, TieProof, UserDeviceCredential,
32    signature_hex,
33};
34use crate::previews::Previews;
35use crate::search::{SearchRequest, SearchResults};
36
37/// The protocol revision inside the `spoolframe/client/1` ALPN. Raised
38/// for coordinated development releases, including breaking wire changes.
39/// A server refuses every other revision at `Hello`.
40pub const PROTOCOL_VERSION: u32 = 1;
41
42/// The maximum raw body of one subtitle chunk on a resource stream.
43pub const SUBTITLE_CHUNK: u64 = 512 << 10;
44
45/// An opaque session token from a login. It is only valid from
46/// the endpoint that logged in.
47#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
48#[serde(transparent)]
49pub struct SessionId(pub String);
50
51impl fmt::Debug for SessionId {
52    // A session is a credential (bound to one endpoint, but still): keep it
53    // out of logs.
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str("SessionId(<redacted>)")
56    }
57}
58
59/// One request, and the session it is made in.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct RequestEnvelope {
62    /// `None` for the pre-auth requests. Several sessions may be used on
63    /// one connection.
64    #[serde(deserialize_with = "spoolframe_types::required::option")]
65    pub session: Option<SessionId>,
66    pub request: Request,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(tag = "type", rename_all = "snake_case")]
71pub enum Request {
72    // Pre-auth: the only requests served without a session.
73    /// The first request on every connection.
74    Hello(Hello),
75    AuthMethods,
76    LoginPassword(LoginPassword),
77    Ping,
78    /// Explicit foreground profile selection. Background requests never select a profile.
79    ActivateProfile,
80    /// Last accepted progress sequence for a restored playback handle.
81    PlaybackProgressSequence {
82        handle: PlaybackHandle,
83    },
84    /// Ask to be signed in by someone approving this device on another
85    /// one they are signed in on. Show the code (and its
86    /// [`crate::device_sign_in::link`] as a QR code), then
87    /// `AwaitDeviceSignIn`. `DeviceSignInStarted`.
88    ///
89    /// `remember` asks for this device to be trusted; the
90    /// approver sees the request and decides. Never true unless the user
91    /// ticked "Remember this device".
92    BeginDeviceSignIn {
93        remember: bool,
94    },
95    /// Wait, up to about 25 s, for `request` to be approved: `LoggedIn`
96    /// with a session for this device, `DeviceSignInPending` (ask again),
97    /// or `DeviceSignInDenied` / `DeviceSignInExpired`. Only the device
98    /// that began the request may ask, and one wait at a time: a newer
99    /// one ends the one before it with `DeviceSignInPending`.
100    AwaitDeviceSignIn {
101        request: String,
102    },
103    /// Begin signing in with an app passkey ([`crate::passkeys`]):
104    /// `PasskeySignInBegun`, a nonce, listing no passkeys (any the
105    /// platform finds): anyone can ask. With `username`, only that user's
106    /// passkeys finish it. The nonce is this device's, for 5 minutes;
107    /// beginning again replaces it. The challenge to sign is
108    /// [`crate::app_passkey_challenge`] of this server's id and the nonce.
109    BeginPasskeySignIn {
110        username: Option<String>,
111    },
112    /// Finish it with what the passkey signed: `LoggedIn`, a session for
113    /// this device, as `LoginPassword` gives (its PIN is asked as usual),
114    /// and with `remember` this device trusted, as `LoginPassword` does.
115    /// Anything that does not sign in is `InvalidCredentials`, counted as
116    /// a failed sign-in (then `RateLimited`).
117    FinishPasskeySignIn {
118        signed: FinishPasskeySignIn,
119        remember: bool,
120    },
121    /// The users this device is trusted for: `TrustedProfiles`,
122    /// for "Who's watching" once their sessions have ended. Only this
123    /// device's own; nothing about other devices. Trust that lapsed is
124    /// left out.
125    TrustedProfiles,
126    /// Start a session on this device for `user_id` (as `TrustedProfiles`
127    /// gives it), without a password: `LoggedIn`, a normal session bound
128    /// to this device, `remembered: true`. A device that asks for the
129    /// user's PIN gets it locked, as after any sign-in. `Unauthenticated`,
130    /// the same for every reason, when this device is not trusted for
131    /// them, the trust lapsed or was removed, or the user is disabled.
132    /// The server never resumes a profile by itself: auto-login is the
133    /// client resuming the profile marked `auto_login` at start.
134    ResumeProfile {
135        user_id: String,
136    },
137    /// Make an account with an invite's code and sign in to it:
138    /// `LoggedIn`, a session bound to this device as `LoginPassword`
139    /// gives, `remembered: false`. The account has the invite's role.
140    ///
141    /// A code that is not one, or whose invite was revoked, is
142    /// `InviteInvalid`, counted as a wrong guess (then `RateLimited`); one
143    /// past its expiry `InviteExpired`; one with no uses left
144    /// `InviteExhausted`. A username someone has is `UsernameTaken`, and a
145    /// username, display name or password that is not acceptable
146    /// `InvalidInput`; the invite is not used up by either. A device that
147    /// is not signed in draws on the sign-in budget all such devices share,
148    /// as `LoginPassword` does.
149    RedeemInvite(RedeemInvite),
150    /// What an invite's code is, before joining with it: `InviteLookup`,
151    /// for the "Got an invite?" screen. Nothing is used up. The code is
152    /// taken as `RedeemInvite` takes it, and counted as it counts one: a
153    /// code no invite has (or that cannot be one) is `no_match`, a wrong
154    /// guess (then `RateLimited`); a revoked, expired or used-up one is
155    /// not counted. On the strangers' budget, as redeeming is.
156    LookupInvite(LookupInvite),
157    /// Begin signing in as a portable user with a device credential:
158    /// `PortableSignInBegun`, a nonce for the device key to sign
159    /// over ([`crate::portable::device_proof_message`] of this server's
160    /// endpoint id and it). The nonce is this device's, for
161    /// `expires_in_secs` (5 minutes), and is used once, whatever the
162    /// finish makes of it; beginning again replaces it. Draws on the
163    /// sign-in budget all devices not signed in share.
164    BeginPortableSignIn,
165    /// Finish it: `LoggedIn`, `remembered: false`, a session
166    /// bound to this device. Local-first: where the identity is tied to an
167    /// account here the session is that account's, as any sign-in
168    /// to it (its PIN is asked as usual); else, where it has a grant here,
169    /// the portable user's own; else nothing. Every refusal (no grant, a
170    /// credential or proof that does not hold, a revoked key, an expired
171    /// or missing nonce, a disabled account) is `InvalidCredentials`,
172    /// counted as a failed sign-in (then `RateLimited`).
173    FinishPortableSignIn(PortableSignIn),
174    /// Redeem a `portable-account` invite as the portable user
175    /// `sign_in` proves, over the nonce `BeginPortableSignIn` gave: the
176    /// server grants them access (no account is made), uses one of the
177    /// invite's uses, and signs them in as `FinishPortableSignIn` does:
178    /// `LoggedIn`. Someone granted here already keeps their grant, and
179    /// the invite its use.
180    ///
181    /// The code is checked as `RedeemInvite` checks it (`InviteInvalid`,
182    /// counted as a wrong guess; `InviteExpired`; `InviteExhausted`); a
183    /// `create-user` invite's code is `WrongInviteKind`, and its use is
184    /// kept. The credential is checked as `FinishPortableSignIn` checks
185    /// it: `InvalidCredentials`, counted.
186    RedeemPortableInvite(RedeemPortableInvite),
187    /// What this server keeps of portable identity `user`: its
188    /// genesis and newest state, `IdentityRecord`, for a device recovering
189    /// the identity with one of its roots. Only an identity known here
190    /// (tied or granted) has one; any other is `NotFound`. Public data,
191    /// served to anyone, on the strangers' budget.
192    IdentityRecord {
193        user: PortableUserId,
194    },
195    /// The record, as `IdentityRecord` answers it, of the identity whose
196    /// genesis handle is `handle`: what a security key gives back
197    /// as its credential's user handle, for a fresh install that holds a
198    /// key and nothing else. A key added to a phrase identity carries the
199    /// identity's id as its handle, so a handle that is the id of a phrase
200    /// identity known here answers that identity's record. Only an
201    /// identity known here has one; any other is `NotFound`. Handles are
202    /// 32 random bytes, so a miss says nothing. Public data, served to
203    /// anyone, on the strangers' budget.
204    IdentityRecordByHandle {
205        #[serde(with = "crate::portable::handle_hex")]
206        handle: [u8; crate::portable::HANDLE_LEN],
207    },
208    /// Hold a device's pairing request under its relay code, for a
209    /// root terminal with no camera to fetch: `Done`. For
210    /// [`crate::pairing::RELAY_TTL_SECS`]; offering again from the same
211    /// device replaces it. A code another device holds is
212    /// `InvalidInput`. On the strangers' budget.
213    OfferPairing(PairingOffer),
214    /// The pairing request held under `code`: `PairingOffered`, or
215    /// `NotFound`. On the strangers' budget, so codes are not guessed.
216    FetchPairing {
217        code: RelayCode,
218    },
219    /// The root terminal's answer to the request under `code`:
220    /// `Done`. One answer only, for the key the request named; another,
221    /// or no request, is `NotFound`; a credential for another key
222    /// `InvalidInput`. The server carries it and checks nothing else: the
223    /// device does. On the strangers' budget.
224    AnswerPairing {
225        code: RelayCode,
226        answer: PairingAnswer,
227    },
228    /// The answer to this device's request under `code`, if one came:
229    /// `PairingAnswered`, taken (the request ends with it) or
230    /// `None` while there is none yet. Only the device that offered it;
231    /// any other, or no request, is `NotFound`. Not on the strangers'
232    /// budget: the device asks every few seconds.
233    CollectPairing {
234        code: RelayCode,
235    },
236
237    // Need a session.
238    Libraries,
239    /// A page of a library's top-level items: `Items`. Without `sort` and
240    /// `filter`, every item by title, as before them. With either: ordered
241    /// by `sort`, then by sort title and id, and only the items `filter`
242    /// keeps, `total` counting those. A key or filter part the library
243    /// does not have (`ItemFilterValues` lists what it has), or a value
244    /// this build does not know, is `InvalidInput`.
245    Items {
246        library: LibraryId,
247        offset: u32,
248        limit: u32,
249        /// Optional for good: left out, the plain order.
250        #[serde(default, skip_serializing_if = "Option::is_none")]
251        sort: Option<spoolframe_types::ItemSort>,
252        /// Optional for good: left out, every item.
253        #[serde(default, skip_serializing_if = "Option::is_none")]
254        filter: Option<spoolframe_types::ItemFilter>,
255    },
256    /// What library `library`'s items can be sorted and filtered by:
257    /// `ItemFilterValues`, the genres, years, content ratings, resolutions
258    /// and ranges its items have, and the sort keys and filter parts it
259    /// applies.
260    ItemFilterValues {
261        library: LibraryId,
262    },
263    Item {
264        id: MediaId,
265    },
266    /// Scoped, grouped search. `Search`; for a client that names
267    /// the experimental `federation` feature, `SearchHits`: this
268    /// server's results and the paired servers' cache's, a title found on
269    /// several servers once.
270    Search(SearchRequest),
271    /// The items a person a search found is in, one page at a
272    /// time. `Items`.
273    PersonItems {
274        person: PersonId,
275        offset: u32,
276        limit: u32,
277    },
278    Tracks {
279        id: MediaId,
280    },
281    /// Who this request's session belongs to.
282    WhoAmI,
283    /// End this request's session (and only it). On a trusted device it
284    /// forgets the device for this user too: the next time is a
285    /// full sign-in.
286    Logout,
287    /// The session user's live sessions on every device.
288    ListSessions,
289    /// How the server would play `id` for this client with these tracks.
290    /// Without a selection the server chooses them from the user's
291    /// preferences and says which in the reply.
292    PlaybackPlan {
293        id: MediaId,
294        #[serde(deserialize_with = "spoolframe_types::required::option")]
295        selection: Option<Selection>,
296        /// How a picked bitmap subtitle is shown.
297        bitmap: BitmapSubtitles,
298        /// What the screen shows now (PGPU-06): its HDR formats and bit
299        /// depth, over Hello's, for this plan. `None` or left out, Hello's.
300        #[serde(default)]
301        display: Option<DisplayCapabilities>,
302    },
303    /// Plan `id` and, if it plays directly, open a playback session to
304    /// read it through. Without a selection, as for `PlaybackPlan`.
305    StartPlayback {
306        id: MediaId,
307        #[serde(deserialize_with = "spoolframe_types::required::option")]
308        selection: Option<Selection>,
309        /// Where to start, for a converted playback: the encode
310        /// begins there. Direct play reads from wherever the client likes.
311        #[serde(deserialize_with = "spoolframe_types::required::option")]
312        start_ms: Option<u64>,
313        /// How a picked bitmap subtitle is shown.
314        bitmap: BitmapSubtitles,
315        /// The quality the viewer chose for it: for the link, at
316        /// most a bitrate, or the original.
317        quality: Quality,
318        /// What the screen shows now (PGPU-06): its HDR formats and bit
319        /// depth, over Hello's, for this plan and the playback it starts;
320        /// a re-plan without one keeps it. `None` or left out, Hello's.
321        #[serde(default)]
322        display: Option<DisplayCapabilities>,
323        /// What the device that will show it plays, in place of
324        /// Hello's, for this playback and its re-plans: a server that plays
325        /// on to one of its own devices (a paired server's proxy) has the
326        /// plan made for that device over its one connection. `display`
327        /// applies over it. Left out, Hello's.
328        #[serde(default, skip_serializing_if = "Option::is_none")]
329        capabilities: Option<spoolframe_types::ClientCapabilities>,
330        /// The share of an uplink the playback goes on over, bits per
331        /// second: a server that plays it on to its own device
332        /// (a paired server's proxy) sends its own, at the start and at
333        /// each re-plan, and the plan keeps under it as under this
334        /// server's own share. Left out, this server's share alone.
335        #[serde(default, skip_serializing_if = "Option::is_none")]
336        onward_share: Option<u64>,
337    },
338    /// End a playback now, and any encode for it.
339    StopPlayback {
340        handle: PlaybackHandle,
341    },
342    /// Recover a handle's configuration revision after reconnecting or
343    /// reopening an SDK. This does not change the encoder's epoch.
344    PlaybackRevision {
345        handle: PlaybackHandle,
346    },
347    /// Restart a converted playback's encode at `position_ms`:
348    /// reads then name the new epoch and start at offset 0.
349    SeekPlayback {
350        handle: PlaybackHandle,
351        position_ms: u64,
352    },
353    /// Set or change the session user's PIN: 4 to 8 digits. `Done`.
354    ///
355    /// A user with no PIN sets their first with no `proof`, from a session
356    /// that signed in within the last 10 minutes; an older one gets
357    /// `RecentSignInRequired`. A user who has one changes it only with a
358    /// [`PinProof`]: the current PIN, or the account password when the PIN
359    /// is forgotten. Without one it is `InvalidInput`. A locked session
360    /// gets `ProfileLocked`.
361    SetPin {
362        pin: String,
363        proof: Option<PinProof>,
364    },
365    /// Remove the session user's PIN, and its requirement on every device,
366    /// with a [`PinProof`], checked as for `SetPin`. `Done`; also for a
367    /// user with no PIN (any PIN passes then).
368    ClearPin {
369        proof: PinProof,
370    },
371    /// Unlock this session on this connection with the user's PIN.
372    /// Wrong PINs are rate-limited; after 10 in a row the session on this
373    /// device is revoked (`Unauthenticated`): sign in with the password.
374    /// `Done`.
375    UnlockProfile {
376        pin: String,
377    },
378    /// The devices the session user has signed in from. `Devices`.
379    ListDevices,
380    /// Begin making an app passkey for the session user:
381    /// `PasskeyRegistrationBegun`, a nonce, as for `BeginPasskeySignIn`.
382    /// Needs a session signed in within the last 10
383    /// minutes, or `RecentSignInRequired`: confirm it is the user
384    /// (`ConfirmPassword`, `BeginConfirmPasskey`) first.
385    BeginPasskeyRegistration,
386    /// Keep the passkey made for it, in the session that began it: `Done`.
387    /// One that does not verify is `InvalidCredentials`; a name that is
388    /// not 1 to 64 characters `InvalidInput` (the challenge is not used
389    /// up then).
390    FinishPasskeyRegistration(FinishPasskeyRegistration),
391    /// The session user's passkeys, the web UI's and the apps', oldest
392    /// first: `Passkeys`.
393    ListPasskeys,
394    /// Rename one of them (`id` from `Passkeys`): `Done`. A name that is
395    /// not 1 to 64 characters (trimmed) is `InvalidInput`; an `id` that is
396    /// not one of the session user's passkeys `NotFound`.
397    RenamePasskey {
398        id: String,
399        name: String,
400    },
401    /// Remove one of them: `Done`. Needs a session signed in within the
402    /// last 10 minutes, or `RecentSignInRequired`; the user's last way to
403    /// sign in is `LastSignInMethod`; an `id` that is not one of their
404    /// passkeys `NotFound`.
405    RemovePasskey {
406        id: String,
407    },
408    /// Confirm it is the session user, with their account password, so
409    /// that a session signed in long ago may make a change that needs a
410    /// recent sign-in (`ApproveDeviceSignIn`, `BeginPasskeyRegistration`,
411    /// `RemovePasskey`, `SetPinRequired` with `required: false`):
412    /// `Confirmed`, and this session counts as signed in now, for 10
413    /// minutes. Only this session; the user's others are as they were.
414    ///
415    /// Checked as `LoginPassword` checks it: a wrong one is a failed
416    /// sign-in for the user's username from this device
417    /// (`InvalidCredentials`, then `RateLimited`, one limit with
418    /// `LoginPassword` and the web UI's confirmation). A user with no
419    /// password gets `NoPassword`, with nothing counted: confirm with an
420    /// app passkey. A locked session gets `ProfileLocked`. The PIN is
421    /// never a confirmation: it guards switching profiles on a shared
422    /// device, and is weaker than a sign-in.
423    ConfirmPassword(ConfirmPassword),
424    /// Change the session user's password: `Done`. `current_password` is
425    /// checked as `LoginPassword` checks it (a wrong one is
426    /// `InvalidCredentials`, counted towards the same limit). A
427    /// `new_password` the server does not take, or the same as the current
428    /// one, is `InvalidInput`. Every other session of the user's ends, on
429    /// the web and on devices. The way out of a session a one-time
430    /// password opened (`PasswordChangeRequired`): this session may then
431    /// do anything again. A user with no password gets `NoPassword`: set
432    /// one in the web UI. Not for a portable user (`NotForPortableUsers`).
433    ChangePassword(ChangePassword),
434    /// Begin confirming it is the session user with one of their app
435    /// passkeys: `PasskeySignInBegun`, a nonce as for
436    /// `BeginPasskeySignIn`, listing their app passkeys only. The nonce is
437    /// this session's on this device, for 5
438    /// minutes; beginning again replaces it. A user with no app passkey
439    /// gets `NotFound`; one whose passkey sign-ins are limited
440    /// `RateLimited`. A locked session gets `ProfileLocked`.
441    BeginConfirmPasskey,
442    /// Finish it with what the passkey signed: `Confirmed`, as for
443    /// `ConfirmPassword`. A passkey that is not the session user's, a
444    /// challenge that is not this session's, or anything else that does
445    /// not verify is `InvalidCredentials`, counted as a failed passkey
446    /// sign-in (then `RateLimited`).
447    FinishConfirmPasskey(FinishPasskeySignIn),
448    /// The session user's Plex account link: `PlexLink`. Read
449    /// only; a client links or unlinks by opening `<web_url>/profile`.
450    GetPlexLink,
451    /// Ask for the session user's PIN on `device` (an endpoint id from
452    /// `Devices`; this device if left out), or stop asking. A locked
453    /// session cannot ask this (nor anything but `WhoAmI` and
454    /// `UnlockProfile`). Stopping the requirement needs recent authentication.
455    /// `Done`.
456    SetPinRequired {
457        #[serde(deserialize_with = "spoolframe_types::required::option")]
458        device: Option<String>,
459        required: bool,
460    },
461    /// Which device shows sign-in code `code`, to ask the user
462    /// before approving it. `DeviceSignInRequest`; `NotFound` for a code
463    /// that is not pending (guesses are rate-limited).
464    LookupDeviceSignIn {
465        code: String,
466    },
467    /// Sign the device showing `code` in as the session user. `Done`.
468    /// Requires recent authentication; an old session cannot mint a fresh one.
469    ///
470    /// `remember`: the approver's answer to the device's request to be
471    /// trusted (`DeviceSignInRequest::remember`). The device is
472    /// trusted only if it asked and this is true; this cannot trust a
473    /// device that did not ask.
474    ApproveDeviceSignIn {
475        code: String,
476        remember: bool,
477    },
478    /// Trust `device` (an endpoint id from `Devices`; this device if left
479    /// out) for the session user, or stop. `Done`.
480    ///
481    /// - Turning trust on, or auto-login on, works for this device only
482    ///   (`InvalidInput` for another: trust another device from the web
483    ///   UI), and needs a recent sign-in (`RecentSignInRequired`).
484    /// - Auto-login needs trust (`InvalidInput` without). It turns
485    ///   auto-login off for the device's other users, and the PIN
486    ///   requirement off for this user there.
487    /// - Turning trust off works for any of the user's devices, and ends
488    ///   the user's sessions there, this one too if it is this device.
489    ///   For another device it needs a recent sign-in; for this one it
490    ///   needs only the session.
491    /// - A device that is not the user's is `NotFound`.
492    SetDeviceTrust {
493        device: Option<String>,
494        trusted: bool,
495        auto_login: bool,
496    },
497    /// Delete one of the session user's other devices: `device`
498    /// is an endpoint id from `Devices`. `Done`. The user's sessions
499    /// there are deleted, and with them its trust and PIN requirement; it
500    /// leaves `Devices`, and if it signs in again it is listed as new.
501    /// Other users' sessions on that device are kept.
502    ///
503    /// - Always needs a recent sign-in (`RecentSignInRequired`).
504    /// - This device is `InvalidInput`: sign out with `Logout`.
505    /// - A device that is not the user's is `NotFound`.
506    ForgetDevice {
507        device: String,
508    },
509    /// Refuse it: the device stops waiting. `Done`.
510    DenyDeviceSignIn {
511        code: String,
512    },
513    /// Pick another subtitle (or none) for a playing playback: it
514    /// is planned again with the same audio. A plan that plays directly
515    /// only changes what `ReadSubtitle` gives; a converted one restarts its
516    /// encode at `position_ms` as a new epoch, from offset 0 (a burned-in
517    /// subtitle is in the picture). `PlaybackChanged`; `CannotPlay` leaves
518    /// the playback as it was.
519    ChangeSubtitle {
520        handle: PlaybackHandle,
521        subtitle: Option<u32>,
522        bitmap: BitmapSubtitles,
523        position_ms: u64,
524        /// What the screen shows now (PGPU-06), over Hello's, for this
525        /// plan and the playback from then on. `None` or left out, what the
526        /// playback started with.
527        #[serde(default)]
528        display: Option<DisplayCapabilities>,
529        /// The share of an uplink the playback goes on over, bits per
530        /// second: a server that plays it on to its own device
531        /// (a paired server's proxy) sends its own, at the start and at
532        /// each re-plan, and the plan keeps under it as under this
533        /// server's own share. Left out, this server's share alone.
534        #[serde(default, skip_serializing_if = "Option::is_none")]
535        onward_share: Option<u64>,
536    },
537    /// Plan a playing playback again for `quality`: the viewer
538    /// chose another, or, with `Auto`, the device found its link too slow
539    /// for a direct play that stalls. The same tracks, and `bitmap` as
540    /// `ChangeSubtitle` takes it. A plan that changes restarts at
541    /// `position_ms` as a new epoch, from offset 0, as `ChangeSubtitle`
542    /// does; one that does not is answered as it is, nothing restarted.
543    /// `PlaybackChanged`.
544    ChangeQuality {
545        handle: PlaybackHandle,
546        quality: Quality,
547        bitmap: BitmapSubtitles,
548        position_ms: u64,
549        /// What the screen shows now (PGPU-06), over Hello's, for this
550        /// plan and the playback from then on. `None` or left out, what the
551        /// playback started with.
552        #[serde(default)]
553        display: Option<DisplayCapabilities>,
554        /// The share of an uplink the playback goes on over, bits per
555        /// second: a server that plays it on to its own device
556        /// (a paired server's proxy) sends its own, at the start and at
557        /// each re-plan, and the plan keeps under it as under this
558        /// server's own share. Left out, this server's share alone.
559        #[serde(default, skip_serializing_if = "Option::is_none")]
560        onward_share: Option<u64>,
561    },
562    /// A converted playback's HLS playlist.
563    GetManifest {
564        handle: PlaybackHandle,
565        kind: ManifestKind,
566        /// For a media playlist, the variant's: a ladder's rung,
567        /// as `v{n}/media.m3u8` in the multivariant playlist. 0 for one
568        /// encode, and for the other kinds.
569        variant: u32,
570    },
571    /// The selected external subtitle of a playback, one chunk of it.
572    /// One the server reads as text answers
573    /// `SubtitleNotReady` until it is done: ask again.
574    ///
575    /// The reply is `SubtitleChunk`: at most [`SUBTITLE_CHUNK`] bytes of
576    /// the file from `offset`, `total`, the file's length, and `version`,
577    /// which names the file as it was when the chunk was read. Ask from
578    /// the end of each chunk, with the first chunk's `version`, until
579    /// `total` bytes are read; an `offset` at or past the end answers no
580    /// bytes. When the file is no longer the one `version` names, the
581    /// answer is `SubtitleChanged`: the chunks read so far are of a file
582    /// that is gone, so start again from 0. The first read has no file
583    /// to hold the server to, and sends no `version`.
584    ReadSubtitle {
585        handle: PlaybackHandle,
586        offset: u64,
587        version: Option<u64>,
588    },
589    /// Segment `n` (from 1) of an HLS playback's subtitle rendition:
590    /// `Subtitle { format: WebVtt, .. }`, the cues over that segment's time,
591    /// timed with `X-TIMESTAMP-MAP` to the video. `SubtitleNotReady` while
592    /// the subtitle is made.
593    ReadSubtitleSegment {
594        handle: PlaybackHandle,
595        n: u32,
596    },
597    /// The frame previews of a movie or episode, for scrubbing:
598    /// `Previews`, `PreviewsNotReady` while the server makes them (asking
599    /// puts the item first in line; ask again in a few seconds, and show
600    /// the time alone meanwhile), or `NoPreviews`.
601    GetPreviews {
602        id: MediaId,
603    },
604    /// Where playback of a movie or episode has got to. Send it now and
605    /// then while playing and on pause or stop; the server decides what is
606    /// written, and when.
607    UpdatePlaybackProgress {
608        handle: PlaybackHandle,
609        sequence: u64,
610        position_ms: u64,
611    },
612    /// Experimental (`federation`): where the user got to in `id`,
613    /// a paired server's (`fed:`) movie or episode, which plays from that
614    /// server rather than from a playback of this one's: `Done`. Sent to
615    /// the user's own server, as `UpdatePlaybackProgress` would be, now and
616    /// then while playing and on pause or stop; the server decides what is
617    /// written, and when. The paired server keeps nothing of it. An id
618    /// that is not a paired server's is `InvalidInput`; one no longer
619    /// available is `NotFound`. Unsupported unless this connection's
620    /// `Hello` named the feature.
621    UpdateWatchProgress {
622        id: MediaId,
623        position_ms: u64,
624    },
625    MarkWatched {
626        id: MediaId,
627    },
628    MarkUnwatched {
629        id: MediaId,
630    },
631    /// Remove the card `id`, a movie or an episode, from the session
632    /// user's Continue watching or Next up, leaving its progress
633    /// and watched state. Only that card: never the episode's whole show.
634    /// `id` is the card's own, not its show's. Playing or marking it again
635    /// brings it back. `Done`.
636    HideFromContinueWatching {
637        id: MediaId,
638    },
639    /// Undo a hide (an "Undo" toast). `Done`.
640    UnhideFromContinueWatching {
641        id: MediaId,
642    },
643    /// The session user's home screen.
644    Home,
645    /// How the session user wants tracks chosen.
646    GetTrackPreferences,
647    /// Replace them, for every device of the user.
648    SetTrackPreferences {
649        preferences: TrackPreferences,
650    },
651    /// Use the tracks of `selection` in `id` for the rest of its series
652    /// (an episode) or for it (anything else), by language and role. No
653    /// subtitle in `selection` means subtitles off.
654    SetTrackOverride {
655        id: MediaId,
656        selection: Selection,
657    },
658    /// Back to the preferences for `id`'s series or for it.
659    ClearTrackOverride {
660        id: MediaId,
661    },
662    /// Begin tying the session user's account to a portable identity:
663    /// `TieChallenge`, a nonce for the identity to sign over
664    /// ([`crate::portable::tie_message`]). The nonce is this session's,
665    /// for its user, for `expires_in_secs` (5 minutes), and is used once,
666    /// whatever `TieFinish` makes of it. Needs a session signed in within
667    /// the last 10 minutes, or `RecentSignInRequired`. An account may be
668    /// tied already: it ties any number of identities.
669    TieBegin,
670    /// Tie the session user's account to `user`, with `proof` that `user`
671    /// signed the tie message over the nonce `TieBegin` gave: by the root,
672    /// or by a device key with a credential for `user` that holds and is
673    /// not revoked by any identity state this server has seen. `Done`.
674    ///
675    /// Needs a recent sign-in, as `TieBegin`. A nonce that is not this
676    /// session's, is used or is over is `TieChallengeExpired`: begin
677    /// again. A proof that does not hold is `InvalidCredentials`. An
678    /// identity tied to another account here is `PortableIdTaken`; one
679    /// tied to this account already is `Done`, changing nothing (its
680    /// first tie date stands). The account's other ties stay.
681    /// Nothing about the account moves: the tie is a link beside it.
682    TieFinish {
683        user: PortableUserId,
684        proof: TieProof,
685    },
686    /// Sever the session user's tie to `user`: `Done`.
687    /// Only that link goes; the account's other ties, its sessions (those
688    /// opened with `user`'s credential too), passkeys and watch state stay
689    /// as they are. Needs a recent sign-in. No tie to `user` on this
690    /// account is `NotFound`.
691    Untie {
692        user: PortableUserId,
693    },
694
695    /// Make an invite ([`crate::invite_admin`]), as the web UI's
696    /// `inviteCreate` does, with its limits: `InviteCreated`, the code
697    /// shown this once. An admin's only (`AdminRequired`), and only after
698    /// they confirmed it is them recently (`RecentSignInRequired`: confirm
699    /// with `ConfirmPassword` or a passkey, then ask again). A
700    /// `federation` invite is `InvalidInput` unless this connection's
701    /// `Hello` named the experimental `federation` feature and the server
702    /// has it on, as are fields out of their limits.
703    CreateInvite(CreateInvite),
704    /// The invites that can still be redeemed, newest first, made here or
705    /// in the web UI: `Invites`. An admin's only; no confirmation needed.
706    ListInvites,
707    /// Revoke invite `id`: its code stops working, and what it made stays.
708    /// `Done`. An admin's only, after a recent confirmation, as
709    /// `CreateInvite`. One that is not live (revoked, expired, used up, or
710    /// none) is `NotFound`.
711    RevokeInvite {
712        id: String,
713    },
714
715    /// Experimental (`http-playback`; see [`crate::experimental`]):
716    /// an HTTP URL for one of this session's playbacks, for a player with
717    /// no Iroh (AirPlay first): `HttpPlaybackUrl`, or
718    /// `HttpPlaybackRefused` with why not. Refused as `Off` unless this
719    /// connection's `Hello` named the feature and the server's answer
720    /// named it back. The URL is
721    /// `http://<address>:<port>/<token>/master.m3u8` for HLS, `.../file`
722    /// for direct play, its token unguessable and bound to this playback:
723    /// it works until the playback ends or is stopped, or nothing asks for
724    /// it for a while. Asked again, it may be the same URL. A newer
725    /// server may change or drop this.
726    HttpPlaybackUrl {
727        handle: PlaybackHandle,
728    },
729
730    /// Experimental (`federation`; see [`crate::federation`]): pair
731    /// this server with the one whose `federation` invite `link` is, as an
732    /// admin pasting it in the web UI would: `ServerPaired`. Unsupported
733    /// unless this connection's `Hello` named the feature and the
734    /// server's answer named it back. An admin's only (`AdminRequired`),
735    /// after a recent confirmation (`RecentSignInRequired`), as
736    /// `CreateInvite`. A link that is not one, has no code, or is this
737    /// server's own is `InvalidInput`; the other server's refusal of the
738    /// code is the invite's own error (`InviteInvalid`, `InviteExpired`,
739    /// `InviteExhausted`, `WrongInviteKind`, `RateLimited`), any other is
740    /// `PairingRefused`; the other server unreachable is `Unavailable`.
741    /// Look the code up on the other server first (`LookupInvite`): it
742    /// tells the kind, the inviter and the key's fingerprint.
743    PairServer(crate::federation::PairServer),
744
745    /// Experimental (`federation`; see [`crate::federation`]):
746    /// share libraries of this server with a paired one, as the app offers
747    /// once `PairServer` paired them: `LibrariesShared`. Every user of the
748    /// paired server may browse and watch them; a library shared already
749    /// stays shared. Unsupported unless this connection's `Hello` named the
750    /// feature and the server's answer named it back. An admin's only
751    /// (`AdminRequired`), after a recent confirmation
752    /// (`RecentSignInRequired`), as `PairServer`. A server not paired is
753    /// `NotFound`; a library this server does not serve is `InvalidInput`,
754    /// and then none is shared.
755    ShareLibraries(crate::federation::ShareLibraries),
756
757    /// Experimental (`federation`): show or hide paired server
758    /// `server_id`'s own row on the user's Home (`HomeScreen::servers`):
759    /// `Done`. Kept per user and server; a server's items stay in Continue
760    /// watching either way. Unsupported unless this connection's `Hello`
761    /// named the feature.
762    SetServerRow {
763        server_id: String,
764        shown: bool,
765    },
766
767    /// Experimental (`federation`; see [`crate::federation`]):
768    /// redeem a play token a paired server got from this one for one of
769    /// its users: `PlayTokenRedeemed`, a session for that one item's
770    /// playback. Pre-auth, on the strangers' budget as a sign-in is. The
771    /// token works once, from the endpoint it was minted for, while its
772    /// pair and the library's share are live; every failure is
773    /// `Unauthenticated`, and the device asks its home server for a new
774    /// token. The session reaches `StartPlayback` of that item and its own
775    /// playback's controls and reads; anything else is `Unauthenticated`.
776    /// A download token is redeemed the same way: its session
777    /// reaches that item's download alone (`DownloadOptions`,
778    /// `PrepareDownload`, `DownloadStatus`, `CancelDownload`, the
779    /// `Download` read and `DownloadChanged`), or, for a device's token,
780    /// its one download's read and status. It lives while the download is
781    /// made and read, and ends at its `CancelDownload`.
782    /// Unsupported unless this connection's `Hello` named the feature.
783    RedeemPlayToken(crate::federation::RedeemPlayToken),
784
785    /// Experimental (`federation`): where the paired server that
786    /// `id`, a `fed:` item, is from may be dialled (`RemoteHints`), and
787    /// whether this server holds a connection to it now. The device dials
788    /// it with a short budget and asks `RemoteGrant` once it reached it; it
789    /// plays `id` from this server otherwise. An id that is not a paired
790    /// server's is `InvalidInput`; one not available here is `NotFound`.
791    /// Unsupported unless this connection's `Hello` named the feature.
792    RemoteHints {
793        id: MediaId,
794    },
795
796    /// Experimental (`federation`): vouch for the session's user to
797    /// the paired server `id` is from, for a play token bound to this
798    /// device (`RemoteGranted`), which it redeems there
799    /// (`RedeemPlayToken`). Each play asks its own. With that server
800    /// offline, `OriginOffline` at once: play `id` from this server. A
801    /// portable guest is `NotForPortableUsers`; an item not shared, or not
802    /// a paired server's, `NotFound`; that server unable to answer now,
803    /// `Unavailable`. A proxied play asks for no grant: it is a
804    /// `StartPlayback` of `id` here. Unsupported unless this connection's
805    /// `Hello` named the feature.
806    ///
807    /// With `download`, the id of a download of `id` this server keeps:
808    /// a download token instead, bound to this device and to that
809    /// one download, which reads it on the paired server
810    /// (`RemoteGranted::download` names it there). A download that is not
811    /// the user's, or not of `id`, is `NotFound`.
812    RemoteGrant {
813        id: MediaId,
814        #[serde(default, skip_serializing_if = "Option::is_none")]
815        download: Option<String>,
816    },
817
818    /// Experimental (`federation`): play the title `title` (any
819    /// copy's id) from paired server `from`, or from this server with
820    /// `None`: `Done`. Remembered for the user by the title's external
821    /// ids, so every copy of it, here or on a paired server, plays from
822    /// there (`SearchHit::play_from`, `Copies::play_from`) while that
823    /// server has one. A title with no external ids has one copy:
824    /// `InvalidInput`. A server not paired, or an item not found, is
825    /// `NotFound`. Unsupported unless this connection's `Hello` named the
826    /// feature.
827    SetPlayFrom {
828        title: MediaId,
829        #[serde(default)]
830        from: Option<String>,
831    },
832
833    /// Leave this server: `Done`, and every session of the user
834    /// here is ended, this one too. Needs a recent sign-in
835    /// (`RecentSignInRequired`): a local user confirms with
836    /// `ConfirmPassword` or a passkey; a portable user signs in
837    /// with its credential again, which opens a new session that counts as
838    /// recent. What leaving does depends on who:
839    ///
840    /// - A portable user's grant is taken away, and its data here (watch
841    ///   state, hidden rows, track preferences) is deleted. Coming back
842    ///   takes a new invite.
843    /// - A local account is set aside, not deleted: disabled and marked
844    ///   as left, its sessions ended and its devices no longer trusted;
845    ///   its data stays, and an admin can restore it.
846    ///
847    /// The last enabled admin (or the last with a password) cannot leave:
848    /// `LastAdmin`. Nothing was changed then.
849    LeaveServer,
850
851    /// Playlists (feature `spoolframe:playlists`): every playlist
852    /// the session user sees, theirs, shared with them and server-wide,
853    /// each with whether it is pinned and where; and the notes of pinned
854    /// ones that left their Pinned. `Playlists`.
855    ListPlaylists,
856    /// One playlist and a page of its entries, from `offset`, at most
857    /// `limit` (200): `Playlist`. Items the user may not see are neither
858    /// listed nor counted; an item whose file cannot be read now is
859    /// listed as unavailable. One they do not see is `NotFound`.
860    GetPlaylist {
861        id: String,
862        offset: u32,
863        limit: u32,
864    },
865    /// Make a playlist the session user owns: `PlaylistInfo`. A name is 1
866    /// to 100 characters; `kinds` ticks at least one. `ServerWide` is an
867    /// admin's only (`AdminRequired`); a share naming someone who is not a
868    /// user here is `InvalidInput`.
869    CreatePlaylist {
870        name: String,
871        kinds: Kinds,
872        visibility: Visibility,
873    },
874    /// Rename a playlist, widen its kinds (never narrow them:
875    /// `InvalidInput`), or change who sees it: `PlaylistInfo`. `None`
876    /// leaves each as it is. Its owner's, or any admin's for a
877    /// server-wide one; anyone else who sees it gets `PlaylistReadOnly`.
878    /// Whoever no longer sees it is sent `PlaylistGone`, and loses its pin
879    /// with a note.
880    UpdatePlaylist {
881        id: String,
882        #[serde(deserialize_with = "spoolframe_types::required::option")]
883        name: Option<String>,
884        #[serde(deserialize_with = "spoolframe_types::required::option")]
885        kinds: Option<Kinds>,
886        #[serde(deserialize_with = "spoolframe_types::required::option")]
887        visibility: Option<Visibility>,
888    },
889    /// Change a playlist's entries, as seen at `revision`: `PlaylistEdited`
890    /// with its new revision. 1 to 100 edits, applied in order, all or
891    /// none. Made on an older revision, the edits are redone on the newer
892    /// one unless one removes or moves an entry changed since:
893    /// `PlaylistConflict` ("Someone changed this playlist; reload"). An
894    /// item of a kind the playlist does not take is `KindNotAllowed`. A
895    /// read-only share gets `PlaylistReadOnly`.
896    EditPlaylist {
897        id: String,
898        revision: u64,
899        edits: Vec<PlaylistEdit>,
900    },
901    /// Delete a playlist: `Done`. Its owner's, or any admin's for a
902    /// server-wide one. Whoever had it pinned gets a note.
903    DeletePlaylist {
904        id: String,
905    },
906    /// Pin a playlist the session user sees to their Pinned at `position`
907    /// (0 first; past the end, last), or move it there: `Done`. Every
908    /// device of theirs is sent `PinsChanged`.
909    PinPlaylist {
910        id: String,
911        position: u32,
912    },
913    /// Take a playlist out of their Pinned: `Done`, also when it was not
914    /// there.
915    UnpinPlaylist {
916        id: String,
917    },
918    /// Start or go on playing a playlist: `PlaylistItem`, the entry to
919    /// play, or `PlaylistFinished` when nothing is left to play. With
920    /// `from`, that entry (or the next playable one after it); without,
921    /// the user's place: the entry they were in, if they had not finished
922    /// it, else the one after it; with no place, the top. The settings are
923    /// kept for the user and playlist, for `NextInPlaylist` and the next
924    /// time. Unavailable entries, and with `skip_watched` watched ones,
925    /// are passed. The client plays the item itself (`StartPlayback`),
926    /// skipping its credits, and records progress as any playback does.
927    PlayPlaylist {
928        id: String,
929        #[serde(deserialize_with = "spoolframe_types::required::option")]
930        from: Option<crate::playlists::EntryId>,
931        shuffle: bool,
932        repeat: crate::playlists::Repeat,
933        skip_watched: bool,
934    },
935    /// What plays after entry `after` ended or was skipped:
936    /// `PlaylistItem`, or `PlaylistFinished` at the end with repeat off,
937    /// which clears the place so the next `PlayPlaylist` starts at the
938    /// top. The server keeps the place.
939    NextInPlaylist {
940        id: String,
941        after: crate::playlists::EntryId,
942    },
943    /// What plays next, without playing it (`spoolframe:playlist-upcoming`):
944    /// `PlaylistUpcoming`, at most `limit` (100) entries after the session
945    /// user's place, each the one `NextInPlaylist` would give after the
946    /// one before. The round's order while shuffling, else the playlist's;
947    /// from the start again with repeat all; with repeat one, the place's
948    /// entry alone. With no place, from the top. Unavailable entries, and
949    /// with `skip_watched` watched ones, are passed. Whoever sees the
950    /// playlist. Only from a client that listed the feature; from any
951    /// other, `Unsupported`.
952    UpcomingInPlaylist {
953        id: String,
954        limit: u32,
955    },
956    /// Keep how the session user plays a playlist, playing nothing
957    /// (`spoolframe:playlist-upcoming`): `Done`. The place and the shuffled
958    /// round stay. Shuffle turned on shuffles anew, from the place, so the
959    /// whole playlist is ahead; turned off, the playlist's order, from the
960    /// place. Whoever sees the playlist. Only from a client that listed
961    /// the feature; from any other, `Unsupported`.
962    SetPlaylistSettings {
963        id: String,
964        shuffle: bool,
965        repeat: crate::playlists::Repeat,
966        skip_watched: bool,
967    },
968    /// Import the session user's Plex playlists, once: each video
969    /// or music playlist of their linked Plex account, on every Plex
970    /// server here, becomes a personal playlist of theirs, its items
971    /// mapped to this server's: `PlexImport`, what was made and what did
972    /// not map. Nothing is synced afterwards. With `dry_run`, nothing is
973    /// made. Without a linked Plex account, `NotFound`; a portable user
974    /// has none (`NotForPortableUsers`). Imported twice, made twice.
975    ImportPlexPlaylists {
976        dry_run: bool,
977    },
978    /// Forget the notes `ListPlaylists` gave: a client showed them.
979    /// `Done`. Notes are per user, not per device.
980    DismissPinNotes,
981    /// Like tracks or albums: their tracks go to the top of the
982    /// session user's Liked, in the order given, an album's in disc and
983    /// track order; a track liked already stays where it is. An album
984    /// likes the tracks it has now: one added to it later is not liked.
985    /// `PlaylistInfo`, Liked as it is now. 1 to 100 items; anything but
986    /// a track or an album is `KindNotAllowed`, an item not here
987    /// `NotFound`. Liked again, nothing changes. Only from a client that
988    /// listed `spoolframe:liked`; from any other, `Unsupported`.
989    Like {
990        items: Vec<MediaId>,
991    },
992    /// Take tracks, or every track of albums, out of the session user's
993    /// Liked: `PlaylistInfo`, Liked as it is now. As `Like`
994    /// takes them; one not liked is no change.
995    Unlike {
996        items: Vec<MediaId>,
997    },
998    /// Whom playlist `id` can be shared with: `ShareCandidates`, a page
999    /// from `offset`, at most `limit` (200), by display name. Every
1000    /// enabled account here and every portable user granted access, but
1001    /// the session user; with a `query`, only those whose display name or
1002    /// username holds it, in any case (empty: everyone). Only whoever
1003    /// manages the playlist asks: anyone else who sees it gets
1004    /// `PlaylistReadOnly`, one who does not `NotFound`. Only from a client
1005    /// that listed `spoolframe:playlist-sharing`; from any other,
1006    /// `Unsupported`.
1007    ListShareCandidates {
1008        id: String,
1009        query: String,
1010        offset: u32,
1011        limit: u32,
1012    },
1013    /// What the session user played lately: `Items`, each item
1014    /// once, by its latest counted play, newest first; a page from
1015    /// `offset`, at most `limit` (500), and how many in all. `kinds` keeps
1016    /// films, episodes or tracks only; `None`, every kind. An item gone
1017    /// from the library is left out of the page. Each item's
1018    /// `PlaybackState` has its `play_count` and `last_played_at`. Only
1019    /// from a client that listed `spoolframe:play-history`; from any
1020    /// other, `Unsupported`.
1021    RecentlyPlayed {
1022        kinds: Option<crate::playlists::Kinds>,
1023        offset: u32,
1024        limit: u32,
1025    },
1026    /// Take away a playlist's uploaded cover: `PlaylistInfo`, its
1027    /// `artwork` the mosaic again. Whoever may edit its entries may, as
1028    /// they may upload one (`SetPlaylistArt`, a resource request); anyone
1029    /// else who sees it, and anyone at all for Liked and All, gets
1030    /// `NotAllowed`. One without a cover is no change. Only from a client
1031    /// that listed `spoolframe:playlist-art`; from any other,
1032    /// `Unsupported`.
1033    RemovePlaylistArt {
1034        id: String,
1035    },
1036    /// Sync item `id`'s subtitle `track` (its place in `Tracks`'
1037    /// `subtitles`) to the file, in the background: an external
1038    /// text subtitle (SRT, WebVTT, ASS) only. `SubtitleTiming`, its state
1039    /// `Syncing` (a track already syncing is left to it); the outcome comes
1040    /// as `SubtitleTimingChanged`, or in `Tracks` asked again. The track
1041    /// is served as it was until the sync is done, then synced; a sync
1042    /// that scores too low is not used (`Uncertain`). Anyone who can play
1043    /// the item may. Another track is `InvalidInput`, a track the item
1044    /// does not have `NotFound`. Only from a client that listed
1045    /// `spoolframe:subtitle-sync`; from any other, `Unsupported`.
1046    SyncSubtitle {
1047        id: MediaId,
1048        track: u32,
1049    },
1050    /// Serve item `id`'s subtitle `track` with its original timing again,
1051    /// for everyone: the sync is set aside, the offset kept.
1052    /// `SubtitleTiming`. As `SyncSubtitle` for who may and which tracks.
1053    UseOriginalSubtitleTiming {
1054        id: MediaId,
1055        track: u32,
1056    },
1057    /// Move item `id`'s subtitle `track` by `offset_ms` (positive: later)
1058    /// on top of its timing, for everyone; 0 resets it. At most
1059    /// ten minutes either way (`InvalidInput`). The track records who set
1060    /// it and when. `SubtitleTiming`. As `SyncSubtitle` for who may and
1061    /// which tracks.
1062    SetSubtitleOffset {
1063        id: MediaId,
1064        track: u32,
1065        offset_ms: i64,
1066    },
1067    /// Search the subtitle sites the admin turned on (OpenSubtitles,
1068    /// SubDL, or both) for item `id`'s subtitles in `language` (an ISO
1069    /// 639-1 code such as `en`, or `pt-BR`), or, with none, in the
1070    /// languages the server offers first. Both sites are asked at
1071    /// once and their results are one list, `SubtitleResults`, best
1072    /// first: those found by the file's hash (made for this release), then
1073    /// the rest by rating and downloads, machine-translated and AI-made
1074    /// after people's, ones removed before as bad last; its `sources` say
1075    /// how each site's part went. Kept a day per site, item and language.
1076    /// Anyone who can play the item may. `NoSubtitleSource` when the
1077    /// server has none set up. When every site failed, the first one's
1078    /// error: `Unavailable` when it cannot be reached, `RateLimited` when
1079    /// it asks to wait, `QuotaExhausted` when it is out. Only from a client
1080    /// that listed `spoolframe:subtitle-search`; from any other,
1081    /// `Unsupported`.
1082    SearchSubtitles {
1083        id: MediaId,
1084        #[serde(default, skip_serializing_if = "Option::is_none")]
1085        language: Option<String>,
1086    },
1087    /// Download result `result` (`SubtitleResult::id`) of a search for
1088    /// item `id`, from the site that found it: the
1089    /// item gains an external subtitle track for everyone, usable at once
1090    /// (`SubtitleDownloaded`). One not found by the file's hash is synced
1091    /// in the background (`spoolframe:subtitle-sync`). The same result
1092    /// downloaded again gives the same track, at no cost. `NotFound` for a
1093    /// `result` no search of the item listed lately (search again);
1094    /// `NotAllowed` for a user the admin took downloads from;
1095    /// `QuotaExhausted` when the server's account or the user's own daily
1096    /// limit is used up; `InvalidInput` for a file that is not a subtitle
1097    /// the server reads. Otherwise as `SearchSubtitles`.
1098    DownloadSubtitle {
1099        id: MediaId,
1100        result: String,
1101    },
1102    /// Remove item `id`'s downloaded subtitle `download`
1103    /// (`SubtitleDownload::id`), for everyone: its files go, and
1104    /// the result is listed last in the item's searches, marked rejected.
1105    /// The one who downloaded it, or an admin, may: `NotAllowed` for
1106    /// anyone else. `Done`; a download already removed is `Done` too.
1107    RemoveSubtitleDownload {
1108        id: MediaId,
1109        download: String,
1110    },
1111
1112    /// What the device may download of film or episode `id`
1113    /// (`spoolframe:downloads`): `DownloadOptions`, its tracks, the choice
1114    /// to show first, the profiles, what original quality would be, and
1115    /// the subtitles a download would leave out. Anyone who can play the
1116    /// item may ask. Only from an iPhone, iPad, Mac or Linux client
1117    /// (`Hello.platform`); from any other, and from a client that did not
1118    /// list the feature, `Unsupported`. With `spoolframe:music-downloads`
1119    /// too, `id` may be a track: its one audio track, no
1120    /// profiles, and what `original` would be.
1121    ///
1122    /// `device` is read only from a paired server playing its user's part
1123    /// (a download token's session): the device the download is
1124    /// for, in place of the connection's `Hello`.
1125    DownloadOptions {
1126        id: MediaId,
1127        #[serde(default, skip_serializing_if = "Option::is_none")]
1128        device: Option<crate::downloads::DownloadDevice>,
1129    },
1130    /// Prepare a download of film or episode `id` from `source` with
1131    /// `tracks`: `Download`, its id and state. The same user's
1132    /// same request is the same id, ready at once when its file is; one
1133    /// that failed is tried again. The file is made in the background;
1134    /// `DownloadChanged` tells its state as it moves. A track the item
1135    /// does not have, or a source or choice this build does not know, is
1136    /// `InvalidInput`; a profile not there `NotFound`. As
1137    /// `DownloadOptions` for who may and from where. A track (with
1138    /// `spoolframe:music-downloads`) takes `original` or `aac256`, and
1139    /// `tracks` is not read; a film or an episode is refused `aac256`.
1140    /// `device` as for `DownloadOptions`.
1141    PrepareDownload {
1142        id: MediaId,
1143        source: crate::downloads::DownloadSource,
1144        tracks: crate::downloads::DownloadTracks,
1145        #[serde(default, skip_serializing_if = "Option::is_none")]
1146        device: Option<crate::downloads::DownloadDevice>,
1147    },
1148    /// The session user's downloads `ids`: `Downloads`, those
1149    /// they have in order, and in `gone` each id they have not (never
1150    /// theirs, cancelled, or no longer kept), so one such id never fails
1151    /// the rest; at most [`crate::downloads::MAX_ASKED`] ids.
1152    DownloadStatus {
1153        ids: Vec<String>,
1154    },
1155    /// Cancel download `id`, as the device also does once it has
1156    /// the file whole and its SHA-256 checked: `Done`. Its file goes once
1157    /// no download names it and no one reads it; one being made stops. An
1158    /// id that is not the session user's, or was cancelled, is `NotFound`.
1159    CancelDownload {
1160        id: String,
1161    },
1162    /// Where the device got to in films and episodes while it had no
1163    /// server (`spoolframe:downloads`): `OfflineWatchSynced`, an
1164    /// outcome per entry, in order. `device_now` is the device's clock
1165    /// now, in Unix seconds: each entry's `at` is moved by the difference
1166    /// to the server's clock, and kept no later than now. An entry is
1167    /// written only when it is newer than what the server has (newest
1168    /// wins, whichever device it came from); watched is judged by the
1169    /// server's rules from the position and the item's credits, or taken
1170    /// from `watched: true`. At most [`crate::downloads::MAX_ASKED`]
1171    /// entries; one with neither a position nor `watched` is
1172    /// `InvalidInput`. As `DownloadOptions` for from where.
1173    SyncOfflineWatch {
1174        device_now: i64,
1175        entries: Vec<crate::downloads::OfflineWatch>,
1176    },
1177    /// What the music downloads a device follows hold now
1178    /// (`spoolframe:music-downloads` with `spoolframe:downloads`):
1179    /// `MusicDownloadChanges`, one change per artist, per playlist, then
1180    /// Liked, in that order, and a cursor to ask with next time. With
1181    /// `since`, the cursor of the last answer, each thing that holds the
1182    /// same tracks is `unchanged`; else, and with no cursor, its tracks
1183    /// now, in full, for the device to compare with what it keeps. A
1184    /// cursor this server cannot read is no cursor. Asked each time the
1185    /// device reaches the server. At most
1186    /// [`crate::downloads::MAX_FOLLOWED`] artists and playlists together;
1187    /// an id that is not an artist, or All, is `InvalidInput`; Liked
1188    /// needs `spoolframe:liked` too (`Unsupported` without). Only the
1189    /// tracks the user may see. As `DownloadOptions` for from where.
1190    MusicDownloadChanges {
1191        artists: Vec<MediaId>,
1192        playlists: Vec<String>,
1193        liked: bool,
1194        #[serde(deserialize_with = "spoolframe_types::required::option")]
1195        since: Option<String>,
1196    },
1197    /// What the device played and liked while it had no server
1198    /// (`spoolframe:music-downloads`): `OfflinePlaysSynced`, an outcome per
1199    /// play and per like, in order. `device_now` is the device's clock
1200    /// now, in Unix seconds: each `at` is moved by the difference to the
1201    /// server's clock, and kept no later than now. Each play of a track is
1202    /// recorded once, counted as the server's rules say from
1203    /// `played_ms`: it is in play counts and last played. A like or an
1204    /// unlike is made only when newer than the track's last change on the
1205    /// server (newest wins, whichever device made it); likes need
1206    /// `spoolframe:liked` too (`Unsupported` without). At most
1207    /// [`crate::downloads::MAX_ASKED`] plays and likes together. As
1208    /// `DownloadOptions` for from where.
1209    SyncOfflinePlays {
1210        device_now: i64,
1211        plays: Vec<crate::downloads::OfflinePlay>,
1212        liked: Vec<crate::downloads::OfflineLike>,
1213    },
1214
1215    /// A request type this build does not know; answered with
1216    /// [`Error::Unsupported`].
1217    #[serde(other)]
1218    Unknown,
1219}
1220
1221impl Request {
1222    /// Served without a session.
1223    pub fn is_pre_auth(&self) -> bool {
1224        matches!(
1225            self,
1226            Request::Hello(_)
1227                | Request::AuthMethods
1228                | Request::LoginPassword(_)
1229                | Request::Ping
1230                | Request::BeginDeviceSignIn { .. }
1231                | Request::AwaitDeviceSignIn { .. }
1232                | Request::BeginPasskeySignIn { .. }
1233                | Request::FinishPasskeySignIn { .. }
1234                | Request::TrustedProfiles
1235                | Request::ResumeProfile { .. }
1236                | Request::RedeemInvite(_)
1237                | Request::LookupInvite(_)
1238                | Request::BeginPortableSignIn
1239                | Request::FinishPortableSignIn(_)
1240                | Request::RedeemPortableInvite(_)
1241                | Request::IdentityRecord { .. }
1242                | Request::IdentityRecordByHandle { .. }
1243                | Request::OfferPairing(_)
1244                | Request::FetchPairing { .. }
1245                | Request::AnswerPairing { .. }
1246                | Request::CollectPairing { .. }
1247                | Request::RedeemPlayToken(_)
1248        )
1249    }
1250}
1251
1252/// The most characters the server keeps of each of `Hello`'s strings:
1253/// `client_name`, `client_version` and `device_name`. It cuts a
1254/// longer one to this many, and keeps and shows only that.
1255pub const MAX_HELLO_TEXT: usize = 128;
1256
1257/// The client introduces itself. Every field is required. Each
1258/// string is cut to [`MAX_HELLO_TEXT`] characters.
1259#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1260pub struct Hello {
1261    pub protocol_version: u32,
1262    /// e.g. `spoolframe-linux`.
1263    pub client_name: String,
1264    pub client_version: String,
1265    /// What kind of client this is: the server keeps it for the device, for
1266    /// its device and session lists. Not taken from `client_name`, which
1267    /// one app may share across platforms.
1268    pub platform: Platform,
1269    /// What the device calls itself (a hostname, "Living room TV"); shown
1270    /// in session lists. `None` when it has no name to give.
1271    #[serde(deserialize_with = "spoolframe_types::required::option")]
1272    pub device_name: Option<String>,
1273    /// What this device can play. `None`: every playback plan is
1274    /// `Unsupported`.
1275    #[serde(deserialize_with = "spoolframe_types::required::option")]
1276    pub capabilities: Option<ClientCapabilities>,
1277    /// The experimental features this client wants, by name
1278    /// ([`crate::experimental`]); the server's answer names those it
1279    /// turned on. Left out when empty, so a client that wants none sends
1280    /// what an older one did; an older server ignores it.
1281    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1282    pub experimental: Vec<String>,
1283}
1284
1285/// `text` cut to [`MAX_HELLO_TEXT`] characters: what a server keeps of a
1286/// device's strings, and a device of an invite link's name.
1287pub(crate) fn cut(text: &mut String) {
1288    if let Some((at, _)) = text.char_indices().nth(MAX_HELLO_TEXT) {
1289        text.truncate(at);
1290    }
1291}
1292
1293impl Hello {
1294    /// This `Hello` with each string cut to [`MAX_HELLO_TEXT`] characters:
1295    /// what a server keeps of it.
1296    pub fn within_bounds(mut self) -> Self {
1297        cut(&mut self.client_name);
1298        cut(&mut self.client_version);
1299        if let Some(name) = &mut self.device_name {
1300            cut(name);
1301        }
1302        self.experimental.truncate(crate::experimental::MAX_ASKED);
1303        for name in &mut self.experimental {
1304            cut(name);
1305        }
1306        self
1307    }
1308}
1309
1310#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1311pub struct LoginPassword {
1312    pub username: String,
1313    pub password: String,
1314    /// Trust this device for the user: it may resume them later
1315    /// without a password (`ResumeProfile`). Never true unless the user
1316    /// ticked "Remember this device".
1317    pub remember: bool,
1318}
1319
1320impl fmt::Debug for LoginPassword {
1321    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1322        f.debug_struct("LoginPassword")
1323            .field("username", &self.username)
1324            .field("password", &"<redacted>")
1325            .field("remember", &self.remember)
1326            .finish()
1327    }
1328}
1329
1330/// An invite's code and the account to make with it (`RedeemInvite`).
1331/// `code` as the link carries it ([`crate::invite::Invite::code`]);
1332/// any case, dashes or spaces are taken.
1333#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1334pub struct RedeemInvite {
1335    pub code: String,
1336    pub username: String,
1337    /// What to show for them; the username when `None`.
1338    #[serde(deserialize_with = "spoolframe_types::required::option")]
1339    pub display_name: Option<String>,
1340    pub password: String,
1341}
1342
1343impl fmt::Debug for RedeemInvite {
1344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1345        f.debug_struct("RedeemInvite")
1346            .field("code", &"<redacted>")
1347            .field("username", &self.username)
1348            .field("display_name", &self.display_name)
1349            .field("password", &"<redacted>")
1350            .finish()
1351    }
1352}
1353
1354/// An invite's code to look up (`LookupInvite`): as `RedeemInvite` takes
1355/// it, in any case, with dashes or spaces.
1356#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1357pub struct LookupInvite {
1358    pub code: String,
1359}
1360
1361impl fmt::Debug for LookupInvite {
1362    // The code is a capability until it is used up: keep it out of logs.
1363    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1364        f.write_str("LookupInvite { code: <redacted> }")
1365    }
1366}
1367
1368/// What an invite's code is (`InviteLookup`). Looking never uses it up.
1369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1370#[serde(tag = "type", rename_all = "snake_case")]
1371pub enum InviteLookupOutcome {
1372    /// It can be redeemed now: `kind` says how (`RedeemInvite` or
1373    /// `RedeemPortableInvite`), and a `create-user` one makes an account
1374    /// with `role`.
1375    Valid {
1376        kind: crate::invite_admin::InviteKind,
1377        /// `consumer` for a `portable-account` one.
1378        role: Role,
1379        /// Unix seconds.
1380        expires_at: i64,
1381        /// The display name of the admin who made it; `None` when they
1382        /// have none, or when the server's CLI made it.
1383        #[serde(deserialize_with = "spoolframe_types::required::option")]
1384        inviter: Option<String>,
1385        /// A `federation` one's: the fingerprint of the key this
1386        /// server pairs with, for the admin about to redeem it on another
1387        /// server to compare. Left out for every other kind, and by an
1388        /// older server.
1389        #[serde(default, skip_serializing_if = "Option::is_none")]
1390        fingerprint: Option<String>,
1391    },
1392    /// It expired at `at`, Unix seconds.
1393    Expired { at: i64 },
1394    /// Every use it had is used.
1395    Used,
1396    /// An admin revoked it.
1397    Revoked,
1398    /// No invite has this code: counted as a wrong guess.
1399    NoMatch,
1400    /// An outcome this build does not know, from a newer server.
1401    #[serde(other)]
1402    Unknown,
1403}
1404
1405/// The most identity states a portable sign-in carries.
1406pub const MAX_SIGN_IN_STATES: usize = 2;
1407
1408/// A portable user's device proving itself (`FinishPortableSignIn`):
1409/// the credential their root gave the device's key, and that
1410/// key's signature over this server's nonce.
1411#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1412pub struct PortableSignIn {
1413    pub credential: UserDeviceCredential,
1414    /// The device key's signature over
1415    /// [`crate::portable::device_proof_message`] of the server's endpoint
1416    /// id and the nonce `BeginPortableSignIn` gave.
1417    #[serde(with = "signature_hex")]
1418    pub proof: ed25519_dalek::Signature,
1419    /// The identity's states the device has, newest last, at most
1420    /// [`MAX_SIGN_IN_STATES`]: the server takes them in before it checks
1421    /// the credential, so a device carries revocations to servers
1422    /// it signs in to.
1423    pub states: Vec<PortableIdentityState>,
1424    /// What they would be called here, for a grant made with this
1425    /// sign-in (a portable-account invite); a grant there already keeps
1426    /// its name.
1427    #[serde(deserialize_with = "spoolframe_types::required::option")]
1428    pub display_name: Option<String>,
1429}
1430
1431/// A `portable-account` invite's code and the portable user redeeming it
1432/// (`RedeemPortableInvite`).
1433#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1434pub struct RedeemPortableInvite {
1435    pub code: String,
1436    pub sign_in: PortableSignIn,
1437}
1438
1439impl fmt::Debug for RedeemPortableInvite {
1440    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441        f.debug_struct("RedeemPortableInvite")
1442            .field("code", &"<redacted>")
1443            .field("sign_in", &self.sign_in)
1444            .finish()
1445    }
1446}
1447
1448/// The account password, to confirm it is the session user
1449/// (`ConfirmPassword`).
1450#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1451pub struct ConfirmPassword {
1452    pub password: String,
1453}
1454
1455impl fmt::Debug for ConfirmPassword {
1456    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1457        f.debug_struct("ConfirmPassword")
1458            .field("password", &"<redacted>")
1459            .finish()
1460    }
1461}
1462
1463/// The session user's password and the one to replace it with
1464/// (`ChangePassword`).
1465#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1466pub struct ChangePassword {
1467    pub current_password: String,
1468    pub new_password: String,
1469}
1470
1471impl fmt::Debug for ChangePassword {
1472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1473        f.write_str("ChangePassword { <redacted> }")
1474    }
1475}
1476
1477/// What proves a PIN change or removal is the user's: the PIN
1478/// they have, or, when it is forgotten, their account password.
1479#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1480#[serde(tag = "type", rename_all = "snake_case")]
1481pub enum PinProof {
1482    /// The current PIN, checked as `UnlockProfile` checks it: a wrong one
1483    /// counts towards the same limit (`InvalidCredentials`, then
1484    /// `RateLimited`) and the same count of wrong PINs in a row; the 10th
1485    /// revokes the session on this device (`Unauthenticated`). Checking it
1486    /// unlocks nothing. A user with no PIN passes any.
1487    Pin { pin: String },
1488    /// The account password, checked as `LoginPassword` checks it: a wrong
1489    /// one is a failed sign-in for this username from this device
1490    /// (`InvalidCredentials`, then `RateLimited`, one limit with
1491    /// `LoginPassword`). It never revokes the session and never touches
1492    /// the PIN's limit. A user with no password (passkeys or SSO only) gets
1493    /// `NoPassword`: the PIN proof, or the web UI, is theirs.
1494    Password { password: String },
1495}
1496
1497impl fmt::Debug for PinProof {
1498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1499        let kind = match self {
1500            PinProof::Pin { .. } => "Pin",
1501            PinProof::Password { .. } => "Password",
1502        };
1503        write!(f, "PinProof::{kind}(<redacted>)")
1504    }
1505}
1506
1507/// The session user's track preferences (`GetTrackPreferences`), and
1508/// whether this server reads picture subtitles as text.
1509#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1510pub struct TrackPreferencesInfo {
1511    pub preferences: TrackPreferences,
1512    /// The server reads picture subtitles as text: `subtitles.ocr` is on
1513    /// and tesseract has at least one language. When false,
1514    /// `preferences.subtitles.bitmap` has no effect, and apps show that
1515    /// choice disabled.
1516    pub ocr_offered: bool,
1517}
1518
1519/// How a user can log in to this server.
1520#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1521#[serde(rename_all = "snake_case")]
1522pub enum AuthMethod {
1523    Password,
1524    /// Approval on another signed-in device: `BeginDeviceSignIn`.
1525    DeviceApproval,
1526    /// A method this build does not know.
1527    #[serde(other)]
1528    Unknown,
1529}
1530
1531/// The answer to one request.
1532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1533#[serde(rename_all = "snake_case")]
1534#[expect(
1535    clippy::large_enum_variant,
1536    reason = "built once per request and encoded at once; boxing would only add noise"
1537)]
1538pub enum Response {
1539    Ok(Reply),
1540    Err(Error),
1541}
1542
1543impl From<Result<Reply, Error>> for Response {
1544    fn from(result: Result<Reply, Error>) -> Self {
1545        match result {
1546            Ok(reply) => Response::Ok(reply),
1547            Err(error) => Response::Err(error),
1548        }
1549    }
1550}
1551
1552impl From<Response> for Result<Reply, Error> {
1553    fn from(response: Response) -> Self {
1554        match response {
1555            Response::Ok(reply) => Ok(reply),
1556            Response::Err(error) => Err(error),
1557        }
1558    }
1559}
1560
1561#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1562#[serde(tag = "type", rename_all = "snake_case")]
1563pub enum Reply {
1564    PlaybackProgressSequence {
1565        sequence: u64,
1566    },
1567    ServerInfo(ServerInfo),
1568    AuthMethods {
1569        methods: Vec<AuthMethod>,
1570    },
1571    LoggedIn {
1572        session: SessionId,
1573        /// This device is trusted for the session's user after it:
1574        /// the sign-in asked to be remembered and it was (by the
1575        /// approver too, for a device sign-in), or the device already was.
1576        remembered: bool,
1577        /// The password was a one-time one an admin reset to: show "Choose
1578        /// a new password" and send `ChangePassword` (its current password
1579        /// is the one-time one). Until then the session gets
1580        /// `PasswordChangeRequired` for anything else but `Logout` and
1581        /// `WhoAmI`, and the device is not trusted.
1582        password_change_required: bool,
1583    },
1584    /// The users this device is trusted for (`TrustedProfiles`), by
1585    /// username.
1586    TrustedProfiles {
1587        profiles: Vec<TrustedProfile>,
1588    },
1589    Pong,
1590    /// A device sign-in is pending. Show `code` (see
1591    /// [`crate::device_sign_in::display`]); keep `request` to await it.
1592    DeviceSignInStarted {
1593        request: String,
1594        code: String,
1595        expires_in_ms: u64,
1596        /// Where a browser approves it
1597        /// ([`crate::device_sign_in::web_link`]), for a QR code a phone's
1598        /// camera opens; `None` if the server's web UI has no public URL.
1599        web_url: Option<String>,
1600    },
1601    /// Not approved yet: `AwaitDeviceSignIn` again.
1602    DeviceSignInPending,
1603    /// What an invite's code is (`LookupInvite`).
1604    InviteLookup {
1605        outcome: InviteLookupOutcome,
1606    },
1607    /// The device a sign-in code belongs to.
1608    DeviceSignInRequest(DeviceSignInRequest),
1609    Libraries {
1610        libraries: Vec<Library>,
1611    },
1612    /// What a library can be sorted and filtered by (`ItemFilterValues`).
1613    ItemFilterValues {
1614        values: spoolframe_types::ItemFilterValues,
1615    },
1616    Items {
1617        items: Vec<Item>,
1618        total: u32,
1619        /// Experimental (`federation`): the items listed that are
1620        /// no longer available, their paired server unpaired or their
1621        /// library no longer shared (`RecentlyPlayed`): shown as such, and
1622        /// not played. Only to a client that named the feature; left out
1623        /// when empty, as experimental fields are.
1624        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1625        unavailable: Vec<MediaId>,
1626    },
1627    Item {
1628        item: Item,
1629        children: Vec<Item>,
1630        /// The item's intro and credits, in order of start; empty
1631        /// for an item that has none.
1632        markers: Vec<Marker>,
1633        /// The playlists the user sees that hold it: a movie,
1634        /// episode or track itself; any of a season's or a show's
1635        /// episodes; any of an album's or an artist's tracks. Empty when
1636        /// none does.
1637        playlists: Vec<PlaylistRef>,
1638        /// Its heart: a track's `all` or `none`; an album's
1639        /// `all`, `some` or `none` by the tracks it has now. `None` for
1640        /// any other item.
1641        #[serde(deserialize_with = "spoolframe_types::required::option")]
1642        liked: Option<crate::playlists::Liked>,
1643        /// An album's tracks among `children` that are liked,
1644        /// for their hearts. Empty for any other item.
1645        liked_children: Vec<MediaId>,
1646        /// Experimental (`federation`): where the item is from, its
1647        /// title's copies on other servers and the one that plays, as a
1648        /// `SearchHit` has them. Only to a client that named the feature.
1649        #[serde(default, skip_serializing_if = "Option::is_none")]
1650        copies: Option<crate::search::Copies>,
1651    },
1652    Search(SearchResults),
1653    /// Experimental (`federation`): `Search`'s answer to a client
1654    /// that named the feature, each item a `SearchHit`. Counts are
1655    /// approximate: a title on several servers is counted once only among
1656    /// what is shown.
1657    SearchHits(SearchResults<crate::search::SearchHit>),
1658    Tracks(MediaTracks),
1659    WhoAmI(WhoAmIReply),
1660    LoggedOut,
1661    Sessions {
1662        sessions: Vec<SessionInfo>,
1663    },
1664    PlaybackPlan {
1665        plan: PlaybackPlan,
1666        /// The tracks the server chose, when the request had no selection.
1667        #[serde(deserialize_with = "spoolframe_types::required::option")]
1668        chosen: Option<ChosenTracks>,
1669    },
1670    PlaybackStarted {
1671        handle: PlaybackHandle,
1672        /// How the server plays it: direct, or converted.
1673        plan: PlaybackPlan,
1674        /// The size of the file the handle reads.
1675        size: u64,
1676        /// The tracks the server chose, when the request had no selection.
1677        #[serde(deserialize_with = "spoolframe_types::required::option")]
1678        chosen: Option<ChosenTracks>,
1679        /// The encode reads name; 0 for direct play.
1680        epoch: u32,
1681        /// The item's intro and credits, as in `Item`, so a player needs
1682        /// no second request for them. Their times are the item's own,
1683        /// wherever the playback starts.
1684        markers: Vec<Marker>,
1685    },
1686    /// A seek restarted the encode: reads name this epoch from offset 0.
1687    PlaybackSeeked {
1688        epoch: u32,
1689    },
1690    PlaybackRevision {
1691        revision: u64,
1692    },
1693    /// The session user's devices, most recently seen first.
1694    Devices {
1695        devices: Vec<DeviceInfo>,
1696    },
1697    /// The session user's Plex link; `None`: not linked (or the server
1698    /// links no Plex accounts).
1699    PlexLink {
1700        link: Option<PlexLink>,
1701    },
1702    /// The playback's new plan after `ChangeSubtitle` or `ChangeQuality`:
1703    /// read `epoch` (0 for direct play), whose size is `size` (0 while a
1704    /// conversion writes it).
1705    PlaybackChanged {
1706        plan: PlaybackPlan,
1707        size: u64,
1708        epoch: u32,
1709    },
1710    /// An HLS playlist, as text.
1711    Manifest {
1712        text: String,
1713    },
1714    /// A segment of a subtitle rendition, whole (`ReadSubtitleSegment`).
1715    Subtitle {
1716        format: SubtitleFormat,
1717        #[serde(with = "serde_bytes")]
1718        bytes: Vec<u8>,
1719    },
1720    /// The chunk of a subtitle file that `ReadSubtitle` asked for.
1721    SubtitleChunk {
1722        format: SubtitleFormat,
1723        #[serde(with = "serde_bytes")]
1724        bytes: Vec<u8>,
1725        /// The whole file's length.
1726        total: u64,
1727        /// The file these bytes are of. It is another value once the file
1728        /// is written again or replaced, and means nothing else to a
1729        /// client: send it back with the next `ReadSubtitle`.
1730        version: u64,
1731    },
1732    /// The request was carried out; there is nothing to return.
1733    Done,
1734    /// The session user confirmed it is them (`ConfirmPassword`,
1735    /// `FinishConfirmPasskey`): this session counts as signed in now.
1736    Confirmed,
1737    Home(HomeScreen),
1738    TrackPreferences(TrackPreferencesInfo),
1739    /// An item's frame previews (`GetPreviews`).
1740    Previews(Previews),
1741    /// What the platform makes an app passkey with, but the challenge:
1742    /// the nonce it is made from (`BeginPasskeyRegistration`).
1743    PasskeyRegistrationBegun(PasskeyRegistrationBegun),
1744    /// What the platform signs in with an app passkey with, but the
1745    /// challenge: the nonce it is made from (`BeginPasskeySignIn`,
1746    /// `BeginConfirmPasskey`).
1747    PasskeySignInBegun(PasskeySignInBegun),
1748    /// The session user's passkeys (`ListPasskeys`).
1749    Passkeys {
1750        passkeys: Vec<PasskeyInfo>,
1751    },
1752    /// What a portable identity signs to tie the session user's account
1753    /// to it (`TieBegin`).
1754    TieChallenge {
1755        /// Used once, for `expires_in_secs`, by this session.
1756        #[serde(with = "serde_bytes")]
1757        nonce: [u8; 32],
1758        /// This server's endpoint id, as the tie message names it. A
1759        /// client signs with the id it dialled, never this one: the field
1760        /// says which server meant to ask.
1761        #[serde(with = "serde_bytes")]
1762        server: [u8; 32],
1763        expires_in_secs: u64,
1764    },
1765    /// What a portable user's device signs to sign in
1766    /// (`BeginPortableSignIn`).
1767    PortableSignInBegun {
1768        /// Used once, for `expires_in_secs`, by this device.
1769        #[serde(with = "serde_bytes")]
1770        nonce: [u8; 32],
1771        expires_in_secs: u64,
1772    },
1773    /// A new invite, with its code (`CreateInvite`).
1774    InviteCreated(InviteCreated),
1775    /// What the server keeps of a portable identity (`IdentityRecord`).
1776    IdentityRecord(IdentityRecord),
1777    /// The pairing request held under a code (`FetchPairing`).
1778    PairingOffered(PairingOffer),
1779    /// The answer to a device's pairing request, or `None` while none
1780    /// came yet (`CollectPairing`).
1781    PairingAnswered {
1782        answer: Option<PairingAnswer>,
1783    },
1784    /// The invites that can still be redeemed (`ListInvites`).
1785    Invites {
1786        invites: Vec<InviteSummary>,
1787    },
1788    /// Experimental (`http-playback`): where a player with no Iroh
1789    /// fetches the playback (`HttpPlaybackUrl`).
1790    HttpPlaybackUrl {
1791        url: String,
1792    },
1793    /// Experimental (`http-playback`): why `HttpPlaybackUrl` gave
1794    /// no URL.
1795    HttpPlaybackRefused {
1796        reason: crate::experimental::HttpPlaybackRefusal,
1797    },
1798    /// Experimental (`federation`): the server paired
1799    /// (`PairServer`).
1800    ServerPaired {
1801        server: crate::federation::PeerServer,
1802    },
1803    /// Experimental (`federation`): the libraries shared with the
1804    /// paired server (`ShareLibraries`), as asked.
1805    LibrariesShared {
1806        libraries: Vec<spoolframe_types::LibraryId>,
1807    },
1808    /// Experimental (`federation`): the session a play token
1809    /// opened (`RedeemPlayToken`).
1810    PlayTokenRedeemed(crate::federation::PlayTokenRedeemed),
1811    /// Experimental (`federation`): where a paired server is
1812    /// (`RemoteHints`).
1813    RemoteHints(crate::federation::RemoteHints),
1814    /// Experimental (`federation`): a paired server's play token
1815    /// for this device (`RemoteGrant`).
1816    RemoteGranted(crate::federation::RemoteGranted),
1817    /// The playlists the user sees (`ListPlaylists`), oldest first,
1818    /// and the notes of pinned ones that left their Pinned.
1819    Playlists {
1820        playlists: Vec<PlaylistSummary>,
1821        pin_notes: Vec<PinNote>,
1822    },
1823    /// One playlist and a page of its entries (`GetPlaylist`).
1824    Playlist(PlaylistPage),
1825    /// A playlist as it is now (`CreatePlaylist`, `UpdatePlaylist`).
1826    PlaylistInfo(PlaylistSummary),
1827    /// A subtitle track's timing after `SyncSubtitle`,
1828    /// `UseOriginalSubtitleTiming` or `SetSubtitleOffset`.
1829    SubtitleTiming(spoolframe_types::SubtitleTiming),
1830    /// What `SearchSubtitles` found.
1831    SubtitleResults(spoolframe_types::SubtitleSearch),
1832    /// The track `DownloadSubtitle` added.
1833    SubtitleDownloaded(spoolframe_types::SubtitleDownloaded),
1834    /// The playlist's revision after `EditPlaylist`.
1835    PlaylistEdited {
1836        revision: u64,
1837    },
1838    /// The entry to play now (`PlayPlaylist`, `NextInPlaylist`).
1839    PlaylistItem(crate::playlists::PlaylistNext),
1840    /// Nothing is left to play: the end, with repeat off, or no entry can
1841    /// be played. The user's place is cleared.
1842    PlaylistFinished,
1843    /// What plays next in a playlist (`UpcomingInPlaylist`), in turn.
1844    PlaylistUpcoming {
1845        entries: Vec<crate::playlists::PlaylistEntry>,
1846    },
1847    /// What importing Plex playlists made, or would (`ImportPlexPlaylists`).
1848    PlexImport(crate::playlists::PlexImport),
1849    /// Whom a playlist can be shared with (`ListShareCandidates`).
1850    ShareCandidates(crate::playlists::ShareCandidatePage),
1851    /// What the device may download of an item (`DownloadOptions`).
1852    DownloadOptions(crate::downloads::DownloadOptionsInfo),
1853    /// A download prepared (`PrepareDownload`).
1854    Download(crate::downloads::DownloadInfo),
1855    /// Downloads, in the order asked (`DownloadStatus`): each the user
1856    /// has, and the ids asked for that they have not. A device treats a
1857    /// gone download as cancelled: preparing it again brings it back.
1858    Downloads {
1859        downloads: Vec<crate::downloads::DownloadInfo>,
1860        /// Left out when empty.
1861        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1862        gone: Vec<String>,
1863    },
1864    /// What became of each offline entry, in order (`SyncOfflineWatch`).
1865    OfflineWatchSynced {
1866        outcomes: Vec<crate::downloads::OfflineWatchOutcome>,
1867    },
1868    /// What each followed thing holds (`MusicDownloadChanges`), and the
1869    /// cursor to ask with next.
1870    MusicDownloadChanges {
1871        changes: Vec<crate::downloads::FollowedChange>,
1872        cursor: String,
1873    },
1874    /// What became of each offline play and like, in order
1875    /// (`SyncOfflinePlays`).
1876    OfflinePlaysSynced {
1877        plays: Vec<crate::downloads::OfflineWatchOutcome>,
1878        liked: Vec<crate::downloads::OfflineWatchOutcome>,
1879    },
1880}
1881
1882/// Which HLS playlist.
1883#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1884#[serde(rename_all = "snake_case")]
1885pub enum ManifestKind {
1886    /// The top playlist, naming the variant.
1887    Multivariant,
1888    /// The variant's segments.
1889    Media,
1890    /// The subtitle rendition's WebVTT segments, read with
1891    /// `ReadSubtitleSegment`; there when the plan has a subtitle.
1892    Subtitles,
1893    #[serde(other)]
1894    Unknown,
1895}
1896
1897/// Rows for a home screen. Every item carries the user's playback state.
1898#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1899pub struct HomeScreen {
1900    /// Started and not finished, most recent first.
1901    pub continue_watching: Vec<Item>,
1902    /// For each recently watched show, its next unwatched episode.
1903    pub next_up: Vec<Item>,
1904    pub recently_added: Vec<Item>,
1905    /// Experimental (`federation`): the items of these rows that
1906    /// are no longer available: their paired server unpaired, or stopped
1907    /// sharing their library. Shown as such, and not played. Only to a
1908    /// client that named the feature, as every `fed:` id is; left out when
1909    /// empty, as experimental fields are.
1910    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1911    pub unavailable: Vec<MediaId>,
1912    /// Experimental (`federation`): each paired server's own row,
1913    /// what it shared lately, by the server's name. A row the user turned
1914    /// off (`SetServerRow`) is listed with no items, for the setting. Left
1915    /// out when empty, as experimental fields are.
1916    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1917    pub servers: Vec<ServerRow>,
1918}
1919
1920/// A paired server's row on Home.
1921#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1922pub struct ServerRow {
1923    pub server: spoolframe_types::LibraryServer,
1924    /// Whether the user shows it (`SetServerRow`); a row not shown has no
1925    /// items.
1926    pub shown: bool,
1927    /// What it shared most recently first, as this server cached it.
1928    pub items: Vec<Item>,
1929}
1930
1931/// A session's user.
1932#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1933pub struct UserSummary {
1934    /// Opaque; stable for the user on this server (today `local:<uuid>`).
1935    /// A server that served `local:<number>` ids changes them once: a
1936    /// client that kept an id reads it again from `WhoAmI`.
1937    pub user_id: String,
1938    pub username: String,
1939    /// What to show; the username when the user has no display name.
1940    pub display_name: String,
1941    /// What the user may do.
1942    pub role: Role,
1943    /// The session needs the user's PIN on this connection before anything
1944    /// but `WhoAmI` and `UnlockProfile`.
1945    pub locked: bool,
1946    /// The user's PIN, if they have one: for "Set ยท 4 digits", and
1947    /// for how many boxes a PIN pad shows. Never the PIN itself.
1948    pub pin: Option<PinState>,
1949    /// The portable identities the account is tied to,
1950    /// the oldest tie first: shown on the account, never as other
1951    /// accounts. Empty for an account with none, and for a portable
1952    /// user's own session, whose identity is its `user_id`.
1953    pub portable: Vec<PortableTie>,
1954}
1955
1956/// One of an account's ties to a portable identity.
1957#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1958pub struct PortableTie {
1959    pub id: PortableUserId,
1960    /// Unix seconds.
1961    pub tied_at: i64,
1962    /// Unix seconds of the identity's last sign-in into the account with
1963    /// its credential; `None` until one.
1964    #[serde(deserialize_with = "spoolframe_types::required::option")]
1965    pub last_used_at: Option<i64>,
1966}
1967
1968/// What `WhoAmI` answers: the session's user, and whether they may leave
1969/// the server. On the wire the user's fields and `can_leave` sit in one
1970/// map, so a client that does not know `can_leave` reads it as a
1971/// [`UserSummary`].
1972#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1973pub struct WhoAmIReply {
1974    #[serde(flatten)]
1975    pub user: UserSummary,
1976    /// `LeaveServer` would be done, not refused with `LastAdmin`:
1977    /// false for the last enabled admin, or the last enabled admin with a
1978    /// password, so an app can grey out "Leave this server" before it is
1979    /// asked. As of this answer: an admin made or demoted later changes
1980    /// it.
1981    pub can_leave: bool,
1982}
1983
1984/// A user's PIN as clients may know it.
1985#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1986pub struct PinState {
1987    /// How many digits it has (4 to 8); `None` for a PIN set before the
1988    /// server kept its length, until it is set again.
1989    pub digits: Option<u8>,
1990}
1991
1992/// A user a device is trusted for, as that device sees them.
1993#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1994pub struct TrustedProfile {
1995    /// What `ResumeProfile` takes: `UserSummary::user_id`.
1996    pub user_id: String,
1997    /// To match the profile with one the device keeps by username.
1998    pub username: String,
1999    /// What to show; the username when the user has no display name.
2000    pub display_name: String,
2001    /// The user's PIN is asked for on this device: a resumed session
2002    /// starts locked.
2003    pub pin_required: bool,
2004    /// Open this profile at start, past "Who's watching". At most one per
2005    /// device.
2006    pub auto_login: bool,
2007}
2008
2009/// One of a user's devices.
2010#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2011pub struct DeviceInfo {
2012    /// Hex `EndpointId`: what `SetPinRequired { device }` takes.
2013    pub endpoint_id: String,
2014    /// What the device calls itself.
2015    #[serde(deserialize_with = "spoolframe_types::required::option")]
2016    pub name: Option<String>,
2017    /// What kind of client it runs, as its `Hello` said; `None` for a
2018    /// device not seen since before the server kept it.
2019    pub platform: Option<Platform>,
2020    /// Unix seconds.
2021    pub last_seen_at: i64,
2022    /// The user's PIN is asked for on it.
2023    pub pin_required: bool,
2024    /// It may resume the user without a password.
2025    pub trusted: bool,
2026    /// It opens the user's profile at start.
2027    pub auto_login: bool,
2028    /// The device this request came from.
2029    pub this_device: bool,
2030}
2031
2032/// A device waiting to be signed in, as the approver sees it.
2033#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2034pub struct DeviceSignInRequest {
2035    /// What the device calls itself (from its `Hello`).
2036    #[serde(deserialize_with = "spoolframe_types::required::option")]
2037    pub device_name: Option<String>,
2038    /// Its app, e.g. `spoolframe-tvos`.
2039    pub client_name: String,
2040    /// What kind of client it runs, as its `Hello` said: shown beside its
2041    /// name ([`Platform::label`], "Apple TV app"), so the approver knows
2042    /// which device asks.
2043    pub platform: Platform,
2044    /// Unix seconds.
2045    pub requested_at: i64,
2046    /// The device asked to be remembered: the approval says "This
2047    /// device will be remembered", ticked, and the approver may untick it.
2048    pub remember: bool,
2049    /// Where the device's `BeginDeviceSignIn` came from, as the server saw
2050    /// it: the one thing on this screen an attacker who
2051    /// sent the approver a code cannot choose. `None` if the server could
2052    /// not tell. The approval shows it, "The TV asked from 192.168.86.20.",
2053    /// and for [`AddressNetwork::Internet`] warns instead: the device is
2054    /// not on the approver's network, so approve only one you can see.
2055    #[serde(deserialize_with = "spoolframe_types::required::option")]
2056    pub requested_from: Option<DeviceAddress>,
2057}
2058
2059/// An address a device reached the server from.
2060#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2061pub struct DeviceAddress {
2062    /// Its IP address as text: `192.168.86.20`, `fd7a:115c:a1e0::1`. An
2063    /// IPv4 address is never in its IPv6-mapped form.
2064    pub address: String,
2065    /// What kind of network that address is on, as the server judges it.
2066    pub network: AddressNetwork,
2067}
2068
2069/// What kind of network an address is on, as the server's web approval
2070/// page judges it too.
2071#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2072#[serde(rename_all = "snake_case")]
2073pub enum AddressNetwork {
2074    /// The server's own machine: `127.0.0.0/8`, `::1`.
2075    Loopback,
2076    /// A home, office or VPN network: private IPv4 ranges, link-local,
2077    /// CGNAT and VPNs' `100.64.0.0/10`, IPv6 unique-local and link-local.
2078    Local,
2079    /// A public address: a device far from the approver, which is what a
2080    /// sign-in code sent to someone else (device-code phishing) looks
2081    /// like. The approval warns.
2082    Internet,
2083    /// A kind this build does not know, from a newer server. Show the
2084    /// address and warn as for [`AddressNetwork::Internet`].
2085    #[serde(other)]
2086    Unknown,
2087}
2088
2089/// One live session, without its token.
2090#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2091pub struct SessionInfo {
2092    /// The device's name; `None` for an admin API session or an unnamed
2093    /// device.
2094    pub device_name: Option<String>,
2095    /// What kind of client the device runs; `None` for an admin API
2096    /// session (the web UI or the CLI) or a device not seen since before
2097    /// the server kept it.
2098    pub platform: Option<Platform>,
2099    /// Unix seconds.
2100    pub created_at: i64,
2101    /// Unix seconds.
2102    pub last_used_at: i64,
2103    /// The session this request was made in.
2104    pub current: bool,
2105}
2106
2107/// Who the server is. `endpoint_id` is what the client pins.
2108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2109pub struct ServerInfo {
2110    pub name: String,
2111    /// Hex, as `spoolframe-server id` prints it.
2112    pub endpoint_id: String,
2113    /// The server's id ([`crate::ServerId`]): made once, kept when its key
2114    /// is replaced. A client pins it beside `endpoint_id`, the first time
2115    /// it sees it.
2116    pub server_id: String,
2117    pub protocol_version: u32,
2118    pub server_version: String,
2119    pub auth_methods: Vec<AuthMethod>,
2120    /// Where a browser reaches the server's web UI (`admin.public_url`),
2121    /// if it has one: for "open in the browser" links, such as linking a
2122    /// Plex account. Absent without a public URL, since the
2123    /// listener's own address may be loopback or one no browser trusts.
2124    pub web_url: Option<String>,
2125    /// The experimental features turned on for this connection:
2126    /// those its `Hello` named that this server knows and has on. Left
2127    /// out when none, as an older server does.
2128    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2129    pub experimental: Vec<String>,
2130    /// An account is made only from an invite (`RedeemInvite`); there is
2131    /// no open sign-up. For a "servers on my network" list, before
2132    /// signing in.
2133    pub invite_only: bool,
2134}
2135
2136/// Why a request failed. Typed, so clients act on the kind, not on text.
2137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
2138#[serde(tag = "type", rename_all = "snake_case")]
2139pub enum Error {
2140    #[error("progress belongs to an older playback or sequence")]
2141    StaleProgress,
2142    #[error("the operation belongs to an earlier server instance")]
2143    ServerRestarted,
2144    #[error("the operation expired; its outcome is no longer recoverable")]
2145    OperationExpired,
2146    #[error("the operation ID was already used with different arguments")]
2147    OperationConflict,
2148    #[error("the playback configuration changed (revision {revision})")]
2149    RevisionConflict { revision: u64 },
2150    /// The connection's first request was not `Hello`.
2151    #[error("send Hello first")]
2152    HandshakeRequired,
2153    /// The request needs a session, and none valid for this endpoint was
2154    /// given.
2155    #[error("not authenticated")]
2156    Unauthenticated,
2157    /// The server does not know this request type.
2158    #[error("unsupported request {request:?}")]
2159    Unsupported { request: String },
2160    #[error("malformed request: {message}")]
2161    Malformed { message: String },
2162    #[error("{what} not found")]
2163    NotFound { what: String },
2164    /// Wrong username or password; deliberately the same for both.
2165    #[error("invalid credentials")]
2166    InvalidCredentials,
2167    /// Too many failed logins for this username or from this endpoint.
2168    #[error("too many failed logins; retry in {retry_after_ms} ms")]
2169    RateLimited { retry_after_ms: u64 },
2170    /// The client cannot play this selection; one reason per stream, as
2171    /// in [`PlaybackPlan::Unsupported`].
2172    #[error("cannot play: {}", reasons.join("; "))]
2173    CannotPlay { reasons: Vec<String> },
2174    /// The playback handle is unknown or has been idle too long. Call
2175    /// `StartPlayback` again and go on from where playback was.
2176    #[error("the playback has expired; start it again")]
2177    PlaybackExpired,
2178    /// An admin stopped the playback on the server. It is over:
2179    /// tell the viewer it ended, and do not start it again on your own
2180    /// as after `PlaybackExpired`. Its progress is kept.
2181    #[error("the playback was stopped on the server")]
2182    PlaybackStopped,
2183    /// The server is converting as many files as it may at once.
2184    #[error("the server is busy converting; try again later")]
2185    Busy,
2186    /// The server plays at most `max` playbacks off its LAN at once
2187    /// (`network.uplink.max_streams`), and that many are playing.
2188    /// Try again when one ends; a device on the server's LAN is not
2189    /// counted.
2190    #[error("the server plays at most {max} playbacks outside its home at once")]
2191    WanStreamsFull { max: u32 },
2192    /// The encode for this playback failed; `reason` is ffmpeg's.
2193    #[error("the conversion failed: {reason}")]
2194    PlaybackFailed { reason: String },
2195    /// The read names an encode that a seek replaced; read `epoch` from
2196    /// offset 0.
2197    #[error("the playback restarted at a seek (epoch {epoch})")]
2198    PlaybackRestarted { epoch: u32 },
2199    /// The subtitle is still being read as text; `done_percent` of
2200    /// its cues are read. Ask again in a few seconds.
2201    #[error("the subtitle is still being read ({done_percent}% done)")]
2202    SubtitleNotReady { done_percent: u8 },
2203    /// The item's frame previews are being made; `done_percent` of
2204    /// them are. Ask again in a few seconds; show the time alone till then.
2205    #[error("the previews are being made ({done_percent}% done)")]
2206    PreviewsNotReady { done_percent: u8 },
2207    /// The item has no frame previews and will not have: music, a file
2208    /// they could not be made of, or a server that makes none. Do not ask
2209    /// again for this item.
2210    #[error("this item has no previews")]
2211    NoPreviews,
2212    /// The subtitle is not the file that `ReadSubtitle`'s `version` names:
2213    /// it was written again or replaced since that chunk. Read it
2214    /// again from offset 0.
2215    #[error("the subtitle changed while it was read")]
2216    SubtitleChanged,
2217    /// The session's profile is locked on this connection: `UnlockProfile`
2218    /// with the user's PIN first.
2219    #[error("this profile is locked; enter its PIN")]
2220    ProfileLocked,
2221    /// A value the request carries is not acceptable (a PIN that is not 4
2222    /// to 8 digits, say); the message says why.
2223    #[error("{message}")]
2224    InvalidInput { message: String },
2225    /// The request carried the user's account password, and they have none:
2226    /// they sign in with a passkey or SSO only (a `PinProof::Password`).
2227    /// Not a wrong password, and nothing was counted. Use another proof, or
2228    /// send them to the server's web UI (`ServerInfo::web_url`, when the
2229    /// server has one).
2230    #[error("this account has no password; use the PIN or the web UI")]
2231    NoPassword,
2232    /// The session was signed in too long ago for this (an app passkey,
2233    /// approving a device): confirm it is the user
2234    /// (`ConfirmPassword`, or `BeginConfirmPasskey`), or sign in again,
2235    /// then ask again. Nothing was changed.
2236    #[error("sign in again first")]
2237    RecentSignInRequired,
2238    /// Removing this would leave the user no way to sign in: it is their
2239    /// only passkey, and they have no password or linked sign-in provider
2240    /// (`RemovePasskey`). Nothing was changed.
2241    #[error("that is the last way to sign in to this account")]
2242    LastSignInMethod,
2243    /// The device sign-in was refused on the approving device.
2244    #[error("the sign-in was denied")]
2245    DeviceSignInDenied,
2246    /// The device sign-in is over: it timed out, or is not this device's.
2247    /// Begin a new one.
2248    #[error("the sign-in code has expired")]
2249    DeviceSignInExpired,
2250    /// The reply would be over the frame limit
2251    /// ([`crate::codec::MAX_FRAME`]); `bytes` is its length. A page of
2252    /// items is to ask for in smaller pages.
2253    #[error("the reply is too large to send ({bytes} bytes)")]
2254    ReplyTooLarge { bytes: u64 },
2255    /// Something the server depends on (Plex, a media mount) is down.
2256    #[error("unavailable: {message}")]
2257    Unavailable { message: String },
2258    /// The server has no library yet: it is waiting to be set up in its
2259    /// web UI. Every catalog and playback request gets this until
2260    /// it is; show "This server is not set up yet", not an error. Signing
2261    /// in and the rest work.
2262    #[error("this server is not set up yet")]
2263    NotSetUp,
2264    /// The invite's code is right, and it is of another kind than the
2265    /// request redeems: a `portable-account` invite's code to
2266    /// `RedeemInvite`, or a `create-user` one's to
2267    /// `RedeemPortableInvite`. Nothing was made and the invite keeps its
2268    /// use: redeem it the other way.
2269    #[error("that invite is of another kind")]
2270    WrongInviteKind,
2271    /// `RedeemInvite` with a code that is no invite's, or whose invite
2272    /// was revoked. Counted as a wrong guess. Offer "Save server
2273    /// only", which pins the server as a link without a code does.
2274    #[error("that invite code is not valid")]
2275    InviteInvalid,
2276    /// The invite's code is right, and it has expired: ask for another.
2277    #[error("the invite has expired")]
2278    InviteExpired,
2279    /// The invite's code is right, and every account it could make has
2280    /// been made: ask for another.
2281    #[error("the invite has been used up")]
2282    InviteExhausted,
2283    /// Someone on this server has that username: pick another. Nothing
2284    /// was made and the invite was not used up.
2285    #[error("that username is taken")]
2286    UsernameTaken,
2287    /// `TieFinish` with a nonce that is not outstanding for this session:
2288    /// it was used, it is over, or `TieBegin` never gave it here.
2289    /// Begin again.
2290    #[error("the tie challenge is used or has expired; begin again")]
2291    TieChallengeExpired,
2292    /// Another account on this server is tied to that portable identity:
2293    /// one identity ties to one account per server. Sever that
2294    /// tie first. Nothing was changed.
2295    #[error("that portable identity is tied to another account here")]
2296    PortableIdTaken,
2297    /// The session is a portable user's, and this is for an
2298    /// account here only: its password, PIN, passkeys, devices, sessions,
2299    /// ties, approving sign-ins. Hide what asks for it while signed in as
2300    /// one. Nothing was changed.
2301    #[error("not for a guest from another identity")]
2302    NotForPortableUsers,
2303    /// The request is an admin's (making and revoking invites),
2304    /// and the session user is not one. Nothing was changed.
2305    #[error("only an admin can do that")]
2306    AdminRequired,
2307    /// The session was opened with a one-time password an admin reset to:
2308    /// it may only `ChangePassword` (or `Logout`, `WhoAmI`) until the user
2309    /// chooses a new password. Nothing was done.
2310    #[error("choose a new password first")]
2311    PasswordChangeRequired,
2312    /// `LeaveServer` from the last enabled admin, or the last enabled
2313    /// admin with a password: make someone else an admin, or give
2314    /// one a password, first. Nothing was changed.
2315    #[error("you are the only admin; make someone else an admin first")]
2316    LastAdmin,
2317    /// The user sees the playlist and may not make this change: an
2318    /// edit on a read-only share, or a rename, sharing change or delete by
2319    /// anyone but its owner (or an admin, for a server-wide one). Nothing
2320    /// was changed.
2321    #[error("you cannot change this playlist")]
2322    PlaylistReadOnly,
2323    /// The playlist does not take items of this kind: its kinds
2324    /// were ticked when it was made. Nothing was changed. A season or
2325    /// show is episodes, an album or artist tracks.
2326    #[error("this playlist does not take a {kind:?}")]
2327    KindNotAllowed { kind: crate::playlists::ItemKind },
2328    /// Someone changed the playlist since the revision the edit was made
2329    /// on, and touched an entry the edit touches: "Someone changed
2330    /// this playlist; reload". `revision` is its revision now. Nothing was
2331    /// changed.
2332    #[error("someone changed this playlist; reload (revision {revision})")]
2333    PlaylistConflict { revision: u64 },
2334    /// The user may not do this to what they see: a cover set or
2335    /// taken away by someone who may not edit the playlist, or on Liked
2336    /// or All, whose tiles are fixed. Nothing was changed.
2337    #[error("you are not allowed to do that")]
2338    NotAllowed,
2339    /// The picture is over `max_bytes` long, or over `max_pixels` by its
2340    /// header. Refused before it was decoded; nothing was
2341    /// changed.
2342    #[error("the picture is too large: at most {max_bytes} bytes and {max_pixels} pixels")]
2343    ImageTooLarge { max_bytes: u64, max_pixels: u64 },
2344    /// Not a JPEG, PNG, WebP or HEIC picture the server can decode, or
2345    /// one that hit the decoder's limits. Nothing was changed.
2346    #[error("the picture cannot be read: a JPEG, PNG, WebP or HEIC is taken")]
2347    ImageUnreadable,
2348    /// The downloads of `whose` are used up for today: the
2349    /// server's account at subtitle site `site` (`opensubtitles`,
2350    /// `subdl`, as `SubtitleResult::source`), or the user's own daily
2351    /// limit on this server (no `site`). `resets_at` (Unix seconds) is when more may be
2352    /// downloaded, when known. Nothing was downloaded; searching still
2353    /// works.
2354    #[error("no subtitle downloads left today ({whose:?})")]
2355    QuotaExhausted {
2356        whose: spoolframe_types::QuotaOf,
2357        #[serde(default, skip_serializing_if = "Option::is_none")]
2358        resets_at: Option<i64>,
2359        #[serde(default, skip_serializing_if = "Option::is_none")]
2360        site: Option<String>,
2361    },
2362    /// The server has no subtitle site set up: hide "Find
2363    /// subtitles". Nothing was asked of any site.
2364    #[error("this server has no subtitle source set up")]
2365    NoSubtitleSource,
2366    /// The download's file is not whole yet: read it once its
2367    /// state is `ready`. A download that failed is prepared again.
2368    #[error("the download is not ready")]
2369    DownloadNotReady,
2370    /// Experimental (`federation`): the other server did not pair
2371    /// (`PairServer`), for `reason`. Nothing was kept.
2372    #[error("the other server did not pair: {reason}")]
2373    PairingRefused {
2374        reason: crate::federation::PairingRefused,
2375    },
2376    /// Experimental (`federation`): the paired server the item is
2377    /// from is offline to this one (`RemoteGrant`): play it from this
2378    /// server, or later.
2379    #[error("the paired server the item is from is offline")]
2380    OriginOffline,
2381    #[error("internal server error")]
2382    Internal,
2383    /// An error type this build does not know.
2384    #[serde(other)]
2385    #[error("unknown error")]
2386    Unknown,
2387}
2388
2389/// Something the server tells the client without being asked, on the
2390/// events stream.
2391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2392#[serde(tag = "type", rename_all = "snake_case")]
2393pub enum Event {
2394    /// The server is stopping; the connection will close.
2395    ShuttingDown,
2396    /// Where this server can be reached, pushed to a connection
2397    /// as soon as it is signed in, and again whenever the list changes.
2398    /// Each one is the whole list: it replaces what was told before.
2399    /// Never sent to a connection that is not signed in.
2400    ServerAddresses {
2401        /// The addresses `network.announce` tells, with their port, as
2402        /// text: `192.168.1.10:4433` or `[2001:db8::1]:4433`.
2403        #[serde(with = "socket_addrs_as_text")]
2404        addrs: Vec<std::net::SocketAddr>,
2405        /// The URLs of the iroh relays the server may use
2406        /// (`network.relays`), its home relay now first; empty while
2407        /// relays are off.
2408        relays: Vec<String>,
2409        /// The pkarr relay the server publishes where it is to
2410        /// (`network.pkarr`), for the device to look it up by its
2411        /// key when nothing else reaches it; `None` while it publishes
2412        /// nothing.
2413        #[serde(deserialize_with = "spoolframe_types::required::option")]
2414        lookup: Option<String>,
2415    },
2416    /// Playback `handle`'s share of the server's WAN uplink changed:
2417    /// another WAN playback started or ended, or the budget
2418    /// changed. A playback in `Quality::Auto` re-plans with
2419    /// `ChangeQuality` at its position (the SDK's managed playback does
2420    /// it by itself); `max_bitrate` is the new cap, `None` none. Sent only
2421    /// for a move of 15% or more, a few seconds after the last start or
2422    /// end. One of another quality may ignore it.
2423    PlaybackShare {
2424        handle: PlaybackHandle,
2425        #[serde(deserialize_with = "spoolframe_types::required::option")]
2426        max_bitrate: Option<u64>,
2427    },
2428    /// A playlist the user sees was made or changed: its entries,
2429    /// name, kinds or sharing. Read it again if it is shown. Only to a
2430    /// client that listed `spoolframe:playlists`.
2431    PlaylistChanged { id: String, revision: u64 },
2432    /// A playlist the user saw is gone to them: deleted, or no longer
2433    /// shared with them. Close it if it is shown.
2434    PlaylistGone { id: String },
2435    /// The user's Pinned, or its notes, changed on another device or by
2436    /// another user's change: `ListPlaylists` again.
2437    PinsChanged,
2438    /// The user liked or unliked a track, on any device: a device
2439    /// that downloaded Liked asks what it holds now
2440    /// (`MusicDownloadChanges`). Only to the user's own connections that
2441    /// listed `spoolframe:music-downloads`.
2442    LikedChanged,
2443    /// Item `id`'s subtitle `track` is timed anew: synced, its
2444    /// sync done or set aside, or its offset changed, by anyone. What it
2445    /// is served with changed: a player showing it reads it again (a
2446    /// `ReadSubtitle` in progress answers `SubtitleChanged`), with no
2447    /// restart. Only to a client that listed `spoolframe:subtitle-sync`,
2448    /// on a connection that asked for the item's `Tracks` or plays it.
2449    SubtitleTimingChanged {
2450        id: MediaId,
2451        track: u32,
2452        timing: spoolframe_types::SubtitleTiming,
2453    },
2454    /// Download `id`'s state moved: `waiting`, then `converting`
2455    /// (told once per percent or every 2 s), `writing`, and `ready` or
2456    /// `failed`. Only to the connections of the user whose it is, that
2457    /// listed `spoolframe:downloads`.
2458    DownloadChanged {
2459        id: String,
2460        state: crate::downloads::DownloadState,
2461    },
2462    /// Experimental (`federation`): the libraries changed: a paired
2463    /// server came online or went offline, or shared or stopped sharing a
2464    /// library. `Libraries` again. Only to a client that named the
2465    /// feature.
2466    LibrariesChanged,
2467    /// Experimental (`federation`): playback `handle`, of a paired
2468    /// server's item, ended other than by its client's stop: stopped by an
2469    /// admin, idle past the limit, its session or its grant ended, or, on
2470    /// the user's own server playing it on, ended where it plays from.
2471    /// `error` is what the client's next use of it is told
2472    /// (`PlaybackStopped`: do not start it again). Only for a play
2473    /// token's session's playbacks, and those played through the user's
2474    /// own server.
2475    PlaybackEnded {
2476        handle: PlaybackHandle,
2477        error: Error,
2478    },
2479    /// An event type this build does not know; ignore it.
2480    #[serde(other)]
2481    Unknown,
2482}
2483
2484/// Socket addresses on the wire as text (`192.168.1.10:4433`,
2485/// `[2001:db8::1]:4433`). CBOR is not a human-readable format to serde, so
2486/// a bare `SocketAddr` would go as serde's enum of byte tuples, which a
2487/// peer outside Rust would have to copy; text is also what JSON shows.
2488pub(crate) mod socket_addrs_as_text {
2489    use std::net::SocketAddr;
2490
2491    use serde::de::Error as _;
2492    use serde::{Deserialize, Deserializer, Serialize, Serializer};
2493
2494    pub fn serialize<S: Serializer>(addrs: &[SocketAddr], s: S) -> Result<S::Ok, S::Error> {
2495        let text: Vec<String> = addrs.iter().map(ToString::to_string).collect();
2496        text.serialize(s)
2497    }
2498
2499    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<SocketAddr>, D::Error> {
2500        Vec::<String>::deserialize(d)?
2501            .iter()
2502            .map(|text| {
2503                text.parse()
2504                    .map_err(|_| D::Error::custom(format!("not a socket address: {text:?}")))
2505            })
2506            .collect()
2507    }
2508}
2509
2510#[cfg(test)]
2511mod tests;