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 /// A request type this build does not know; answered with
1256 /// [`Error::Unsupported`].
1257 #[serde(other)]
1258 Unknown,
1259}
1260
1261/// Which episode `NextEpisode` finds after the one given.
1262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1263#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
1264#[serde(rename_all = "snake_case")]
1265pub enum NextMode {
1266 /// The one right after it.
1267 InOrder,
1268 /// The first after it the user has not watched.
1269 FirstUnwatched,
1270}
1271
1272impl Request {
1273 /// Served without a session.
1274 pub fn is_pre_auth(&self) -> bool {
1275 matches!(
1276 self,
1277 Request::Hello(_)
1278 | Request::AuthMethods
1279 | Request::LoginPassword(_)
1280 | Request::Ping
1281 | Request::BeginDeviceSignIn { .. }
1282 | Request::AwaitDeviceSignIn { .. }
1283 | Request::BeginPasskeySignIn { .. }
1284 | Request::FinishPasskeySignIn { .. }
1285 | Request::TrustedProfiles
1286 | Request::ResumeProfile { .. }
1287 | Request::RedeemInvite(_)
1288 | Request::BeginInvitePasskey(_)
1289 | Request::RedeemInviteWithPasskey(_)
1290 | Request::LookupInvite(_)
1291 | Request::BeginPortableSignIn
1292 | Request::FinishPortableSignIn(_)
1293 | Request::RedeemPortableInvite(_)
1294 | Request::IdentityRecord { .. }
1295 | Request::IdentityRecordByHandle { .. }
1296 | Request::OfferPairing(_)
1297 | Request::FetchPairing { .. }
1298 | Request::AnswerPairing { .. }
1299 | Request::CollectPairing { .. }
1300 | Request::RedeemPlayToken(_)
1301 )
1302 }
1303
1304 /// The feature it belongs to, if any: the server answers it only on a
1305 /// connection where that feature is on, and is `Unsupported`
1306 /// otherwise. Every request is named here, so a new one is given its
1307 /// feature, or none, on purpose.
1308 pub fn feature(&self) -> Option<Feature> {
1309 match self {
1310 Request::BeginInvitePasskey(_) => Some(Feature::October2026),
1311 Request::RedeemInviteWithPasskey(_) => Some(Feature::October2026),
1312 Request::NextEpisode { .. } | Request::ShowNext { .. } => Some(Feature::October2026),
1313 Request::Hello { .. }
1314 | Request::AuthMethods
1315 | Request::LoginPassword { .. }
1316 | Request::Ping
1317 | Request::ActivateProfile
1318 | Request::PlaybackProgressSequence { .. }
1319 | Request::BeginDeviceSignIn { .. }
1320 | Request::AwaitDeviceSignIn { .. }
1321 | Request::BeginPasskeySignIn { .. }
1322 | Request::FinishPasskeySignIn { .. }
1323 | Request::TrustedProfiles
1324 | Request::ResumeProfile { .. }
1325 | Request::RedeemInvite { .. }
1326 | Request::LookupInvite { .. }
1327 | Request::BeginPortableSignIn
1328 | Request::FinishPortableSignIn { .. }
1329 | Request::RedeemPortableInvite { .. }
1330 | Request::IdentityRecord { .. }
1331 | Request::IdentityRecordByHandle { .. }
1332 | Request::OfferPairing { .. }
1333 | Request::FetchPairing { .. }
1334 | Request::AnswerPairing { .. }
1335 | Request::CollectPairing { .. }
1336 | Request::Libraries
1337 | Request::Items { .. }
1338 | Request::ItemFilterValues { .. }
1339 | Request::Item { .. }
1340 | Request::Search { .. }
1341 | Request::PersonItems { .. }
1342 | Request::Tracks { .. }
1343 | Request::WhoAmI
1344 | Request::Logout
1345 | Request::ListSessions
1346 | Request::PlaybackPlan { .. }
1347 | Request::StartPlayback { .. }
1348 | Request::StopPlayback { .. }
1349 | Request::PlaybackRevision { .. }
1350 | Request::SeekPlayback { .. }
1351 | Request::SetPin { .. }
1352 | Request::ClearPin { .. }
1353 | Request::UnlockProfile { .. }
1354 | Request::ListDevices
1355 | Request::BeginPasskeyRegistration
1356 | Request::FinishPasskeyRegistration { .. }
1357 | Request::ListPasskeys
1358 | Request::RenamePasskey { .. }
1359 | Request::RemovePasskey { .. }
1360 | Request::ConfirmPassword { .. }
1361 | Request::ChangePassword { .. }
1362 | Request::BeginConfirmPasskey
1363 | Request::FinishConfirmPasskey { .. }
1364 | Request::GetPlexLink
1365 | Request::SetPinRequired { .. }
1366 | Request::LookupDeviceSignIn { .. }
1367 | Request::ApproveDeviceSignIn { .. }
1368 | Request::SetDeviceTrust { .. }
1369 | Request::ForgetDevice { .. }
1370 | Request::DenyDeviceSignIn { .. }
1371 | Request::ChangeSubtitle { .. }
1372 | Request::ChangeQuality { .. }
1373 | Request::GetManifest { .. }
1374 | Request::ReadSubtitle { .. }
1375 | Request::ReadSubtitleSegment { .. }
1376 | Request::GetPreviews { .. }
1377 | Request::UpdatePlaybackProgress { .. }
1378 | Request::UpdateWatchProgress { .. }
1379 | Request::MarkWatched { .. }
1380 | Request::MarkUnwatched { .. }
1381 | Request::HideFromContinueWatching { .. }
1382 | Request::UnhideFromContinueWatching { .. }
1383 | Request::Home
1384 | Request::GetTrackPreferences
1385 | Request::SetTrackPreferences { .. }
1386 | Request::SetTrackOverride { .. }
1387 | Request::ClearTrackOverride { .. }
1388 | Request::TieBegin
1389 | Request::TieFinish { .. }
1390 | Request::Untie { .. }
1391 | Request::CreateInvite { .. }
1392 | Request::ListInvites
1393 | Request::RevokeInvite { .. }
1394 | Request::HttpPlaybackUrl { .. }
1395 | Request::PairServer { .. }
1396 | Request::ShareLibraries { .. }
1397 | Request::SetServerRow { .. }
1398 | Request::RedeemPlayToken { .. }
1399 | Request::RemoteHints { .. }
1400 | Request::RemoteGrant { .. }
1401 | Request::SetPlayFrom { .. }
1402 | Request::LeaveServer
1403 | Request::ListPlaylists
1404 | Request::GetPlaylist { .. }
1405 | Request::CreatePlaylist { .. }
1406 | Request::UpdatePlaylist { .. }
1407 | Request::EditPlaylist { .. }
1408 | Request::DeletePlaylist { .. }
1409 | Request::PinPlaylist { .. }
1410 | Request::UnpinPlaylist { .. }
1411 | Request::PlayPlaylist { .. }
1412 | Request::NextInPlaylist { .. }
1413 | Request::UpcomingInPlaylist { .. }
1414 | Request::SetPlaylistSettings { .. }
1415 | Request::ImportPlexPlaylists { .. }
1416 | Request::DismissPinNotes
1417 | Request::Like { .. }
1418 | Request::Unlike { .. }
1419 | Request::ListShareCandidates { .. }
1420 | Request::RecentlyPlayed { .. }
1421 | Request::RemovePlaylistArt { .. }
1422 | Request::SyncSubtitle { .. }
1423 | Request::UseOriginalSubtitleTiming { .. }
1424 | Request::SetSubtitleOffset { .. }
1425 | Request::SearchSubtitles { .. }
1426 | Request::DownloadSubtitle { .. }
1427 | Request::RemoveSubtitleDownload { .. }
1428 | Request::DownloadOptions { .. }
1429 | Request::PrepareDownload { .. }
1430 | Request::DownloadStatus { .. }
1431 | Request::CancelDownload { .. }
1432 | Request::SyncOfflineWatch { .. }
1433 | Request::MusicDownloadChanges { .. }
1434 | Request::SyncOfflinePlays { .. }
1435 | Request::Unknown => None,
1436 }
1437 }
1438}
1439
1440/// The most characters the server keeps of each of `Hello`'s strings:
1441/// `client_name`, `client_version` and `device_name`. It cuts a
1442/// longer one to this many, and keeps and shows only that.
1443pub const MAX_HELLO_TEXT: usize = 128;
1444
1445/// The client introduces itself. Every field is required. Each
1446/// string is cut to [`MAX_HELLO_TEXT`] characters.
1447#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1448pub struct Hello {
1449 pub protocol_version: u32,
1450 /// e.g. `spoolframe-linux`.
1451 pub client_name: String,
1452 pub client_version: String,
1453 /// What kind of client this is: the server keeps it for the device, for
1454 /// its device and session lists. Not taken from `client_name`, which
1455 /// one app may share across platforms.
1456 pub platform: Platform,
1457 /// What the device calls itself (a hostname, "Living room TV"); shown
1458 /// in session lists. `None` when it has no name to give.
1459 #[serde(deserialize_with = "spoolframe_types::required::option")]
1460 pub device_name: Option<String>,
1461 /// What this device can play. `None`: every playback plan is
1462 /// `Unsupported`.
1463 #[serde(deserialize_with = "spoolframe_types::required::option")]
1464 pub capabilities: Option<ClientCapabilities>,
1465 /// The experimental features this client wants, by name
1466 /// ([`crate::experimental`]); the server's answer names those it
1467 /// turned on. Left out when empty, so a client that wants none sends
1468 /// what an older one did; an older server ignores it.
1469 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1470 pub experimental: Vec<String>,
1471 /// The regular features this client handles ([`crate::features`]);
1472 /// the server's answer names those of them it has. Left out when
1473 /// empty, as an older client does; an older server ignores it.
1474 #[serde(
1475 default,
1476 with = "crate::features::names",
1477 skip_serializing_if = "Features::is_empty"
1478 )]
1479 pub features: Features,
1480 /// The device's language, as BCP 47 (`en-US`): what a saved `device`
1481 /// in track preferences stands for. It chooses nothing by itself.
1482 /// Left out when the app says nothing, as an older client does; an
1483 /// older server ignores it.
1484 #[serde(default, skip_serializing_if = "Option::is_none")]
1485 pub language: Option<String>,
1486}
1487
1488/// `text` cut to [`MAX_HELLO_TEXT`] characters: what a server keeps of a
1489/// device's strings, and a device of an invite link's name.
1490pub(crate) fn cut(text: &mut String) {
1491 if let Some((at, _)) = text.char_indices().nth(MAX_HELLO_TEXT) {
1492 text.truncate(at);
1493 }
1494}
1495
1496impl Hello {
1497 /// This `Hello` with each string cut to [`MAX_HELLO_TEXT`] characters:
1498 /// what a server keeps of it.
1499 pub fn within_bounds(mut self) -> Self {
1500 cut(&mut self.client_name);
1501 cut(&mut self.client_version);
1502 if let Some(name) = &mut self.device_name {
1503 cut(name);
1504 }
1505 if let Some(language) = &mut self.language {
1506 cut(language);
1507 }
1508 self.experimental.truncate(crate::experimental::MAX_ASKED);
1509 for name in &mut self.experimental {
1510 cut(name);
1511 }
1512 self
1513 }
1514}
1515
1516#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1517pub struct LoginPassword {
1518 pub username: String,
1519 pub password: String,
1520 /// Trust this device for the user: it may resume them later
1521 /// without a password (`ResumeProfile`). Never true unless the user
1522 /// ticked "Remember this device".
1523 pub remember: bool,
1524}
1525
1526impl fmt::Debug for LoginPassword {
1527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1528 f.debug_struct("LoginPassword")
1529 .field("username", &self.username)
1530 .field("password", &"<redacted>")
1531 .field("remember", &self.remember)
1532 .finish()
1533 }
1534}
1535
1536/// An invite's code and the account to make with it (`RedeemInvite`).
1537/// `code` as the link carries it ([`crate::invite::Invite::code`]);
1538/// any case, dashes or spaces are taken.
1539#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1540pub struct RedeemInvite {
1541 pub code: String,
1542 pub username: String,
1543 /// What to show for them; the username when `None`.
1544 #[serde(deserialize_with = "spoolframe_types::required::option")]
1545 pub display_name: Option<String>,
1546 pub password: String,
1547}
1548
1549impl fmt::Debug for RedeemInvite {
1550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1551 f.debug_struct("RedeemInvite")
1552 .field("code", &"<redacted>")
1553 .field("username", &self.username)
1554 .field("display_name", &self.display_name)
1555 .field("password", &"<redacted>")
1556 .finish()
1557 }
1558}
1559
1560/// An invite's code and the account to make with it and a passkey
1561/// (`BeginInvitePasskey`).
1562#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1563pub struct BeginInvitePasskey {
1564 pub code: String,
1565 pub username: String,
1566 /// What to show for them; the username when `None`.
1567 #[serde(deserialize_with = "spoolframe_types::required::option")]
1568 pub display_name: Option<String>,
1569}
1570
1571impl fmt::Debug for BeginInvitePasskey {
1572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1573 f.debug_struct("BeginInvitePasskey")
1574 .field("code", &"<redacted>")
1575 .field("username", &self.username)
1576 .field("display_name", &self.display_name)
1577 .finish()
1578 }
1579}
1580
1581/// The invite's code again, and the passkey made for the account
1582/// (`RedeemInviteWithPasskey`).
1583#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1584pub struct RedeemInviteWithPasskey {
1585 pub code: String,
1586 pub finish: FinishPasskeyRegistration,
1587 /// Trust this device for the new user, as `LoginPassword`'s.
1588 pub remember: bool,
1589}
1590
1591impl fmt::Debug for RedeemInviteWithPasskey {
1592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1593 f.debug_struct("RedeemInviteWithPasskey")
1594 .field("code", &"<redacted>")
1595 .field("finish", &self.finish)
1596 .field("remember", &self.remember)
1597 .finish()
1598 }
1599}
1600
1601/// An invite's code to look up (`LookupInvite`): as `RedeemInvite` takes
1602/// it, in any case, with dashes or spaces.
1603#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1604pub struct LookupInvite {
1605 pub code: String,
1606}
1607
1608impl fmt::Debug for LookupInvite {
1609 // The code is a capability until it is used up: keep it out of logs.
1610 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1611 f.write_str("LookupInvite { code: <redacted> }")
1612 }
1613}
1614
1615/// What an invite's code is (`InviteLookup`). Looking never uses it up.
1616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1617#[serde(tag = "type", rename_all = "snake_case")]
1618pub enum InviteLookupOutcome {
1619 /// It can be redeemed now: `kind` says how (`RedeemInvite` or
1620 /// `RedeemPortableInvite`), and a `create-user` one makes an account
1621 /// with `role`.
1622 Valid {
1623 kind: crate::invite_admin::InviteKind,
1624 /// `consumer` for a `portable-account` one.
1625 role: Role,
1626 /// Unix seconds.
1627 expires_at: i64,
1628 /// The display name of the admin who made it; `None` when they
1629 /// have none, or when the server's CLI made it.
1630 #[serde(deserialize_with = "spoolframe_types::required::option")]
1631 inviter: Option<String>,
1632 /// A `federation` one's: the fingerprint of the key this
1633 /// server pairs with, for the admin about to redeem it on another
1634 /// server to compare. Left out for every other kind, and by an
1635 /// older server.
1636 #[serde(default, skip_serializing_if = "Option::is_none")]
1637 fingerprint: Option<String>,
1638 },
1639 /// It expired at `at`, Unix seconds.
1640 Expired { at: i64 },
1641 /// Every use it had is used.
1642 Used,
1643 /// An admin revoked it.
1644 Revoked,
1645 /// No invite has this code: counted as a wrong guess.
1646 NoMatch,
1647 /// An outcome this build does not know, from a newer server.
1648 #[serde(other)]
1649 Unknown,
1650}
1651
1652/// The most identity states a portable sign-in carries.
1653pub const MAX_SIGN_IN_STATES: usize = 2;
1654
1655/// A portable user's device proving itself (`FinishPortableSignIn`):
1656/// the credential their root gave the device's key, and that
1657/// key's signature over this server's nonce.
1658#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1659pub struct PortableSignIn {
1660 pub credential: UserDeviceCredential,
1661 /// The device key's signature over
1662 /// [`crate::portable::device_proof_message`] of the server's endpoint
1663 /// id and the nonce `BeginPortableSignIn` gave.
1664 #[serde(with = "signature_hex")]
1665 pub proof: ed25519_dalek::Signature,
1666 /// The identity's states the device has, newest last, at most
1667 /// [`MAX_SIGN_IN_STATES`]: the server takes them in before it checks
1668 /// the credential, so a device carries revocations to servers
1669 /// it signs in to.
1670 pub states: Vec<PortableIdentityState>,
1671 /// What they would be called here, for a grant made with this
1672 /// sign-in (a portable-account invite); a grant there already keeps
1673 /// its name.
1674 #[serde(deserialize_with = "spoolframe_types::required::option")]
1675 pub display_name: Option<String>,
1676}
1677
1678/// A `portable-account` invite's code and the portable user redeeming it
1679/// (`RedeemPortableInvite`).
1680#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1681pub struct RedeemPortableInvite {
1682 pub code: String,
1683 pub sign_in: PortableSignIn,
1684}
1685
1686impl fmt::Debug for RedeemPortableInvite {
1687 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1688 f.debug_struct("RedeemPortableInvite")
1689 .field("code", &"<redacted>")
1690 .field("sign_in", &self.sign_in)
1691 .finish()
1692 }
1693}
1694
1695/// The account password, to confirm it is the session user
1696/// (`ConfirmPassword`).
1697#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1698pub struct ConfirmPassword {
1699 pub password: String,
1700}
1701
1702impl fmt::Debug for ConfirmPassword {
1703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1704 f.debug_struct("ConfirmPassword")
1705 .field("password", &"<redacted>")
1706 .finish()
1707 }
1708}
1709
1710/// The session user's password and the one to replace it with
1711/// (`ChangePassword`).
1712#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1713pub struct ChangePassword {
1714 pub current_password: String,
1715 pub new_password: String,
1716}
1717
1718impl fmt::Debug for ChangePassword {
1719 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1720 f.write_str("ChangePassword { <redacted> }")
1721 }
1722}
1723
1724/// What proves a PIN change or removal is the user's: the PIN
1725/// they have, or, when it is forgotten, their account password.
1726#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1727#[serde(tag = "type", rename_all = "snake_case")]
1728pub enum PinProof {
1729 /// The current PIN, checked as `UnlockProfile` checks it: a wrong one
1730 /// counts towards the same limit (`InvalidCredentials`, then
1731 /// `RateLimited`) and the same count of wrong PINs in a row; the 10th
1732 /// revokes the session on this device (`Unauthenticated`). Checking it
1733 /// unlocks nothing. A user with no PIN passes any.
1734 Pin { pin: String },
1735 /// The account password, checked as `LoginPassword` checks it: a wrong
1736 /// one is a failed sign-in for this username from this device
1737 /// (`InvalidCredentials`, then `RateLimited`, one limit with
1738 /// `LoginPassword`). It never revokes the session and never touches
1739 /// the PIN's limit. A user with no password (passkeys or SSO only) gets
1740 /// `NoPassword`: the PIN proof, or the web UI, is theirs.
1741 Password { password: String },
1742}
1743
1744impl fmt::Debug for PinProof {
1745 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1746 let kind = match self {
1747 PinProof::Pin { .. } => "Pin",
1748 PinProof::Password { .. } => "Password",
1749 };
1750 write!(f, "PinProof::{kind}(<redacted>)")
1751 }
1752}
1753
1754/// The session user's track preferences (`GetTrackPreferences`), and
1755/// whether this server reads picture subtitles as text.
1756#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1757#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
1758pub struct TrackPreferencesInfo {
1759 pub preferences: TrackPreferences,
1760 /// The server reads picture subtitles as text: `subtitles.ocr` is on
1761 /// and tesseract has at least one language. When false,
1762 /// `preferences.subtitles.bitmap` has no effect, and apps show that
1763 /// choice disabled.
1764 pub ocr_offered: bool,
1765}
1766
1767/// How a user can log in to this server.
1768#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1769#[serde(rename_all = "snake_case")]
1770pub enum AuthMethod {
1771 Password,
1772 /// Approval on another signed-in device: `BeginDeviceSignIn`.
1773 DeviceApproval,
1774 /// A method this build does not know.
1775 #[serde(other)]
1776 Unknown,
1777}
1778
1779/// The answer to one request.
1780#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1781#[serde(rename_all = "snake_case")]
1782#[expect(
1783 clippy::large_enum_variant,
1784 reason = "built once per request and encoded at once; boxing would only add noise"
1785)]
1786pub enum Response {
1787 Ok(Reply),
1788 Err(Error),
1789}
1790
1791impl From<Result<Reply, Error>> for Response {
1792 fn from(result: Result<Reply, Error>) -> Self {
1793 match result {
1794 Ok(reply) => Response::Ok(reply),
1795 Err(error) => Response::Err(error),
1796 }
1797 }
1798}
1799
1800impl From<Response> for Result<Reply, Error> {
1801 fn from(response: Response) -> Self {
1802 match response {
1803 Response::Ok(reply) => Ok(reply),
1804 Response::Err(error) => Err(error),
1805 }
1806 }
1807}
1808
1809#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1810#[serde(tag = "type", rename_all = "snake_case")]
1811pub enum Reply {
1812 PlaybackProgressSequence {
1813 sequence: u64,
1814 },
1815 ServerInfo(ServerInfo),
1816 AuthMethods {
1817 methods: Vec<AuthMethod>,
1818 },
1819 LoggedIn {
1820 session: SessionId,
1821 /// This device is trusted for the session's user after it:
1822 /// the sign-in asked to be remembered and it was (by the
1823 /// approver too, for a device sign-in), or the device already was.
1824 remembered: bool,
1825 /// The password was a one-time one an admin reset to: show "Choose
1826 /// a new password" and send `ChangePassword` (its current password
1827 /// is the one-time one). Until then the session gets
1828 /// `PasswordChangeRequired` for anything else but `Logout` and
1829 /// `WhoAmI`, and the device is not trusted.
1830 password_change_required: bool,
1831 },
1832 /// The users this device is trusted for (`TrustedProfiles`), by
1833 /// username.
1834 TrustedProfiles {
1835 profiles: Vec<TrustedProfile>,
1836 },
1837 Pong,
1838 /// A device sign-in is pending. Show `code` (see
1839 /// [`crate::device_sign_in::display`]); keep `request` to await it.
1840 DeviceSignInStarted {
1841 request: String,
1842 code: String,
1843 expires_in_ms: u64,
1844 /// Where a browser approves it
1845 /// ([`crate::device_sign_in::web_link`]), for a QR code a phone's
1846 /// camera opens; `None` if the server's web UI has no public URL.
1847 web_url: Option<String>,
1848 },
1849 /// Not approved yet: `AwaitDeviceSignIn` again.
1850 DeviceSignInPending,
1851 /// What an invite's code is (`LookupInvite`).
1852 InviteLookup {
1853 outcome: InviteLookupOutcome,
1854 },
1855 /// The device a sign-in code belongs to.
1856 DeviceSignInRequest(DeviceSignInRequest),
1857 Libraries {
1858 libraries: Vec<Library>,
1859 },
1860 /// What a library can be sorted and filtered by (`ItemFilterValues`).
1861 ItemFilterValues {
1862 values: spoolframe_types::ItemFilterValues,
1863 },
1864 Items {
1865 items: Vec<Item>,
1866 total: u32,
1867 /// Experimental (`federation`): the items listed that are
1868 /// no longer available, their paired server unpaired or their
1869 /// library no longer shared (`RecentlyPlayed`): shown as such, and
1870 /// not played. Only to a client that named the feature; left out
1871 /// when empty, as experimental fields are.
1872 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1873 unavailable: Vec<MediaId>,
1874 },
1875 Item {
1876 item: Item,
1877 children: Vec<Item>,
1878 /// The item's intro and credits, in order of start; empty
1879 /// for an item that has none.
1880 markers: Markers,
1881 /// The playlists the user sees that hold it: a movie,
1882 /// episode or track itself; any of a season's or a show's
1883 /// episodes; any of an album's or an artist's tracks. Empty when
1884 /// none does.
1885 playlists: Vec<PlaylistRef>,
1886 /// Its heart: a track's `all` or `none`; an album's
1887 /// `all`, `some` or `none` by the tracks it has now. `None` for
1888 /// any other item.
1889 #[serde(deserialize_with = "spoolframe_types::required::option")]
1890 liked: Option<crate::playlists::Liked>,
1891 /// An album's tracks among `children` that are liked,
1892 /// for their hearts. Empty for any other item.
1893 liked_children: Vec<MediaId>,
1894 /// Experimental (`federation`): where the item is from, its
1895 /// title's copies on other servers and the one that plays, as a
1896 /// `SearchHit` has them. Only to a client that named the feature.
1897 #[serde(default, skip_serializing_if = "Option::is_none")]
1898 copies: Option<crate::search::Copies>,
1899 },
1900 Search(SearchResults),
1901 /// Experimental (`federation`): `Search`'s answer to a client
1902 /// that named the feature, each item a `SearchHit`. Counts are
1903 /// approximate: a title on several servers is counted once only among
1904 /// what is shown.
1905 SearchHits(SearchResults<crate::search::SearchHit>),
1906 Tracks(MediaTracks),
1907 /// What `NextEpisode` and `ShowNext` found: `None` when there is
1908 /// nothing to play.
1909 NextEpisode {
1910 #[serde(deserialize_with = "spoolframe_types::required::option")]
1911 item: Option<Item>,
1912 },
1913 WhoAmI(WhoAmIReply),
1914 LoggedOut,
1915 Sessions {
1916 sessions: Vec<SessionInfo>,
1917 },
1918 PlaybackPlan {
1919 plan: PlaybackPlan,
1920 /// The tracks the server chose, when the request had no selection.
1921 #[serde(deserialize_with = "spoolframe_types::required::option")]
1922 chosen: Option<ChosenTracks>,
1923 },
1924 PlaybackStarted {
1925 handle: PlaybackHandle,
1926 /// How the server plays it: direct, or converted.
1927 plan: PlaybackPlan,
1928 /// The size of the file the handle reads.
1929 size: u64,
1930 /// The tracks the server chose, when the request had no selection.
1931 #[serde(deserialize_with = "spoolframe_types::required::option")]
1932 chosen: Option<ChosenTracks>,
1933 /// The encode reads name; 0 for direct play.
1934 epoch: u32,
1935 /// The item's intro and credits, as in `Item`, so a player needs
1936 /// no second request for them. Their times are the item's own,
1937 /// wherever the playback starts.
1938 markers: Markers,
1939 /// The item's running time, when the server knows it, so a player
1940 /// needs no second request for it either. Absent from an older
1941 /// server's reply. `duration_ms` on the wire.
1942 #[serde(
1943 default,
1944 rename = "duration_ms",
1945 with = "spoolframe_types::serde_time::millis::option"
1946 )]
1947 duration: Option<std::time::Duration>,
1948 /// Whether this server counts the device off its LAN (PX-46): its
1949 /// verdict on the path it goes by, from `network.lan_prefixes` and
1950 /// `network.wan_prefixes` too, which the device cannot see. Absent
1951 /// from an older server's reply.
1952 #[serde(default, skip_serializing_if = "Option::is_none")]
1953 wan: Option<bool>,
1954 },
1955 /// A seek restarted the encode: reads name this epoch from offset 0.
1956 PlaybackSeeked {
1957 epoch: u32,
1958 },
1959 PlaybackRevision {
1960 revision: u64,
1961 },
1962 /// The session user's devices, most recently seen first.
1963 Devices {
1964 devices: Vec<DeviceInfo>,
1965 },
1966 /// The session user's Plex link; `None`: not linked (or the server
1967 /// links no Plex accounts).
1968 PlexLink {
1969 link: Option<PlexLink>,
1970 },
1971 /// The playback's new plan after `ChangeSubtitle` or `ChangeQuality`:
1972 /// read `epoch` (0 for direct play), whose size is `size` (0 while a
1973 /// conversion writes it).
1974 PlaybackChanged {
1975 plan: PlaybackPlan,
1976 size: u64,
1977 epoch: u32,
1978 /// As `PlaybackStarted`'s, as this re-plan was made.
1979 #[serde(default, skip_serializing_if = "Option::is_none")]
1980 wan: Option<bool>,
1981 },
1982 /// An HLS playlist, as text.
1983 Manifest {
1984 text: String,
1985 },
1986 /// A segment of a subtitle rendition, whole (`ReadSubtitleSegment`).
1987 Subtitle {
1988 format: SubtitleFormat,
1989 #[serde(with = "serde_bytes")]
1990 bytes: Vec<u8>,
1991 },
1992 /// The chunk of a subtitle file that `ReadSubtitle` asked for.
1993 SubtitleChunk {
1994 format: SubtitleFormat,
1995 #[serde(with = "serde_bytes")]
1996 bytes: Vec<u8>,
1997 /// The whole file's length.
1998 total: u64,
1999 /// The file these bytes are of. It is another value once the file
2000 /// is written again or replaced, and means nothing else to a
2001 /// client: send it back with the next `ReadSubtitle`.
2002 version: u64,
2003 },
2004 /// The request was carried out; there is nothing to return.
2005 Done,
2006 /// The session user confirmed it is them (`ConfirmPassword`,
2007 /// `FinishConfirmPasskey`): this session counts as signed in now.
2008 Confirmed,
2009 Home(HomeScreen),
2010 TrackPreferences(TrackPreferencesInfo),
2011 /// An item's frame previews (`GetPreviews`).
2012 Previews(Previews),
2013 /// What the platform makes an app passkey with, but the challenge:
2014 /// the nonce it is made from (`BeginPasskeyRegistration`).
2015 PasskeyRegistrationBegun(PasskeyRegistrationBegun),
2016 /// What the platform signs in with an app passkey with, but the
2017 /// challenge: the nonce it is made from (`BeginPasskeySignIn`,
2018 /// `BeginConfirmPasskey`).
2019 PasskeySignInBegun(PasskeySignInBegun),
2020 /// The session user's passkeys (`ListPasskeys`).
2021 Passkeys {
2022 passkeys: Vec<PasskeyInfo>,
2023 },
2024 /// What a portable identity signs to tie the session user's account
2025 /// to it (`TieBegin`).
2026 TieChallenge {
2027 /// Used once, for `expires_in_secs`, by this session.
2028 #[serde(with = "serde_bytes")]
2029 nonce: [u8; 32],
2030 /// This server's endpoint id, as the tie message names it. A
2031 /// client signs with the id it dialled, never this one: the field
2032 /// says which server meant to ask.
2033 #[serde(with = "serde_bytes")]
2034 server: [u8; 32],
2035 expires_in_secs: u64,
2036 },
2037 /// What a portable user's device signs to sign in
2038 /// (`BeginPortableSignIn`).
2039 PortableSignInBegun {
2040 /// Used once, for `expires_in_secs`, by this device.
2041 #[serde(with = "serde_bytes")]
2042 nonce: [u8; 32],
2043 expires_in_secs: u64,
2044 },
2045 /// A new invite, with its code (`CreateInvite`).
2046 InviteCreated(InviteCreated),
2047 /// What the server keeps of a portable identity (`IdentityRecord`).
2048 IdentityRecord(IdentityRecord),
2049 /// The pairing request held under a code (`FetchPairing`).
2050 PairingOffered(PairingOffer),
2051 /// The answer to a device's pairing request, or `None` while none
2052 /// came yet (`CollectPairing`).
2053 PairingAnswered {
2054 answer: Option<PairingAnswer>,
2055 },
2056 /// The invites that can still be redeemed (`ListInvites`).
2057 Invites {
2058 invites: Vec<InviteSummary>,
2059 },
2060 /// Experimental (`http-playback`): where a player with no Iroh
2061 /// fetches the playback (`HttpPlaybackUrl`).
2062 HttpPlaybackUrl {
2063 url: String,
2064 },
2065 /// Experimental (`http-playback`): why `HttpPlaybackUrl` gave
2066 /// no URL.
2067 HttpPlaybackRefused {
2068 reason: crate::experimental::HttpPlaybackRefusal,
2069 },
2070 /// Experimental (`federation`): the server paired
2071 /// (`PairServer`).
2072 ServerPaired {
2073 server: crate::federation::PeerServer,
2074 },
2075 /// Experimental (`federation`): the libraries shared with the
2076 /// paired server (`ShareLibraries`), as asked.
2077 LibrariesShared {
2078 libraries: Vec<spoolframe_types::LibraryId>,
2079 },
2080 /// Experimental (`federation`): the session a play token
2081 /// opened (`RedeemPlayToken`).
2082 PlayTokenRedeemed(crate::federation::PlayTokenRedeemed),
2083 /// Experimental (`federation`): where a paired server is
2084 /// (`RemoteHints`).
2085 RemoteHints(crate::federation::RemoteHints),
2086 /// Experimental (`federation`): a paired server's play token
2087 /// for this device (`RemoteGrant`).
2088 RemoteGranted(crate::federation::RemoteGranted),
2089 /// The playlists the user sees (`ListPlaylists`), oldest first,
2090 /// and the notes of pinned ones that left their Pinned.
2091 Playlists {
2092 playlists: Vec<PlaylistSummary>,
2093 pin_notes: Vec<PinNote>,
2094 },
2095 /// One playlist and a page of its entries (`GetPlaylist`).
2096 Playlist(PlaylistPage),
2097 /// A playlist as it is now (`CreatePlaylist`, `UpdatePlaylist`).
2098 PlaylistInfo(PlaylistSummary),
2099 /// A subtitle track's timing after `SyncSubtitle`,
2100 /// `UseOriginalSubtitleTiming` or `SetSubtitleOffset`.
2101 SubtitleTiming(spoolframe_types::SubtitleTiming),
2102 /// What `SearchSubtitles` found.
2103 SubtitleResults(spoolframe_types::SubtitleSearch),
2104 /// The track `DownloadSubtitle` added.
2105 SubtitleDownloaded(spoolframe_types::SubtitleDownloaded),
2106 /// The playlist's revision after `EditPlaylist`, and the entries its
2107 /// adds made, in the edits' order (a show's add makes one an
2108 /// episode). `None` only from a server older than the field, which
2109 /// leaves it out.
2110 PlaylistEdited {
2111 revision: u64,
2112 #[serde(default, skip_serializing_if = "Option::is_none")]
2113 added: Option<Vec<crate::playlists::EntryId>>,
2114 },
2115 /// The entry to play now (`PlayPlaylist`, `NextInPlaylist`).
2116 PlaylistItem(crate::playlists::PlaylistNext),
2117 /// Nothing is left to play: the end, with repeat off, or no entry can
2118 /// be played. The user's place is cleared.
2119 PlaylistFinished,
2120 /// What plays next in a playlist (`UpcomingInPlaylist`), in turn.
2121 PlaylistUpcoming {
2122 entries: Vec<crate::playlists::PlaylistEntry>,
2123 },
2124 /// What importing Plex playlists made, or would (`ImportPlexPlaylists`).
2125 PlexImport(crate::playlists::PlexImport),
2126 /// Whom a playlist can be shared with (`ListShareCandidates`).
2127 ShareCandidates(crate::playlists::ShareCandidatePage),
2128 /// What the device may download of an item (`DownloadOptions`).
2129 DownloadOptions(crate::downloads::DownloadOptionsInfo),
2130 /// A download prepared (`PrepareDownload`).
2131 Download(crate::downloads::DownloadInfo),
2132 /// Downloads, in the order asked (`DownloadStatus`): each the user
2133 /// has, and the ids asked for that they have not. A device treats a
2134 /// gone download as cancelled: preparing it again brings it back.
2135 Downloads {
2136 downloads: Vec<crate::downloads::DownloadInfo>,
2137 /// Left out when empty.
2138 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2139 gone: Vec<String>,
2140 },
2141 /// What became of each offline entry, in order (`SyncOfflineWatch`).
2142 OfflineWatchSynced {
2143 outcomes: Vec<crate::downloads::OfflineWatchOutcome>,
2144 },
2145 /// What each followed thing holds (`MusicDownloadChanges`), and the
2146 /// cursor to ask with next.
2147 MusicDownloadChanges {
2148 changes: Vec<crate::downloads::FollowedChange>,
2149 cursor: String,
2150 },
2151 /// What became of each offline play and like, in order
2152 /// (`SyncOfflinePlays`).
2153 OfflinePlaysSynced {
2154 plays: Vec<crate::downloads::OfflineWatchOutcome>,
2155 liked: Vec<crate::downloads::OfflineWatchOutcome>,
2156 },
2157}
2158
2159/// Which HLS playlist.
2160#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2161#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2162#[serde(rename_all = "snake_case")]
2163pub enum ManifestKind {
2164 /// The top playlist, naming the variant.
2165 Multivariant,
2166 /// The variant's segments.
2167 Media,
2168 /// The subtitle rendition's WebVTT segments, read with
2169 /// `ReadSubtitleSegment`; there when the plan has a subtitle.
2170 Subtitles,
2171 #[serde(other)]
2172 Unknown,
2173}
2174
2175/// Rows for a home screen. Every item carries the user's playback state.
2176#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
2177#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2178pub struct HomeScreen {
2179 /// Started and not finished, most recent first.
2180 pub continue_watching: Vec<Item>,
2181 /// For each recently watched show, its next unwatched episode.
2182 pub next_up: Vec<Item>,
2183 pub recently_added: Vec<Item>,
2184 /// Experimental (`federation`): the items of these rows that
2185 /// are no longer available: their paired server unpaired, or stopped
2186 /// sharing their library. Shown as such, and not played. Only to a
2187 /// client that named the feature, as every `fed:` id is; left out when
2188 /// empty, as experimental fields are.
2189 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2190 pub unavailable: Vec<MediaId>,
2191 /// Experimental (`federation`): each paired server's own row,
2192 /// what it shared lately, by the server's name. A row the user turned
2193 /// off (`SetServerRow`) is listed with no items, for the setting. Left
2194 /// out when empty, as experimental fields are.
2195 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2196 pub servers: Vec<ServerRow>,
2197}
2198
2199/// A paired server's row on Home.
2200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2201#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2202pub struct ServerRow {
2203 pub server: spoolframe_types::LibraryServer,
2204 /// Whether the user shows it (`SetServerRow`); a row not shown has no
2205 /// items.
2206 pub shown: bool,
2207 /// What it shared most recently first, as this server cached it.
2208 pub items: Vec<Item>,
2209}
2210
2211/// A session's user.
2212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2213pub struct UserSummary {
2214 /// Opaque; stable for the user on this server (today `local:<uuid>`).
2215 /// A server that served `local:<number>` ids changes them once: a
2216 /// client that kept an id reads it again from `WhoAmI`.
2217 pub user_id: String,
2218 pub username: String,
2219 /// What to show; the username when the user has no display name.
2220 pub display_name: String,
2221 /// What the user may do.
2222 pub role: Role,
2223 /// The session needs the user's PIN on this connection before anything
2224 /// but `WhoAmI` and `UnlockProfile`.
2225 pub locked: bool,
2226 /// The user's PIN, if they have one: for "Set · 4 digits", and
2227 /// for how many boxes a PIN pad shows. Never the PIN itself.
2228 pub pin: Option<PinState>,
2229 /// The portable identities the account is tied to,
2230 /// the oldest tie first: shown on the account, never as other
2231 /// accounts. Empty for an account with none, and for a portable
2232 /// user's own session, whose identity is its `user_id`.
2233 pub portable: Vec<PortableTie>,
2234}
2235
2236impl UserSummary {
2237 /// The portable identity a guest's session is (`portable:<hex>`);
2238 /// `None` for an account of this server's own.
2239 pub fn portable_id(&self) -> Option<crate::portable::PortableUserId> {
2240 self.user_id.strip_prefix("portable:")?.parse().ok()
2241 }
2242
2243 /// The session is a portable identity's, a guest's, rather than an
2244 /// account of this server's own.
2245 pub fn is_guest(&self) -> bool {
2246 self.portable_id().is_some()
2247 }
2248}
2249
2250/// One of an account's ties to a portable identity.
2251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2252pub struct PortableTie {
2253 pub id: PortableUserId,
2254 /// Unix seconds.
2255 pub tied_at: i64,
2256 /// Unix seconds of the identity's last sign-in into the account with
2257 /// its credential; `None` until one.
2258 #[serde(deserialize_with = "spoolframe_types::required::option")]
2259 pub last_used_at: Option<i64>,
2260}
2261
2262/// What `WhoAmI` answers: the session's user, and whether they may leave
2263/// the server. On the wire the user's fields and `can_leave` sit in one
2264/// map, so a client that does not know `can_leave` reads it as a
2265/// [`UserSummary`].
2266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2267pub struct WhoAmIReply {
2268 #[serde(flatten)]
2269 pub user: UserSummary,
2270 /// `LeaveServer` would be done, not refused with `LastAdmin`:
2271 /// false for the last enabled admin, or the last enabled admin with a
2272 /// password, so an app can grey out "Leave this server" before it is
2273 /// asked. As of this answer: an admin made or demoted later changes
2274 /// it.
2275 pub can_leave: bool,
2276}
2277
2278/// A user's PIN as clients may know it.
2279#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2280#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2281pub struct PinState {
2282 /// How many digits it has (4 to 8); `None` for a PIN set before the
2283 /// server kept its length, until it is set again.
2284 pub digits: Option<u8>,
2285}
2286
2287/// A user a device is trusted for, as that device sees them.
2288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2289#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2290pub struct TrustedProfile {
2291 /// What `ResumeProfile` takes: `UserSummary::user_id`.
2292 pub user_id: String,
2293 /// To match the profile with one the device keeps by username.
2294 pub username: String,
2295 /// What to show; the username when the user has no display name.
2296 pub display_name: String,
2297 /// The user's PIN is asked for on this device: a resumed session
2298 /// starts locked.
2299 pub pin_required: bool,
2300 /// How many digits that PIN has (4 to 8), for the boxes a PIN pad
2301 /// shows. `None` when it is not asked for here, for a PIN set before
2302 /// the server kept its length (until it is set again), and from a
2303 /// server older than the field.
2304 #[serde(default)]
2305 pub pin_digits: Option<u8>,
2306 /// Open this profile at start, past "Who's watching". At most one per
2307 /// device.
2308 pub auto_login: bool,
2309}
2310
2311/// One of a user's devices.
2312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2313#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2314pub struct DeviceInfo {
2315 /// Hex `EndpointId`: what `SetPinRequired { device }` takes.
2316 pub endpoint_id: String,
2317 /// What the device calls itself.
2318 #[serde(deserialize_with = "spoolframe_types::required::option")]
2319 pub name: Option<String>,
2320 /// What kind of client it runs, as its `Hello` said; `None` for a
2321 /// device not seen since before the server kept it.
2322 pub platform: Option<Platform>,
2323 /// Unix seconds on the wire.
2324 #[serde(with = "spoolframe_types::serde_time::unix_seconds")]
2325 pub last_seen_at: std::time::SystemTime,
2326 /// The user's PIN is asked for on it.
2327 pub pin_required: bool,
2328 /// It may resume the user without a password.
2329 pub trusted: bool,
2330 /// It opens the user's profile at start.
2331 pub auto_login: bool,
2332 /// The device this request came from.
2333 pub this_device: bool,
2334}
2335
2336/// A device waiting to be signed in, as the approver sees it.
2337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2338#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2339pub struct DeviceSignInRequest {
2340 /// What the device calls itself (from its `Hello`).
2341 #[serde(deserialize_with = "spoolframe_types::required::option")]
2342 pub device_name: Option<String>,
2343 /// Its app, e.g. `spoolframe-tvos`.
2344 pub client_name: String,
2345 /// What kind of client it runs, as its `Hello` said: shown beside its
2346 /// name ([`Platform::label`], "Apple TV app"), so the approver knows
2347 /// which device asks.
2348 pub platform: Platform,
2349 /// Unix seconds on the wire.
2350 #[serde(with = "spoolframe_types::serde_time::unix_seconds")]
2351 pub requested_at: std::time::SystemTime,
2352 /// The device asked to be remembered: the approval says "This
2353 /// device will be remembered", ticked, and the approver may untick it.
2354 pub remember: bool,
2355 /// Where the device's `BeginDeviceSignIn` came from, as the server saw
2356 /// it: the one thing on this screen an attacker who
2357 /// sent the approver a code cannot choose. `None` if the server could
2358 /// not tell. The approval shows it, "The TV asked from 192.168.86.20.",
2359 /// and for [`AddressNetwork::Internet`] warns instead: the device is
2360 /// not on the approver's network, so approve only one you can see.
2361 #[serde(deserialize_with = "spoolframe_types::required::option")]
2362 pub requested_from: Option<DeviceAddress>,
2363}
2364
2365/// An address a device reached the server from.
2366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2367#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
2368pub struct DeviceAddress {
2369 /// Its IP address as text: `192.168.86.20`, `fd7a:115c:a1e0::1`. An
2370 /// IPv4 address is never in its IPv6-mapped form.
2371 pub address: String,
2372 /// What kind of network that address is on, as the server judges it.
2373 pub network: AddressNetwork,
2374}
2375
2376/// What kind of network an address is on, as the server's web approval
2377/// page judges it too.
2378#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
2379#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
2380#[serde(rename_all = "snake_case")]
2381pub enum AddressNetwork {
2382 /// The server's own machine: `127.0.0.0/8`, `::1`.
2383 Loopback,
2384 /// A home, office or VPN network: private IPv4 ranges, link-local,
2385 /// CGNAT and VPNs' `100.64.0.0/10`, IPv6 unique-local and link-local.
2386 Local,
2387 /// A public address: a device far from the approver, which is what a
2388 /// sign-in code sent to someone else (device-code phishing) looks
2389 /// like. The approval warns.
2390 Internet,
2391 /// A kind this build does not know, from a newer server. Show the
2392 /// address and warn as for [`AddressNetwork::Internet`].
2393 #[serde(other)]
2394 Unknown,
2395}
2396
2397#[cfg_attr(feature = "uniffi", uniffi::export)]
2398impl DeviceAddress {
2399 /// On the server's own machine or its network: the approval says
2400 /// where it asked from rather than warn.
2401 pub fn is_local(&self) -> bool {
2402 matches!(
2403 self.network,
2404 AddressNetwork::Loopback | AddressNetwork::Local
2405 )
2406 }
2407}
2408
2409#[cfg_attr(feature = "uniffi", uniffi::export)]
2410impl DeviceSignInRequest {
2411 /// It asked from the server's machine or network
2412 /// ([`DeviceAddress::is_local`]); false where the server couldn't
2413 /// tell, which the approval warns about as for one far away.
2414 pub fn is_local(&self) -> bool {
2415 self.requested_from
2416 .as_ref()
2417 .is_some_and(DeviceAddress::is_local)
2418 }
2419}
2420
2421/// One live session, without its token.
2422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2423pub struct SessionInfo {
2424 /// The device's name; `None` for an admin API session or an unnamed
2425 /// device.
2426 pub device_name: Option<String>,
2427 /// What kind of client the device runs; `None` for an admin API
2428 /// session (the web UI or the CLI) or a device not seen since before
2429 /// the server kept it.
2430 pub platform: Option<Platform>,
2431 /// Unix seconds.
2432 pub created_at: i64,
2433 /// Unix seconds.
2434 pub last_used_at: i64,
2435 /// The session this request was made in.
2436 pub current: bool,
2437}
2438
2439/// Who the server is. `endpoint_id` is what the client pins.
2440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2441pub struct ServerInfo {
2442 pub name: String,
2443 /// Hex, as `spoolframe-server id` prints it.
2444 pub endpoint_id: String,
2445 /// The server's id ([`crate::ServerId`]): made once, kept when its key
2446 /// is replaced. A client pins it beside `endpoint_id`, the first time
2447 /// it sees it.
2448 pub server_id: String,
2449 pub protocol_version: u32,
2450 pub server_version: String,
2451 pub auth_methods: Vec<AuthMethod>,
2452 /// Where a browser reaches the server's web UI (`admin.public_url`),
2453 /// if it has one: for "open in the browser" links, such as linking a
2454 /// Plex account. Absent without a public URL, since the
2455 /// listener's own address may be loopback or one no browser trusts.
2456 pub web_url: Option<String>,
2457 /// The experimental features turned on for this connection:
2458 /// those its `Hello` named that this server knows and has on. Left
2459 /// out when none, as an older server does.
2460 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2461 pub experimental: Vec<String>,
2462 /// The regular features on for this connection
2463 /// ([`crate::features`]): those its `Hello` named that this server
2464 /// has. Left out when none, as an older server does.
2465 #[serde(
2466 default,
2467 with = "crate::features::names",
2468 skip_serializing_if = "Features::is_empty"
2469 )]
2470 pub features: Features,
2471 /// An account is made only from an invite (`RedeemInvite`); there is
2472 /// no open sign-up. For a "servers on my network" list, before
2473 /// signing in.
2474 pub invite_only: bool,
2475}
2476
2477/// Why a request failed. Typed, so clients act on the kind, not on text.
2478#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
2479#[serde(tag = "type", rename_all = "snake_case")]
2480pub enum Error {
2481 #[error("progress belongs to an older playback or sequence")]
2482 StaleProgress,
2483 #[error("the operation belongs to an earlier server instance")]
2484 ServerRestarted,
2485 #[error("the operation expired; its outcome is no longer recoverable")]
2486 OperationExpired,
2487 #[error("the operation ID was already used with different arguments")]
2488 OperationConflict,
2489 #[error("the playback configuration changed (revision {revision})")]
2490 RevisionConflict { revision: u64 },
2491 /// The connection's first request was not `Hello`.
2492 #[error("send Hello first")]
2493 HandshakeRequired,
2494 /// The request needs a session, and none valid for this endpoint was
2495 /// given.
2496 #[error("not authenticated")]
2497 Unauthenticated,
2498 /// The server does not know this request type.
2499 #[error("unsupported request {request:?}")]
2500 Unsupported { request: String },
2501 #[error("malformed request: {message}")]
2502 Malformed { message: String },
2503 #[error("{what} not found")]
2504 NotFound { what: String },
2505 /// Wrong username or password; deliberately the same for both.
2506 #[error("invalid credentials")]
2507 InvalidCredentials,
2508 /// Too many requests: failed sign-ins for this username or from this
2509 /// endpoint, or more operations than a pool has room for now.
2510 #[error("too many requests; retry in {retry_after_ms} ms")]
2511 RateLimited { retry_after_ms: u64 },
2512 /// The client cannot play this selection; one reason per stream, as
2513 /// in [`PlaybackPlan::Unsupported`].
2514 #[error("cannot play: {}", reasons.join("; "))]
2515 CannotPlay { reasons: Vec<String> },
2516 /// The playback handle is unknown or has been idle too long. Call
2517 /// `StartPlayback` again and go on from where playback was.
2518 #[error("the playback has expired; start it again")]
2519 PlaybackExpired,
2520 /// An admin stopped the playback on the server. It is over:
2521 /// tell the viewer it ended, and do not start it again on your own
2522 /// as after `PlaybackExpired`. Its progress is kept.
2523 #[error("the playback was stopped on the server")]
2524 PlaybackStopped,
2525 /// The server is converting as many files as it may at once.
2526 #[error("the server is busy converting; try again later")]
2527 Busy,
2528 /// The server plays at most `max` playbacks off its LAN at once
2529 /// (`network.uplink.max_streams`), and that many are playing.
2530 /// Try again when one ends; a device on the server's LAN is not
2531 /// counted.
2532 #[error("the server plays at most {max} playbacks outside its home at once")]
2533 WanStreamsFull { max: u32 },
2534 /// The encode for this playback failed; `reason` is ffmpeg's.
2535 #[error("the conversion failed: {reason}")]
2536 PlaybackFailed { reason: String },
2537 /// The read names an encode that a seek replaced; read `epoch` from
2538 /// offset 0.
2539 #[error("the playback restarted at a seek (epoch {epoch})")]
2540 PlaybackRestarted { epoch: u32 },
2541 /// The subtitle is still being read as text; `done_percent` of
2542 /// its cues are read. Ask again in a few seconds.
2543 #[error("the subtitle is still being read ({done_percent}% done)")]
2544 SubtitleNotReady { done_percent: u8 },
2545 /// The item's frame previews are being made; `done_percent` of
2546 /// them are. Ask again in a few seconds; show the time alone till then.
2547 #[error("the previews are being made ({done_percent}% done)")]
2548 PreviewsNotReady { done_percent: u8 },
2549 /// The item has no frame previews and will not have: music, a file
2550 /// they could not be made of, or a server that makes none. Do not ask
2551 /// again for this item.
2552 #[error("this item has no previews")]
2553 NoPreviews,
2554 /// The subtitle is not the file that `ReadSubtitle`'s `version` names:
2555 /// it was written again or replaced since that chunk. Read it
2556 /// again from offset 0.
2557 #[error("the subtitle changed while it was read")]
2558 SubtitleChanged,
2559 /// The session's profile is locked on this connection: `UnlockProfile`
2560 /// with the user's PIN first.
2561 #[error("this profile is locked; enter its PIN")]
2562 ProfileLocked,
2563 /// A value the request carries is not acceptable (a PIN that is not 4
2564 /// to 8 digits, say); the message says why.
2565 #[error("{message}")]
2566 InvalidInput { message: String },
2567 /// The request carried the user's account password, and they have none:
2568 /// they sign in with a passkey or SSO only (a `PinProof::Password`).
2569 /// Not a wrong password, and nothing was counted. Use another proof, or
2570 /// send them to the server's web UI (`ServerInfo::web_url`, when the
2571 /// server has one).
2572 #[error("this account has no password; use the PIN or the web UI")]
2573 NoPassword,
2574 /// The session was signed in too long ago for this (an app passkey,
2575 /// approving a device): confirm it is the user
2576 /// (`ConfirmPassword`, or `BeginConfirmPasskey`), or sign in again,
2577 /// then ask again. Nothing was changed.
2578 #[error("sign in again first")]
2579 RecentSignInRequired,
2580 /// Removing this would leave the user no way to sign in: it is their
2581 /// only passkey, and they have no password or linked sign-in provider
2582 /// (`RemovePasskey`). Nothing was changed.
2583 #[error("that is the last way to sign in to this account")]
2584 LastSignInMethod,
2585 /// The device sign-in was refused on the approving device.
2586 #[error("the sign-in was denied")]
2587 DeviceSignInDenied,
2588 /// The device sign-in is over: it timed out, or is not this device's.
2589 /// Begin a new one.
2590 #[error("the sign-in code has expired")]
2591 DeviceSignInExpired,
2592 /// The reply would be over the frame limit
2593 /// ([`crate::codec::MAX_FRAME`]); `bytes` is its length. A page of
2594 /// items is to ask for in smaller pages.
2595 #[error("the reply is too large to send ({bytes} bytes)")]
2596 ReplyTooLarge { bytes: u64 },
2597 /// Something the server depends on (Plex, a media mount) is down.
2598 #[error("unavailable: {message}")]
2599 Unavailable { message: String },
2600 /// The server has no library yet: it is waiting to be set up in its
2601 /// web UI. Every catalog and playback request gets this until
2602 /// it is; show "This server is not set up yet", not an error. Signing
2603 /// in and the rest work.
2604 #[error("this server is not set up yet")]
2605 NotSetUp,
2606 /// The invite's code is right, and it is of another kind than the
2607 /// request redeems: a `portable-account` invite's code to
2608 /// `RedeemInvite`, or a `create-user` one's to
2609 /// `RedeemPortableInvite`. Nothing was made and the invite keeps its
2610 /// use: redeem it the other way.
2611 #[error("that invite is of another kind")]
2612 WrongInviteKind,
2613 /// `RedeemInvite` with a code that is no invite's, or whose invite
2614 /// was revoked. Counted as a wrong guess. Offer "Save server
2615 /// only", which pins the server as a link without a code does.
2616 #[error("that invite code is not valid")]
2617 InviteInvalid,
2618 /// The invite's code is right, and it has expired: ask for another.
2619 #[error("the invite has expired")]
2620 InviteExpired,
2621 /// The invite's code is right, and every account it could make has
2622 /// been made: ask for another.
2623 #[error("the invite has been used up")]
2624 InviteExhausted,
2625 /// Someone on this server has that username: pick another. Nothing
2626 /// was made and the invite was not used up.
2627 #[error("that username is taken")]
2628 UsernameTaken,
2629 /// `TieFinish` with a nonce that is not outstanding for this session:
2630 /// it was used, it is over, or `TieBegin` never gave it here.
2631 /// Begin again.
2632 #[error("the tie challenge is used or has expired; begin again")]
2633 TieChallengeExpired,
2634 /// Another account on this server is tied to that portable identity:
2635 /// one identity ties to one account per server. Sever that
2636 /// tie first. Nothing was changed.
2637 #[error("that portable identity is tied to another account here")]
2638 PortableIdTaken,
2639 /// The session is a portable user's, and this is for an
2640 /// account here only: its password, PIN, passkeys, devices, sessions,
2641 /// ties, approving sign-ins. Hide what asks for it while signed in as
2642 /// one. Nothing was changed.
2643 #[error("not for a guest from another identity")]
2644 NotForPortableUsers,
2645 /// The request is an admin's (making and revoking invites),
2646 /// and the session user is not one. Nothing was changed.
2647 #[error("only an admin can do that")]
2648 AdminRequired,
2649 /// The session was opened with a one-time password an admin reset to:
2650 /// it may only `ChangePassword` (or `Logout`, `WhoAmI`) until the user
2651 /// chooses a new password. Nothing was done.
2652 #[error("choose a new password first")]
2653 PasswordChangeRequired,
2654 /// `LeaveServer` from the last enabled admin, or the last enabled
2655 /// admin with a password: make someone else an admin, or give
2656 /// one a password, first. Nothing was changed.
2657 #[error("you are the only admin; make someone else an admin first")]
2658 LastAdmin,
2659 /// The user sees the playlist and may not make this change: an
2660 /// edit on a read-only share, or a rename, sharing change or delete by
2661 /// anyone but its owner (or an admin, for a server-wide one). Nothing
2662 /// was changed.
2663 #[error("you cannot change this playlist")]
2664 PlaylistReadOnly,
2665 /// The playlist does not take items of this kind: its kinds
2666 /// were ticked when it was made. Nothing was changed. A season or
2667 /// show is episodes, an album or artist tracks.
2668 #[error("this playlist does not take a {kind:?}")]
2669 KindNotAllowed { kind: crate::playlists::ItemKind },
2670 /// Someone changed the playlist since the revision the edit was made
2671 /// on, and touched an entry the edit touches: "Someone changed
2672 /// this playlist; reload". `revision` is its revision now. Nothing was
2673 /// changed.
2674 #[error("someone changed this playlist; reload (revision {revision})")]
2675 PlaylistConflict { revision: u64 },
2676 /// The user may not do this to what they see: a cover set or
2677 /// taken away by someone who may not edit the playlist, or on Liked
2678 /// or All, whose tiles are fixed. Nothing was changed.
2679 #[error("you are not allowed to do that")]
2680 NotAllowed,
2681 /// The picture is over `max_bytes` long, or over `max_pixels` by its
2682 /// header. Refused before it was decoded; nothing was
2683 /// changed.
2684 #[error("the picture is too large: at most {max_bytes} bytes and {max_pixels} pixels")]
2685 ImageTooLarge { max_bytes: u64, max_pixels: u64 },
2686 /// Not a JPEG, PNG, WebP or HEIC picture the server can decode, or
2687 /// one that hit the decoder's limits. Nothing was changed.
2688 #[error("the picture cannot be read: a JPEG, PNG, WebP or HEIC is taken")]
2689 ImageUnreadable,
2690 /// The downloads of `whose` are used up for today: the
2691 /// server's account at subtitle site `site` (`opensubtitles`,
2692 /// `subdl`, as `SubtitleResult::source`), or the user's own daily
2693 /// limit on this server (no `site`). `resets_at` (Unix seconds) is when more may be
2694 /// downloaded, when known. Nothing was downloaded; searching still
2695 /// works.
2696 #[error("no subtitle downloads left today ({whose:?})")]
2697 QuotaExhausted {
2698 whose: spoolframe_types::QuotaOf,
2699 #[serde(default, skip_serializing_if = "Option::is_none")]
2700 resets_at: Option<i64>,
2701 #[serde(default, skip_serializing_if = "Option::is_none")]
2702 site: Option<String>,
2703 },
2704 /// The server has no subtitle site set up: hide "Find
2705 /// subtitles". Nothing was asked of any site.
2706 #[error("this server has no subtitle source set up")]
2707 NoSubtitleSource,
2708 /// The download's file is not whole yet: read it once its
2709 /// state is `ready`. A download that failed is prepared again.
2710 #[error("the download is not ready")]
2711 DownloadNotReady,
2712 /// Experimental (`federation`): the other server did not pair
2713 /// (`PairServer`), for `reason`. Nothing was kept.
2714 #[error("the other server did not pair: {reason}")]
2715 PairingRefused {
2716 reason: crate::federation::PairingRefused,
2717 },
2718 /// Experimental (`federation`): the paired server the item is
2719 /// from is offline to this one (`RemoteGrant`): play it from this
2720 /// server, or later.
2721 #[error("the paired server the item is from is offline")]
2722 OriginOffline,
2723 #[error("internal server error")]
2724 Internal,
2725 /// An error type this build does not know.
2726 #[serde(other)]
2727 #[error("unknown error")]
2728 Unknown,
2729}
2730
2731/// Something the server tells the client without being asked, on the
2732/// events stream.
2733#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2734#[serde(tag = "type", rename_all = "snake_case")]
2735pub enum Event {
2736 /// The server is stopping; the connection will close.
2737 ShuttingDown,
2738 /// Where this server can be reached, pushed to a connection
2739 /// as soon as it is signed in, and again whenever the list changes.
2740 /// Each one is the whole list: it replaces what was told before.
2741 /// Never sent to a connection that is not signed in.
2742 ServerAddresses {
2743 /// The addresses `network.announce` tells, with their port, as
2744 /// text: `192.168.1.10:4433` or `[2001:db8::1]:4433`.
2745 #[serde(with = "socket_addrs_as_text")]
2746 addrs: Vec<std::net::SocketAddr>,
2747 /// The URLs of the iroh relays the server may use
2748 /// (`network.relays`), its home relay now first; empty while
2749 /// relays are off.
2750 relays: Vec<String>,
2751 /// The pkarr relay the server publishes where it is to
2752 /// (`network.pkarr`), for the device to look it up by its
2753 /// key when nothing else reaches it; `None` while it publishes
2754 /// nothing.
2755 #[serde(deserialize_with = "spoolframe_types::required::option")]
2756 lookup: Option<String>,
2757 },
2758 /// Playback `handle`'s share of the server's WAN uplink changed:
2759 /// another WAN playback started or ended, or the budget
2760 /// changed. A playback in `Quality::Auto` re-plans with
2761 /// `ChangeQuality` at its position (the SDK's managed playback does
2762 /// it by itself); `max_bitrate` is the new cap, `None` none. Sent only
2763 /// for a move of 15% or more, a few seconds after the last start or
2764 /// end. One of another quality may ignore it.
2765 PlaybackShare {
2766 handle: PlaybackHandle,
2767 #[serde(deserialize_with = "spoolframe_types::required::option")]
2768 max_bitrate: Option<u64>,
2769 },
2770 /// A playlist the user sees was made or changed: its entries,
2771 /// name, kinds or sharing. Read it again if it is shown. Only to a
2772 /// client that listed `spoolframe:playlists`.
2773 PlaylistChanged { id: String, revision: u64 },
2774 /// A playlist the user saw is gone to them: deleted, or no longer
2775 /// shared with them. Close it if it is shown.
2776 PlaylistGone { id: String },
2777 /// The user's Pinned, or its notes, changed on another device or by
2778 /// another user's change: `ListPlaylists` again.
2779 PinsChanged,
2780 /// The user liked or unliked a track, on any device: a device
2781 /// that downloaded Liked asks what it holds now
2782 /// (`MusicDownloadChanges`). Only to the user's own connections that
2783 /// listed `spoolframe:music-downloads`.
2784 LikedChanged,
2785 /// Item `id`'s subtitle `track` is timed anew: synced, its
2786 /// sync done or set aside, or its offset changed, by anyone. What it
2787 /// is served with changed: a player showing it reads it again (a
2788 /// `ReadSubtitle` in progress answers `SubtitleChanged`), with no
2789 /// restart. Only to a client that listed `spoolframe:subtitle-sync`,
2790 /// on a connection that asked for the item's `Tracks` or plays it.
2791 SubtitleTimingChanged {
2792 id: MediaId,
2793 track: u32,
2794 timing: spoolframe_types::SubtitleTiming,
2795 },
2796 /// Download `id`'s state moved: `waiting`, then `converting`
2797 /// (told once per percent or every 2 s), `writing`, and `ready` or
2798 /// `failed`. Only to the connections of the user whose it is, that
2799 /// listed `spoolframe:downloads`.
2800 DownloadChanged {
2801 id: String,
2802 state: crate::downloads::DownloadState,
2803 },
2804 /// Experimental (`federation`): the libraries changed: a paired
2805 /// server came online or went offline, or shared or stopped sharing a
2806 /// library. `Libraries` again. Only to a client that named the
2807 /// feature.
2808 LibrariesChanged,
2809 /// Experimental (`federation`): playback `handle`, of a paired
2810 /// server's item, ended other than by its client's stop: stopped by an
2811 /// admin, idle past the limit, its session or its grant ended, or, on
2812 /// the user's own server playing it on, ended where it plays from.
2813 /// `error` is what the client's next use of it is told
2814 /// (`PlaybackStopped`: do not start it again). Only for a play
2815 /// token's session's playbacks, and those played through the user's
2816 /// own server.
2817 PlaybackEnded {
2818 handle: PlaybackHandle,
2819 error: Error,
2820 },
2821 /// The profile of local user `user` (a user id, as `WhoAmI` names
2822 /// it) is gone from this device: the user was disabled or deleted, or
2823 /// an admin forgot this device for them. Their sessions here end with
2824 /// it; the next request in one is `Unauthenticated`. Leave the profile,
2825 /// and offer to sign in again only if the user is not deleted. Only to
2826 /// that user's connections, and sent only to a connection where the
2827 /// `spoolframe:october-2026` feature is on (both sides named it).
2828 ProfileRemoved { user: String },
2829 /// Local user `user`'s PIN changed: set, changed or removed, by them on
2830 /// another device or by an admin. `required` is whether they have a PIN
2831 /// now. A device that has their profile unlocked locks it again where
2832 /// the PIN is asked for; one that kept the old PIN to check offline
2833 /// forgets it. Only to that user's connections, not the one that made
2834 /// the change, and sent only to a connection where the
2835 /// `spoolframe:october-2026` feature is on (both sides named it).
2836 PinChanged { user: String, required: bool },
2837 /// The user's watch state of `items` changed on another connection:
2838 /// marked watched or unwatched (a season's or a show's id marks its
2839 /// episodes), hidden from or put back in Continue watching, synced
2840 /// from offline, or played into progress, to watched, or stopped (not
2841 /// each progress report). Read again what shows them (Home, an item's page). Only
2842 /// to that user's other connections, and sent only to a connection
2843 /// where the `spoolframe:october-2026` feature is on (both sides
2844 /// named it).
2845 WatchChanged { items: Vec<MediaId> },
2846 /// An event type this build does not know; ignore it.
2847 #[serde(other)]
2848 Unknown,
2849}
2850
2851/// Socket addresses on the wire as text (`192.168.1.10:4433`,
2852/// `[2001:db8::1]:4433`). CBOR is not a human-readable format to serde, so
2853/// a bare `SocketAddr` would go as serde's enum of byte tuples, which a
2854/// peer outside Rust would have to copy; text is also what JSON shows.
2855pub(crate) mod socket_addrs_as_text {
2856 use std::net::SocketAddr;
2857
2858 use serde::de::Error as _;
2859 use serde::{Deserialize, Deserializer, Serialize, Serializer};
2860
2861 pub fn serialize<S: Serializer>(addrs: &[SocketAddr], s: S) -> Result<S::Ok, S::Error> {
2862 let text: Vec<String> = addrs.iter().map(ToString::to_string).collect();
2863 text.serialize(s)
2864 }
2865
2866 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<SocketAddr>, D::Error> {
2867 Vec::<String>::deserialize(d)?
2868 .iter()
2869 .map(|text| {
2870 text.parse()
2871 .map_err(|_| D::Error::custom(format!("not a socket address: {text:?}")))
2872 })
2873 .collect()
2874 }
2875}
2876
2877#[cfg(test)]
2878mod tests;