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