Skip to main content

spoolframe_protocol/
downloads.rs

1//! Downloads for offline viewing (PX-38, feature `spoolframe:downloads`):
2//! the messages of [`crate::Request::DownloadOptions`],
3//! [`crate::Request::PrepareDownload`], [`crate::Request::DownloadStatus`],
4//! [`crate::Request::CancelDownload`] and
5//! [`crate::Request::SyncOfflineWatch`], the
6//! [`crate::Event::DownloadChanged`] event, and the
7//! [`crate::resource::ResourceRequest::Download`] read.
8//!
9//! A download is a film or an episode written as one file for the
10//! device: the source file as it is (with every track, when the device
11//! plays it so), a remux of the tracks chosen, or a remux with what the
12//! device cannot play converted. Apple devices (iOS, iPadOS, macOS) get
13//! MP4, Linux ones Matroska; tvOS and the web have none. Tracks are named
14//! by their place in the item's `Tracks`: `audio[i]`, `subtitles[i]`.
15//!
16//! With `spoolframe:music-downloads` too (PX-51), a download may be a
17//! track: in `original` quality, the file as it is when the device plays
18//! it, byte for byte; else, converted, lossless as ALAC (Apple) or FLAC
19//! (Linux) and lossy as AAC; or as AAC at 256 kbit/s (`aac256`). A
20//! converted track keeps its tags and its cover. What a device follows
21//! (an artist, a playlist, Liked) is asked with
22//! [`crate::Request::MusicDownloadChanges`], and what it played offline
23//! sent with [`crate::Request::SyncOfflinePlays`].
24
25use serde::{Deserialize, Serialize};
26use spoolframe_types::{ClientCapabilities, Container, MediaId, MediaTracks, Platform};
27
28/// The most ids one `DownloadStatus` asks about, and the most entries one
29/// `SyncOfflineWatch` carries.
30pub const MAX_ASKED: usize = 500;
31
32/// The device a paired server's item is downloaded for (P8-07): what the
33/// server its user is at home on (SB) sends with `DownloadOptions` and
34/// `PrepareDownload` on the paired server (SA), which plans for it in place
35/// of SB's own `Hello`, as `StartPlayback`'s `capabilities` does a play.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37pub struct DownloadDevice {
38    pub platform: Platform,
39    /// What it plays; its platform's own when left out.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub capabilities: Option<ClientCapabilities>,
42}
43
44/// What a download is made from.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(tag = "type", rename_all = "snake_case")]
47pub enum DownloadSource {
48    /// Original quality: the file, converted only where the device needs
49    /// it, at its resolution and with its HDR.
50    Original,
51    /// The copy in an optimized profile (PX-37), by name, as
52    /// `DownloadOptions::profiles` lists them. A film or an episode only.
53    Profile { name: String },
54    /// A track as AAC at 256 kbit/s (PX-51, `spoolframe:music-downloads`),
55    /// smaller than the original: for a device short of space. A lossy
56    /// file at or under 256 kbit/s the device plays is sent as it is. A
57    /// track only.
58    Aac256,
59    /// A source this build does not know, from a newer client: the server
60    /// answers `InvalidInput`.
61    #[serde(other)]
62    Unknown,
63}
64
65/// Which tracks a download carries. The video is always there.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(tag = "type", rename_all = "snake_case")]
68pub enum DownloadTracks {
69    /// Every track of the file: the only choice that may send the file
70    /// as it is, byte for byte.
71    All,
72    /// These, by their place in `Tracks`' `audio` and `subtitles`. Order
73    /// and repeats do not count.
74    Chosen {
75        audio: Vec<u32>,
76        subtitles: Vec<u32>,
77    },
78    /// A choice this build does not know: the server answers
79    /// `InvalidInput`.
80    #[serde(other)]
81    Unknown,
82}
83
84impl DownloadTracks {
85    /// The same choice, each list in order and without repeats: two
86    /// requests that differ only so are one.
87    pub fn normalized(&self) -> Self {
88        match self {
89            Self::Chosen { audio, subtitles } => {
90                let sorted = |v: &[u32]| {
91                    let mut v = v.to_vec();
92                    v.sort_unstable();
93                    v.dedup();
94                    v
95                };
96                Self::Chosen {
97                    audio: sorted(audio),
98                    subtitles: sorted(subtitles),
99                }
100            }
101            other => other.clone(),
102        }
103    }
104}
105
106/// What a download in original quality with every track would be
107/// (`DownloadOptions::original`).
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(tag = "type", rename_all = "snake_case")]
110pub enum OriginalDownload {
111    /// The file itself, byte for byte: the device plays it as it is.
112    AsIs,
113    /// A remux, with nothing converted: another container, or subtitles
114    /// beside the file to carry.
115    Remux,
116    /// What the device cannot play is converted first (the server keeps
117    /// the conversion for the next download): the video when `video`,
118    /// and the audio tracks in `audio`, by place. A choice of tracks
119    /// that leaves out every one of them, and keeps the video, is a
120    /// remux.
121    Convert { video: bool, audio: Vec<u32> },
122    /// A kind this build does not know.
123    #[serde(other)]
124    Unknown,
125}
126
127/// A subtitle a download would leave out, and why (`DownloadOptions`):
128/// a picture subtitle in an Apple file when the viewer prefers pictures
129/// (MP4 carries none), or one the server cannot write to a file.
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131pub struct LeftOutSubtitle {
132    /// Its place in `Tracks`' `subtitles`.
133    pub subtitle: u32,
134    /// Said to the user as it is.
135    pub reason: String,
136}
137
138/// What the device may download of an item (`DownloadOptions`).
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140pub struct DownloadOptionsInfo {
141    /// The item's tracks, as `Tracks` gives them: what `Chosen` names by
142    /// place.
143    pub tracks: MediaTracks,
144    /// The choice to show first: one or two audio tracks in the viewer's
145    /// languages, and every text subtitle in their languages, with the
146    /// subtitle playback would pick. Always `Chosen`.
147    pub preferred: DownloadTracks,
148    /// The optimized profiles a download may be made in, in the order
149    /// the admin set.
150    pub profiles: Vec<String>,
151    /// What original quality with every track would be. For a choice of
152    /// tracks: `convert` when the video is converted or a chosen audio
153    /// track is among `audio`, else `remux`.
154    pub original: OriginalDownload,
155    /// The subtitles this device's download would leave out, of all the
156    /// item's, with why: leave them unticked.
157    pub left_out: Vec<LeftOutSubtitle>,
158    /// About each option: `Original` first, then each of `profiles` in
159    /// its order. Films and episodes only: empty for a track.
160    pub estimates: Vec<DownloadEstimate>,
161}
162
163/// About one download option (`DownloadOptions`): how large it is and
164/// whether it waits for a conversion.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166pub struct DownloadEstimate {
167    pub source: DownloadSource,
168    /// About how many bytes the file is with every track: the item's
169    /// own size where nothing is converted, else the converted video's
170    /// rate and the rest of the file's over its length. `None` when the
171    /// server cannot tell (the file's length is not known).
172    pub size_bytes: Option<u64>,
173    pub readiness: DownloadReadiness,
174}
175
176/// Whether a download option waits for a conversion.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
178#[serde(rename_all = "snake_case")]
179pub enum DownloadReadiness {
180    /// Nothing to convert, or the server already keeps the conversion:
181    /// the file is written at once.
182    Ready,
183    /// The server converts first: the download waits for it.
184    ConvertsFirst,
185    /// A kind this build does not know.
186    #[serde(other)]
187    Unknown,
188}
189
190/// Where a download is.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(tag = "type", rename_all = "snake_case")]
193pub enum DownloadState {
194    /// Waiting its turn: for its conversion, for room on the server, or
195    /// for a place to write it.
196    Waiting,
197    /// What the device cannot play is being converted, or picture
198    /// subtitles read as text: `done_percent` of it, and about
199    /// `eta_secs` to go, once known.
200    Converting {
201        done_percent: Option<u8>,
202        eta_secs: Option<u64>,
203    },
204    /// The file is being written: `done_percent` of it, once known.
205    Writing { done_percent: Option<u8> },
206    /// The file is whole: `size` bytes, with this SHA-256 (64 hex
207    /// digits). Read it with `ResourceRequest::Download`.
208    Ready { size: u64, sha256: String },
209    /// It could not be made: a conversion failed, the file is gone, or
210    /// the server removed it a day after its last read. `PrepareDownload`
211    /// again tries again, under the same id.
212    Failed {
213        /// Said to the user as it is.
214        reason: String,
215        /// Why, for the app to choose what to show and offer; `other`
216        /// from a server before it was sent.
217        #[serde(default)]
218        cause: DownloadFailure,
219    },
220    /// A state this build does not know: ask `DownloadStatus` later.
221    #[serde(other)]
222    Unknown,
223}
224
225/// Why a download failed (`DownloadState::Failed`), beside its reason in
226/// words.
227#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(tag = "type", rename_all = "snake_case")]
229pub enum DownloadFailure {
230    /// The device has no room for it: `needed_bytes` more must be free.
231    /// A device's own; a server never sends it.
232    NoSpace { needed_bytes: u64 },
233    /// The server's conversion of it (its video, its audio, or picture
234    /// subtitles read as text) failed, or stopped with the server.
235    ServerStoppedConverting,
236    /// The media file it is made from is gone from the server, or
237    /// changed since it was prepared.
238    SourceMissing,
239    /// Talking to the server failed: a device's own, for an answer that
240    /// broke off or made no sense, or a file that arrived damaged.
241    Network,
242    /// A paired server's item (P8-07) that is no longer available before
243    /// its file was made: that server stopped sharing it, or the servers
244    /// unpaired. A download made already stays `Ready`, marked
245    /// [`DownloadInfo::no_longer_available`].
246    NoLongerAvailable,
247    /// Anything else: the reason says.
248    #[default]
249    Other,
250    /// A cause this build does not know.
251    #[serde(other)]
252    Unknown,
253}
254
255/// The tracks a download's file carries, by their place in `Tracks`, in
256/// the file's order after its video.
257#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
258pub struct FileTracks {
259    pub audio: Vec<u32>,
260    pub subtitles: Vec<u32>,
261}
262
263/// What a download's file is: for a player, and for labelling its tracks
264/// offline.
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct DownloadFile {
267    pub container: Container,
268    pub tracks: FileTracks,
269}
270
271/// A download, as `PrepareDownload` and `DownloadStatus` answer.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273pub struct DownloadInfo {
274    /// The download's id: the session user's, for this item, source and
275    /// tracks; the same id each time they prepare the same.
276    pub id: String,
277    pub state: DownloadState,
278    /// What the file is; `None` where the server does not know it.
279    #[serde(deserialize_with = "spoolframe_types::required::option")]
280    pub file: Option<DownloadFile>,
281    /// About how many bytes the file will be, for showing before it is
282    /// ready ("Waiting for Wi-Fi ยท 2.8 GB"): a film's or an episode's as
283    /// `DownloadEstimate::size_bytes` says, a track's its file's size, or
284    /// its converted rate over its length. Sent with `PrepareDownload`'s
285    /// answer and with `DownloadStatus`'s; `None` when the server cannot
286    /// tell, and from a server before it was sent (an older server
287    /// sends it only with `PrepareDownload`'s). `Ready`'s `size` is exact.
288    #[serde(default, skip_serializing_if = "Option::is_none")]
289    pub expected_size: Option<u64>,
290    /// A paired server's item's download (P8-07) whose file was made, and
291    /// that is no longer available: that server stopped sharing it, or the
292    /// servers unpaired. Its state stays `Ready`, so the device keeps a
293    /// file it has whole; nothing more of it is read. One not made yet is
294    /// `Failed` with the cause `NoLongerAvailable` instead. Left out when
295    /// false.
296    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
297    pub no_longer_available: bool,
298}
299
300/// Where a device got to in an item while it had no server
301/// (`SyncOfflineWatch`).
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303pub struct OfflineWatch {
304    /// A film or an episode.
305    pub id: MediaId,
306    /// Where it stopped; `None` when only `watched` changed.
307    #[serde(deserialize_with = "spoolframe_types::required::option")]
308    pub position_ms: Option<u64>,
309    /// Marked watched (`true`) or unwatched (`false`) on the device;
310    /// `None` when only the position changed. With a position, the
311    /// server judges watched by its own rules, and `true` makes it
312    /// watched whatever they say; `false` alone starts it over.
313    #[serde(deserialize_with = "spoolframe_types::required::option")]
314    pub watched: Option<bool>,
315    /// When, by the device's clock, in Unix seconds.
316    pub at: i64,
317}
318
319/// What became of one [`OfflineWatch`], and of one [`OfflinePlay`] or
320/// [`OfflineLike`] (PX-51).
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
322#[serde(rename_all = "snake_case")]
323pub enum OfflineWatchOutcome {
324    /// Written: it was newer than what the server had. A play is always
325    /// written, once: sent again, it is `applied` and not counted twice.
326    Applied,
327    /// Not written: the server has a newer state for the item (from
328    /// another device, say). Show the server's.
329    Older,
330    /// Not written: the item has no watch state (not a film or an
331    /// episode; for a play or a like, not a track), or is not on the
332    /// server any more.
333    NotTracked,
334    /// An outcome this build does not know.
335    #[serde(other)]
336    Unknown,
337}
338
339/// The most artists and playlists one `MusicDownloadChanges` asks about,
340/// together.
341pub const MAX_FOLLOWED: usize = 100;
342
343/// What a device's music download follows (PX-51): it keeps every track
344/// of it, as it is now.
345#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
346#[serde(tag = "type", rename_all = "snake_case")]
347pub enum Followed {
348    /// Every track of every album of the artist, those it gains later
349    /// included.
350    Artist { id: MediaId },
351    /// The tracks of a playlist (PX-40), by its id; not All.
352    Playlist { id: String },
353    /// The tracks of the user's Liked (PX-43).
354    Liked,
355    /// One this build does not know.
356    #[serde(other)]
357    Unknown,
358}
359
360/// The tracks a followed thing holds, against the cursor asked with.
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362#[serde(tag = "type", rename_all = "snake_case")]
363pub enum FollowedTracks {
364    /// The same as at the cursor: nothing to do.
365    Unchanged,
366    /// Every track it holds now, in its order, each once: the device
367    /// fetches those it does not have, and deletes those it has that are
368    /// no longer here unless another download covers them. Sent with no
369    /// cursor, or when something changed since it.
370    Tracks { tracks: Vec<MediaId> },
371    /// Not on the server any more, or not the user's to see: the device
372    /// drops the download.
373    Gone,
374    /// One this build does not know: ask again with no cursor.
375    #[serde(other)]
376    Unknown,
377}
378
379/// One followed thing's tracks (`MusicDownloadChanges`).
380#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381pub struct FollowedChange {
382    pub followed: Followed,
383    pub tracks: FollowedTracks,
384}
385
386/// A track played on a device with no server (`SyncOfflinePlays`).
387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
388pub struct OfflinePlay {
389    pub track: MediaId,
390    /// When the play ended, by the device's clock, in Unix seconds. With
391    /// `track`, what makes the play one: sent twice, it counts once.
392    pub at: i64,
393    /// How much of it was played: the server judges by its rules whether
394    /// it counts as a play.
395    pub played_ms: u64,
396}
397
398/// A track liked or unliked on a device with no server
399/// (`SyncOfflinePlays`).
400#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
401pub struct OfflineLike {
402    pub track: MediaId,
403    pub liked: bool,
404    /// When, by the device's clock, in Unix seconds.
405    pub at: i64,
406}