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