redseat-api 0.16.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
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
//! 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.
//!
//! Mobile apps that cannot move bytes in-process (iOS background `URLSession`,
//! Android `WorkManager` / `DownloadManager`) open [`Downloads`] with
//! [`Downloads::open_native`] instead. The queue, concurrency, persistence, pause,
//! resume, removal, retries, page, and playback ([`Downloads::source`], including
//! on-the-fly decryption) stay shared; instead of fetching bytes itself, `Downloads`
//! emits [`TransferEvent::Start`] with a [`TransferJob`] (URL, server token, absolute
//! destination path, and resume offset) and [`TransferEvent::Cancel`] on pause or
//! removal (active jobs can also be read with [`Downloads::pending_transfers`]). On
//! launch, the app calls [`Downloads::reconcile_transfers`] with the `(id, run)`
//! pairs still running in the OS so surviving transfers keep running without
//! duplicate starts and dropped ones restart with a higher run number. The app
//! reports progress with [`Downloads::transferred`], completion or failure with
//! [`Downloads::transfer_ended`], and asks [`Downloads::refresh_transfer`] for a
//! fresh job when a token expires or the server answers 401.
//!
//! The app reads the state ([`Downloads::offline_files`], [`Downloads::page`],
//! [`Downloads::copies`]) and reads it again when the listener given to
//! [`Downloads::open`] or [`Downloads::open_native`] 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, mpsc, oneshot};
use tokio::task::AbortHandle;

use super::ServerCopy;
use super::catalog::{Playable, episode_label};
use super::text;
use crate::client::{AuthorizedUrl, 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, MediaFileQuery};
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 {}

/// One offline file ready for the app's native downloader (iOS `URLSession`,
/// Android `WorkManager` / `DownloadManager`), emitted by [`Downloads::open_native`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferJob {
    pub id: OfflineId,
    /// Identifies this attempt: pass it back to [`Downloads::transferred`],
    /// [`Downloads::transfer_ended`] and [`Downloads::refresh_transfer`] so a stale
    /// callback never overrides a newer run.
    pub run: u64,
    /// Absolute URL and server token. Send the token with
    /// [`AuthorizedUrl::authorization`] (or [`Self::headers`]), or in the URL with
    /// [`AuthorizedUrl::with_token_query`] when the downloader cannot set headers.
    /// Ask [`Downloads::refresh_transfer`] for a fresh job when the server answers
    /// 401 or before [`AuthorizedUrl::expires`].
    pub source: AuthorizedUrl,
    /// Absolute path in `files/` to write to (appending from `offset`).
    pub path: PathBuf,
    /// Bytes already on disk to resume from (`Range: bytes=<offset>-`).
    pub offset: u64,
}

impl TransferJob {
    /// HTTP headers to send with the request: `Authorization`, and `Range` when
    /// resuming from a non-zero `offset`.
    pub fn headers(&self) -> Vec<(String, String)> {
        let mut headers = vec![("Authorization".to_owned(), self.source.authorization())];
        if self.offset > 0 {
            headers.push(("Range".to_owned(), format!("bytes={}-", self.offset)));
        }
        headers
    }
}

/// What the app's native downloader hears from [`Downloads::open_native`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransferEvent {
    /// Start (or resume) downloading this file.
    Start(TransferJob),
    /// Stop the OS transfer for `(id, run)`: it was paused or removed.
    Cancel { id: OfflineId, run: u64 },
}

/// What the app gives [`Downloads::open_native`] to hear native transfer jobs.
/// Called on the runtime's threads.
pub trait OnTransfer: Fn(TransferEvent) + Send + Sync + 'static {}
impl<F: Fn(TransferEvent) + Send + Sync + 'static> OnTransfer for F {}

/// How a native transfer ended, reported to [`Downloads::transfer_ended`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransferOutcome {
    /// The whole file is on disk at the job's path.
    Completed,
    /// Interrupted by the network or a timeout: queued again after a short wait,
    /// or once the copy connects again.
    NetworkLost,
    /// Stopped on an error retrying on its own will not fix (404, disk full,
    /// bad response...): marked [`OfflineState::Failed`].
    Failed(String),
}

/// 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()
    }
}

enum TransferMsg {
    Event(TransferEvent),
    /// Completes once all prior events have been delivered to `on_transfer`.
    Flush(oneshot::Sender<()>),
}

struct Shared {
    copy: ServerCopy,
    dir: PathBuf,
    runtime: tokio::runtime::Handle,
    /// Ordered delivery to the [`OnDownloads`] listener on the runtime.
    events: mpsc::UnboundedSender<DownloadsEvent>,
    /// Ordered delivery to the [`OnTransfer`] listener in native mode; `None` in
    /// in-process mode.
    transfers: Option<mpsc::UnboundedSender<TransferMsg>>,
    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, in order, as [`OnDownloads`] promises:
    /// never inside the app's own call, whatever executor it makes it from.
    fn tell(&self, event: DownloadsEvent) {
        let _ = self.events.send(event);
    }

    /// Tells the native transfer listener on the runtime, in order.
    fn tell_transfer(&self, event: TransferEvent) {
        if let Some(transfers) = &self.transfers {
            let _ = transfers.send(TransferMsg::Event(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 {
            // Abort in-process tasks and native preparations; active OS transfers
            // are left running (keeping `transfer_run` in `offline.json`) so
            // background downloads survive app close.
            match kept.active.take() {
                Some(Active::Task(task) | Active::Preparing(task)) => task.abort(),
                Some(Active::Native(_) | Active::Restored(_) | Active::Refreshing) | None => {}
            }
        }
        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,
}

/// Active work on a kept file, occupying one [`CONCURRENT`] slot.
enum Active {
    /// In-process task downloading the file.
    Task(AbortHandle),
    /// Native transfer being prepared (reading disk offset and server token).
    Preparing(AbortHandle),
    /// Native transfer handed to the app in this session.
    Native(TransferJob),
    /// Native transfer left running in the OS from a previous session, until it
    /// ends, refreshes, cancels, or [`Downloads::reconcile_transfers`] reports
    /// that the OS no longer has it.
    Restored(u64),
    /// Previous native run cancelled; waiting for `on_transfer` to finish
    /// cancelling it and settling the disk offset before starting the replacement.
    Refreshing,
}

struct Kept {
    record: OfflineRecord,
    /// Bytes on disk, counted as they are written.
    received: Arc<AtomicU64>,
    /// While it downloads (in-process task, native prep, or handed to the app).
    active: Option<Active>,
    /// The run of `active`.
    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.active.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,
        }
    }

    fn is_preparing_run(&self, run: u64) -> bool {
        matches!(self.active, Some(Active::Preparing(_))) && self.run == run
    }

    fn is_refreshing_run(&self, run: u64) -> bool {
        matches!(self.active, Some(Active::Refreshing)) && self.run == run
    }

    fn is_native_run(&self, run: u64) -> bool {
        matches!(self.active, Some(Active::Native(_) | Active::Restored(_))) && self.run == run
    }

    /// Stops any active work on this file. Returns the run number if a native
    /// transfer had been handed to the app and must be cancelled.
    fn stop(&mut self) -> Option<u64> {
        self.record.transfer_run = None;
        match self.active.take() {
            Some(Active::Task(task) | Active::Preparing(task)) => {
                task.abort();
                None
            }
            Some(Active::Native(job)) => Some(job.run),
            Some(Active::Restored(run)) => Some(run),
            // Cancel for the previous run was already enqueued by `refresh_transfer`.
            Some(Active::Refreshing) | None => None,
        }
    }
}

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>,
    /// Run number of the native transfer handed to the OS, kept across restarts
    /// until it ends or [`Downloads::reconcile_transfers`] clears it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    transfer_run: Option<u64>,
    /// Highest native run number issued for this record, so `next_run` stays
    /// monotonic across restarts.
    #[serde(default, skip_serializing_if = "is_zero")]
    last_run: u64,
    status: Stored,
    added: i64,
}

fn is_zero(value: &u64) -> bool {
    *value == 0
}

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> {
        Self::open_inner(copy, dir, listener, None).await
    }

    /// Like [`Self::open`], but hands offline file transfers to the app's native
    /// downloader (iOS `URLSession`, Android `WorkManager` / `DownloadManager`)
    /// through `on_transfer` instead of fetching bytes in-process.
    ///
    /// Native transfers that were running before an app restart are restored as
    /// active so no duplicate [`TransferEvent::Start`] is emitted and surviving OS
    /// callbacks match their persisted run numbers. Call
    /// [`Self::reconcile_transfers`] after launch with the `(id, run)` pairs still
    /// alive in the OS so dropped transfers restart and orphaned OS tasks cancel.
    ///
    /// The app reports progress with [`Self::transferred`], completion or failure
    /// with [`Self::transfer_ended`], and asks [`Self::refresh_transfer`] for a fresh
    /// job when a token expires or the server answers 401. Active jobs issued in
    /// this session are also listed by [`Self::pending_transfers`].
    pub async fn open_native(
        copy: ServerCopy,
        dir: PathBuf,
        listener: impl OnDownloads,
        on_transfer: impl OnTransfer,
    ) -> Result<Self> {
        Self::open_inner(copy, dir, listener, Some(Arc::new(on_transfer))).await
    }

    async fn open_inner(
        copy: ServerCopy,
        dir: PathBuf,
        listener: impl OnDownloads,
        on_transfer: Option<Arc<dyn Fn(TransferEvent) + Send + Sync>>,
    ) -> Result<Self> {
        let dir = std::path::absolute(&dir).unwrap_or(dir);
        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 native = on_transfer.is_some();
        let mut next_run = 0u64;
        let mut offline = Vec::with_capacity(records.len());
        for mut record in records {
            next_run = next_run
                .max(record.last_run)
                .max(record.transfer_run.unwrap_or(0));
            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;
            }
            let (active, run) = if native && record.status == Stored::Queued {
                if let Some(run) = record.transfer_run {
                    (Some(Active::Restored(run)), run)
                } else {
                    (None, 0)
                }
            } else {
                record.transfer_run = None;
                (None, 0)
            };
            offline.push(Kept {
                record,
                received: Arc::new(AtomicU64::new(len)),
                active,
                run,
                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 runtime = tokio::runtime::Handle::current();
        let (events, mut events_rx) = mpsc::unbounded_channel();
        runtime.spawn(async move {
            while let Some(event) = events_rx.recv().await {
                listener(event);
            }
        });
        let transfers = on_transfer.map(|on_transfer| {
            let (tx, mut rx) = mpsc::unbounded_channel::<TransferMsg>();
            runtime.spawn(async move {
                while let Some(msg) = rx.recv().await {
                    match msg {
                        TransferMsg::Event(event) => on_transfer(event),
                        TransferMsg::Flush(done) => {
                            let _ = done.send(());
                        }
                    }
                }
            });
            tx
        });
        let downloads = Downloads {
            shared: Arc::new(Shared {
                copy,
                dir,
                runtime,
                events,
                transfers,
                state: Mutex::new(State {
                    offline,
                    copies,
                    next_copy,
                    next_run,
                }),
                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;
                    kept.wait_until = None;
                } 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,
                        transfer_run: None,
                        last_run: 0,
                        status: Stored::Queued,
                        added: now_ms(),
                    },
                    received: Arc::new(AtomicU64::new(0)),
                    active: 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;
            }
            // Enqueue Cancel while holding `state` so it stays strictly ordered
            // after the corresponding Start.
            if let Some(run) = kept.stop() {
                self.cancel_transfer(id.clone(), run);
            }
            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;
                kept.wait_until = None;
            } 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.
    ///
    /// In native mode, waits until `on_transfer` has finished processing any
    /// preceding [`TransferEvent::Start`] and [`TransferEvent::Cancel`] before
    /// deleting the file so a queued start cannot recreate it after removal.
    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(run) = kept.stop() {
                self.cancel_transfer(id.clone(), run);
            }
            if kept.record.status == Stored::Queued {
                kept.record.status = Stored::Paused;
            }
            kept.record.file.clone()
        };
        self.save_offline();
        self.changed();
        self.pump();
        // Wait for `on_transfer` to finish processing any queued Start and Cancel
        // (including from a preceding pause) before deleting the destination file.
        self.flush_transfers().await;
        // 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 resumed_path = {
            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.
                let mut removed = state.offline.remove(ix);
                if let Some(run) = removed.stop() {
                    self.cancel_transfer(id.clone(), run);
                    Some(self.files_dir().join(&removed.record.file))
                } else {
                    None
                }
            } else {
                None
            }
        };
        if let Some(path) = resumed_path {
            self.flush_transfers().await;
            let _ = self
                .shared
                .runtime
                .spawn_blocking(move || remove_file(&path))
                .await;
        }
        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();
    }

    // --- Native transfers

    /// Active native transfer jobs handed to the app in this session (empty in
    /// in-process mode). Transfers restored from a previous session are not listed
    /// here because tokens are never written to disk; call [`Self::refresh_transfer`]
    /// if a restored transfer needs a fresh URL and token.
    pub fn pending_transfers(&self) -> Vec<TransferJob> {
        let state = lock(&self.shared.state);
        state
            .offline
            .iter()
            .filter_map(|kept| match &kept.active {
                Some(Active::Native(job)) => Some(job.clone()),
                _ => None,
            })
            .collect()
    }

    /// Reconciles OS background transfers that survived an app restart.
    ///
    /// Pass the `(id, run)` pairs still alive in the OS downloader (from
    /// `URLSession.getAllTasks` or Android `WorkManager`) right after
    /// [`Self::open_native`]:
    ///
    /// - Restored transfers still in `running` stay active without emitting a
    ///   duplicate [`TransferEvent::Start`] and keep accepting
    ///   [`Self::transferred`], [`Self::transfer_ended`] and
    ///   [`Self::refresh_transfer`].
    /// - Restored transfers absent from `running` (dropped by the OS while the app
    ///   was closed, or already finished without delivering a callback) are
    ///   requeued and pumped with a higher run number resuming from the bytes on
    ///   disk (or marked [`OfflineState::Available`] if already complete).
    /// - Any `(id, run)` in `running` that is not active here (for example paused
    ///   or removed before a crash) gets a [`TransferEvent::Cancel`].
    pub fn reconcile_transfers(&self, running: &[(OfflineId, u64)]) {
        let mut changed = false;
        {
            let mut state = lock(&self.shared.state);
            for (_, run) in running {
                state.next_run = state.next_run.max(*run);
            }
            for kept in &mut state.offline {
                if let Some(Active::Restored(run)) = kept.active {
                    let id = kept.record.id();
                    if !running
                        .iter()
                        .any(|(r_id, r_run)| r_id == &id && *r_run == run)
                    {
                        kept.active = None;
                        kept.record.transfer_run = None;
                        changed = true;
                    }
                }
            }
            for (id, run) in running {
                let active = state
                    .offline
                    .iter()
                    .any(|kept| &kept.record.id() == id && kept.is_native_run(*run));
                if !active {
                    self.cancel_transfer(id.clone(), *run);
                }
            }
        }
        if changed {
            self.save_offline();
            self.changed();
            self.pump();
        }
    }

    /// Reports progress of a running native transfer: `received` bytes are now on
    /// disk, out of `total` once known. Ignored if `id` is not running `run`.
    pub fn transferred(&self, id: &OfflineId, run: u64, received: u64, total: Option<u64>) {
        let total_changed = {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state
                .offline
                .iter_mut()
                .find(|k| &k.record.id() == id && k.is_native_run(run))
            else {
                return;
            };
            kept.received.store(received, Ordering::Relaxed);
            match total {
                Some(total) if kept.record.total != Some(total) => {
                    kept.record.total = Some(total);
                    true
                }
                _ => false,
            }
        };
        if total_changed {
            self.save_offline();
        }
        progressed(&Arc::downgrade(&self.shared));
    }

    /// Reports the end of a running native transfer (`id`, `run`). Ignored if `id`
    /// is no longer running `run` (for example after a pause, removal or refresh).
    ///
    /// On [`TransferOutcome::Completed`], checks the file on disk (on the runtime's
    /// blocking pool) so its stored size matches what was written before marking it
    /// [`OfflineState::Available`].
    pub async fn transfer_ended(&self, id: &OfflineId, run: u64, outcome: TransferOutcome) {
        let outcome = match outcome {
            TransferOutcome::Completed => {
                let info = {
                    let state = lock(&self.shared.state);
                    (state.offline.iter())
                        .find(|kept| &kept.record.id() == id && kept.is_native_run(run))
                        .map(|kept| (kept.record.file.clone(), kept.record.total))
                };
                let Some((file, expected_total)) = info else {
                    return;
                };
                let _writing = self.writer(&file).lock_owned().await;
                let path = self.files_dir().join(&file);
                let len = (self
                    .shared
                    .runtime
                    .spawn_blocking(move || std::fs::metadata(&path).map(|m| m.len())))
                .await;
                match len {
                    Ok(Ok(len)) => {
                        if let Some(expected) = expected_total
                            && len != expected
                        {
                            let state = lock(&self.shared.state);
                            if let Some(kept) = state
                                .offline
                                .iter()
                                .find(|k| &k.record.id() == id && k.is_native_run(run))
                            {
                                kept.received.store(len, Ordering::Relaxed);
                            }
                            TransferOutcome::Failed(
                                "downloaded file size does not match expected size".to_owned(),
                            )
                        } else {
                            {
                                let mut state = lock(&self.shared.state);
                                let Some(kept) = state
                                    .offline
                                    .iter_mut()
                                    .find(|k| &k.record.id() == id && k.is_native_run(run))
                                else {
                                    return;
                                };
                                kept.received.store(len, Ordering::Relaxed);
                                kept.record.total = Some(len);
                            }
                            TransferOutcome::Completed
                        }
                    }
                    Ok(Err(error)) => {
                        TransferOutcome::Failed(format!("downloaded file is missing: {error}"))
                    }
                    Err(error) => {
                        TransferOutcome::Failed(format!("cannot check downloaded file: {error}"))
                    }
                }
            }
            other => other,
        };
        self.offline_ended(id, run, outcome, true);
    }

    /// Renews the server token and queues a fresh [`TransferJob`] on `on_transfer`
    /// for a running native transfer whose token expired or was refused with 401.
    ///
    /// Once the new token is obtained, cancels `run` on `on_transfer` and waits for
    /// `on_transfer` to finish processing that cancellation before reading the
    /// settled byte offset on disk (for proactive refreshes, ensure the OS task
    /// stops writing inside `on_transfer` or before calling this). Then advances
    /// [`TransferJob::run`] and enqueues [`TransferEvent::Start`] atomically with
    /// activating the new run so a concurrent [`Self::pause`] or [`Self::remove`]
    /// cannot deliver [`TransferEvent::Cancel`] ahead of it.
    ///
    /// Returns `Ok(true)` if a fresh job was emitted, or `Ok(false)` if `id` is no
    /// longer running `run` (for example after a pause, removal, concurrent
    /// refresh, or because the file finished on disk while refreshing and was
    /// marked [`OfflineState::Available`]).
    pub async fn refresh_transfer(&self, id: &OfflineId, run: u64) -> Result<bool> {
        let info = {
            let state = lock(&self.shared.state);
            (state.offline.iter())
                .find(|kept| &kept.record.id() == id && kept.is_native_run(run))
                .map(|kept| {
                    (
                        kept.record.library.clone(),
                        kept.record.media.clone(),
                        kept.record.file.clone(),
                        kept.record.total,
                        Arc::clone(&kept.received),
                    )
                })
        };
        let Some((library, media, file, total, received)) = info else {
            return Ok(false);
        };
        let api = (self.shared.copy.mirror())
            .library_api(&library)
            .ok_or_else(offline_error)?;
        api.client().renew_token().await?;
        let source = api.media_url(&media, &MediaFileQuery::default()).await?;
        // Stop the previous run before reading the resume offset so the old OS
        // transfer cannot write concurrently with the replacement.
        {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state
                .offline
                .iter_mut()
                .find(|k| &k.record.id() == id && k.is_native_run(run))
            else {
                return Ok(false);
            };
            kept.active = Some(Active::Refreshing);
            kept.record.transfer_run = None;
            self.cancel_transfer(id.clone(), run);
        }
        // If this future is dropped or errors before activating the replacement,
        // requeue the file so it is never left stuck in `Active::Refreshing`.
        struct RefreshGuard<'a> {
            downloads: &'a Downloads,
            id: OfflineId,
            run: u64,
            armed: bool,
        }
        impl Drop for RefreshGuard<'_> {
            fn drop(&mut self) {
                if self.armed {
                    self.downloads.offline_ended(
                        &self.id,
                        self.run,
                        TransferOutcome::NetworkLost,
                        false,
                    );
                }
            }
        }
        let mut guard = RefreshGuard {
            downloads: self,
            id: id.clone(),
            run,
            armed: true,
        };
        self.flush_transfers().await;
        // Re-check before touching disk in case pause/remove ran during flush.
        {
            let state = lock(&self.shared.state);
            let still_refreshing = state.offline.iter().any(|k| {
                &k.record.id() == id && matches!(k.active, Some(Active::Refreshing)) && k.run == run
            });
            if !still_refreshing {
                guard.armed = false;
                return Ok(false);
            }
        }
        let path = self.files_dir().join(&file);
        let writer = self.writer(&file);
        let settled = settled_offset(
            &api,
            &self.shared.runtime,
            &media,
            &path,
            &writer,
            total,
            &received,
            || {
                let state = lock(&self.shared.state);
                state
                    .offline
                    .iter()
                    .any(|k| &k.record.id() == id && k.is_refreshing_run(run))
            },
        )
        .await?;
        match settled {
            OffsetState::Cancelled => {
                guard.armed = false;
                Ok(false)
            }
            OffsetState::AlreadyComplete(len) => {
                {
                    let mut state = lock(&self.shared.state);
                    let Some(kept) = state
                        .offline
                        .iter_mut()
                        .find(|k| &k.record.id() == id && k.is_refreshing_run(run))
                    else {
                        guard.armed = false;
                        return Ok(false);
                    };
                    kept.received.store(len, Ordering::Relaxed);
                    kept.record.total = Some(len);
                    guard.armed = false;
                }
                self.offline_ended(id, run, TransferOutcome::Completed, false);
                Ok(false)
            }
            OffsetState::Resume { offset, new_total } => {
                // Persist the replacement run identity to `offline.json` before
                // making Start observable, while keeping `Active::Refreshing` so a
                // concurrent pause/remove cannot emit Cancel ahead of Start.
                let next_run = {
                    let _saving = lock(&self.shared.saving);
                    let (next_run, records) = {
                        let mut state = lock(&self.shared.state);
                        let Some(ix) = state
                            .offline
                            .iter()
                            .position(|k| &k.record.id() == id && k.is_refreshing_run(run))
                        else {
                            guard.armed = false;
                            return Ok(false);
                        };
                        state.next_run += 1;
                        let next_run = state.next_run;
                        let kept = &mut state.offline[ix];
                        if let Some(total) = new_total {
                            kept.record.total = Some(total);
                        }
                        kept.record.transfer_run = Some(next_run);
                        kept.record.last_run = kept.record.last_run.max(next_run);
                        let records: Vec<OfflineRecord> =
                            state.offline.iter().map(|k| k.record.clone()).collect();
                        (next_run, records)
                    };
                    write_json(&self.shared.dir.join("offline.json"), &records);
                    next_run
                };
                {
                    let mut state = lock(&self.shared.state);
                    let Some(ix) = state
                        .offline
                        .iter()
                        .position(|k| &k.record.id() == id && k.is_refreshing_run(run))
                    else {
                        guard.armed = false;
                        return Ok(false);
                    };
                    let job = TransferJob {
                        id: id.clone(),
                        run: next_run,
                        source,
                        path,
                        offset,
                    };
                    let kept = &mut state.offline[ix];
                    kept.received.store(offset, Ordering::Relaxed);
                    kept.run = next_run;
                    kept.active = Some(Active::Native(job.clone()));
                    // Enqueue Start while holding `state` so a concurrent pause or remove
                    // cannot enqueue Cancel ahead of it.
                    self.shared.tell_transfer(TransferEvent::Start(job));
                    guard.armed = false;
                }
                self.changed();
                Ok(true)
            }
        }
    }

    // --- The queue

    /// Starts queued downloads while slots are free and the server is reached.
    fn pump(&self) {
        let native = self.shared.transfers.is_some();
        let mut started = false;
        {
            let mut guard = lock(&self.shared.state);
            let state = &mut *guard;
            let running = state.offline.iter().filter(|k| k.active.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.active.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;
                if native {
                    let task = self.shared.runtime.spawn(async move {
                        let id = record.id();
                        // Wait for any pending Cancel (e.g. from an immediate
                        // pause+resume) to finish in `on_transfer` so the disk
                        // offset is settled before preparing the new job.
                        if let Some(shared) = weak.upgrade() {
                            Downloads { shared }.flush_transfers().await;
                        } else {
                            return;
                        }
                        let still_owned = {
                            let weak = weak.clone();
                            let id = id.clone();
                            move || {
                                let Some(shared) = weak.upgrade() else {
                                    return false;
                                };
                                let state = lock(&shared.state);
                                state
                                    .offline
                                    .iter()
                                    .any(|k| k.record.id() == id && k.is_preparing_run(run))
                            }
                        };
                        let result = prepare_transfer(
                            &api,
                            &record,
                            run,
                            path,
                            writer,
                            &received,
                            still_owned,
                        )
                        .await;
                        if let Some(shared) = weak.upgrade() {
                            Downloads { shared }.native_prepared(&id, run, result);
                        }
                    });
                    kept.active = Some(Active::Preparing(task.abort_handle()));
                } else {
                    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 }.in_process_ended(&id, run, result);
                        }
                    });
                    kept.active = Some(Active::Task(task.abort_handle()));
                }
                kept.run = run;
                started = true;
                free -= 1;
            }
        }
        if started {
            self.changed();
        }
    }

    fn native_prepared(&self, id: &OfflineId, run: u64, result: Result<Prepared>) {
        match result {
            Ok(Prepared::Cancelled) => {}
            Ok(Prepared::AlreadyComplete(len)) => {
                {
                    let mut state = lock(&self.shared.state);
                    let Some(kept) = state
                        .offline
                        .iter_mut()
                        .find(|k| &k.record.id() == id && k.is_preparing_run(run))
                    else {
                        return;
                    };
                    kept.received.store(len, Ordering::Relaxed);
                    kept.record.total = Some(len);
                }
                self.offline_ended(id, run, TransferOutcome::Completed, false);
            }
            Ok(Prepared::Job { job, new_total }) => {
                // Persist the run identity before publishing Start while keeping
                // `Active::Preparing` so a concurrent pause/remove cannot emit
                // Cancel ahead of Start.
                {
                    let _saving = lock(&self.shared.saving);
                    let records = {
                        let mut state = lock(&self.shared.state);
                        let Some(kept) = state
                            .offline
                            .iter_mut()
                            .find(|k| &k.record.id() == id && k.is_preparing_run(run))
                        else {
                            return;
                        };
                        if let Some(total) = new_total {
                            kept.record.total = Some(total);
                        }
                        kept.record.transfer_run = Some(run);
                        kept.record.last_run = kept.record.last_run.max(run);
                        state
                            .offline
                            .iter()
                            .map(|k| k.record.clone())
                            .collect::<Vec<_>>()
                    };
                    write_json(&self.shared.dir.join("offline.json"), &records);
                }
                {
                    let mut state = lock(&self.shared.state);
                    let Some(kept) = state
                        .offline
                        .iter_mut()
                        .find(|k| &k.record.id() == id && k.is_preparing_run(run))
                    else {
                        return;
                    };
                    kept.active = Some(Active::Native(job.clone()));
                    // Enqueue Start while holding `state` so a concurrent pause or
                    // remove cannot enqueue Cancel ahead of it.
                    self.shared.tell_transfer(TransferEvent::Start(job));
                }
                self.changed();
            }
            Err(error) => {
                let outcome = outcome_from_error(self.shared.copy.api().is_some(), error);
                self.offline_ended(id, run, outcome, false);
            }
        }
    }

    fn in_process_ended(&self, id: &OfflineId, run: u64, result: Result<()>) {
        let connected = self.shared.copy.api().is_some();
        let outcome = match result {
            Ok(()) => TransferOutcome::Completed,
            Err(error) => outcome_from_error(connected, error),
        };
        self.offline_ended(id, run, outcome, false);
    }

    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, outcome: TransferOutcome, native_only: bool) {
        let connected = self.shared.copy.api().is_some();
        let retry = matches!(outcome, TransferOutcome::NetworkLost);
        {
            let mut state = lock(&self.shared.state);
            let Some(kept) = state.offline.iter_mut().find(|k| &k.record.id() == id) else {
                return;
            };
            let matches = if native_only {
                kept.is_native_run(run)
            } else {
                kept.active.is_some() && kept.run == run
            };
            if !matches {
                return;
            }
            kept.active = None;
            kept.record.transfer_run = None;
            kept.record.status = match &outcome {
                TransferOutcome::Completed => Stored::Completed,
                // Lost with the connection: it goes on once the server is back.
                TransferOutcome::NetworkLost if !connected => Stored::Queued,
                // Lost with the network: it goes on a little later, or once the copy
                // connects again.
                TransferOutcome::NetworkLost => {
                    kept.wait_until = Some(Instant::now() + RETRY_AFTER);
                    Stored::Queued
                }
                TransferOutcome::Failed(error) => Stored::Failed(error.clone()),
            };
        }
        if retry && 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 outcome == TransferOutcome::Completed {
            self.shared.tell(DownloadsEvent::Available(id.clone()));
        }
        self.pump();
    }

    fn cancel_transfer(&self, id: OfflineId, run: u64) {
        self.shared.tell_transfer(TransferEvent::Cancel { id, run });
    }

    /// Waits until `on_transfer` has processed every event enqueued so far.
    async fn flush_transfers(&self) {
        let Some(transfers) = &self.shared.transfers else {
            return;
        };
        let (tx, rx) = oneshot::channel();
        if transfers.send(TransferMsg::Flush(tx)).is_ok() {
            let _ = rx.await;
        }
    }

    /// 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))
}

fn outcome_from_error(connected: bool, error: Error) -> TransferOutcome {
    if !connected || matches!(error, Error::Network { .. } | Error::Timeout { .. }) {
        TransferOutcome::NetworkLost
    } else {
        TransferOutcome::Failed(error.to_string())
    }
}

enum Prepared {
    Job {
        job: TransferJob,
        new_total: Option<u64>,
    },
    AlreadyComplete(u64),
    Cancelled,
}

enum OffsetState {
    Resume { offset: u64, new_total: Option<u64> },
    AlreadyComplete(u64),
    Cancelled,
}

/// Checks the settled bytes on disk for a native transfer: truncates if the file
/// outgrew `total` or the server's file changed size, confirms completion when the
/// file already reached the server's length (even if `total` was never persisted),
/// and otherwise returns the byte offset to resume from.
///
/// Re-checks `still_owned` under the per-file writer lock before mutating the file
/// or updating `received` so a superseded preparation or refresh never truncates a
/// newer run's destination.
#[allow(clippy::too_many_arguments)]
async fn settled_offset(
    api: &LibraryApi,
    runtime: &tokio::runtime::Handle,
    media: &str,
    path: &Path,
    writer: &Arc<AsyncMutex<()>>,
    total: Option<u64>,
    received: &AtomicU64,
    still_owned: impl Fn() -> bool,
) -> Result<OffsetState> {
    let mut offset = {
        let writing = Arc::new(Arc::clone(writer).lock_owned().await);
        if !still_owned() {
            return Ok(OffsetState::Cancelled);
        }
        let len = file_len(runtime, path).await;
        if total.is_some_and(|expected| len > expected) {
            if !still_owned() {
                return Ok(OffsetState::Cancelled);
            }
            truncate(runtime, path, &writing).await?;
            received.store(0, Ordering::Relaxed);
            0
        } else {
            received.store(len, Ordering::Relaxed);
            len
        }
    };
    let mut new_total = None;
    if offset > 0 && total.is_none_or(|expected| offset == expected) {
        let remote = remote_len(api, media).await?;
        if !still_owned() {
            return Ok(OffsetState::Cancelled);
        }
        if remote == offset {
            return Ok(OffsetState::AlreadyComplete(offset));
        }
        new_total = Some(remote);
        // Keep a partial file whose size was not yet known; truncate if it outgrew
        // the server's file or the server's file changed size since `total`.
        if offset > remote || total.is_some() {
            let writing = Arc::new(Arc::clone(writer).lock_owned().await);
            if !still_owned() {
                return Ok(OffsetState::Cancelled);
            }
            truncate(runtime, path, &writing).await?;
            offset = 0;
            received.store(0, Ordering::Relaxed);
        }
    }
    Ok(OffsetState::Resume { offset, new_total })
}

/// Prepares a [`TransferJob`] on the runtime: checks the bytes already on disk
/// (truncating if the file outgrew the expected size, or confirming completion if it
/// already reached it) and obtains an [`AuthorizedUrl`] with a valid server token.
async fn prepare_transfer(
    api: &LibraryApi,
    record: &OfflineRecord,
    run: u64,
    path: PathBuf,
    writer: Arc<AsyncMutex<()>>,
    received: &AtomicU64,
    still_owned: impl Fn() -> bool,
) -> Result<Prepared> {
    let runtime = tokio::runtime::Handle::current();
    let (offset, new_total) = match settled_offset(
        api,
        &runtime,
        &record.media,
        &path,
        &writer,
        record.total,
        received,
        still_owned,
    )
    .await?
    {
        OffsetState::Cancelled => return Ok(Prepared::Cancelled),
        OffsetState::AlreadyComplete(len) => return Ok(Prepared::AlreadyComplete(len)),
        OffsetState::Resume { offset, new_total } => (offset, new_total),
    };
    let source = api
        .media_url(&record.media, &MediaFileQuery::default())
        .await?;
    Ok(Prepared::Job {
        job: TransferJob {
            id: record.id(),
            run,
            source,
            path,
            offset,
        },
        new_total,
    })
}

async fn file_len(runtime: &tokio::runtime::Handle, path: &Path) -> u64 {
    let path = path.to_owned();
    runtime
        .spawn_blocking(move || std::fs::metadata(path).map(|m| m.len()).unwrap_or(0))
        .await
        .unwrap_or(0)
}

/// 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();
}