redseat-api 0.14.0

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
//! Files of a server downloaded to this device, in two kinds:
//!
//! - **Kept offline**: a movie's or an episode's file the app downloads to its own
//!   folder, to play without the server ([`Downloads::keep_offline`]). The app tracks
//!   them: their progress, pause and resume, removal, and the source a player reads
//!   ([`Downloads::source`]). A file of an encrypted library stays encrypted on disk,
//!   as the server serves it, and is decrypted as it plays, with the library's key.
//! - **Saved copies**: a media's file saved where the user chose
//!   ([`Downloads::save_copy`]), decrypted in an encrypted library; once saved, it is
//!   the user's. The last [`COPIES_KEPT`] are listed, saved or failed.
//!
//! One [`Downloads`] per server copy, in a folder of the copy's ([`Downloads::open`]):
//! `offline.json` (the files kept), `copies.json` (the saved copies listed) and
//! `files/`. Files come by ranges of [`CHUNK`] bytes, so a download goes on where it
//! stopped (a pause, the app closing, the connection lost) and never holds a file in
//! memory. At most [`CONCURRENT`] files kept offline download at once; the others
//! wait in line. Those waiting for the server start when it is reached again.
//!
//! The app reads the state ([`Downloads::offline_files`], [`Downloads::page`],
//! [`Downloads::copies`]) and reads it again when the listener given to
//! [`Downloads::open`] is called: on every change, and every [`PROGRESS_EVERY`] at
//! most while files download.
//!
//! Names are never written to disk: a kept file records its library, media and title
//! ids, and the page reads their names from the copy (decrypted once the library is
//! unlocked).

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use tokio::io::AsyncWriteExt as _;
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
use tokio::task::AbortHandle;

use super::ServerCopy;
use super::catalog::{Playable, episode_label};
use super::text;
use crate::client::now_ms;
use crate::encrypted::EncryptedMediaReader;
use crate::error::{Error, Result};
use crate::library::{LibraryApi, decode_iv};
use crate::mirror::MirrorEvent;
use crate::transport::Request;
use crate::types::episode::Episode;
use crate::types::media::Media;
use crate::types::movie::Movie;
use crate::types::serie::Serie;

/// Bytes asked from the server at once.
pub const CHUNK: u64 = 8 * 1024 * 1024;
/// Files kept offline that download at the same time.
pub const CONCURRENT: usize = 2;
/// The listener is called at most this often for progress alone.
pub const PROGRESS_EVERY: Duration = Duration::from_millis(250);
/// Saved copies listed, newest first.
pub const COPIES_KEPT: usize = 50;
/// After a lost network, a download tries again this late, or when the copy
/// connects again.
const RETRY_AFTER: Duration = if cfg!(test) {
    Duration::from_millis(100)
} else {
    Duration::from_secs(10)
};
/// Partial file names tried beside one chosen file.
const PART_ATTEMPTS: u32 = 100;

/// What the listener hears.
#[derive(Debug, Clone, PartialEq)]
pub enum DownloadsEvent {
    /// The state changed, or files moved on: read it again.
    Changed,
    /// A file kept offline is complete.
    Available(OfflineId),
    /// A saved copy ended, saved or failed ([`SavedCopy::state`]).
    CopyEnded(SavedCopy),
}

/// What the app gives to hear the changes. Called on the runtime's threads.
pub trait OnDownloads: Fn(DownloadsEvent) + Send + Sync + 'static {}
impl<F: Fn(DownloadsEvent) + Send + Sync + 'static> OnDownloads for F {}

/// A file kept offline: a media of a library.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct OfflineId {
    pub library: String,
    pub media: String,
}

impl OfflineId {
    pub fn new(library: &str, media: &str) -> OfflineId {
        OfflineId {
            library: library.to_owned(),
            media: media.to_owned(),
        }
    }
}

/// Where a file kept offline is in its life.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OfflineState {
    /// In line: for a free slot, or for the server.
    Queued,
    Downloading,
    /// Stopped by the user; [`Downloads::resume`] goes on where it stopped.
    Paused,
    /// Complete: it plays without the server.
    Available,
    /// It was complete, but its file is gone or shorter: download it again.
    Missing,
    /// The download stopped on an error; [`Downloads::resume`] tries again.
    Failed(String),
}

/// A file kept offline, as it is now.
#[derive(Debug, Clone, PartialEq)]
pub struct OfflineFile {
    pub id: OfflineId,
    /// The movie or episode it is a file of.
    pub target: Playable,
    pub state: OfflineState,
    /// Bytes on disk.
    pub received: u64,
    /// The file's size, once the server gave it.
    pub total: Option<u64>,
    /// When it was asked for, Unix milliseconds.
    pub added: i64,
}

impl OfflineFile {
    /// From 0 to 1, once the size is known.
    pub fn progress(&self) -> Option<f32> {
        let total = self.total.filter(|total| *total > 0)?;
        Some((self.received as f64 / total as f64).min(1.) as f32)
    }

    /// Whether it is on its way: in line, downloading or paused.
    pub fn in_progress(&self) -> bool {
        matches!(
            self.state,
            OfflineState::Queued | OfflineState::Downloading | OfflineState::Paused
        )
    }

    /// "1.4 GB · Available offline", "Downloading · 42%", "Waiting to download",
    /// "Paused · 42%", "File missing · Download again", or the failure.
    pub fn status(&self) -> String {
        let percent = || {
            self.progress()
                .map(|progress| format!("{}%", (progress * 100.).floor() as u32))
        };
        match &self.state {
            OfflineState::Available => {
                format!("{} · Available offline", text::bytes(self.received))
            }
            OfflineState::Downloading => match percent() {
                Some(percent) => format!("Downloading · {percent}"),
                None => "Downloading…".to_owned(),
            },
            OfflineState::Queued => "Waiting to download".to_owned(),
            OfflineState::Paused => match percent() {
                Some(percent) => format!("Paused · {percent}"),
                None => "Paused".to_owned(),
            },
            OfflineState::Missing => "File missing · Download again".to_owned(),
            OfflineState::Failed(error) => format!("Download failed: {error}"),
        }
    }
}

/// A file kept offline as the Downloads screen shows it, with its title read from the
/// copy.
#[derive(Debug, Clone, PartialEq)]
pub struct OfflineRow {
    pub file: OfflineFile,
    /// The movie's name, or the show's.
    pub title: String,
    /// "2019", or "S1, E2 · Pilot".
    pub subtitle: String,
    /// The media's file name.
    pub file_name: String,
    /// What the row shows of its state: [`OfflineFile::status`].
    pub status: String,
    /// The movie, for its poster; `None` for an episode or when the copy lost it.
    pub movie: Option<Movie>,
    /// The show and the episode, for the show's poster and the episode's still.
    pub serie: Option<Serie>,
    pub episode: Option<Episode>,
}

/// The Downloads screen.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct DownloadsPage {
    /// Queued, downloading and paused, oldest first.
    pub downloading: Vec<OfflineRow>,
    /// Failed or missing.
    pub attention: Vec<OfflineRow>,
    /// Ready to play offline, newest first.
    pub available: Vec<OfflineRow>,
    /// The saved copies, newest first.
    pub copies: Vec<SavedCopy>,
    /// Bytes of the files kept offline on disk.
    pub used: u64,
    /// "2 movies · 5 episodes · 12 GB", or `None` when nothing is kept.
    pub summary: Option<String>,
}

impl DownloadsPage {
    pub fn is_empty(&self) -> bool {
        self.downloading.is_empty()
            && self.attention.is_empty()
            && self.available.is_empty()
            && self.copies.is_empty()
    }
}

/// Where a saved copy is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CopyState {
    Saving,
    Saved,
    Failed(String),
}

/// A media's file saved where the user chose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SavedCopy {
    /// Unique among this server's copies.
    pub id: u64,
    pub media: String,
    /// The media's name.
    pub name: String,
    pub path: PathBuf,
    pub state: CopyState,
    /// Bytes written.
    pub received: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub total: Option<u64>,
    /// When it ended, Unix milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finished: Option<i64>,
}

impl SavedCopy {
    /// From 0 to 1, once the size is known.
    pub fn progress(&self) -> Option<f32> {
        let total = self.total.filter(|total| *total > 0)?;
        Some((self.received as f64 / total as f64).min(1.) as f32)
    }

    /// "Saving · 42%", "1.4 GB", or the failure.
    pub fn status(&self) -> String {
        match &self.state {
            CopyState::Saving => match self.progress() {
                Some(progress) => format!("Saving · {}%", (progress * 100.).floor() as u32),
                None => "Saving…".to_owned(),
            },
            CopyState::Saved => text::bytes(self.received),
            CopyState::Failed(error) => format!("Failed: {error}"),
        }
    }
}

/// What a player reads to play a file kept offline.
// One per video played: its size does not matter.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum OfflineSource {
    /// A plain file.
    File(PathBuf),
    /// An encrypted library's file, decrypted as it is read.
    Encrypted(EncryptedMediaReader),
}

/// The files of a server downloaded to this device. A cheap handle: clones share
/// them. Dropping the last one stops the downloads; those kept offline go on at the
/// next [`Downloads::open`].
#[derive(Clone)]
pub struct Downloads {
    shared: Arc<Shared>,
}

impl std::fmt::Debug for Downloads {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Downloads")
            .field("dir", &self.shared.dir)
            .finish_non_exhaustive()
    }
}

struct Shared {
    copy: ServerCopy,
    dir: PathBuf,
    runtime: tokio::runtime::Handle,
    listener: Arc<dyn Fn(DownloadsEvent) + Send + Sync>,
    state: Mutex<State>,
    /// When the listener last heard of progress alone.
    last_progress: Mutex<Option<Instant>>,
    /// Follows the copy's connection.
    follow: Mutex<Option<AbortHandle>>,
    /// Held from a snapshot of the state to its file, so writers never mix.
    saving: Mutex<()>,
    /// Per file in `files/`, held by the download writing it until its last write is
    /// on disk, aborted or not: the next one goes on from the end of that.
    writers: Mutex<HashMap<String, Arc<AsyncMutex<()>>>>,
}

impl Shared {
    /// Tells the listener on the runtime, as [`OnDownloads`] promises: never inside
    /// the app's own call, whatever executor it makes it from.
    fn tell(&self, event: DownloadsEvent) {
        let listener = Arc::clone(&self.listener);
        self.runtime.spawn(async move { listener(event) });
    }
}

impl Drop for Shared {
    fn drop(&mut self) {
        if let Some(follow) = lock(&self.follow).take() {
            follow.abort();
        }
        let state = self.state.get_mut().unwrap_or_else(PoisonError::into_inner);
        for kept in &mut state.offline {
            if let Some(task) = kept.task.take() {
                task.abort();
            }
        }
        for copy in &mut state.copies {
            if let Some(task) = copy.task.take() {
                task.abort();
            }
        }
    }
}

#[derive(Default)]
struct State {
    /// In the order asked.
    offline: Vec<Kept>,
    /// Newest first.
    copies: Vec<Copy>,
    next_copy: u64,
    /// Numbers each download started, so an old one never ends a newer one.
    next_run: u64,
}

struct Kept {
    record: OfflineRecord,
    /// Bytes on disk, counted as they are written.
    received: Arc<AtomicU64>,
    /// While it downloads.
    task: Option<AbortHandle>,
    /// The run of `task`.
    run: u64,
    /// After a lost network: not started again before.
    wait_until: Option<Instant>,
}

impl Kept {
    fn file(&self) -> OfflineFile {
        let state = match &self.record.status {
            Stored::Queued if self.task.is_some() => OfflineState::Downloading,
            Stored::Queued => OfflineState::Queued,
            Stored::Paused => OfflineState::Paused,
            Stored::Completed => OfflineState::Available,
            Stored::Missing => OfflineState::Missing,
            Stored::Failed(error) => OfflineState::Failed(error.clone()),
        };
        OfflineFile {
            id: self.record.id(),
            target: self.record.target.playable(),
            state,
            received: self.received.load(Ordering::Relaxed),
            total: self.record.total,
            added: self.record.added,
        }
    }
}

struct Copy {
    copy: SavedCopy,
    received: Arc<AtomicU64>,
    task: Option<AbortHandle>,
}

impl Copy {
    fn saved(&self) -> SavedCopy {
        SavedCopy {
            received: self.received.load(Ordering::Relaxed),
            ..self.copy.clone()
        }
    }
}

/// A file kept offline, as `offline.json` keeps it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct OfflineRecord {
    library: String,
    media: String,
    target: Target,
    /// Its file in `files/`.
    file: String,
    /// The media's IV, in an encrypted library: the file stays encrypted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    iv: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    total: Option<u64>,
    status: Stored,
    added: i64,
}

impl OfflineRecord {
    fn id(&self) -> OfflineId {
        OfflineId::new(&self.library, &self.media)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum Stored {
    /// To download, or downloading while its task runs.
    Queued,
    Paused,
    Completed,
    Missing,
    Failed(String),
}

/// [`Playable`], as stored.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
enum Target {
    Movie(String),
    Episode {
        serie: String,
        season: u32,
        number: u32,
    },
}

impl Target {
    fn of(playable: &Playable) -> Target {
        match playable {
            Playable::Movie(movie) => Target::Movie(movie.clone()),
            Playable::Episode {
                serie,
                season,
                number,
            } => Target::Episode {
                serie: serie.clone(),
                season: *season,
                number: *number,
            },
        }
    }

    fn playable(&self) -> Playable {
        match self {
            Target::Movie(movie) => Playable::Movie(movie.clone()),
            Target::Episode {
                serie,
                season,
                number,
            } => Playable::Episode {
                serie: serie.clone(),
                season: *season,
                number: *number,
            },
        }
    }
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

fn storage(what: &str) -> impl Fn(std::io::Error) -> Error + '_ {
    move |error| Error::Storage {
        message: format!("{what}: {error}"),
    }
}

fn offline_error() -> Error {
    Error::Network {
        message: "Not connected to the server.".to_owned(),
        path: None,
    }
}

impl Downloads {
    /// The downloads of `copy`'s server, kept in `dir` (give each server its own,
    /// beside its copy). Those that were downloading go on once the server is reached.
    /// `listener` hears every change. Call it on a tokio runtime: the downloads run
    /// there.
    pub async fn open(copy: ServerCopy, dir: PathBuf, listener: impl OnDownloads) -> Result<Self> {
        tokio::fs::create_dir_all(dir.join("files"))
            .await
            .map_err(storage("cannot create the downloads folder"))?;
        let records: Vec<OfflineRecord> = read_json(&dir.join("offline.json")).await;
        let copies: Vec<SavedCopy> = read_json(&dir.join("copies.json")).await;
        let mut offline = Vec::with_capacity(records.len());
        for mut record in records {
            let len = tokio::fs::metadata(dir.join("files").join(&record.file))
                .await
                .map(|meta| meta.len())
                .unwrap_or(0);
            if record.status == Stored::Completed && record.total.is_some_and(|t| t != len) {
                record.status = Stored::Missing;
            } else if record.status == Stored::Missing && record.total == Some(len) {
                record.status = Stored::Completed;
            }
            offline.push(Kept {
                record,
                received: Arc::new(AtomicU64::new(len)),
                task: None,
                run: 0,
                wait_until: None,
            });
        }
        let next_copy = copies.iter().map(|c| c.id + 1).max().unwrap_or(0);
        let copies = (copies.into_iter())
            .map(|mut copy| {
                // A copy saving when the app closed did not end.
                if copy.state == CopyState::Saving {
                    copy.state = CopyState::Failed("The app closed before it was saved.".into());
                }
                Copy {
                    received: Arc::new(AtomicU64::new(copy.received)),
                    copy,
                    task: None,
                }
            })
            .collect();
        let downloads = Downloads {
            shared: Arc::new(Shared {
                copy,
                dir,
                runtime: tokio::runtime::Handle::current(),
                listener: Arc::new(listener),
                state: Mutex::new(State {
                    offline,
                    copies,
                    next_copy,
                    next_run: 0,
                }),
                last_progress: Mutex::new(None),
                follow: Mutex::new(None),
                saving: Mutex::new(()),
                writers: Mutex::default(),
            }),
        };
        downloads.save_offline();
        downloads.save_copies();
        downloads.follow_connection();
        downloads.pump();
        Ok(downloads)
    }

    /// Starts the queued downloads each time the copy connects.
    fn follow_connection(&self) {
        let mut events = self.shared.copy.mirror().subscribe();
        let weak = Arc::downgrade(&self.shared);
        let task = self.shared.runtime.spawn(async move {
            loop {
                match events.recv().await {
                    Ok(MirrorEvent::Connection(_))
                    | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                        let Some(shared) = weak.upgrade() else {
                            return;
                        };
                        for kept in &mut lock(&shared.state).offline {
                            kept.wait_until = None;
                        }
                        Downloads { shared }.pump();
                    }
                    Ok(_) => {}
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
                }
            }
        });
        *lock(&self.shared.follow) = Some(task.abort_handle());
    }

    // --- Kept offline

    /// Downloads a file of a movie or an episode (`target`) to play it without the
    /// server. Already kept, it is left as it is (a failed or missing one starts
    /// again). It waits in line for a free slot and for the server.
    pub fn keep_offline(&self, library: &str, media: &Media, target: &Playable) {
        let id = OfflineId::new(library, &media.id);
        {
            let mut state = lock(&self.shared.state);
            if let Some(kept) = state.offline.iter_mut().find(|k| k.record.id() == id) {
                if matches!(kept.record.status, Stored::Failed(_) | Stored::Missing) {
                    kept.record.status = Stored::Queued;
                } else {
                    return;
                }
            } else {
                let encrypted = media.iv.is_some();
                state.offline.push(Kept {
                    record: OfflineRecord {
                        library: library.to_owned(),
                        media: media.id.clone(),
                        target: Target::of(target),
                        file: file_name(library, media, encrypted),
                        iv: media.iv.clone(),
                        total: None,
                        status: Stored::Queued,
                        added: now_ms(),
                    },
                    received: Arc::new(AtomicU64::new(0)),
                    task: None,
                    run: 0,
                    wait_until: None,
                });
            }
        }
        self.save_offline();
        self.changed();
        self.pump();
    }

    /// Stops a download where it is; [`Self::resume`] goes on from there.
    pub fn pause(&self, id: &OfflineId) {
        {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state.offline.iter_mut().find(|k| &k.record.id() == id) else {
                return;
            };
            if kept.record.status != Stored::Queued {
                return;
            }
            if let Some(task) = kept.task.take() {
                task.abort();
            }
            kept.record.status = Stored::Paused;
        }
        self.save_offline();
        self.changed();
        self.pump();
    }

    /// Goes on with a paused download, or tries a failed or missing one again.
    pub fn resume(&self, id: &OfflineId) {
        {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state.offline.iter_mut().find(|k| &k.record.id() == id) else {
                return;
            };
            if matches!(
                kept.record.status,
                Stored::Paused | Stored::Failed(_) | Stored::Missing
            ) {
                kept.record.status = Stored::Queued;
            } else {
                return;
            }
        }
        self.save_offline();
        self.changed();
        self.pump();
    }

    /// Removes a file kept offline, or stops its download: the file is deleted. The
    /// media stays in the library. A file that cannot be deleted stays listed (its
    /// download paused), to remove again.
    pub async fn remove(&self, id: &OfflineId) -> Result<()> {
        let file = {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state.offline.iter_mut().find(|k| &k.record.id() == id) else {
                return Ok(());
            };
            if let Some(task) = kept.task.take() {
                task.abort();
            }
            if kept.record.status == Stored::Queued {
                kept.record.status = Stored::Paused;
            }
            kept.record.file.clone()
        };
        self.save_offline();
        self.changed();
        self.pump();
        // Once its writer stopped, else a write would come after the removal.
        let _writing = self.writer(&file).lock_owned().await;
        // On the runtime: the app may await this on its own executor.
        let path = self.files_dir().join(&file);
        (self
            .shared
            .runtime
            .spawn_blocking(move || remove_file(&path)))
        .await
        .map_err(|error| Error::Storage {
            message: format!("cannot remove the file: {error}"),
        })??;
        {
            let mut state = lock(&self.shared.state);
            if let Some(ix) = state.offline.iter().position(|k| &k.record.id() == id) {
                // Resumed meanwhile: stopped for good.
                if let Some(task) = state.offline.remove(ix).task {
                    task.abort();
                }
            }
        }
        self.save_offline();
        self.changed();
        self.pump();
        Ok(())
    }

    /// Removes every file kept offline of a library, as [`Self::remove`].
    pub async fn remove_library(&self, library: &str) -> Result<()> {
        let ids: Vec<OfflineId> = (lock(&self.shared.state).offline.iter())
            .filter(|kept| kept.record.library == library)
            .map(|kept| kept.record.id())
            .collect();
        for id in ids {
            self.remove(&id).await?;
        }
        Ok(())
    }

    /// Every file kept offline, in the order asked.
    pub fn offline_files(&self) -> Vec<OfflineFile> {
        (lock(&self.shared.state).offline.iter())
            .map(Kept::file)
            .collect()
    }

    /// A media's file kept offline.
    pub fn offline_file(&self, library: &str, media: &str) -> Option<OfflineFile> {
        let state = lock(&self.shared.state);
        (state.offline.iter())
            .find(|kept| kept.record.library == library && kept.record.media == media)
            .map(Kept::file)
    }

    /// The files kept offline of a movie or an episode.
    pub fn offline_files_of(&self, library: &str, target: &Playable) -> Vec<OfflineFile> {
        let target = Target::of(target);
        let state = lock(&self.shared.state);
        (state.offline.iter())
            .filter(|kept| kept.record.library == library && kept.record.target == target)
            .map(Kept::file)
            .collect()
    }

    /// Whether files download now or wait in line.
    pub fn busy(&self) -> bool {
        let state = lock(&self.shared.state);
        state
            .offline
            .iter()
            .any(|kept| kept.record.status == Stored::Queued)
            || state.copies.iter().any(|copy| copy.task.is_some())
    }

    /// How many files are on their way (kept offline or saved copies), and their
    /// share already written, from 0 to 1, when every size is known.
    pub fn activity(&self) -> (usize, Option<f32>) {
        let state = lock(&self.shared.state);
        let mut count = 0;
        let mut sizes = Some((0u64, 0u64));
        let mut add = |received: u64, total: Option<u64>| {
            count += 1;
            sizes = match (sizes, total) {
                (Some((r, t)), Some(total)) => Some((r + received, t + total)),
                _ => None,
            };
        };
        for kept in &state.offline {
            if kept.record.status == Stored::Queued {
                add(kept.received.load(Ordering::Relaxed), kept.record.total);
            }
        }
        for copy in &state.copies {
            if copy.task.is_some() {
                add(copy.received.load(Ordering::Relaxed), copy.copy.total);
            }
        }
        let progress = sizes
            .filter(|(_, total)| *total > 0)
            .map(|(received, total)| (received as f64 / total as f64).min(1.) as f32);
        (count, progress)
    }

    /// What a player reads to play a media's file kept offline: `None` until it is
    /// complete. An encrypted library's needs its passphrase set on the copy
    /// ([`Error::PassphraseRequired`] otherwise). A file found missing or short is
    /// marked [`OfflineState::Missing`] and gives `None`.
    pub async fn source(&self, library: &str, media: &str) -> Result<Option<OfflineSource>> {
        let id = OfflineId::new(library, media);
        let record = {
            let state = lock(&self.shared.state);
            (state.offline.iter())
                .find(|kept| kept.record.id() == id && kept.record.status == Stored::Completed)
                .map(|kept| kept.record.clone())
        };
        let Some(record) = record else {
            return Ok(None);
        };
        let path = self.files_dir().join(&record.file);
        // On the runtime: the player may await this on its own executor.
        let len = {
            let path = path.clone();
            (self
                .shared
                .runtime
                .spawn_blocking(move || std::fs::metadata(path)))
            .await
            .ok()
            .and_then(|metadata| metadata.ok())
            .map(|metadata| metadata.len())
        };
        if len.is_none() || len != record.total {
            self.set_status(&id, Stored::Missing, |_| {});
            return Ok(None);
        }
        let Some(iv) = record.iv else {
            return Ok(Some(OfflineSource::File(path)));
        };
        let key = (self.shared.copy.mirror())
            .library_key(library)
            .ok_or(Error::PassphraseRequired)?;
        let runtime = self.shared.runtime.clone();
        let reader = EncryptedMediaReader::open_file(path, runtime, key, decode_iv(&iv)?).await?;
        Ok(Some(OfflineSource::Encrypted(reader)))
    }

    /// The Downloads screen: the files kept offline by state, with their titles read
    /// from the copy, and the saved copies.
    pub async fn page(&self) -> Result<DownloadsPage> {
        let files = self.offline_files();
        let mut page = DownloadsPage {
            copies: self.copies(),
            ..Default::default()
        };
        let (mut movies, mut episodes) = (0, 0);
        for file in files {
            let row = self.row(file).await?;
            match row.file.state {
                OfflineState::Available => {
                    page.used += row.file.received;
                    match row.file.target {
                        Playable::Movie(_) => movies += 1,
                        Playable::Episode { .. } => episodes += 1,
                    }
                    page.available.push(row);
                }
                OfflineState::Missing | OfflineState::Failed(_) => {
                    page.used += row.file.received;
                    page.attention.push(row)
                }
                _ => {
                    page.used += row.file.received;
                    page.downloading.push(row)
                }
            }
        }
        page.available.reverse();
        let mut parts = Vec::new();
        match movies {
            0 => {}
            1 => parts.push("1 movie".to_owned()),
            n => parts.push(format!("{n} movies")),
        }
        match episodes {
            0 => {}
            1 => parts.push("1 episode".to_owned()),
            n => parts.push(format!("{n} episodes")),
        }
        if page.used > 0 {
            parts.push(text::bytes(page.used));
        }
        page.summary = (!parts.is_empty()).then(|| parts.join(" · "));
        Ok(page)
    }

    async fn row(&self, file: OfflineFile) -> Result<OfflineRow> {
        let copy = &self.shared.copy;
        let library = &file.id.library.clone();
        let file_name = (copy.media(library, &file.id.media).await?)
            .map(|media| media.item.name)
            .unwrap_or_default();
        let mut row = OfflineRow {
            status: file.status(),
            title: String::new(),
            subtitle: String::new(),
            file_name,
            movie: None,
            serie: None,
            episode: None,
            file,
        };
        match &row.file.target {
            Playable::Movie(id) => {
                if let Some(movie) = copy.movie(library, id).await? {
                    row.title = movie.item.name.clone();
                    row.subtitle = (movie.item.year)
                        .map(|year| year.to_string())
                        .unwrap_or_default();
                    row.movie = Some(movie.item);
                }
            }
            Playable::Episode {
                serie,
                season,
                number,
            } => {
                if let Some(found) = copy.serie(library, serie).await? {
                    row.title = found.item.name.clone();
                    row.serie = Some(found.item);
                }
                let id = format!("{serie}x{season}x{number}");
                let label = format!("S{season}, E{number}");
                row.subtitle = label;
                if let Some(episode) = copy.episode(library, &id).await? {
                    row.subtitle = match episode.name.as_deref().filter(|n| !n.is_empty()) {
                        Some(name) => format!("{} · {name}", episode_label(&episode)),
                        None => episode_label(&episode),
                    };
                    row.episode = Some(episode);
                }
            }
        }
        if row.title.is_empty() {
            row.title = row.file_name.clone();
        }
        Ok(row)
    }

    // --- Saved copies

    /// Saves a media's file to `path`, replacing what is there, decrypted in an
    /// encrypted library (set its passphrase first). It goes to a partial file of its
    /// own beside `path` (`<name>.part`, `<name>.1.part`...), which takes its place
    /// once complete: a failure or a cancel never leaves a truncated file, nor removes
    /// the file it was to replace. Returns its id.
    pub fn save_copy(&self, library: &str, media: &Media, path: PathBuf) -> Result<u64> {
        let api = (self.shared.copy.mirror())
            .library_api(library)
            .ok_or_else(offline_error)?;
        let received = Arc::new(AtomicU64::new(0));
        let weak = Arc::downgrade(&self.shared);
        let id = {
            // Held until the copy is listed: its task, ending at once (a file that
            // cannot be created), finds it there.
            let mut state = lock(&self.shared.state);
            let id = state.next_copy;
            state.next_copy += 1;
            let task = {
                let (media, path, received) = (media.clone(), path.clone(), received.clone());
                self.shared.runtime.spawn(async move {
                    let result = save_media(&api, &media, &path, &received, &weak).await;
                    if let Some(shared) = weak.upgrade() {
                        Downloads { shared }.copy_ended(id, result);
                    }
                })
            };
            state.copies.insert(
                0,
                Copy {
                    copy: SavedCopy {
                        id,
                        media: media.id.clone(),
                        name: media.name.clone(),
                        path,
                        state: CopyState::Saving,
                        received: 0,
                        total: media.size,
                        finished: None,
                    },
                    received,
                    task: Some(task.abort_handle()),
                },
            );
            id
        };
        self.changed();
        Ok(id)
    }

    /// Stops a copy being saved, removing its partial file, and forgets it.
    pub fn cancel_copy(&self, id: u64) {
        {
            let mut state = lock(&self.shared.state);
            let Some(ix) = state.copies.iter().position(|c| c.copy.id == id) else {
                return;
            };
            let mut copy = state.copies.remove(ix);
            if let Some(task) = copy.task.take() {
                task.abort();
            }
        }
        self.save_copies();
        self.changed();
    }

    /// Forgets the copies that ended (their files stay).
    pub fn clear_copies(&self) {
        lock(&self.shared.state)
            .copies
            .retain(|copy| copy.task.is_some());
        self.save_copies();
        self.changed();
    }

    /// The saved copies, newest first: being saved, saved or failed.
    pub fn copies(&self) -> Vec<SavedCopy> {
        (lock(&self.shared.state).copies.iter())
            .map(Copy::saved)
            .collect()
    }

    /// Whether a media's file is being saved somewhere.
    pub fn is_saving(&self, media: &str) -> bool {
        (lock(&self.shared.state).copies.iter())
            .any(|copy| copy.task.is_some() && copy.copy.media == media)
    }

    fn copy_ended(&self, id: u64, result: Result<()>) {
        let ended = {
            let mut state = lock(&self.shared.state);
            let Some(copy) = state.copies.iter_mut().find(|c| c.copy.id == id) else {
                return;
            };
            copy.task = None;
            copy.copy.received = copy.received.load(Ordering::Relaxed);
            copy.copy.finished = Some(now_ms());
            copy.copy.state = match result {
                Ok(()) => CopyState::Saved,
                Err(error) => CopyState::Failed(error.to_string()),
            };
            let ended = copy.copy.clone();
            // Only ended copies count against the limit.
            let mut ended_seen = 0;
            state.copies.retain(|copy| {
                if copy.task.is_some() {
                    return true;
                }
                ended_seen += 1;
                ended_seen <= COPIES_KEPT
            });
            ended
        };
        self.save_copies();
        self.shared.tell(DownloadsEvent::CopyEnded(ended));
        self.changed();
    }

    // --- The queue

    /// Starts queued downloads while slots are free and the server is reached.
    fn pump(&self) {
        let mut started = Vec::new();
        {
            let mut guard = lock(&self.shared.state);
            let state = &mut *guard;
            let running = state.offline.iter().filter(|k| k.task.is_some()).count();
            let mut free = CONCURRENT.saturating_sub(running);
            for kept in &mut state.offline {
                if free == 0 {
                    break;
                }
                if kept.record.status != Stored::Queued
                    || kept.task.is_some()
                    || kept.wait_until.is_some_and(|until| until > Instant::now())
                {
                    continue;
                }
                let Some(api) = self.shared.copy.mirror().library_api(&kept.record.library) else {
                    continue;
                };
                let weak = Arc::downgrade(&self.shared);
                let record = kept.record.clone();
                let received = kept.received.clone();
                let path = self.files_dir().join(&record.file);
                let writer = self.writer(&record.file);
                state.next_run += 1;
                let run = state.next_run;
                let task = self.shared.runtime.spawn(async move {
                    let id = record.id();
                    let file = (&api, record.media.as_str(), path.as_path(), writer);
                    let result = fetch_to_file(file, &received, &weak, {
                        let weak = weak.clone();
                        let id = id.clone();
                        move |total| {
                            if let Some(shared) = weak.upgrade() {
                                Downloads { shared }.set_total(&id, total);
                            }
                        }
                    })
                    .await;
                    if let Some(shared) = weak.upgrade() {
                        Downloads { shared }.offline_ended(&id, run, result);
                    }
                });
                kept.task = Some(task.abort_handle());
                kept.run = run;
                started.push(());
                free -= 1;
            }
        }
        if !started.is_empty() {
            self.changed();
        }
    }

    fn set_total(&self, id: &OfflineId, total: u64) {
        let changed = {
            let mut state = lock(&self.shared.state);
            match state.offline.iter_mut().find(|k| &k.record.id() == id) {
                Some(kept) if kept.record.total != Some(total) => {
                    kept.record.total = Some(total);
                    true
                }
                _ => false,
            }
        };
        if changed {
            self.save_offline();
        }
    }

    /// Ends the download `run` of a kept file, unless it was stopped (paused,
    /// removed) or another one started since.
    fn offline_ended(&self, id: &OfflineId, run: u64, result: Result<()>) {
        let connected = self.shared.copy.api().is_some();
        let lost = matches!(result, Err(Error::Network { .. } | Error::Timeout { .. }));
        {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state.offline.iter_mut().find(|k| &k.record.id() == id) else {
                return;
            };
            if kept.task.is_none() || kept.run != run {
                return;
            }
            kept.task = None;
            kept.record.status = match &result {
                Ok(()) => Stored::Completed,
                // Lost with the connection: it goes on once the server is back.
                Err(_) if !connected => Stored::Queued,
                // Lost with the network: it goes on a little later, or once the copy
                // connects again.
                Err(_) if lost => {
                    kept.wait_until = Some(Instant::now() + RETRY_AFTER);
                    Stored::Queued
                }
                Err(error) => Stored::Failed(error.to_string()),
            };
        }
        if lost && connected {
            let weak = Arc::downgrade(&self.shared);
            self.shared.runtime.spawn(async move {
                tokio::time::sleep(RETRY_AFTER).await;
                if let Some(shared) = weak.upgrade() {
                    Downloads { shared }.pump();
                }
            });
        }
        self.save_offline();
        self.changed();
        if result.is_ok() {
            self.shared.tell(DownloadsEvent::Available(id.clone()));
        }
        self.pump();
    }

    /// Sets a kept file's status, then lets `change` change it further.
    fn set_status(&self, id: &OfflineId, status: Stored, change: impl FnOnce(&mut Kept)) {
        {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state.offline.iter_mut().find(|k| &k.record.id() == id) else {
                return;
            };
            kept.record.status = status;
            change(kept);
        }
        self.save_offline();
        self.changed();
    }

    // --- Storage and listener

    fn files_dir(&self) -> PathBuf {
        self.shared.dir.join("files")
    }

    /// The writer lock of a file in `files/` (see [`Shared::writers`]).
    fn writer(&self, file: &str) -> Arc<AsyncMutex<()>> {
        let mut writers = lock(&self.shared.writers);
        Arc::clone(writers.entry(file.to_owned()).or_default())
    }

    fn changed(&self) {
        *lock(&self.shared.last_progress) = Some(Instant::now());
        self.shared.tell(DownloadsEvent::Changed);
    }

    fn save_offline(&self) {
        let _saving = lock(&self.shared.saving);
        let records: Vec<OfflineRecord> = (lock(&self.shared.state).offline.iter())
            .map(|kept| kept.record.clone())
            .collect();
        write_json(&self.shared.dir.join("offline.json"), &records);
    }

    fn save_copies(&self) {
        let _saving = lock(&self.shared.saving);
        let copies: Vec<SavedCopy> = (lock(&self.shared.state).copies.iter())
            .filter(|copy| copy.task.is_none())
            .map(Copy::saved)
            .collect();
        write_json(&self.shared.dir.join("copies.json"), &copies);
    }
}

/// Tells the listener of progress, at most every [`PROGRESS_EVERY`].
fn progressed(shared: &Weak<Shared>) {
    let Some(shared) = shared.upgrade() else {
        return;
    };
    {
        let mut last = lock(&shared.last_progress);
        if last.is_some_and(|last| last.elapsed() < PROGRESS_EVERY) {
            return;
        }
        *last = Some(Instant::now());
    }
    shared.tell(DownloadsEvent::Changed);
}

/// The name of a kept file in `files/`: the library and media ids, made safe, with
/// the extension of its name; an encrypted one's is `.enc` (its name is secret and
/// its bytes are not the plain file's).
fn file_name(library: &str, media: &Media, encrypted: bool) -> String {
    let safe = |text: &str| -> String {
        text.chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() || c == '-' {
                    c
                } else {
                    '_'
                }
            })
            .collect()
    };
    let extension = if encrypted {
        "enc".to_owned()
    } else {
        Path::new(&media.name)
            .extension()
            .and_then(|e| e.to_str())
            .map(safe)
            .filter(|e| !e.is_empty() && e.len() <= 8)
            .unwrap_or_else(|| "bin".to_owned())
    };
    format!("{}.{}.{extension}", safe(library), safe(&media.id))
}

/// The media `.1` of the library `.0` to download to the file `.2`, with that
/// file's writer lock (see [`Shared::writers`]).
type FileToFetch<'a> = (&'a LibraryApi, &'a str, &'a Path, Arc<AsyncMutex<()>>);

/// Downloads a media's file (its data part in an encrypted library, as the server
/// serves it by ranges) to a file, going on from what the file already holds.
/// `received` follows the bytes on disk; `on_total` hears the size once known.
///
/// Holds the file's writer lock until its last write is on disk, even once aborted:
/// each write runs on the blocking pool with the lock and the file.
async fn fetch_to_file(
    (api, media, path, writer): FileToFetch<'_>,
    received: &AtomicU64,
    shared: &Weak<Shared>,
    on_total: impl Fn(u64),
) -> Result<()> {
    let writing = Arc::new(writer.lock_owned().await);
    let runtime = tokio::runtime::Handle::current();
    let opened = {
        let path = path.to_owned();
        runtime.spawn_blocking(move || {
            let file = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)?;
            let len = file.metadata()?.len();
            Ok::<_, std::io::Error>((Arc::new(file), len))
        })
    };
    let (file, mut offset) = (opened.await)
        .map_err(|error| Error::Storage {
            message: format!("cannot write the file: {error}"),
        })?
        .map_err(storage("cannot write the file"))?;
    received.store(offset, Ordering::Relaxed);
    loop {
        let range = format!("bytes={}-{}", offset, offset + CHUNK - 1);
        let request = Request::get(api.media_path(media)).header("Range", range);
        let response = match api.client().request(request).await {
            // Asked past the end: complete if the server's file is that long, else it
            // changed since (now shorter): start over.
            Err(Error::Transport {
                status: Some(416), ..
            }) if offset > 0 => {
                if remote_len(api, media).await? == offset {
                    on_total(offset);
                    return Ok(());
                }
                truncate(&runtime, path, &writing).await?;
                offset = 0;
                received.store(0, Ordering::Relaxed);
                continue;
            }
            other => other?,
        };
        let total = match response.status {
            206 => content_range_total(response.header("content-range")).ok_or_else(|| {
                Error::malformed("a part of the file came without its size", None)
            })?,
            // No range support: the whole file, only from its start.
            200 if offset == 0 => response.body.len() as u64,
            200 => {
                return Err(Error::malformed(
                    "the server cannot send parts of this file: it needs an update",
                    None,
                ));
            }
            status => {
                return Err(Error::malformed(
                    format!("unexpected answer {status} to a part of the file"),
                    None,
                ));
            }
        };
        on_total(total);
        if response.body.is_empty() && offset < total {
            return Err(Error::malformed("the server sent an empty part", None));
        }
        let len = response.body.len() as u64;
        write_part(&runtime, &file, &writing, response.body).await?;
        offset += len;
        received.store(offset, Ordering::Relaxed);
        progressed(shared);
        if offset >= total {
            break;
        }
    }
    Ok(())
}

/// The length of a media's file on the server (its data part in an encrypted
/// library).
async fn remote_len(api: &LibraryApi, media: &str) -> Result<u64> {
    let request = Request::get(api.media_path(media)).header("Range", "bytes=0-0");
    let response = api.client().request(request).await?;
    match response.status {
        206 => content_range_total(response.header("content-range"))
            .ok_or_else(|| Error::malformed("a part of the file came without its size", None)),
        _ => Ok(response.body.len() as u64),
    }
}

/// Empties the file at `path` on the blocking pool, holding `writing` until done.
/// Through a handle of its own: one that appends cannot truncate (Windows).
async fn truncate(
    runtime: &tokio::runtime::Handle,
    path: &Path,
    writing: &Arc<OwnedMutexGuard<()>>,
) -> Result<()> {
    let (path, writing) = (path.to_owned(), Arc::clone(writing));
    let emptied = runtime.spawn_blocking(move || {
        let _writing = writing;
        std::fs::OpenOptions::new()
            .write(true)
            .open(path)?
            .set_len(0)
    });
    (emptied.await)
        .map_err(|error| Error::Storage {
            message: format!("cannot write the file: {error}"),
        })?
        .map_err(storage("cannot write the file"))
}

/// Appends `bytes` to `file` on the blocking pool, holding `writing` until done.
async fn write_part(
    runtime: &tokio::runtime::Handle,
    file: &Arc<std::fs::File>,
    writing: &Arc<OwnedMutexGuard<()>>,
    bytes: Vec<u8>,
) -> Result<()> {
    use std::io::Write as _;
    let (file, writing) = (Arc::clone(file), Arc::clone(writing));
    let written = runtime.spawn_blocking(move || {
        let _writing = writing;
        (&*file).write_all(&bytes)
    });
    (written.await)
        .map_err(|error| Error::Storage {
            message: format!("cannot write the file: {error}"),
        })?
        .map_err(storage("cannot write the file"))
}

/// The total of a `Content-Range: bytes a-b/total` header.
fn content_range_total(header: Option<&str>) -> Option<u64> {
    header?.rsplit('/').next()?.trim().parse().ok()
}

/// Saves a media's file to `path` through a partial file of its own (see
/// [`Downloads::save_copy`]).
async fn save_media(
    api: &LibraryApi,
    media: &Media,
    path: &Path,
    received: &AtomicU64,
    shared: &Weak<Shared>,
) -> Result<()> {
    let part = create_part(path).await?;
    let written = async {
        if api.is_encrypted() {
            let reader = api.open_encrypted_media(media).await?;
            let mut file = tokio::fs::OpenOptions::new()
                .write(true)
                .open(&part.path)
                .await
                .map_err(storage("cannot write the file"))?;
            let mut offset = 0;
            while offset < reader.len() {
                let chunk = reader.read_at(offset, CHUNK as usize).await?;
                if chunk.is_empty() {
                    break;
                }
                file.write_all(&chunk)
                    .await
                    .map_err(storage("cannot write the file"))?;
                offset += chunk.len() as u64;
                received.store(offset, Ordering::Relaxed);
                progressed(shared);
            }
            file.flush().await.map_err(storage("cannot write the file"))
        } else {
            let file = (api, media.id.as_str(), part.path.as_path(), Arc::default());
            fetch_to_file(file, received, shared, |_| {}).await
        }
    }
    .await;
    written?;
    part.finish(path).await
}

/// A partial file, removed when dropped unless [`Part::finish`]ed.
struct Part {
    path: PathBuf,
    done: bool,
}

impl Drop for Part {
    fn drop(&mut self) {
        if !self.done {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

impl Part {
    /// Moves it in place of `path`.
    async fn finish(mut self, path: &Path) -> Result<()> {
        tokio::fs::rename(&self.path, path)
            .await
            .map_err(storage("cannot save the file"))?;
        self.done = true;
        Ok(())
    }
}

/// The partial file of `path` at `attempt`: `photo.jpg` downloads to `photo.jpg.part`,
/// then `photo.jpg.1.part`...
fn part_path(path: &Path, attempt: u32) -> PathBuf {
    let mut name = path.file_name().map(OsString::from).unwrap_or_default();
    if attempt > 0 {
        name.push(format!(".{attempt}"));
    }
    name.push(".part");
    path.with_file_name(name)
}

/// Creates a partial file of its own beside `path`, never an existing one.
async fn create_part(path: &Path) -> Result<Part> {
    for attempt in 0..PART_ATTEMPTS {
        let candidate = part_path(path, attempt);
        match tokio::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&candidate)
            .await
        {
            Ok(_) => {
                return Ok(Part {
                    path: candidate,
                    done: false,
                });
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(storage("cannot create the file")(error)),
        }
    }
    Err(Error::Storage {
        message: "too many partial files beside this one".to_owned(),
    })
}

fn remove_file(path: &Path) -> Result<()> {
    match std::fs::remove_file(path) {
        Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
            Err(storage("cannot remove the file")(error))
        }
        _ => Ok(()),
    }
}

/// A missing or unreadable file gives the default.
async fn read_json<T: serde::de::DeserializeOwned + Default>(path: &Path) -> T {
    tokio::fs::read(path)
        .await
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
        .unwrap_or_default()
}

/// Written through a temporary file, so a crash never leaves half of it.
fn write_json<T: Serialize>(path: &Path, value: &T) {
    let write = || -> std::io::Result<()> {
        let json = serde_json::to_vec_pretty(value).map_err(std::io::Error::other)?;
        let temp = path.with_extension("json.tmp");
        std::fs::write(&temp, json)?;
        std::fs::rename(&temp, path)
    };
    // The state stays right in memory; the next write tries again.
    let _ = write();
}