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