Skip to main content

spoolframe_protocol/
downloads.rs

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