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