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