spoolframe-protocol 0.17.0-beta.1

The spoolframe/client/1 wire protocol.
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
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
//! The messages of `spoolframe/client/1`.
//!
//! Every enum is internally tagged: `{"type": "ping"}`,
//! `{"type": "item", "id": "plex:movie:1"}`. Peers ignore fields they do
//! not know, and an error or event type they do not know decodes as
//! `Unknown`, so a newer peer can add both without breaking an older one.
//! A request type the server does not know is answered with
//! [`Error::Unsupported`].

use std::fmt;

use serde::{Deserialize, Serialize};
use spoolframe_types::{
    ClientCapabilities, DisplayCapabilities, Item, Library, LibraryId, Markers, MediaId,
    MediaTracks, PersonId, Platform, Role, SubtitleFormat, TrackPreferences,
};

use crate::features::{Feature, Features};
use crate::invite_admin::{CreateInvite, InviteCreated, InviteSummary};
use crate::media::PlaybackHandle;
use crate::pairing::{PairingAnswer, PairingOffer, RelayCode};
use crate::passkeys::{
    FinishPasskeyRegistration, FinishPasskeySignIn, PasskeyInfo, PasskeyRegistrationBegun,
    PasskeySignInBegun,
};
use crate::playback::{BitmapSubtitles, ChosenTracks, PlaybackPlan, Quality, Selection};
use crate::playlists::{
    Kinds, PinNote, PlaylistEdit, PlaylistPage, PlaylistRef, PlaylistSummary, Visibility,
};
use crate::plex::PlexLink;
use crate::portable::{
    IdentityRecord, PortableIdentityState, PortableUserId, TieProof, UserDeviceCredential,
    signature_hex,
};
use crate::previews::Previews;
use crate::search::{SearchRequest, SearchResults};

/// The protocol revision inside the `spoolframe/client/1` ALPN. Raised
/// for coordinated development releases, including breaking wire changes.
/// A server refuses every other revision at `Hello`.
pub const PROTOCOL_VERSION: u32 = 1;

/// The maximum raw body of one subtitle chunk on a resource stream.
pub const SUBTITLE_CHUNK: u64 = 512 << 10;

/// An opaque session token from a login. It is only valid from
/// the endpoint that logged in.
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(pub String);

impl fmt::Debug for SessionId {
    // A session is a credential (bound to one endpoint, but still): keep it
    // out of logs.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SessionId(<redacted>)")
    }
}

/// One request, and the session it is made in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequestEnvelope {
    /// `None` for the pre-auth requests. Several sessions may be used on
    /// one connection.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub session: Option<SessionId>,
    pub request: Request,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Request {
    // Pre-auth: the only requests served without a session.
    /// The first request on every connection.
    Hello(Hello),
    AuthMethods,
    LoginPassword(LoginPassword),
    Ping,
    /// Explicit foreground profile selection. Background requests never select a profile.
    ActivateProfile,
    /// Last accepted progress sequence for a restored playback handle.
    PlaybackProgressSequence {
        handle: PlaybackHandle,
    },
    /// Ask to be signed in by someone approving this device on another
    /// one they are signed in on. Show the code (and its
    /// [`crate::device_sign_in::link`] as a QR code), then
    /// `AwaitDeviceSignIn`. `DeviceSignInStarted`.
    ///
    /// `remember` asks for this device to be trusted; the
    /// approver sees the request and decides. Never true unless the user
    /// ticked "Remember this device".
    BeginDeviceSignIn {
        remember: bool,
    },
    /// Wait, up to about 25 s, for `request` to be approved: `LoggedIn`
    /// with a session for this device, `DeviceSignInPending` (ask again),
    /// or `DeviceSignInDenied` / `DeviceSignInExpired`. Only the device
    /// that began the request may ask, and one wait at a time: a newer
    /// one ends the one before it with `DeviceSignInPending`.
    AwaitDeviceSignIn {
        request: String,
    },
    /// Begin signing in with an app passkey ([`crate::passkeys`]):
    /// `PasskeySignInBegun`, a nonce, listing no passkeys (any the
    /// platform finds): anyone can ask. With `username`, only that user's
    /// passkeys finish it. The nonce is this device's, for 5 minutes;
    /// beginning again replaces it. The challenge to sign is
    /// [`crate::app_passkey_challenge`] of this server's id and the nonce.
    BeginPasskeySignIn {
        username: Option<String>,
    },
    /// Finish it with what the passkey signed: `LoggedIn`, a session for
    /// this device, as `LoginPassword` gives (its PIN is asked as usual),
    /// and with `remember` this device trusted, as `LoginPassword` does.
    /// Anything that does not sign in is `InvalidCredentials`, counted as
    /// a failed sign-in (then `RateLimited`).
    FinishPasskeySignIn {
        signed: FinishPasskeySignIn,
        remember: bool,
    },
    /// The users this device is trusted for: `TrustedProfiles`,
    /// for "Who's watching" once their sessions have ended. Only this
    /// device's own; nothing about other devices. Trust that lapsed is
    /// left out.
    TrustedProfiles,
    /// Start a session on this device for `user_id` (as `TrustedProfiles`
    /// gives it), without a password: `LoggedIn`, a normal session bound
    /// to this device, `remembered: true`. A device that asks for the
    /// user's PIN gets it locked, as after any sign-in. `Unauthenticated`,
    /// the same for every reason, when this device is not trusted for
    /// them, the trust lapsed or was removed, or the user is disabled.
    /// The server never resumes a profile by itself: auto-login is the
    /// client resuming the profile marked `auto_login` at start.
    ResumeProfile {
        user_id: String,
    },
    /// Make an account with an invite's code and sign in to it:
    /// `LoggedIn`, a session bound to this device as `LoginPassword`
    /// gives, `remembered: false`. The account has the invite's role.
    ///
    /// A code that is not one, or whose invite was revoked, is
    /// `InviteInvalid`, counted as a wrong guess (then `RateLimited`); one
    /// past its expiry `InviteExpired`; one with no uses left
    /// `InviteExhausted`. A username someone has is `UsernameTaken`, and a
    /// username, display name or password that is not acceptable
    /// `InvalidInput`; the invite is not used up by either. A device that
    /// is not signed in draws on the sign-in budget all such devices share,
    /// as `LoginPassword` does.
    RedeemInvite(RedeemInvite),
    /// Begin making an account with an invite's code and an app passkey,
    /// no password (feature `spoolframe:invite-passkeys`): `PasskeyRegistrationBegun`, a nonce, as
    /// for `BeginPasskeyRegistration`, for the account `username` is to
    /// be. The code and username are checked as `RedeemInvite` checks
    /// them, with its errors; nothing is made or used up yet. The
    /// registration is this device's, for 5 minutes, and beginning again
    /// replaces it. On the strangers' budget, as redeeming is.
    BeginInvitePasskey(BeginInvitePasskey),
    /// Finish it with the passkey the platform made (feature
    /// `spoolframe:invite-passkeys`): the
    /// account is made with the invite's role, its one way to sign in the
    /// passkey, one use of the invite taken, and the device signed in:
    /// `LoggedIn`, trusted when `remember`. Only the device that began it,
    /// with the same code, finishes it, once; otherwise
    /// `InvalidCredentials`, as a passkey that does not verify is. The
    /// invite is checked again, as `RedeemInvite` checks it, and a
    /// username taken meanwhile is `UsernameTaken`; neither uses the
    /// invite up.
    RedeemInviteWithPasskey(RedeemInviteWithPasskey),
    /// What an invite's code is, before joining with it: `InviteLookup`,
    /// for the "Got an invite?" screen. Nothing is used up. The code is
    /// taken as `RedeemInvite` takes it, and counted as it counts one: a
    /// code no invite has (or that cannot be one) is `no_match`, a wrong
    /// guess (then `RateLimited`); a revoked, expired or used-up one is
    /// not counted. On the strangers' budget, as redeeming is.
    LookupInvite(LookupInvite),
    /// Begin signing in as a portable user with a device credential:
    /// `PortableSignInBegun`, a nonce for the device key to sign
    /// over ([`crate::portable::device_proof_message`] of this server's
    /// endpoint id and it). The nonce is this device's, for
    /// `expires_in_secs` (5 minutes), and is used once, whatever the
    /// finish makes of it; beginning again replaces it. Draws on the
    /// sign-in budget all devices not signed in share.
    BeginPortableSignIn,
    /// Finish it: `LoggedIn`, `remembered: false`, a session
    /// bound to this device. Local-first: where the identity is tied to an
    /// account here the session is that account's, as any sign-in
    /// to it (its PIN is asked as usual); else, where it has a grant here,
    /// the portable user's own; else nothing. Every refusal (no grant, a
    /// credential or proof that does not hold, a revoked key, an expired
    /// or missing nonce, a disabled account) is `InvalidCredentials`,
    /// counted as a failed sign-in (then `RateLimited`).
    FinishPortableSignIn(PortableSignIn),
    /// Redeem a `portable-account` invite as the portable user
    /// `sign_in` proves, over the nonce `BeginPortableSignIn` gave: the
    /// server grants them access (no account is made), uses one of the
    /// invite's uses, and signs them in as `FinishPortableSignIn` does:
    /// `LoggedIn`. Someone granted here already keeps their grant, and
    /// the invite its use.
    ///
    /// The code is checked as `RedeemInvite` checks it (`InviteInvalid`,
    /// counted as a wrong guess; `InviteExpired`; `InviteExhausted`); a
    /// `create-user` invite's code is `WrongInviteKind`, and its use is
    /// kept. The credential is checked as `FinishPortableSignIn` checks
    /// it: `InvalidCredentials`, counted.
    RedeemPortableInvite(RedeemPortableInvite),
    /// What this server keeps of portable identity `user`: its
    /// genesis and newest state, `IdentityRecord`, for a device recovering
    /// the identity with one of its roots. Only an identity known here
    /// (tied or granted) has one; any other is `NotFound`. Public data,
    /// served to anyone, on the strangers' budget.
    IdentityRecord {
        user: PortableUserId,
    },
    /// The record, as `IdentityRecord` answers it, of the identity whose
    /// genesis handle is `handle`: what a security key gives back
    /// as its credential's user handle, for a fresh install that holds a
    /// key and nothing else. A key added to a phrase identity carries the
    /// identity's id as its handle, so a handle that is the id of a phrase
    /// identity known here answers that identity's record. Only an
    /// identity known here has one; any other is `NotFound`. Handles are
    /// 32 random bytes, so a miss says nothing. Public data, served to
    /// anyone, on the strangers' budget.
    IdentityRecordByHandle {
        #[serde(with = "crate::portable::handle_hex")]
        handle: [u8; crate::portable::HANDLE_LEN],
    },
    /// Hold a device's pairing request under its relay code, for a
    /// root terminal with no camera to fetch: `Done`. For
    /// [`crate::pairing::RELAY_TTL_SECS`]; offering again from the same
    /// device replaces it. A code another device holds is
    /// `InvalidInput`. On the strangers' budget.
    OfferPairing(PairingOffer),
    /// The pairing request held under `code`: `PairingOffered`, or
    /// `NotFound`. On the strangers' budget, so codes are not guessed.
    FetchPairing {
        code: RelayCode,
    },
    /// The root terminal's answer to the request under `code`:
    /// `Done`. One answer only, for the key the request named; another,
    /// or no request, is `NotFound`; a credential for another key
    /// `InvalidInput`. The server carries it and checks nothing else: the
    /// device does. On the strangers' budget.
    AnswerPairing {
        code: RelayCode,
        answer: PairingAnswer,
    },
    /// The answer to this device's request under `code`, if one came:
    /// `PairingAnswered`, taken (the request ends with it) or
    /// `None` while there is none yet. Only the device that offered it;
    /// any other, or no request, is `NotFound`. Not on the strangers'
    /// budget: the device asks every few seconds.
    CollectPairing {
        code: RelayCode,
    },

    // Need a session.
    Libraries,
    /// A page of a library's top-level items: `Items`. Without `sort` and
    /// `filter`, every item by title, as before them. With either: ordered
    /// by `sort`, then by sort title and id, and only the items `filter`
    /// keeps, `total` counting those. A key or filter part the library
    /// does not have (`ItemFilterValues` lists what it has), or a value
    /// this build does not know, is `InvalidInput`.
    Items {
        library: LibraryId,
        offset: u32,
        limit: u32,
        /// Optional for good: left out, the plain order.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sort: Option<spoolframe_types::ItemSort>,
        /// Optional for good: left out, every item.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        filter: Option<spoolframe_types::ItemFilter>,
    },
    /// What library `library`'s items can be sorted and filtered by:
    /// `ItemFilterValues`, the genres, years, content ratings, resolutions
    /// and ranges its items have, and the sort keys and filter parts it
    /// applies.
    ItemFilterValues {
        library: LibraryId,
    },
    Item {
        id: MediaId,
    },
    /// The episode to play after episode `item` (feature
    /// `spoolframe:next-episode`): `NextEpisode`, filled as `Item`'s
    /// children are, and `None` at the show's end. `in_order` is the
    /// one right after it; `first_unwatched` the first after it the user
    /// has not watched. Specials (season 0) are in the order only when
    /// `specials`, first, as a show lists its seasons; without them, a
    /// special has no episode after it. An episode the user may not see
    /// is `None`. An item that is not an episode is `InvalidInput`.
    NextEpisode {
        item: MediaId,
        mode: NextMode,
        specials: bool,
    },
    /// What a show's Continue goes to (feature
    /// `spoolframe:next-episode`): `NextEpisode`, the first episode in
    /// progress, else the first the user has not watched, specials left
    /// out, else `None`. An item that is not a show is `InvalidInput`.
    ShowNext {
        show: MediaId,
    },
    /// Scoped, grouped search. `Search`; for a client that names
    /// the experimental `federation` feature, `SearchHits`: this
    /// server's results and the paired servers' cache's, a title found on
    /// several servers once.
    Search(SearchRequest),
    /// The items a person a search found is in, one page at a
    /// time. `Items`.
    PersonItems {
        person: PersonId,
        offset: u32,
        limit: u32,
    },
    Tracks {
        id: MediaId,
    },
    /// Who this request's session belongs to.
    WhoAmI,
    /// End this request's session (and only it). On a trusted device it
    /// forgets the device for this user too: the next time is a
    /// full sign-in.
    Logout,
    /// The session user's live sessions on every device.
    ListSessions,
    /// How the server would play `id` for this client with these tracks.
    /// Without a selection the server chooses them from the user's
    /// preferences and says which in the reply.
    PlaybackPlan {
        id: MediaId,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        selection: Option<Selection>,
        /// How a picked bitmap subtitle is shown.
        bitmap: BitmapSubtitles,
        /// What the screen shows now (PGPU-06): its HDR formats and bit
        /// depth, over Hello's, for this plan. `None` or left out, Hello's.
        #[serde(default)]
        display: Option<DisplayCapabilities>,
    },
    /// Plan `id` and, if it plays directly, open a playback session to
    /// read it through. Without a selection, as for `PlaybackPlan`.
    StartPlayback {
        id: MediaId,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        selection: Option<Selection>,
        /// Where to start, for a converted playback: the encode
        /// begins there. Direct play reads from wherever the client likes.
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        start_ms: Option<u64>,
        /// How a picked bitmap subtitle is shown.
        bitmap: BitmapSubtitles,
        /// The quality the viewer chose for it: for the link, at
        /// most a bitrate, or the original.
        quality: Quality,
        /// What the screen shows now (PGPU-06): its HDR formats and bit
        /// depth, over Hello's, for this plan and the playback it starts;
        /// a re-plan without one keeps it. `None` or left out, Hello's.
        #[serde(default)]
        display: Option<DisplayCapabilities>,
        /// What the device that will show it plays, in place of
        /// Hello's, for this playback and its re-plans: a server that plays
        /// on to one of its own devices (a paired server's proxy) has the
        /// plan made for that device over its one connection. `display`
        /// applies over it. Left out, Hello's.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        capabilities: Option<spoolframe_types::ClientCapabilities>,
        /// The share of an uplink the playback goes on over, bits per
        /// second: a server that plays it on to its own device
        /// (a paired server's proxy) sends its own, at the start and at
        /// each re-plan, and the plan keeps under it as under this
        /// server's own share. Left out, this server's share alone.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        onward_share: Option<u64>,
    },
    /// End a playback now, and any encode for it.
    StopPlayback {
        handle: PlaybackHandle,
    },
    /// Recover a handle's configuration revision after reconnecting or
    /// reopening an SDK. This does not change the encoder's epoch.
    PlaybackRevision {
        handle: PlaybackHandle,
    },
    /// Restart a converted playback's encode at `position_ms`:
    /// reads then name the new epoch and start at offset 0.
    SeekPlayback {
        handle: PlaybackHandle,
        position_ms: u64,
    },
    /// Set or change the session user's PIN: 4 to 8 digits. `Done`.
    ///
    /// A user with no PIN sets their first with no `proof`, from a session
    /// that signed in within the last 10 minutes; an older one gets
    /// `RecentSignInRequired`. A user who has one changes it only with a
    /// [`PinProof`]: the current PIN, or the account password when the PIN
    /// is forgotten. Without one it is `InvalidInput`. A locked session
    /// gets `ProfileLocked`.
    SetPin {
        pin: String,
        proof: Option<PinProof>,
    },
    /// Remove the session user's PIN, and its requirement on every device,
    /// with a [`PinProof`], checked as for `SetPin`. `Done`; also for a
    /// user with no PIN (any PIN passes then).
    ClearPin {
        proof: PinProof,
    },
    /// Unlock this session on this connection with the user's PIN.
    /// Wrong PINs are rate-limited; after 10 in a row the session on this
    /// device is revoked (`Unauthenticated`): sign in with the password.
    /// `Done`.
    UnlockProfile {
        pin: String,
    },
    /// The devices the session user has signed in from. `Devices`.
    ListDevices,
    /// Begin making an app passkey for the session user:
    /// `PasskeyRegistrationBegun`, a nonce, as for `BeginPasskeySignIn`.
    /// Needs a session signed in within the last 10
    /// minutes, or `RecentSignInRequired`: confirm it is the user
    /// (`ConfirmPassword`, `BeginConfirmPasskey`) first.
    BeginPasskeyRegistration,
    /// Keep the passkey made for it, in the session that began it: `Done`.
    /// One that does not verify is `InvalidCredentials`; a name that is
    /// not 1 to 64 characters `InvalidInput` (the challenge is not used
    /// up then).
    FinishPasskeyRegistration(FinishPasskeyRegistration),
    /// The session user's passkeys, the web UI's and the apps', oldest
    /// first: `Passkeys`.
    ListPasskeys,
    /// Rename one of them (`id` from `Passkeys`): `Done`. A name that is
    /// not 1 to 64 characters (trimmed) is `InvalidInput`; an `id` that is
    /// not one of the session user's passkeys `NotFound`.
    RenamePasskey {
        id: String,
        name: String,
    },
    /// Remove one of them: `Done`. Needs a session signed in within the
    /// last 10 minutes, or `RecentSignInRequired`; the user's last way to
    /// sign in is `LastSignInMethod`; an `id` that is not one of their
    /// passkeys `NotFound`.
    RemovePasskey {
        id: String,
    },
    /// Confirm it is the session user, with their account password, so
    /// that a session signed in long ago may make a change that needs a
    /// recent sign-in (`ApproveDeviceSignIn`, `BeginPasskeyRegistration`,
    /// `RemovePasskey`, `SetPinRequired` with `required: false`):
    /// `Confirmed`, and this session counts as signed in now, for 10
    /// minutes. Only this session; the user's others are as they were.
    ///
    /// Checked as `LoginPassword` checks it: a wrong one is a failed
    /// sign-in for the user's username from this device
    /// (`InvalidCredentials`, then `RateLimited`, one limit with
    /// `LoginPassword` and the web UI's confirmation). A user with no
    /// password gets `NoPassword`, with nothing counted: confirm with an
    /// app passkey. A locked session gets `ProfileLocked`. The PIN is
    /// never a confirmation: it guards switching profiles on a shared
    /// device, and is weaker than a sign-in.
    ConfirmPassword(ConfirmPassword),
    /// Change the session user's password: `Done`. `current_password` is
    /// checked as `LoginPassword` checks it (a wrong one is
    /// `InvalidCredentials`, counted towards the same limit). A
    /// `new_password` the server does not take, or the same as the current
    /// one, is `InvalidInput`. Every other session of the user's ends, on
    /// the web and on devices. The way out of a session a one-time
    /// password opened (`PasswordChangeRequired`): this session may then
    /// do anything again. A user with no password gets `NoPassword`: set
    /// one in the web UI. Not for a portable user (`NotForPortableUsers`).
    ChangePassword(ChangePassword),
    /// Begin confirming it is the session user with one of their app
    /// passkeys: `PasskeySignInBegun`, a nonce as for
    /// `BeginPasskeySignIn`, listing their app passkeys only. The nonce is
    /// this session's on this device, for 5
    /// minutes; beginning again replaces it. A user with no app passkey
    /// gets `NotFound`; one whose passkey sign-ins are limited
    /// `RateLimited`. A locked session gets `ProfileLocked`.
    BeginConfirmPasskey,
    /// Finish it with what the passkey signed: `Confirmed`, as for
    /// `ConfirmPassword`. A passkey that is not the session user's, a
    /// challenge that is not this session's, or anything else that does
    /// not verify is `InvalidCredentials`, counted as a failed passkey
    /// sign-in (then `RateLimited`).
    FinishConfirmPasskey(FinishPasskeySignIn),
    /// The session user's Plex account link: `PlexLink`. Read
    /// only; a client links or unlinks by opening `<web_url>/profile`.
    GetPlexLink,
    /// Ask for the session user's PIN on `device` (an endpoint id from
    /// `Devices`; this device if left out), or stop asking. A locked
    /// session cannot ask this (nor anything but `WhoAmI` and
    /// `UnlockProfile`). Stopping the requirement needs recent authentication.
    /// `Done`.
    SetPinRequired {
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        device: Option<String>,
        required: bool,
    },
    /// Which device shows sign-in code `code`, to ask the user
    /// before approving it. `DeviceSignInRequest`; `NotFound` for a code
    /// that is not pending (guesses are rate-limited).
    LookupDeviceSignIn {
        code: String,
    },
    /// Sign the device showing `code` in as the session user. `Done`.
    /// Requires recent authentication; an old session cannot mint a fresh one.
    ///
    /// `remember`: the approver's answer to the device's request to be
    /// trusted (`DeviceSignInRequest::remember`). The device is
    /// trusted only if it asked and this is true; this cannot trust a
    /// device that did not ask.
    ApproveDeviceSignIn {
        code: String,
        remember: bool,
    },
    /// Trust `device` (an endpoint id from `Devices`; this device if left
    /// out) for the session user, or stop. `Done`.
    ///
    /// - Turning trust on, or auto-login on, works for this device only
    ///   (`InvalidInput` for another: trust another device from the web
    ///   UI), and needs a recent sign-in (`RecentSignInRequired`).
    /// - Auto-login needs trust (`InvalidInput` without). It turns
    ///   auto-login off for the device's other users, and the PIN
    ///   requirement off for this user there.
    /// - Turning trust off works for any of the user's devices, and ends
    ///   the user's sessions there, this one too if it is this device.
    ///   For another device it needs a recent sign-in; for this one it
    ///   needs only the session.
    /// - A device that is not the user's is `NotFound`.
    SetDeviceTrust {
        device: Option<String>,
        trusted: bool,
        auto_login: bool,
    },
    /// Delete one of the session user's other devices: `device`
    /// is an endpoint id from `Devices`. `Done`. The user's sessions
    /// there are deleted, and with them its trust and PIN requirement; it
    /// leaves `Devices`, and if it signs in again it is listed as new.
    /// Other users' sessions on that device are kept.
    ///
    /// - Always needs a recent sign-in (`RecentSignInRequired`).
    /// - This device is `InvalidInput`: sign out with `Logout`.
    /// - A device that is not the user's is `NotFound`.
    ForgetDevice {
        device: String,
    },
    /// Refuse it: the device stops waiting. `Done`.
    DenyDeviceSignIn {
        code: String,
    },
    /// Pick another subtitle (or none) for a playing playback: it
    /// is planned again with the same audio. A plan that plays directly
    /// only changes what `ReadSubtitle` gives; a converted one restarts its
    /// encode at `position_ms` as a new epoch, from offset 0 (a burned-in
    /// subtitle is in the picture). `PlaybackChanged`; `CannotPlay` leaves
    /// the playback as it was.
    ChangeSubtitle {
        handle: PlaybackHandle,
        subtitle: Option<u32>,
        bitmap: BitmapSubtitles,
        position_ms: u64,
        /// What the screen shows now (PGPU-06), over Hello's, for this
        /// plan and the playback from then on. `None` or left out, what the
        /// playback started with.
        #[serde(default)]
        display: Option<DisplayCapabilities>,
        /// The share of an uplink the playback goes on over, bits per
        /// second: a server that plays it on to its own device
        /// (a paired server's proxy) sends its own, at the start and at
        /// each re-plan, and the plan keeps under it as under this
        /// server's own share. Left out, this server's share alone.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        onward_share: Option<u64>,
    },
    /// Plan a playing playback again for `quality`: the viewer
    /// chose another, or, with `Auto`, the device found its link too slow
    /// for a direct play that stalls. The same tracks, and `bitmap` as
    /// `ChangeSubtitle` takes it. A plan that changes restarts at
    /// `position_ms` as a new epoch, from offset 0, as `ChangeSubtitle`
    /// does; one that does not is answered as it is, nothing restarted.
    /// `PlaybackChanged`.
    ChangeQuality {
        handle: PlaybackHandle,
        quality: Quality,
        bitmap: BitmapSubtitles,
        position_ms: u64,
        /// What the screen shows now (PGPU-06), over Hello's, for this
        /// plan and the playback from then on. `None` or left out, what the
        /// playback started with.
        #[serde(default)]
        display: Option<DisplayCapabilities>,
        /// The share of an uplink the playback goes on over, bits per
        /// second: a server that plays it on to its own device
        /// (a paired server's proxy) sends its own, at the start and at
        /// each re-plan, and the plan keeps under it as under this
        /// server's own share. Left out, this server's share alone.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        onward_share: Option<u64>,
    },
    /// A converted playback's HLS playlist.
    GetManifest {
        handle: PlaybackHandle,
        kind: ManifestKind,
        /// For a media playlist, the variant's: a ladder's rung,
        /// as `v{n}/media.m3u8` in the multivariant playlist. 0 for one
        /// encode, and for the other kinds.
        variant: u32,
    },
    /// The selected external subtitle of a playback, one chunk of it.
    /// One the server reads as text answers
    /// `SubtitleNotReady` until it is done: ask again.
    ///
    /// The reply is `SubtitleChunk`: at most [`SUBTITLE_CHUNK`] bytes of
    /// the file from `offset`, `total`, the file's length, and `version`,
    /// which names the file as it was when the chunk was read. Ask from
    /// the end of each chunk, with the first chunk's `version`, until
    /// `total` bytes are read; an `offset` at or past the end answers no
    /// bytes. When the file is no longer the one `version` names, the
    /// answer is `SubtitleChanged`: the chunks read so far are of a file
    /// that is gone, so start again from 0. The first read has no file
    /// to hold the server to, and sends no `version`.
    ReadSubtitle {
        handle: PlaybackHandle,
        offset: u64,
        version: Option<u64>,
    },
    /// Segment `n` (from 1) of an HLS playback's subtitle rendition:
    /// `Subtitle { format: WebVtt, .. }`, the cues over that segment's time,
    /// timed with `X-TIMESTAMP-MAP` to the video. `SubtitleNotReady` while
    /// the subtitle is made.
    ReadSubtitleSegment {
        handle: PlaybackHandle,
        n: u32,
    },
    /// The frame previews of a movie or episode, for scrubbing:
    /// `Previews`, `PreviewsNotReady` while the server makes them (asking
    /// puts the item first in line; ask again in a few seconds, and show
    /// the time alone meanwhile), or `NoPreviews`.
    GetPreviews {
        id: MediaId,
    },
    /// Where playback of a movie or episode has got to. Send it now and
    /// then while playing and on pause or stop; the server decides what is
    /// written, and when.
    UpdatePlaybackProgress {
        handle: PlaybackHandle,
        sequence: u64,
        position_ms: u64,
    },
    /// Experimental (`federation`): where the user got to in `id`,
    /// a paired server's (`fed:`) movie or episode, which plays from that
    /// server rather than from a playback of this one's: `Done`. Sent to
    /// the user's own server, as `UpdatePlaybackProgress` would be, now and
    /// then while playing and on pause or stop; the server decides what is
    /// written, and when. The paired server keeps nothing of it. An id
    /// that is not a paired server's is `InvalidInput`; one no longer
    /// available is `NotFound`. Unsupported unless this connection's
    /// `Hello` named the feature.
    UpdateWatchProgress {
        id: MediaId,
        position_ms: u64,
    },
    MarkWatched {
        id: MediaId,
    },
    MarkUnwatched {
        id: MediaId,
    },
    /// Remove the card `id`, a movie or an episode, from the session
    /// user's Continue watching or Next up, leaving its progress
    /// and watched state. Only that card: never the episode's whole show.
    /// `id` is the card's own, not its show's. Playing or marking it again
    /// brings it back. `Done`.
    HideFromContinueWatching {
        id: MediaId,
    },
    /// Undo a hide (an "Undo" toast). `Done`.
    UnhideFromContinueWatching {
        id: MediaId,
    },
    /// The session user's home screen.
    Home,
    /// How the session user wants tracks chosen.
    GetTrackPreferences,
    /// Replace them, for every device of the user.
    SetTrackPreferences {
        preferences: TrackPreferences,
    },
    /// Use the tracks of `selection` in `id` for the rest of its series
    /// (an episode) or for it (anything else), by language and role. No
    /// subtitle in `selection` means subtitles off.
    SetTrackOverride {
        id: MediaId,
        selection: Selection,
    },
    /// Back to the preferences for `id`'s series or for it.
    ClearTrackOverride {
        id: MediaId,
    },
    /// Begin tying the session user's account to a portable identity:
    /// `TieChallenge`, a nonce for the identity to sign over
    /// ([`crate::portable::tie_message`]). The nonce is this session's,
    /// for its user, for `expires_in_secs` (5 minutes), and is used once,
    /// whatever `TieFinish` makes of it. Needs a session signed in within
    /// the last 10 minutes, or `RecentSignInRequired`. An account may be
    /// tied already: it ties any number of identities.
    TieBegin,
    /// Tie the session user's account to `user`, with `proof` that `user`
    /// signed the tie message over the nonce `TieBegin` gave: by the root,
    /// or by a device key with a credential for `user` that holds and is
    /// not revoked by any identity state this server has seen. `Done`.
    ///
    /// Needs a recent sign-in, as `TieBegin`. A nonce that is not this
    /// session's, is used or is over is `TieChallengeExpired`: begin
    /// again. A proof that does not hold is `InvalidCredentials`. An
    /// identity tied to another account here is `PortableIdTaken`; one
    /// tied to this account already is `Done`, changing nothing (its
    /// first tie date stands). The account's other ties stay.
    /// Nothing about the account moves: the tie is a link beside it.
    TieFinish {
        user: PortableUserId,
        proof: TieProof,
    },
    /// Sever the session user's tie to `user`: `Done`.
    /// Only that link goes; the account's other ties, its sessions (those
    /// opened with `user`'s credential too), passkeys and watch state stay
    /// as they are. Needs a recent sign-in. No tie to `user` on this
    /// account is `NotFound`.
    Untie {
        user: PortableUserId,
    },

    /// Make an invite ([`crate::invite_admin`]), as the web UI's
    /// `inviteCreate` does, with its limits: `InviteCreated`, the code
    /// shown this once. An admin's only (`AdminRequired`), and only after
    /// they confirmed it is them recently (`RecentSignInRequired`: confirm
    /// with `ConfirmPassword` or a passkey, then ask again). A
    /// `federation` invite is `InvalidInput` unless this connection's
    /// `Hello` named the experimental `federation` feature and the server
    /// has it on, as are fields out of their limits.
    CreateInvite(CreateInvite),
    /// The invites that can still be redeemed, newest first, made here or
    /// in the web UI: `Invites`. An admin's only; no confirmation needed.
    ListInvites,
    /// Revoke invite `id`: its code stops working, and what it made stays.
    /// `Done`. An admin's only, after a recent confirmation, as
    /// `CreateInvite`. One that is not live (revoked, expired, used up, or
    /// none) is `NotFound`.
    RevokeInvite {
        id: String,
    },

    /// Experimental (`http-playback`; see [`crate::experimental`]):
    /// an HTTP URL for one of this session's playbacks, for a player with
    /// no Iroh (AirPlay first): `HttpPlaybackUrl`, or
    /// `HttpPlaybackRefused` with why not. Refused as `Off` unless this
    /// connection's `Hello` named the feature and the server's answer
    /// named it back. The URL is
    /// `http://<address>:<port>/<token>/master.m3u8` for HLS, `.../file`
    /// for direct play, its token unguessable and bound to this playback:
    /// it works until the playback ends or is stopped, or nothing asks for
    /// it for a while. Asked again, it may be the same URL. A newer
    /// server may change or drop this.
    HttpPlaybackUrl {
        handle: PlaybackHandle,
    },

    /// Experimental (`federation`; see [`crate::federation`]): pair
    /// this server with the one whose `federation` invite `link` is, as an
    /// admin pasting it in the web UI would: `ServerPaired`. Unsupported
    /// unless this connection's `Hello` named the feature and the
    /// server's answer named it back. An admin's only (`AdminRequired`),
    /// after a recent confirmation (`RecentSignInRequired`), as
    /// `CreateInvite`. A link that is not one, has no code, or is this
    /// server's own is `InvalidInput`; the other server's refusal of the
    /// code is the invite's own error (`InviteInvalid`, `InviteExpired`,
    /// `InviteExhausted`, `WrongInviteKind`, `RateLimited`), any other is
    /// `PairingRefused`; the other server unreachable is `Unavailable`.
    /// Look the code up on the other server first (`LookupInvite`): it
    /// tells the kind, the inviter and the key's fingerprint.
    PairServer(crate::federation::PairServer),

    /// Experimental (`federation`; see [`crate::federation`]):
    /// share libraries of this server with a paired one, as the app offers
    /// once `PairServer` paired them: `LibrariesShared`. Every user of the
    /// paired server may browse and watch them; a library shared already
    /// stays shared. Unsupported unless this connection's `Hello` named the
    /// feature and the server's answer named it back. An admin's only
    /// (`AdminRequired`), after a recent confirmation
    /// (`RecentSignInRequired`), as `PairServer`. A server not paired is
    /// `NotFound`; a library this server does not serve is `InvalidInput`,
    /// and then none is shared.
    ShareLibraries(crate::federation::ShareLibraries),

    /// Experimental (`federation`): show or hide paired server
    /// `server_id`'s own row on the user's Home (`HomeScreen::servers`):
    /// `Done`. Kept per user and server; a server's items stay in Continue
    /// watching either way. Unsupported unless this connection's `Hello`
    /// named the feature.
    SetServerRow {
        server_id: String,
        shown: bool,
    },

    /// Experimental (`federation`; see [`crate::federation`]):
    /// redeem a play token a paired server got from this one for one of
    /// its users: `PlayTokenRedeemed`, a session for that one item's
    /// playback. Pre-auth, on the strangers' budget as a sign-in is. The
    /// token works once, from the endpoint it was minted for, while its
    /// pair and the library's share are live; every failure is
    /// `Unauthenticated`, and the device asks its home server for a new
    /// token. The session reaches `StartPlayback` of that item and its own
    /// playback's controls and reads; anything else is `Unauthenticated`.
    /// A download token is redeemed the same way: its session
    /// reaches that item's download alone (`DownloadOptions`,
    /// `PrepareDownload`, `DownloadStatus`, `CancelDownload`, the
    /// `Download` read and `DownloadChanged`), or, for a device's token,
    /// its one download's read and status. It lives while the download is
    /// made and read, and ends at its `CancelDownload`.
    /// Unsupported unless this connection's `Hello` named the feature.
    RedeemPlayToken(crate::federation::RedeemPlayToken),

    /// Experimental (`federation`): where the paired server that
    /// `id`, a `fed:` item, is from may be dialled (`RemoteHints`), and
    /// whether this server holds a connection to it now. The device dials
    /// it with a short budget and asks `RemoteGrant` once it reached it; it
    /// plays `id` from this server otherwise. An id that is not a paired
    /// server's is `InvalidInput`; one not available here is `NotFound`.
    /// Unsupported unless this connection's `Hello` named the feature.
    RemoteHints {
        id: MediaId,
    },

    /// Experimental (`federation`): vouch for the session's user to
    /// the paired server `id` is from, for a play token bound to this
    /// device (`RemoteGranted`), which it redeems there
    /// (`RedeemPlayToken`). Each play asks its own. With that server
    /// offline, `OriginOffline` at once: play `id` from this server. A
    /// portable guest is `NotForPortableUsers`; an item not shared, or not
    /// a paired server's, `NotFound`; that server unable to answer now,
    /// `Unavailable`. A proxied play asks for no grant: it is a
    /// `StartPlayback` of `id` here. Unsupported unless this connection's
    /// `Hello` named the feature.
    ///
    /// With `download`, the id of a download of `id` this server keeps:
    /// a download token instead, bound to this device and to that
    /// one download, which reads it on the paired server
    /// (`RemoteGranted::download` names it there). A download that is not
    /// the user's, or not of `id`, is `NotFound`.
    RemoteGrant {
        id: MediaId,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        download: Option<String>,
    },

    /// Experimental (`federation`): play the title `title` (any
    /// copy's id) from paired server `from`, or from this server with
    /// `None`: `Done`. Remembered for the user by the title's external
    /// ids, so every copy of it, here or on a paired server, plays from
    /// there (`SearchHit::play_from`, `Copies::play_from`) while that
    /// server has one. A title with no external ids has one copy:
    /// `InvalidInput`. A server not paired, or an item not found, is
    /// `NotFound`. Unsupported unless this connection's `Hello` named the
    /// feature.
    SetPlayFrom {
        title: MediaId,
        #[serde(default)]
        from: Option<String>,
    },

    /// Leave this server: `Done`, and every session of the user
    /// here is ended, this one too. Needs a recent sign-in
    /// (`RecentSignInRequired`): a local user confirms with
    /// `ConfirmPassword` or a passkey; a portable user signs in
    /// with its credential again, which opens a new session that counts as
    /// recent. What leaving does depends on who:
    ///
    /// - A portable user's grant is taken away, and its data here (watch
    ///   state, hidden rows, track preferences) is deleted. Coming back
    ///   takes a new invite.
    /// - A local account is set aside, not deleted: disabled and marked
    ///   as left, its sessions ended and its devices no longer trusted;
    ///   its data stays, and an admin can restore it.
    ///
    /// The last enabled admin (or the last with a password) cannot leave:
    /// `LastAdmin`. Nothing was changed then.
    LeaveServer,

    /// Playlists (feature `spoolframe:playlists`): every playlist
    /// the session user sees, theirs, shared with them and server-wide,
    /// each with whether it is pinned and where; and the notes of pinned
    /// ones that left their Pinned. `Playlists`.
    ListPlaylists,
    /// One playlist and a page of its entries, from `offset`, at most
    /// `limit` (200): `Playlist`. Items the user may not see are neither
    /// listed nor counted; an item whose file cannot be read now is
    /// listed as unavailable. One they do not see is `NotFound`.
    GetPlaylist {
        id: String,
        offset: u32,
        limit: u32,
    },
    /// Make a playlist the session user owns: `PlaylistInfo`. A name is 1
    /// to 100 characters; `kinds` ticks at least one. `ServerWide` is an
    /// admin's only (`AdminRequired`); a share naming someone who is not a
    /// user here is `InvalidInput`.
    CreatePlaylist {
        name: String,
        kinds: Kinds,
        visibility: Visibility,
    },
    /// Rename a playlist, widen its kinds (never narrow them:
    /// `InvalidInput`), or change who sees it: `PlaylistInfo`. `None`
    /// leaves each as it is. Its owner's, or any admin's for a
    /// server-wide one; anyone else who sees it gets `PlaylistReadOnly`.
    /// Whoever no longer sees it is sent `PlaylistGone`, and loses its pin
    /// with a note.
    UpdatePlaylist {
        id: String,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        name: Option<String>,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        kinds: Option<Kinds>,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        visibility: Option<Visibility>,
    },
    /// Change a playlist's entries, as seen at `revision`: `PlaylistEdited`
    /// with its new revision. 1 to 100 edits, applied in order, all or
    /// none. Made on an older revision, the edits are redone on the newer
    /// one unless one removes or moves an entry changed since:
    /// `PlaylistConflict` ("Someone changed this playlist; reload"). An
    /// item of a kind the playlist does not take is `KindNotAllowed`. A
    /// read-only share gets `PlaylistReadOnly`.
    EditPlaylist {
        id: String,
        revision: u64,
        edits: Vec<PlaylistEdit>,
    },
    /// Delete a playlist: `Done`. Its owner's, or any admin's for a
    /// server-wide one. Whoever had it pinned gets a note.
    DeletePlaylist {
        id: String,
    },
    /// Pin a playlist the session user sees to their Pinned at `position`
    /// (0 first; past the end, last), or move it there: `Done`. Every
    /// device of theirs is sent `PinsChanged`.
    PinPlaylist {
        id: String,
        position: u32,
    },
    /// Take a playlist out of their Pinned: `Done`, also when it was not
    /// there.
    UnpinPlaylist {
        id: String,
    },
    /// Start or go on playing a playlist: `PlaylistItem`, the entry to
    /// play, or `PlaylistFinished` when nothing is left to play. With
    /// `from`, that entry (or the next playable one after it); without,
    /// the user's place: the entry they were in, if they had not finished
    /// it, else the one after it; with no place, the top. The settings are
    /// kept for the user and playlist, for `NextInPlaylist` and the next
    /// time. Unavailable entries, and with `skip_watched` watched ones,
    /// are passed. The client plays the item itself (`StartPlayback`),
    /// skipping its credits, and records progress as any playback does.
    PlayPlaylist {
        id: String,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        from: Option<crate::playlists::EntryId>,
        shuffle: bool,
        repeat: crate::playlists::Repeat,
        skip_watched: bool,
    },
    /// What plays after entry `after` ended or was skipped:
    /// `PlaylistItem`, or `PlaylistFinished` at the end with repeat off,
    /// which clears the place so the next `PlayPlaylist` starts at the
    /// top. The server keeps the place.
    NextInPlaylist {
        id: String,
        after: crate::playlists::EntryId,
    },
    /// What plays next, without playing it (`spoolframe:playlist-upcoming`):
    /// `PlaylistUpcoming`, at most `limit` (100) entries after the session
    /// user's place, each the one `NextInPlaylist` would give after the
    /// one before. The round's order while shuffling, else the playlist's;
    /// from the start again with repeat all; with repeat one, the place's
    /// entry alone. With no place, from the top. Unavailable entries, and
    /// with `skip_watched` watched ones, are passed. Whoever sees the
    /// playlist. Only from a client that listed the feature; from any
    /// other, `Unsupported`.
    UpcomingInPlaylist {
        id: String,
        limit: u32,
    },
    /// Keep how the session user plays a playlist, playing nothing
    /// (`spoolframe:playlist-upcoming`): `Done`. The place and the shuffled
    /// round stay. Shuffle turned on shuffles anew, from the place, so the
    /// whole playlist is ahead; turned off, the playlist's order, from the
    /// place. Whoever sees the playlist. Only from a client that listed
    /// the feature; from any other, `Unsupported`.
    SetPlaylistSettings {
        id: String,
        shuffle: bool,
        repeat: crate::playlists::Repeat,
        skip_watched: bool,
    },
    /// Import the session user's Plex playlists, once: each video
    /// or music playlist of their linked Plex account, on every Plex
    /// server here, becomes a personal playlist of theirs, its items
    /// mapped to this server's: `PlexImport`, what was made and what did
    /// not map. Nothing is synced afterwards. With `dry_run`, nothing is
    /// made. Without a linked Plex account, `NotFound`; a portable user
    /// has none (`NotForPortableUsers`). Imported twice, made twice.
    ImportPlexPlaylists {
        dry_run: bool,
    },
    /// Forget the notes `ListPlaylists` gave: a client showed them.
    /// `Done`. Notes are per user, not per device.
    DismissPinNotes,
    /// Like tracks or albums: their tracks go to the top of the
    /// session user's Liked, in the order given, an album's in disc and
    /// track order; a track liked already stays where it is. An album
    /// likes the tracks it has now: one added to it later is not liked.
    /// `PlaylistInfo`, Liked as it is now. 1 to 100 items; anything but
    /// a track or an album is `KindNotAllowed`, an item not here
    /// `NotFound`. Liked again, nothing changes. Only from a client that
    /// listed `spoolframe:liked`; from any other, `Unsupported`.
    Like {
        items: Vec<MediaId>,
    },
    /// Take tracks, or every track of albums, out of the session user's
    /// Liked: `PlaylistInfo`, Liked as it is now. As `Like`
    /// takes them; one not liked is no change.
    Unlike {
        items: Vec<MediaId>,
    },
    /// Whom playlist `id` can be shared with: `ShareCandidates`, a page
    /// from `offset`, at most `limit` (200), by display name. Every
    /// enabled account here and every portable user granted access, but
    /// the session user; with a `query`, only those whose display name or
    /// username holds it, in any case (empty: everyone). Only whoever
    /// manages the playlist asks: anyone else who sees it gets
    /// `PlaylistReadOnly`, one who does not `NotFound`. Only from a client
    /// that listed `spoolframe:playlist-sharing`; from any other,
    /// `Unsupported`.
    ListShareCandidates {
        id: String,
        query: String,
        offset: u32,
        limit: u32,
    },
    /// What the session user played lately: `Items`, each item
    /// once, by its latest counted play, newest first; a page from
    /// `offset`, at most `limit` (500), and how many in all. `kinds` keeps
    /// films, episodes or tracks only; `None`, every kind. An item gone
    /// from the library is left out of the page. Each item's
    /// `PlaybackState` has its `play_count` and `last_played_at`. Only
    /// from a client that listed `spoolframe:play-history`; from any
    /// other, `Unsupported`.
    RecentlyPlayed {
        kinds: Option<crate::playlists::Kinds>,
        offset: u32,
        limit: u32,
    },
    /// Take away a playlist's uploaded cover: `PlaylistInfo`, its
    /// `artwork` the mosaic again. Whoever may edit its entries may, as
    /// they may upload one (`SetPlaylistArt`, a resource request); anyone
    /// else who sees it, and anyone at all for Liked and All, gets
    /// `NotAllowed`. One without a cover is no change. Only from a client
    /// that listed `spoolframe:playlist-art`; from any other,
    /// `Unsupported`.
    RemovePlaylistArt {
        id: String,
    },
    /// Sync item `id`'s subtitle `track` (its place in `Tracks`'
    /// `subtitles`) to the file, in the background: an external
    /// text subtitle (SRT, WebVTT, ASS) only. `SubtitleTiming`, its state
    /// `Syncing` (a track already syncing is left to it); the outcome comes
    /// as `SubtitleTimingChanged`, or in `Tracks` asked again. The track
    /// is served as it was until the sync is done, then synced; a sync
    /// that scores too low is not used (`Uncertain`). Anyone who can play
    /// the item may. Another track is `InvalidInput`, a track the item
    /// does not have `NotFound`. Only from a client that listed
    /// `spoolframe:subtitle-sync`; from any other, `Unsupported`.
    SyncSubtitle {
        id: MediaId,
        track: u32,
    },
    /// Serve item `id`'s subtitle `track` with its original timing again,
    /// for everyone: the sync is set aside, the offset kept.
    /// `SubtitleTiming`. As `SyncSubtitle` for who may and which tracks.
    UseOriginalSubtitleTiming {
        id: MediaId,
        track: u32,
    },
    /// Move item `id`'s subtitle `track` by `offset_ms` (positive: later)
    /// on top of its timing, for everyone; 0 resets it. At most
    /// ten minutes either way (`InvalidInput`). The track records who set
    /// it and when. `SubtitleTiming`. As `SyncSubtitle` for who may and
    /// which tracks.
    SetSubtitleOffset {
        id: MediaId,
        track: u32,
        offset_ms: i64,
    },
    /// Search the subtitle sites the admin turned on (OpenSubtitles,
    /// SubDL, or both) for item `id`'s subtitles in `language` (an ISO
    /// 639-1 code such as `en`, or `pt-BR`), or, with none, in the
    /// languages the server offers first. Both sites are asked at
    /// once and their results are one list, `SubtitleResults`, best
    /// first: those found by the file's hash (made for this release), then
    /// the rest by rating and downloads, machine-translated and AI-made
    /// after people's, ones removed before as bad last; its `sources` say
    /// how each site's part went. Kept a day per site, item and language.
    /// Anyone who can play the item may. `NoSubtitleSource` when the
    /// server has none set up. When every site failed, the first one's
    /// error: `Unavailable` when it cannot be reached, `RateLimited` when
    /// it asks to wait, `QuotaExhausted` when it is out. Only from a client
    /// that listed `spoolframe:subtitle-search`; from any other,
    /// `Unsupported`.
    SearchSubtitles {
        id: MediaId,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        language: Option<String>,
    },
    /// Download result `result` (`SubtitleResult::id`) of a search for
    /// item `id`, from the site that found it: the
    /// item gains an external subtitle track for everyone, usable at once
    /// (`SubtitleDownloaded`). One not found by the file's hash is synced
    /// in the background (`spoolframe:subtitle-sync`). The same result
    /// downloaded again gives the same track, at no cost. `NotFound` for a
    /// `result` no search of the item listed lately (search again);
    /// `NotAllowed` for a user the admin took downloads from;
    /// `QuotaExhausted` when the server's account or the user's own daily
    /// limit is used up; `InvalidInput` for a file that is not a subtitle
    /// the server reads. Otherwise as `SearchSubtitles`.
    DownloadSubtitle {
        id: MediaId,
        result: String,
    },
    /// Remove item `id`'s downloaded subtitle `download`
    /// (`SubtitleDownload::id`), for everyone: its files go, and
    /// the result is listed last in the item's searches, marked rejected.
    /// The one who downloaded it, or an admin, may: `NotAllowed` for
    /// anyone else. `Done`; a download already removed is `Done` too.
    RemoveSubtitleDownload {
        id: MediaId,
        download: String,
    },

    /// What the device may download of film or episode `id`
    /// (`spoolframe:downloads`): `DownloadOptions`, its tracks, the choice
    /// to show first, the profiles, what original quality would be, and
    /// the subtitles a download would leave out. Anyone who can play the
    /// item may ask. Only from an iPhone, iPad, Mac or Linux client
    /// (`Hello.platform`); from any other, and from a client that did not
    /// list the feature, `Unsupported`. With `spoolframe:music-downloads`
    /// too, `id` may be a track: its one audio track, no
    /// profiles, and what `original` would be.
    ///
    /// `device` is read only from a paired server playing its user's part
    /// (a download token's session): the device the download is
    /// for, in place of the connection's `Hello`.
    DownloadOptions {
        id: MediaId,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        device: Option<crate::downloads::DownloadDevice>,
    },
    /// Prepare a download of film or episode `id` from `source` with
    /// `tracks`: `Download`, its id and state. The same user's
    /// same request is the same id, ready at once when its file is; one
    /// that failed is tried again. The file is made in the background;
    /// `DownloadChanged` tells its state as it moves. A track the item
    /// does not have, or a source or choice this build does not know, is
    /// `InvalidInput`; a profile not there `NotFound`. As
    /// `DownloadOptions` for who may and from where. A track (with
    /// `spoolframe:music-downloads`) takes `original` or `aac256`, and
    /// `tracks` is not read; a film or an episode is refused `aac256`.
    /// `device` as for `DownloadOptions`.
    PrepareDownload {
        id: MediaId,
        source: crate::downloads::DownloadSource,
        tracks: crate::downloads::DownloadTracks,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        device: Option<crate::downloads::DownloadDevice>,
    },
    /// The session user's downloads `ids`: `Downloads`, those
    /// they have in order, and in `gone` each id they have not (never
    /// theirs, cancelled, or no longer kept), so one such id never fails
    /// the rest; at most [`crate::downloads::MAX_ASKED`] ids.
    DownloadStatus {
        ids: Vec<String>,
    },
    /// Cancel download `id`, as the device also does once it has
    /// the file whole and its SHA-256 checked: `Done`. Its file goes once
    /// no download names it and no one reads it; one being made stops. An
    /// id that is not the session user's, or was cancelled, is `NotFound`.
    CancelDownload {
        id: String,
    },
    /// Where the device got to in films and episodes while it had no
    /// server (`spoolframe:downloads`): `OfflineWatchSynced`, an
    /// outcome per entry, in order. `device_now` is the device's clock
    /// now, in Unix seconds: each entry's `at` is moved by the difference
    /// to the server's clock, and kept no later than now. An entry is
    /// written only when it is newer than what the server has (newest
    /// wins, whichever device it came from); watched is judged by the
    /// server's rules from the position and the item's credits, or taken
    /// from `watched: true`. At most [`crate::downloads::MAX_ASKED`]
    /// entries; one with neither a position nor `watched` is
    /// `InvalidInput`. As `DownloadOptions` for from where.
    SyncOfflineWatch {
        device_now: i64,
        entries: Vec<crate::downloads::OfflineWatch>,
    },
    /// What the music downloads a device follows hold now
    /// (`spoolframe:music-downloads` with `spoolframe:downloads`):
    /// `MusicDownloadChanges`, one change per artist, per playlist, then
    /// Liked, in that order, and a cursor to ask with next time. With
    /// `since`, the cursor of the last answer, each thing that holds the
    /// same tracks is `unchanged`; else, and with no cursor, its tracks
    /// now, in full, for the device to compare with what it keeps. A
    /// cursor this server cannot read is no cursor. Asked each time the
    /// device reaches the server. At most
    /// [`crate::downloads::MAX_FOLLOWED`] artists and playlists together;
    /// an id that is not an artist, or All, is `InvalidInput`; Liked
    /// needs `spoolframe:liked` too (`Unsupported` without). Only the
    /// tracks the user may see. As `DownloadOptions` for from where.
    MusicDownloadChanges {
        artists: Vec<MediaId>,
        playlists: Vec<String>,
        liked: bool,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        since: Option<String>,
    },
    /// What the device played and liked while it had no server
    /// (`spoolframe:music-downloads`): `OfflinePlaysSynced`, an outcome per
    /// play and per like, in order. `device_now` is the device's clock
    /// now, in Unix seconds: each `at` is moved by the difference to the
    /// server's clock, and kept no later than now. Each play of a track is
    /// recorded once, counted as the server's rules say from
    /// `played_ms`: it is in play counts and last played. A like or an
    /// unlike is made only when newer than the track's last change on the
    /// server (newest wins, whichever device made it); likes need
    /// `spoolframe:liked` too (`Unsupported` without). At most
    /// [`crate::downloads::MAX_ASKED`] plays and likes together. As
    /// `DownloadOptions` for from where.
    SyncOfflinePlays {
        device_now: i64,
        plays: Vec<crate::downloads::OfflinePlay>,
        liked: Vec<crate::downloads::OfflineLike>,
    },

    /// A request type this build does not know; answered with
    /// [`Error::Unsupported`].
    #[serde(other)]
    Unknown,
}

/// Which episode `NextEpisode` finds after the one given.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum NextMode {
    /// The one right after it.
    InOrder,
    /// The first after it the user has not watched.
    FirstUnwatched,
}

impl Request {
    /// Served without a session.
    pub fn is_pre_auth(&self) -> bool {
        matches!(
            self,
            Request::Hello(_)
                | Request::AuthMethods
                | Request::LoginPassword(_)
                | Request::Ping
                | Request::BeginDeviceSignIn { .. }
                | Request::AwaitDeviceSignIn { .. }
                | Request::BeginPasskeySignIn { .. }
                | Request::FinishPasskeySignIn { .. }
                | Request::TrustedProfiles
                | Request::ResumeProfile { .. }
                | Request::RedeemInvite(_)
                | Request::BeginInvitePasskey(_)
                | Request::RedeemInviteWithPasskey(_)
                | Request::LookupInvite(_)
                | Request::BeginPortableSignIn
                | Request::FinishPortableSignIn(_)
                | Request::RedeemPortableInvite(_)
                | Request::IdentityRecord { .. }
                | Request::IdentityRecordByHandle { .. }
                | Request::OfferPairing(_)
                | Request::FetchPairing { .. }
                | Request::AnswerPairing { .. }
                | Request::CollectPairing { .. }
                | Request::RedeemPlayToken(_)
        )
    }

    /// The feature it belongs to, if any: the server answers it only on a
    /// connection where that feature is on, and is `Unsupported`
    /// otherwise. Every request is named here, so a new one is given its
    /// feature, or none, on purpose.
    pub fn feature(&self) -> Option<Feature> {
        match self {
            Request::BeginInvitePasskey(_) => Some(Feature::InvitePasskeys),
            Request::RedeemInviteWithPasskey(_) => Some(Feature::InvitePasskeys),
            Request::NextEpisode { .. } | Request::ShowNext { .. } => Some(Feature::NextEpisodes),
            Request::Hello { .. }
            | Request::AuthMethods
            | Request::LoginPassword { .. }
            | Request::Ping
            | Request::ActivateProfile
            | Request::PlaybackProgressSequence { .. }
            | Request::BeginDeviceSignIn { .. }
            | Request::AwaitDeviceSignIn { .. }
            | Request::BeginPasskeySignIn { .. }
            | Request::FinishPasskeySignIn { .. }
            | Request::TrustedProfiles
            | Request::ResumeProfile { .. }
            | Request::RedeemInvite { .. }
            | Request::LookupInvite { .. }
            | Request::BeginPortableSignIn
            | Request::FinishPortableSignIn { .. }
            | Request::RedeemPortableInvite { .. }
            | Request::IdentityRecord { .. }
            | Request::IdentityRecordByHandle { .. }
            | Request::OfferPairing { .. }
            | Request::FetchPairing { .. }
            | Request::AnswerPairing { .. }
            | Request::CollectPairing { .. }
            | Request::Libraries
            | Request::Items { .. }
            | Request::ItemFilterValues { .. }
            | Request::Item { .. }
            | Request::Search { .. }
            | Request::PersonItems { .. }
            | Request::Tracks { .. }
            | Request::WhoAmI
            | Request::Logout
            | Request::ListSessions
            | Request::PlaybackPlan { .. }
            | Request::StartPlayback { .. }
            | Request::StopPlayback { .. }
            | Request::PlaybackRevision { .. }
            | Request::SeekPlayback { .. }
            | Request::SetPin { .. }
            | Request::ClearPin { .. }
            | Request::UnlockProfile { .. }
            | Request::ListDevices
            | Request::BeginPasskeyRegistration
            | Request::FinishPasskeyRegistration { .. }
            | Request::ListPasskeys
            | Request::RenamePasskey { .. }
            | Request::RemovePasskey { .. }
            | Request::ConfirmPassword { .. }
            | Request::ChangePassword { .. }
            | Request::BeginConfirmPasskey
            | Request::FinishConfirmPasskey { .. }
            | Request::GetPlexLink
            | Request::SetPinRequired { .. }
            | Request::LookupDeviceSignIn { .. }
            | Request::ApproveDeviceSignIn { .. }
            | Request::SetDeviceTrust { .. }
            | Request::ForgetDevice { .. }
            | Request::DenyDeviceSignIn { .. }
            | Request::ChangeSubtitle { .. }
            | Request::ChangeQuality { .. }
            | Request::GetManifest { .. }
            | Request::ReadSubtitle { .. }
            | Request::ReadSubtitleSegment { .. }
            | Request::GetPreviews { .. }
            | Request::UpdatePlaybackProgress { .. }
            | Request::UpdateWatchProgress { .. }
            | Request::MarkWatched { .. }
            | Request::MarkUnwatched { .. }
            | Request::HideFromContinueWatching { .. }
            | Request::UnhideFromContinueWatching { .. }
            | Request::Home
            | Request::GetTrackPreferences
            | Request::SetTrackPreferences { .. }
            | Request::SetTrackOverride { .. }
            | Request::ClearTrackOverride { .. }
            | Request::TieBegin
            | Request::TieFinish { .. }
            | Request::Untie { .. }
            | Request::CreateInvite { .. }
            | Request::ListInvites
            | Request::RevokeInvite { .. }
            | Request::HttpPlaybackUrl { .. }
            | Request::PairServer { .. }
            | Request::ShareLibraries { .. }
            | Request::SetServerRow { .. }
            | Request::RedeemPlayToken { .. }
            | Request::RemoteHints { .. }
            | Request::RemoteGrant { .. }
            | Request::SetPlayFrom { .. }
            | Request::LeaveServer
            | Request::ListPlaylists
            | Request::GetPlaylist { .. }
            | Request::CreatePlaylist { .. }
            | Request::UpdatePlaylist { .. }
            | Request::EditPlaylist { .. }
            | Request::DeletePlaylist { .. }
            | Request::PinPlaylist { .. }
            | Request::UnpinPlaylist { .. }
            | Request::PlayPlaylist { .. }
            | Request::NextInPlaylist { .. }
            | Request::UpcomingInPlaylist { .. }
            | Request::SetPlaylistSettings { .. }
            | Request::ImportPlexPlaylists { .. }
            | Request::DismissPinNotes
            | Request::Like { .. }
            | Request::Unlike { .. }
            | Request::ListShareCandidates { .. }
            | Request::RecentlyPlayed { .. }
            | Request::RemovePlaylistArt { .. }
            | Request::SyncSubtitle { .. }
            | Request::UseOriginalSubtitleTiming { .. }
            | Request::SetSubtitleOffset { .. }
            | Request::SearchSubtitles { .. }
            | Request::DownloadSubtitle { .. }
            | Request::RemoveSubtitleDownload { .. }
            | Request::DownloadOptions { .. }
            | Request::PrepareDownload { .. }
            | Request::DownloadStatus { .. }
            | Request::CancelDownload { .. }
            | Request::SyncOfflineWatch { .. }
            | Request::MusicDownloadChanges { .. }
            | Request::SyncOfflinePlays { .. }
            | Request::Unknown => None,
        }
    }
}

/// The most characters the server keeps of each of `Hello`'s strings:
/// `client_name`, `client_version` and `device_name`. It cuts a
/// longer one to this many, and keeps and shows only that.
pub const MAX_HELLO_TEXT: usize = 128;

/// The client introduces itself. Every field is required. Each
/// string is cut to [`MAX_HELLO_TEXT`] characters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hello {
    pub protocol_version: u32,
    /// e.g. `spoolframe-linux`.
    pub client_name: String,
    pub client_version: String,
    /// What kind of client this is: the server keeps it for the device, for
    /// its device and session lists. Not taken from `client_name`, which
    /// one app may share across platforms.
    pub platform: Platform,
    /// What the device calls itself (a hostname, "Living room TV"); shown
    /// in session lists. `None` when it has no name to give.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub device_name: Option<String>,
    /// What this device can play. `None`: every playback plan is
    /// `Unsupported`.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub capabilities: Option<ClientCapabilities>,
    /// The experimental features this client wants, by name
    /// ([`crate::experimental`]); the server's answer names those it
    /// turned on. Left out when empty, so a client that wants none sends
    /// what an older one did; an older server ignores it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub experimental: Vec<String>,
    /// The regular features this client handles ([`crate::features`]);
    /// the server's answer names those of them it has. Left out when
    /// empty, as an older client does; an older server ignores it.
    #[serde(
        default,
        with = "crate::features::names",
        skip_serializing_if = "Features::is_empty"
    )]
    pub features: Features,
}

/// `text` cut to [`MAX_HELLO_TEXT`] characters: what a server keeps of a
/// device's strings, and a device of an invite link's name.
pub(crate) fn cut(text: &mut String) {
    if let Some((at, _)) = text.char_indices().nth(MAX_HELLO_TEXT) {
        text.truncate(at);
    }
}

impl Hello {
    /// This `Hello` with each string cut to [`MAX_HELLO_TEXT`] characters:
    /// what a server keeps of it.
    pub fn within_bounds(mut self) -> Self {
        cut(&mut self.client_name);
        cut(&mut self.client_version);
        if let Some(name) = &mut self.device_name {
            cut(name);
        }
        self.experimental.truncate(crate::experimental::MAX_ASKED);
        for name in &mut self.experimental {
            cut(name);
        }
        self
    }
}

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoginPassword {
    pub username: String,
    pub password: String,
    /// Trust this device for the user: it may resume them later
    /// without a password (`ResumeProfile`). Never true unless the user
    /// ticked "Remember this device".
    pub remember: bool,
}

impl fmt::Debug for LoginPassword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LoginPassword")
            .field("username", &self.username)
            .field("password", &"<redacted>")
            .field("remember", &self.remember)
            .finish()
    }
}

/// An invite's code and the account to make with it (`RedeemInvite`).
/// `code` as the link carries it ([`crate::invite::Invite::code`]);
/// any case, dashes or spaces are taken.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedeemInvite {
    pub code: String,
    pub username: String,
    /// What to show for them; the username when `None`.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub display_name: Option<String>,
    pub password: String,
}

impl fmt::Debug for RedeemInvite {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RedeemInvite")
            .field("code", &"<redacted>")
            .field("username", &self.username)
            .field("display_name", &self.display_name)
            .field("password", &"<redacted>")
            .finish()
    }
}

/// An invite's code and the account to make with it and a passkey
/// (`BeginInvitePasskey`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BeginInvitePasskey {
    pub code: String,
    pub username: String,
    /// What to show for them; the username when `None`.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub display_name: Option<String>,
}

impl fmt::Debug for BeginInvitePasskey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BeginInvitePasskey")
            .field("code", &"<redacted>")
            .field("username", &self.username)
            .field("display_name", &self.display_name)
            .finish()
    }
}

/// The invite's code again, and the passkey made for the account
/// (`RedeemInviteWithPasskey`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedeemInviteWithPasskey {
    pub code: String,
    pub finish: FinishPasskeyRegistration,
    /// Trust this device for the new user, as `LoginPassword`'s.
    pub remember: bool,
}

impl fmt::Debug for RedeemInviteWithPasskey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RedeemInviteWithPasskey")
            .field("code", &"<redacted>")
            .field("finish", &self.finish)
            .field("remember", &self.remember)
            .finish()
    }
}

/// An invite's code to look up (`LookupInvite`): as `RedeemInvite` takes
/// it, in any case, with dashes or spaces.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LookupInvite {
    pub code: String,
}

impl fmt::Debug for LookupInvite {
    // The code is a capability until it is used up: keep it out of logs.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("LookupInvite { code: <redacted> }")
    }
}

/// What an invite's code is (`InviteLookup`). Looking never uses it up.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InviteLookupOutcome {
    /// It can be redeemed now: `kind` says how (`RedeemInvite` or
    /// `RedeemPortableInvite`), and a `create-user` one makes an account
    /// with `role`.
    Valid {
        kind: crate::invite_admin::InviteKind,
        /// `consumer` for a `portable-account` one.
        role: Role,
        /// Unix seconds.
        expires_at: i64,
        /// The display name of the admin who made it; `None` when they
        /// have none, or when the server's CLI made it.
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        inviter: Option<String>,
        /// A `federation` one's: the fingerprint of the key this
        /// server pairs with, for the admin about to redeem it on another
        /// server to compare. Left out for every other kind, and by an
        /// older server.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        fingerprint: Option<String>,
    },
    /// It expired at `at`, Unix seconds.
    Expired { at: i64 },
    /// Every use it had is used.
    Used,
    /// An admin revoked it.
    Revoked,
    /// No invite has this code: counted as a wrong guess.
    NoMatch,
    /// An outcome this build does not know, from a newer server.
    #[serde(other)]
    Unknown,
}

/// The most identity states a portable sign-in carries.
pub const MAX_SIGN_IN_STATES: usize = 2;

/// A portable user's device proving itself (`FinishPortableSignIn`):
/// the credential their root gave the device's key, and that
/// key's signature over this server's nonce.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableSignIn {
    pub credential: UserDeviceCredential,
    /// The device key's signature over
    /// [`crate::portable::device_proof_message`] of the server's endpoint
    /// id and the nonce `BeginPortableSignIn` gave.
    #[serde(with = "signature_hex")]
    pub proof: ed25519_dalek::Signature,
    /// The identity's states the device has, newest last, at most
    /// [`MAX_SIGN_IN_STATES`]: the server takes them in before it checks
    /// the credential, so a device carries revocations to servers
    /// it signs in to.
    pub states: Vec<PortableIdentityState>,
    /// What they would be called here, for a grant made with this
    /// sign-in (a portable-account invite); a grant there already keeps
    /// its name.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub display_name: Option<String>,
}

/// A `portable-account` invite's code and the portable user redeeming it
/// (`RedeemPortableInvite`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RedeemPortableInvite {
    pub code: String,
    pub sign_in: PortableSignIn,
}

impl fmt::Debug for RedeemPortableInvite {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RedeemPortableInvite")
            .field("code", &"<redacted>")
            .field("sign_in", &self.sign_in)
            .finish()
    }
}

/// The account password, to confirm it is the session user
/// (`ConfirmPassword`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfirmPassword {
    pub password: String,
}

impl fmt::Debug for ConfirmPassword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConfirmPassword")
            .field("password", &"<redacted>")
            .finish()
    }
}

/// The session user's password and the one to replace it with
/// (`ChangePassword`).
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChangePassword {
    pub current_password: String,
    pub new_password: String,
}

impl fmt::Debug for ChangePassword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ChangePassword { <redacted> }")
    }
}

/// What proves a PIN change or removal is the user's: the PIN
/// they have, or, when it is forgotten, their account password.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PinProof {
    /// The current PIN, checked as `UnlockProfile` checks it: a wrong one
    /// counts towards the same limit (`InvalidCredentials`, then
    /// `RateLimited`) and the same count of wrong PINs in a row; the 10th
    /// revokes the session on this device (`Unauthenticated`). Checking it
    /// unlocks nothing. A user with no PIN passes any.
    Pin { pin: String },
    /// The account password, checked as `LoginPassword` checks it: a wrong
    /// one is a failed sign-in for this username from this device
    /// (`InvalidCredentials`, then `RateLimited`, one limit with
    /// `LoginPassword`). It never revokes the session and never touches
    /// the PIN's limit. A user with no password (passkeys or SSO only) gets
    /// `NoPassword`: the PIN proof, or the web UI, is theirs.
    Password { password: String },
}

impl fmt::Debug for PinProof {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = match self {
            PinProof::Pin { .. } => "Pin",
            PinProof::Password { .. } => "Password",
        };
        write!(f, "PinProof::{kind}(<redacted>)")
    }
}

/// The session user's track preferences (`GetTrackPreferences`), and
/// whether this server reads picture subtitles as text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct TrackPreferencesInfo {
    pub preferences: TrackPreferences,
    /// The server reads picture subtitles as text: `subtitles.ocr` is on
    /// and tesseract has at least one language. When false,
    /// `preferences.subtitles.bitmap` has no effect, and apps show that
    /// choice disabled.
    pub ocr_offered: bool,
}

/// How a user can log in to this server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthMethod {
    Password,
    /// Approval on another signed-in device: `BeginDeviceSignIn`.
    DeviceApproval,
    /// A method this build does not know.
    #[serde(other)]
    Unknown,
}

/// The answer to one request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[expect(
    clippy::large_enum_variant,
    reason = "built once per request and encoded at once; boxing would only add noise"
)]
pub enum Response {
    Ok(Reply),
    Err(Error),
}

impl From<Result<Reply, Error>> for Response {
    fn from(result: Result<Reply, Error>) -> Self {
        match result {
            Ok(reply) => Response::Ok(reply),
            Err(error) => Response::Err(error),
        }
    }
}

impl From<Response> for Result<Reply, Error> {
    fn from(response: Response) -> Self {
        match response {
            Response::Ok(reply) => Ok(reply),
            Response::Err(error) => Err(error),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Reply {
    PlaybackProgressSequence {
        sequence: u64,
    },
    ServerInfo(ServerInfo),
    AuthMethods {
        methods: Vec<AuthMethod>,
    },
    LoggedIn {
        session: SessionId,
        /// This device is trusted for the session's user after it:
        /// the sign-in asked to be remembered and it was (by the
        /// approver too, for a device sign-in), or the device already was.
        remembered: bool,
        /// The password was a one-time one an admin reset to: show "Choose
        /// a new password" and send `ChangePassword` (its current password
        /// is the one-time one). Until then the session gets
        /// `PasswordChangeRequired` for anything else but `Logout` and
        /// `WhoAmI`, and the device is not trusted.
        password_change_required: bool,
    },
    /// The users this device is trusted for (`TrustedProfiles`), by
    /// username.
    TrustedProfiles {
        profiles: Vec<TrustedProfile>,
    },
    Pong,
    /// A device sign-in is pending. Show `code` (see
    /// [`crate::device_sign_in::display`]); keep `request` to await it.
    DeviceSignInStarted {
        request: String,
        code: String,
        expires_in_ms: u64,
        /// Where a browser approves it
        /// ([`crate::device_sign_in::web_link`]), for a QR code a phone's
        /// camera opens; `None` if the server's web UI has no public URL.
        web_url: Option<String>,
    },
    /// Not approved yet: `AwaitDeviceSignIn` again.
    DeviceSignInPending,
    /// What an invite's code is (`LookupInvite`).
    InviteLookup {
        outcome: InviteLookupOutcome,
    },
    /// The device a sign-in code belongs to.
    DeviceSignInRequest(DeviceSignInRequest),
    Libraries {
        libraries: Vec<Library>,
    },
    /// What a library can be sorted and filtered by (`ItemFilterValues`).
    ItemFilterValues {
        values: spoolframe_types::ItemFilterValues,
    },
    Items {
        items: Vec<Item>,
        total: u32,
        /// Experimental (`federation`): the items listed that are
        /// no longer available, their paired server unpaired or their
        /// library no longer shared (`RecentlyPlayed`): shown as such, and
        /// not played. Only to a client that named the feature; left out
        /// when empty, as experimental fields are.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        unavailable: Vec<MediaId>,
    },
    Item {
        item: Item,
        children: Vec<Item>,
        /// The item's intro and credits, in order of start; empty
        /// for an item that has none.
        markers: Markers,
        /// The playlists the user sees that hold it: a movie,
        /// episode or track itself; any of a season's or a show's
        /// episodes; any of an album's or an artist's tracks. Empty when
        /// none does.
        playlists: Vec<PlaylistRef>,
        /// Its heart: a track's `all` or `none`; an album's
        /// `all`, `some` or `none` by the tracks it has now. `None` for
        /// any other item.
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        liked: Option<crate::playlists::Liked>,
        /// An album's tracks among `children` that are liked,
        /// for their hearts. Empty for any other item.
        liked_children: Vec<MediaId>,
        /// Experimental (`federation`): where the item is from, its
        /// title's copies on other servers and the one that plays, as a
        /// `SearchHit` has them. Only to a client that named the feature.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        copies: Option<crate::search::Copies>,
    },
    Search(SearchResults),
    /// Experimental (`federation`): `Search`'s answer to a client
    /// that named the feature, each item a `SearchHit`. Counts are
    /// approximate: a title on several servers is counted once only among
    /// what is shown.
    SearchHits(SearchResults<crate::search::SearchHit>),
    Tracks(MediaTracks),
    /// What `NextEpisode` and `ShowNext` found: `None` when there is
    /// nothing to play.
    NextEpisode {
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        item: Option<Item>,
    },
    WhoAmI(WhoAmIReply),
    LoggedOut,
    Sessions {
        sessions: Vec<SessionInfo>,
    },
    PlaybackPlan {
        plan: PlaybackPlan,
        /// The tracks the server chose, when the request had no selection.
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        chosen: Option<ChosenTracks>,
    },
    PlaybackStarted {
        handle: PlaybackHandle,
        /// How the server plays it: direct, or converted.
        plan: PlaybackPlan,
        /// The size of the file the handle reads.
        size: u64,
        /// The tracks the server chose, when the request had no selection.
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        chosen: Option<ChosenTracks>,
        /// The encode reads name; 0 for direct play.
        epoch: u32,
        /// The item's intro and credits, as in `Item`, so a player needs
        /// no second request for them. Their times are the item's own,
        /// wherever the playback starts.
        markers: Markers,
        /// The item's running time, when the server knows it, so a player
        /// needs no second request for it either. Absent from an older
        /// server's reply. `duration_ms` on the wire.
        #[serde(
            default,
            rename = "duration_ms",
            with = "spoolframe_types::serde_time::millis::option"
        )]
        duration: Option<std::time::Duration>,
    },
    /// A seek restarted the encode: reads name this epoch from offset 0.
    PlaybackSeeked {
        epoch: u32,
    },
    PlaybackRevision {
        revision: u64,
    },
    /// The session user's devices, most recently seen first.
    Devices {
        devices: Vec<DeviceInfo>,
    },
    /// The session user's Plex link; `None`: not linked (or the server
    /// links no Plex accounts).
    PlexLink {
        link: Option<PlexLink>,
    },
    /// The playback's new plan after `ChangeSubtitle` or `ChangeQuality`:
    /// read `epoch` (0 for direct play), whose size is `size` (0 while a
    /// conversion writes it).
    PlaybackChanged {
        plan: PlaybackPlan,
        size: u64,
        epoch: u32,
    },
    /// An HLS playlist, as text.
    Manifest {
        text: String,
    },
    /// A segment of a subtitle rendition, whole (`ReadSubtitleSegment`).
    Subtitle {
        format: SubtitleFormat,
        #[serde(with = "serde_bytes")]
        bytes: Vec<u8>,
    },
    /// The chunk of a subtitle file that `ReadSubtitle` asked for.
    SubtitleChunk {
        format: SubtitleFormat,
        #[serde(with = "serde_bytes")]
        bytes: Vec<u8>,
        /// The whole file's length.
        total: u64,
        /// The file these bytes are of. It is another value once the file
        /// is written again or replaced, and means nothing else to a
        /// client: send it back with the next `ReadSubtitle`.
        version: u64,
    },
    /// The request was carried out; there is nothing to return.
    Done,
    /// The session user confirmed it is them (`ConfirmPassword`,
    /// `FinishConfirmPasskey`): this session counts as signed in now.
    Confirmed,
    Home(HomeScreen),
    TrackPreferences(TrackPreferencesInfo),
    /// An item's frame previews (`GetPreviews`).
    Previews(Previews),
    /// What the platform makes an app passkey with, but the challenge:
    /// the nonce it is made from (`BeginPasskeyRegistration`).
    PasskeyRegistrationBegun(PasskeyRegistrationBegun),
    /// What the platform signs in with an app passkey with, but the
    /// challenge: the nonce it is made from (`BeginPasskeySignIn`,
    /// `BeginConfirmPasskey`).
    PasskeySignInBegun(PasskeySignInBegun),
    /// The session user's passkeys (`ListPasskeys`).
    Passkeys {
        passkeys: Vec<PasskeyInfo>,
    },
    /// What a portable identity signs to tie the session user's account
    /// to it (`TieBegin`).
    TieChallenge {
        /// Used once, for `expires_in_secs`, by this session.
        #[serde(with = "serde_bytes")]
        nonce: [u8; 32],
        /// This server's endpoint id, as the tie message names it. A
        /// client signs with the id it dialled, never this one: the field
        /// says which server meant to ask.
        #[serde(with = "serde_bytes")]
        server: [u8; 32],
        expires_in_secs: u64,
    },
    /// What a portable user's device signs to sign in
    /// (`BeginPortableSignIn`).
    PortableSignInBegun {
        /// Used once, for `expires_in_secs`, by this device.
        #[serde(with = "serde_bytes")]
        nonce: [u8; 32],
        expires_in_secs: u64,
    },
    /// A new invite, with its code (`CreateInvite`).
    InviteCreated(InviteCreated),
    /// What the server keeps of a portable identity (`IdentityRecord`).
    IdentityRecord(IdentityRecord),
    /// The pairing request held under a code (`FetchPairing`).
    PairingOffered(PairingOffer),
    /// The answer to a device's pairing request, or `None` while none
    /// came yet (`CollectPairing`).
    PairingAnswered {
        answer: Option<PairingAnswer>,
    },
    /// The invites that can still be redeemed (`ListInvites`).
    Invites {
        invites: Vec<InviteSummary>,
    },
    /// Experimental (`http-playback`): where a player with no Iroh
    /// fetches the playback (`HttpPlaybackUrl`).
    HttpPlaybackUrl {
        url: String,
    },
    /// Experimental (`http-playback`): why `HttpPlaybackUrl` gave
    /// no URL.
    HttpPlaybackRefused {
        reason: crate::experimental::HttpPlaybackRefusal,
    },
    /// Experimental (`federation`): the server paired
    /// (`PairServer`).
    ServerPaired {
        server: crate::federation::PeerServer,
    },
    /// Experimental (`federation`): the libraries shared with the
    /// paired server (`ShareLibraries`), as asked.
    LibrariesShared {
        libraries: Vec<spoolframe_types::LibraryId>,
    },
    /// Experimental (`federation`): the session a play token
    /// opened (`RedeemPlayToken`).
    PlayTokenRedeemed(crate::federation::PlayTokenRedeemed),
    /// Experimental (`federation`): where a paired server is
    /// (`RemoteHints`).
    RemoteHints(crate::federation::RemoteHints),
    /// Experimental (`federation`): a paired server's play token
    /// for this device (`RemoteGrant`).
    RemoteGranted(crate::federation::RemoteGranted),
    /// The playlists the user sees (`ListPlaylists`), oldest first,
    /// and the notes of pinned ones that left their Pinned.
    Playlists {
        playlists: Vec<PlaylistSummary>,
        pin_notes: Vec<PinNote>,
    },
    /// One playlist and a page of its entries (`GetPlaylist`).
    Playlist(PlaylistPage),
    /// A playlist as it is now (`CreatePlaylist`, `UpdatePlaylist`).
    PlaylistInfo(PlaylistSummary),
    /// A subtitle track's timing after `SyncSubtitle`,
    /// `UseOriginalSubtitleTiming` or `SetSubtitleOffset`.
    SubtitleTiming(spoolframe_types::SubtitleTiming),
    /// What `SearchSubtitles` found.
    SubtitleResults(spoolframe_types::SubtitleSearch),
    /// The track `DownloadSubtitle` added.
    SubtitleDownloaded(spoolframe_types::SubtitleDownloaded),
    /// The playlist's revision after `EditPlaylist`, and the entries its
    /// adds made, in the edits' order (a show's add makes one an
    /// episode). `None` only from a server older than the field, which
    /// leaves it out.
    PlaylistEdited {
        revision: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        added: Option<Vec<crate::playlists::EntryId>>,
    },
    /// The entry to play now (`PlayPlaylist`, `NextInPlaylist`).
    PlaylistItem(crate::playlists::PlaylistNext),
    /// Nothing is left to play: the end, with repeat off, or no entry can
    /// be played. The user's place is cleared.
    PlaylistFinished,
    /// What plays next in a playlist (`UpcomingInPlaylist`), in turn.
    PlaylistUpcoming {
        entries: Vec<crate::playlists::PlaylistEntry>,
    },
    /// What importing Plex playlists made, or would (`ImportPlexPlaylists`).
    PlexImport(crate::playlists::PlexImport),
    /// Whom a playlist can be shared with (`ListShareCandidates`).
    ShareCandidates(crate::playlists::ShareCandidatePage),
    /// What the device may download of an item (`DownloadOptions`).
    DownloadOptions(crate::downloads::DownloadOptionsInfo),
    /// A download prepared (`PrepareDownload`).
    Download(crate::downloads::DownloadInfo),
    /// Downloads, in the order asked (`DownloadStatus`): each the user
    /// has, and the ids asked for that they have not. A device treats a
    /// gone download as cancelled: preparing it again brings it back.
    Downloads {
        downloads: Vec<crate::downloads::DownloadInfo>,
        /// Left out when empty.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        gone: Vec<String>,
    },
    /// What became of each offline entry, in order (`SyncOfflineWatch`).
    OfflineWatchSynced {
        outcomes: Vec<crate::downloads::OfflineWatchOutcome>,
    },
    /// What each followed thing holds (`MusicDownloadChanges`), and the
    /// cursor to ask with next.
    MusicDownloadChanges {
        changes: Vec<crate::downloads::FollowedChange>,
        cursor: String,
    },
    /// What became of each offline play and like, in order
    /// (`SyncOfflinePlays`).
    OfflinePlaysSynced {
        plays: Vec<crate::downloads::OfflineWatchOutcome>,
        liked: Vec<crate::downloads::OfflineWatchOutcome>,
    },
}

/// Which HLS playlist.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum ManifestKind {
    /// The top playlist, naming the variant.
    Multivariant,
    /// The variant's segments.
    Media,
    /// The subtitle rendition's WebVTT segments, read with
    /// `ReadSubtitleSegment`; there when the plan has a subtitle.
    Subtitles,
    #[serde(other)]
    Unknown,
}

/// Rows for a home screen. Every item carries the user's playback state.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct HomeScreen {
    /// Started and not finished, most recent first.
    pub continue_watching: Vec<Item>,
    /// For each recently watched show, its next unwatched episode.
    pub next_up: Vec<Item>,
    pub recently_added: Vec<Item>,
    /// Experimental (`federation`): the items of these rows that
    /// are no longer available: their paired server unpaired, or stopped
    /// sharing their library. Shown as such, and not played. Only to a
    /// client that named the feature, as every `fed:` id is; left out when
    /// empty, as experimental fields are.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unavailable: Vec<MediaId>,
    /// Experimental (`federation`): each paired server's own row,
    /// what it shared lately, by the server's name. A row the user turned
    /// off (`SetServerRow`) is listed with no items, for the setting. Left
    /// out when empty, as experimental fields are.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub servers: Vec<ServerRow>,
}

/// A paired server's row on Home.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct ServerRow {
    pub server: spoolframe_types::LibraryServer,
    /// Whether the user shows it (`SetServerRow`); a row not shown has no
    /// items.
    pub shown: bool,
    /// What it shared most recently first, as this server cached it.
    pub items: Vec<Item>,
}

/// A session's user.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserSummary {
    /// Opaque; stable for the user on this server (today `local:<uuid>`).
    /// A server that served `local:<number>` ids changes them once: a
    /// client that kept an id reads it again from `WhoAmI`.
    pub user_id: String,
    pub username: String,
    /// What to show; the username when the user has no display name.
    pub display_name: String,
    /// What the user may do.
    pub role: Role,
    /// The session needs the user's PIN on this connection before anything
    /// but `WhoAmI` and `UnlockProfile`.
    pub locked: bool,
    /// The user's PIN, if they have one: for "Set · 4 digits", and
    /// for how many boxes a PIN pad shows. Never the PIN itself.
    pub pin: Option<PinState>,
    /// The portable identities the account is tied to,
    /// the oldest tie first: shown on the account, never as other
    /// accounts. Empty for an account with none, and for a portable
    /// user's own session, whose identity is its `user_id`.
    pub portable: Vec<PortableTie>,
}

impl UserSummary {
    /// The portable identity a guest's session is (`portable:<hex>`);
    /// `None` for an account of this server's own.
    pub fn portable_id(&self) -> Option<crate::portable::PortableUserId> {
        self.user_id.strip_prefix("portable:")?.parse().ok()
    }

    /// The session is a portable identity's, a guest's, rather than an
    /// account of this server's own.
    pub fn is_guest(&self) -> bool {
        self.portable_id().is_some()
    }
}

/// One of an account's ties to a portable identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableTie {
    pub id: PortableUserId,
    /// Unix seconds.
    pub tied_at: i64,
    /// Unix seconds of the identity's last sign-in into the account with
    /// its credential; `None` until one.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub last_used_at: Option<i64>,
}

/// What `WhoAmI` answers: the session's user, and whether they may leave
/// the server. On the wire the user's fields and `can_leave` sit in one
/// map, so a client that does not know `can_leave` reads it as a
/// [`UserSummary`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WhoAmIReply {
    #[serde(flatten)]
    pub user: UserSummary,
    /// `LeaveServer` would be done, not refused with `LastAdmin`:
    /// false for the last enabled admin, or the last enabled admin with a
    /// password, so an app can grey out "Leave this server" before it is
    /// asked. As of this answer: an admin made or demoted later changes
    /// it.
    pub can_leave: bool,
}

/// A user's PIN as clients may know it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct PinState {
    /// How many digits it has (4 to 8); `None` for a PIN set before the
    /// server kept its length, until it is set again.
    pub digits: Option<u8>,
}

/// A user a device is trusted for, as that device sees them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct TrustedProfile {
    /// What `ResumeProfile` takes: `UserSummary::user_id`.
    pub user_id: String,
    /// To match the profile with one the device keeps by username.
    pub username: String,
    /// What to show; the username when the user has no display name.
    pub display_name: String,
    /// The user's PIN is asked for on this device: a resumed session
    /// starts locked.
    pub pin_required: bool,
    /// How many digits that PIN has (4 to 8), for the boxes a PIN pad
    /// shows. `None` when it is not asked for here, for a PIN set before
    /// the server kept its length (until it is set again), and from a
    /// server older than the field.
    #[serde(default)]
    pub pin_digits: Option<u8>,
    /// Open this profile at start, past "Who's watching". At most one per
    /// device.
    pub auto_login: bool,
}

/// One of a user's devices.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct DeviceInfo {
    /// Hex `EndpointId`: what `SetPinRequired { device }` takes.
    pub endpoint_id: String,
    /// What the device calls itself.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub name: Option<String>,
    /// What kind of client it runs, as its `Hello` said; `None` for a
    /// device not seen since before the server kept it.
    pub platform: Option<Platform>,
    /// Unix seconds on the wire.
    #[serde(with = "spoolframe_types::serde_time::unix_seconds")]
    pub last_seen_at: std::time::SystemTime,
    /// The user's PIN is asked for on it.
    pub pin_required: bool,
    /// It may resume the user without a password.
    pub trusted: bool,
    /// It opens the user's profile at start.
    pub auto_login: bool,
    /// The device this request came from.
    pub this_device: bool,
}

/// A device waiting to be signed in, as the approver sees it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct DeviceSignInRequest {
    /// What the device calls itself (from its `Hello`).
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub device_name: Option<String>,
    /// Its app, e.g. `spoolframe-tvos`.
    pub client_name: String,
    /// What kind of client it runs, as its `Hello` said: shown beside its
    /// name ([`Platform::label`], "Apple TV app"), so the approver knows
    /// which device asks.
    pub platform: Platform,
    /// Unix seconds on the wire.
    #[serde(with = "spoolframe_types::serde_time::unix_seconds")]
    pub requested_at: std::time::SystemTime,
    /// The device asked to be remembered: the approval says "This
    /// device will be remembered", ticked, and the approver may untick it.
    pub remember: bool,
    /// Where the device's `BeginDeviceSignIn` came from, as the server saw
    /// it: the one thing on this screen an attacker who
    /// sent the approver a code cannot choose. `None` if the server could
    /// not tell. The approval shows it, "The TV asked from 192.168.86.20.",
    /// and for [`AddressNetwork::Internet`] warns instead: the device is
    /// not on the approver's network, so approve only one you can see.
    #[serde(deserialize_with = "spoolframe_types::required::option")]
    pub requested_from: Option<DeviceAddress>,
}

/// An address a device reached the server from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct DeviceAddress {
    /// Its IP address as text: `192.168.86.20`, `fd7a:115c:a1e0::1`. An
    /// IPv4 address is never in its IPv6-mapped form.
    pub address: String,
    /// What kind of network that address is on, as the server judges it.
    pub network: AddressNetwork,
}

/// What kind of network an address is on, as the server's web approval
/// page judges it too.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum AddressNetwork {
    /// The server's own machine: `127.0.0.0/8`, `::1`.
    Loopback,
    /// A home, office or VPN network: private IPv4 ranges, link-local,
    /// CGNAT and VPNs' `100.64.0.0/10`, IPv6 unique-local and link-local.
    Local,
    /// A public address: a device far from the approver, which is what a
    /// sign-in code sent to someone else (device-code phishing) looks
    /// like. The approval warns.
    Internet,
    /// A kind this build does not know, from a newer server. Show the
    /// address and warn as for [`AddressNetwork::Internet`].
    #[serde(other)]
    Unknown,
}

#[cfg_attr(feature = "uniffi", uniffi::export)]
impl DeviceAddress {
    /// On the server's own machine or its network: the approval says
    /// where it asked from rather than warn.
    pub fn is_local(&self) -> bool {
        matches!(
            self.network,
            AddressNetwork::Loopback | AddressNetwork::Local
        )
    }
}

#[cfg_attr(feature = "uniffi", uniffi::export)]
impl DeviceSignInRequest {
    /// It asked from the server's machine or network
    /// ([`DeviceAddress::is_local`]); false where the server couldn't
    /// tell, which the approval warns about as for one far away.
    pub fn is_local(&self) -> bool {
        self.requested_from
            .as_ref()
            .is_some_and(DeviceAddress::is_local)
    }
}

/// One live session, without its token.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionInfo {
    /// The device's name; `None` for an admin API session or an unnamed
    /// device.
    pub device_name: Option<String>,
    /// What kind of client the device runs; `None` for an admin API
    /// session (the web UI or the CLI) or a device not seen since before
    /// the server kept it.
    pub platform: Option<Platform>,
    /// Unix seconds.
    pub created_at: i64,
    /// Unix seconds.
    pub last_used_at: i64,
    /// The session this request was made in.
    pub current: bool,
}

/// Who the server is. `endpoint_id` is what the client pins.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerInfo {
    pub name: String,
    /// Hex, as `spoolframe-server id` prints it.
    pub endpoint_id: String,
    /// The server's id ([`crate::ServerId`]): made once, kept when its key
    /// is replaced. A client pins it beside `endpoint_id`, the first time
    /// it sees it.
    pub server_id: String,
    pub protocol_version: u32,
    pub server_version: String,
    pub auth_methods: Vec<AuthMethod>,
    /// Where a browser reaches the server's web UI (`admin.public_url`),
    /// if it has one: for "open in the browser" links, such as linking a
    /// Plex account. Absent without a public URL, since the
    /// listener's own address may be loopback or one no browser trusts.
    pub web_url: Option<String>,
    /// The experimental features turned on for this connection:
    /// those its `Hello` named that this server knows and has on. Left
    /// out when none, as an older server does.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub experimental: Vec<String>,
    /// The regular features on for this connection
    /// ([`crate::features`]): those its `Hello` named that this server
    /// has. Left out when none, as an older server does.
    #[serde(
        default,
        with = "crate::features::names",
        skip_serializing_if = "Features::is_empty"
    )]
    pub features: Features,
    /// An account is made only from an invite (`RedeemInvite`); there is
    /// no open sign-up. For a "servers on my network" list, before
    /// signing in.
    pub invite_only: bool,
}

/// Why a request failed. Typed, so clients act on the kind, not on text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Error {
    #[error("progress belongs to an older playback or sequence")]
    StaleProgress,
    #[error("the operation belongs to an earlier server instance")]
    ServerRestarted,
    #[error("the operation expired; its outcome is no longer recoverable")]
    OperationExpired,
    #[error("the operation ID was already used with different arguments")]
    OperationConflict,
    #[error("the playback configuration changed (revision {revision})")]
    RevisionConflict { revision: u64 },
    /// The connection's first request was not `Hello`.
    #[error("send Hello first")]
    HandshakeRequired,
    /// The request needs a session, and none valid for this endpoint was
    /// given.
    #[error("not authenticated")]
    Unauthenticated,
    /// The server does not know this request type.
    #[error("unsupported request {request:?}")]
    Unsupported { request: String },
    #[error("malformed request: {message}")]
    Malformed { message: String },
    #[error("{what} not found")]
    NotFound { what: String },
    /// Wrong username or password; deliberately the same for both.
    #[error("invalid credentials")]
    InvalidCredentials,
    /// Too many failed logins for this username or from this endpoint.
    #[error("too many failed logins; retry in {retry_after_ms} ms")]
    RateLimited { retry_after_ms: u64 },
    /// The client cannot play this selection; one reason per stream, as
    /// in [`PlaybackPlan::Unsupported`].
    #[error("cannot play: {}", reasons.join("; "))]
    CannotPlay { reasons: Vec<String> },
    /// The playback handle is unknown or has been idle too long. Call
    /// `StartPlayback` again and go on from where playback was.
    #[error("the playback has expired; start it again")]
    PlaybackExpired,
    /// An admin stopped the playback on the server. It is over:
    /// tell the viewer it ended, and do not start it again on your own
    /// as after `PlaybackExpired`. Its progress is kept.
    #[error("the playback was stopped on the server")]
    PlaybackStopped,
    /// The server is converting as many files as it may at once.
    #[error("the server is busy converting; try again later")]
    Busy,
    /// The server plays at most `max` playbacks off its LAN at once
    /// (`network.uplink.max_streams`), and that many are playing.
    /// Try again when one ends; a device on the server's LAN is not
    /// counted.
    #[error("the server plays at most {max} playbacks outside its home at once")]
    WanStreamsFull { max: u32 },
    /// The encode for this playback failed; `reason` is ffmpeg's.
    #[error("the conversion failed: {reason}")]
    PlaybackFailed { reason: String },
    /// The read names an encode that a seek replaced; read `epoch` from
    /// offset 0.
    #[error("the playback restarted at a seek (epoch {epoch})")]
    PlaybackRestarted { epoch: u32 },
    /// The subtitle is still being read as text; `done_percent` of
    /// its cues are read. Ask again in a few seconds.
    #[error("the subtitle is still being read ({done_percent}% done)")]
    SubtitleNotReady { done_percent: u8 },
    /// The item's frame previews are being made; `done_percent` of
    /// them are. Ask again in a few seconds; show the time alone till then.
    #[error("the previews are being made ({done_percent}% done)")]
    PreviewsNotReady { done_percent: u8 },
    /// The item has no frame previews and will not have: music, a file
    /// they could not be made of, or a server that makes none. Do not ask
    /// again for this item.
    #[error("this item has no previews")]
    NoPreviews,
    /// The subtitle is not the file that `ReadSubtitle`'s `version` names:
    /// it was written again or replaced since that chunk. Read it
    /// again from offset 0.
    #[error("the subtitle changed while it was read")]
    SubtitleChanged,
    /// The session's profile is locked on this connection: `UnlockProfile`
    /// with the user's PIN first.
    #[error("this profile is locked; enter its PIN")]
    ProfileLocked,
    /// A value the request carries is not acceptable (a PIN that is not 4
    /// to 8 digits, say); the message says why.
    #[error("{message}")]
    InvalidInput { message: String },
    /// The request carried the user's account password, and they have none:
    /// they sign in with a passkey or SSO only (a `PinProof::Password`).
    /// Not a wrong password, and nothing was counted. Use another proof, or
    /// send them to the server's web UI (`ServerInfo::web_url`, when the
    /// server has one).
    #[error("this account has no password; use the PIN or the web UI")]
    NoPassword,
    /// The session was signed in too long ago for this (an app passkey,
    /// approving a device): confirm it is the user
    /// (`ConfirmPassword`, or `BeginConfirmPasskey`), or sign in again,
    /// then ask again. Nothing was changed.
    #[error("sign in again first")]
    RecentSignInRequired,
    /// Removing this would leave the user no way to sign in: it is their
    /// only passkey, and they have no password or linked sign-in provider
    /// (`RemovePasskey`). Nothing was changed.
    #[error("that is the last way to sign in to this account")]
    LastSignInMethod,
    /// The device sign-in was refused on the approving device.
    #[error("the sign-in was denied")]
    DeviceSignInDenied,
    /// The device sign-in is over: it timed out, or is not this device's.
    /// Begin a new one.
    #[error("the sign-in code has expired")]
    DeviceSignInExpired,
    /// The reply would be over the frame limit
    /// ([`crate::codec::MAX_FRAME`]); `bytes` is its length. A page of
    /// items is to ask for in smaller pages.
    #[error("the reply is too large to send ({bytes} bytes)")]
    ReplyTooLarge { bytes: u64 },
    /// Something the server depends on (Plex, a media mount) is down.
    #[error("unavailable: {message}")]
    Unavailable { message: String },
    /// The server has no library yet: it is waiting to be set up in its
    /// web UI. Every catalog and playback request gets this until
    /// it is; show "This server is not set up yet", not an error. Signing
    /// in and the rest work.
    #[error("this server is not set up yet")]
    NotSetUp,
    /// The invite's code is right, and it is of another kind than the
    /// request redeems: a `portable-account` invite's code to
    /// `RedeemInvite`, or a `create-user` one's to
    /// `RedeemPortableInvite`. Nothing was made and the invite keeps its
    /// use: redeem it the other way.
    #[error("that invite is of another kind")]
    WrongInviteKind,
    /// `RedeemInvite` with a code that is no invite's, or whose invite
    /// was revoked. Counted as a wrong guess. Offer "Save server
    /// only", which pins the server as a link without a code does.
    #[error("that invite code is not valid")]
    InviteInvalid,
    /// The invite's code is right, and it has expired: ask for another.
    #[error("the invite has expired")]
    InviteExpired,
    /// The invite's code is right, and every account it could make has
    /// been made: ask for another.
    #[error("the invite has been used up")]
    InviteExhausted,
    /// Someone on this server has that username: pick another. Nothing
    /// was made and the invite was not used up.
    #[error("that username is taken")]
    UsernameTaken,
    /// `TieFinish` with a nonce that is not outstanding for this session:
    /// it was used, it is over, or `TieBegin` never gave it here.
    /// Begin again.
    #[error("the tie challenge is used or has expired; begin again")]
    TieChallengeExpired,
    /// Another account on this server is tied to that portable identity:
    /// one identity ties to one account per server. Sever that
    /// tie first. Nothing was changed.
    #[error("that portable identity is tied to another account here")]
    PortableIdTaken,
    /// The session is a portable user's, and this is for an
    /// account here only: its password, PIN, passkeys, devices, sessions,
    /// ties, approving sign-ins. Hide what asks for it while signed in as
    /// one. Nothing was changed.
    #[error("not for a guest from another identity")]
    NotForPortableUsers,
    /// The request is an admin's (making and revoking invites),
    /// and the session user is not one. Nothing was changed.
    #[error("only an admin can do that")]
    AdminRequired,
    /// The session was opened with a one-time password an admin reset to:
    /// it may only `ChangePassword` (or `Logout`, `WhoAmI`) until the user
    /// chooses a new password. Nothing was done.
    #[error("choose a new password first")]
    PasswordChangeRequired,
    /// `LeaveServer` from the last enabled admin, or the last enabled
    /// admin with a password: make someone else an admin, or give
    /// one a password, first. Nothing was changed.
    #[error("you are the only admin; make someone else an admin first")]
    LastAdmin,
    /// The user sees the playlist and may not make this change: an
    /// edit on a read-only share, or a rename, sharing change or delete by
    /// anyone but its owner (or an admin, for a server-wide one). Nothing
    /// was changed.
    #[error("you cannot change this playlist")]
    PlaylistReadOnly,
    /// The playlist does not take items of this kind: its kinds
    /// were ticked when it was made. Nothing was changed. A season or
    /// show is episodes, an album or artist tracks.
    #[error("this playlist does not take a {kind:?}")]
    KindNotAllowed { kind: crate::playlists::ItemKind },
    /// Someone changed the playlist since the revision the edit was made
    /// on, and touched an entry the edit touches: "Someone changed
    /// this playlist; reload". `revision` is its revision now. Nothing was
    /// changed.
    #[error("someone changed this playlist; reload (revision {revision})")]
    PlaylistConflict { revision: u64 },
    /// The user may not do this to what they see: a cover set or
    /// taken away by someone who may not edit the playlist, or on Liked
    /// or All, whose tiles are fixed. Nothing was changed.
    #[error("you are not allowed to do that")]
    NotAllowed,
    /// The picture is over `max_bytes` long, or over `max_pixels` by its
    /// header. Refused before it was decoded; nothing was
    /// changed.
    #[error("the picture is too large: at most {max_bytes} bytes and {max_pixels} pixels")]
    ImageTooLarge { max_bytes: u64, max_pixels: u64 },
    /// Not a JPEG, PNG, WebP or HEIC picture the server can decode, or
    /// one that hit the decoder's limits. Nothing was changed.
    #[error("the picture cannot be read: a JPEG, PNG, WebP or HEIC is taken")]
    ImageUnreadable,
    /// The downloads of `whose` are used up for today: the
    /// server's account at subtitle site `site` (`opensubtitles`,
    /// `subdl`, as `SubtitleResult::source`), or the user's own daily
    /// limit on this server (no `site`). `resets_at` (Unix seconds) is when more may be
    /// downloaded, when known. Nothing was downloaded; searching still
    /// works.
    #[error("no subtitle downloads left today ({whose:?})")]
    QuotaExhausted {
        whose: spoolframe_types::QuotaOf,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resets_at: Option<i64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        site: Option<String>,
    },
    /// The server has no subtitle site set up: hide "Find
    /// subtitles". Nothing was asked of any site.
    #[error("this server has no subtitle source set up")]
    NoSubtitleSource,
    /// The download's file is not whole yet: read it once its
    /// state is `ready`. A download that failed is prepared again.
    #[error("the download is not ready")]
    DownloadNotReady,
    /// Experimental (`federation`): the other server did not pair
    /// (`PairServer`), for `reason`. Nothing was kept.
    #[error("the other server did not pair: {reason}")]
    PairingRefused {
        reason: crate::federation::PairingRefused,
    },
    /// Experimental (`federation`): the paired server the item is
    /// from is offline to this one (`RemoteGrant`): play it from this
    /// server, or later.
    #[error("the paired server the item is from is offline")]
    OriginOffline,
    #[error("internal server error")]
    Internal,
    /// An error type this build does not know.
    #[serde(other)]
    #[error("unknown error")]
    Unknown,
}

/// Something the server tells the client without being asked, on the
/// events stream.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    /// The server is stopping; the connection will close.
    ShuttingDown,
    /// Where this server can be reached, pushed to a connection
    /// as soon as it is signed in, and again whenever the list changes.
    /// Each one is the whole list: it replaces what was told before.
    /// Never sent to a connection that is not signed in.
    ServerAddresses {
        /// The addresses `network.announce` tells, with their port, as
        /// text: `192.168.1.10:4433` or `[2001:db8::1]:4433`.
        #[serde(with = "socket_addrs_as_text")]
        addrs: Vec<std::net::SocketAddr>,
        /// The URLs of the iroh relays the server may use
        /// (`network.relays`), its home relay now first; empty while
        /// relays are off.
        relays: Vec<String>,
        /// The pkarr relay the server publishes where it is to
        /// (`network.pkarr`), for the device to look it up by its
        /// key when nothing else reaches it; `None` while it publishes
        /// nothing.
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        lookup: Option<String>,
    },
    /// Playback `handle`'s share of the server's WAN uplink changed:
    /// another WAN playback started or ended, or the budget
    /// changed. A playback in `Quality::Auto` re-plans with
    /// `ChangeQuality` at its position (the SDK's managed playback does
    /// it by itself); `max_bitrate` is the new cap, `None` none. Sent only
    /// for a move of 15% or more, a few seconds after the last start or
    /// end. One of another quality may ignore it.
    PlaybackShare {
        handle: PlaybackHandle,
        #[serde(deserialize_with = "spoolframe_types::required::option")]
        max_bitrate: Option<u64>,
    },
    /// A playlist the user sees was made or changed: its entries,
    /// name, kinds or sharing. Read it again if it is shown. Only to a
    /// client that listed `spoolframe:playlists`.
    PlaylistChanged { id: String, revision: u64 },
    /// A playlist the user saw is gone to them: deleted, or no longer
    /// shared with them. Close it if it is shown.
    PlaylistGone { id: String },
    /// The user's Pinned, or its notes, changed on another device or by
    /// another user's change: `ListPlaylists` again.
    PinsChanged,
    /// The user liked or unliked a track, on any device: a device
    /// that downloaded Liked asks what it holds now
    /// (`MusicDownloadChanges`). Only to the user's own connections that
    /// listed `spoolframe:music-downloads`.
    LikedChanged,
    /// Item `id`'s subtitle `track` is timed anew: synced, its
    /// sync done or set aside, or its offset changed, by anyone. What it
    /// is served with changed: a player showing it reads it again (a
    /// `ReadSubtitle` in progress answers `SubtitleChanged`), with no
    /// restart. Only to a client that listed `spoolframe:subtitle-sync`,
    /// on a connection that asked for the item's `Tracks` or plays it.
    SubtitleTimingChanged {
        id: MediaId,
        track: u32,
        timing: spoolframe_types::SubtitleTiming,
    },
    /// Download `id`'s state moved: `waiting`, then `converting`
    /// (told once per percent or every 2 s), `writing`, and `ready` or
    /// `failed`. Only to the connections of the user whose it is, that
    /// listed `spoolframe:downloads`.
    DownloadChanged {
        id: String,
        state: crate::downloads::DownloadState,
    },
    /// Experimental (`federation`): the libraries changed: a paired
    /// server came online or went offline, or shared or stopped sharing a
    /// library. `Libraries` again. Only to a client that named the
    /// feature.
    LibrariesChanged,
    /// Experimental (`federation`): playback `handle`, of a paired
    /// server's item, ended other than by its client's stop: stopped by an
    /// admin, idle past the limit, its session or its grant ended, or, on
    /// the user's own server playing it on, ended where it plays from.
    /// `error` is what the client's next use of it is told
    /// (`PlaybackStopped`: do not start it again). Only for a play
    /// token's session's playbacks, and those played through the user's
    /// own server.
    PlaybackEnded {
        handle: PlaybackHandle,
        error: Error,
    },
    /// The profile of local user `user` (a user id, as `WhoAmI` names
    /// it) is gone from this device: the user was disabled or deleted, or
    /// an admin forgot this device for them. Their sessions here end with
    /// it; the next request in one is `Unauthenticated`. Leave the profile,
    /// and offer to sign in again only if the user is not deleted. Only to
    /// that user's connections, and sent only to a connection where the
    /// `spoolframe:profile-events` feature is on (both sides named it).
    ProfileRemoved { user: String },
    /// Local user `user`'s PIN changed: set, changed or removed, by them on
    /// another device or by an admin. `required` is whether they have a PIN
    /// now. A device that has their profile unlocked locks it again where
    /// the PIN is asked for; one that kept the old PIN to check offline
    /// forgets it. Only to that user's connections, not the one that made
    /// the change, and sent only to a connection where the
    /// `spoolframe:profile-events` feature is on (both sides named it).
    PinChanged { user: String, required: bool },
    /// The user's watch state of `items` changed on another connection:
    /// marked watched or unwatched (a season's or a show's id marks its
    /// episodes), hidden from or put back in Continue watching, synced
    /// from offline, or played into progress, to watched, or stopped (not
    /// each progress report). Read again what shows them (Home, an item's page). Only
    /// to that user's other connections, and sent only to a connection
    /// where the `spoolframe:watch-events` feature is on (both sides
    /// named it).
    WatchChanged { items: Vec<MediaId> },
    /// An event type this build does not know; ignore it.
    #[serde(other)]
    Unknown,
}

/// Socket addresses on the wire as text (`192.168.1.10:4433`,
/// `[2001:db8::1]:4433`). CBOR is not a human-readable format to serde, so
/// a bare `SocketAddr` would go as serde's enum of byte tuples, which a
/// peer outside Rust would have to copy; text is also what JSON shows.
pub(crate) mod socket_addrs_as_text {
    use std::net::SocketAddr;

    use serde::de::Error as _;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(addrs: &[SocketAddr], s: S) -> Result<S::Ok, S::Error> {
        let text: Vec<String> = addrs.iter().map(ToString::to_string).collect();
        text.serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<SocketAddr>, D::Error> {
        Vec::<String>::deserialize(d)?
            .iter()
            .map(|text| {
                text.parse()
                    .map_err(|_| D::Error::custom(format!("not a socket address: {text:?}")))
            })
            .collect()
    }
}

#[cfg(test)]
mod tests;