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