redseat-api 0.19.1

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

#[cfg(test)]
mod tests;

use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};

use futures_util::StreamExt as _;
use tokio::sync::Notify;

use super::ServerCopy;
use super::catalog::Playable;
use super::text;
use crate::error::{Error, Result};
use crate::library::LibraryApi;
use crate::mirror::runtime::{Task, spawn};
use crate::types::media::{FileEpisode, Media};
use rs_plugin_common_interfaces::lookup::{RsLookupMatchType, SseLookupSearchEvent};
use rs_plugin_common_interfaces::request::{
    RsGroupDownload, RsRequest, RsRequestFiles, RsRequestStatus,
};

/// A video's quality class, best first in the default order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VideoTier {
    DolbyVision4k,
    Hdr4k,
    Uhd4k,
    Fhd1080p,
    Remux4k,
    Remux1080p,
    Hd720p,
    Sd,
    Unknown,
}

impl VideoTier {
    /// The default order: 4K Dolby Vision first, disc copies after the usual 1080p.
    pub const DEFAULT_ORDER: [VideoTier; 9] = [
        VideoTier::DolbyVision4k,
        VideoTier::Hdr4k,
        VideoTier::Uhd4k,
        VideoTier::Fhd1080p,
        VideoTier::Remux4k,
        VideoTier::Remux1080p,
        VideoTier::Hd720p,
        VideoTier::Sd,
        VideoTier::Unknown,
    ];

    pub fn label(self) -> &'static str {
        match self {
            VideoTier::DolbyVision4k => "4K Dolby Vision",
            VideoTier::Hdr4k => "4K HDR",
            VideoTier::Uhd4k => "4K",
            VideoTier::Remux4k => "4K Remux",
            VideoTier::Remux1080p => "1080p Remux",
            VideoTier::Fhd1080p => "1080p",
            VideoTier::Hd720p => "720p",
            VideoTier::Sd => "SD",
            VideoTier::Unknown => "Unknown resolution",
        }
    }

    fn rank(self) -> usize {
        (Self::DEFAULT_ORDER.iter())
            .position(|tier| *tier == self)
            .unwrap_or(usize::MAX)
    }
}

/// An audio format class, best first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AudioTier {
    Atmos,
    DtsX,
    TrueHd,
    DtsHd,
    Dts,
    DolbyDigitalPlus,
    DolbyDigital,
    Aac,
    Other,
}

impl AudioTier {
    pub fn label(self) -> &'static str {
        match self {
            AudioTier::Atmos => "Dolby Atmos",
            AudioTier::DtsX => "DTS:X",
            AudioTier::TrueHd => "Dolby TrueHD",
            AudioTier::DtsHd => "DTS-HD MA",
            AudioTier::Dts => "DTS",
            AudioTier::DolbyDigitalPlus => "Dolby Digital Plus",
            AudioTier::DolbyDigital => "Dolby Digital",
            AudioTier::Aac => "AAC",
            AudioTier::Other => "Other or unknown",
        }
    }

    /// A badge's short words.
    fn badge(self) -> Option<&'static str> {
        Some(match self {
            AudioTier::Atmos => "Atmos",
            AudioTier::DtsX => "DTS:X",
            AudioTier::TrueHd => "TrueHD",
            AudioTier::DtsHd => "DTS-HD MA",
            AudioTier::Dts => "DTS",
            AudioTier::DolbyDigitalPlus => "DD+",
            AudioTier::DolbyDigital => "DD",
            AudioTier::Aac => "AAC",
            AudioTier::Other => return None,
        })
    }
}

/// What a result offers now.
#[derive(Debug, Clone, PartialEq)]
pub enum SourceAction {
    /// Play and Add to Library.
    Idle,
    /// Working on it: "Opening…", "Checking the source…", "Adding to your library…".
    Working(String),
    /// Several files: pick one, then Play or Add again with it.
    ChooseFile(Vec<SourceFile>),
    /// Only the server can read it: add it to the library to watch it.
    AddToWatch,
    /// Added: the server downloads it and the file joins the title.
    Added,
    /// The server prepares it in the background; it joins the library when ready.
    Preparing,
    Failed(String),
}

/// A file of a source holding several.
#[derive(Debug, Clone, PartialEq)]
pub struct SourceFile {
    pub name: String,
    /// "1.4 GB · 1080p"
    pub details: String,
    /// It is the episode's video.
    pub matches: bool,
}

/// A result of a source: one file, or a pack of several added at once.
#[derive(Debug, Clone, PartialEq)]
pub struct SourceResult {
    /// Unique in the search: its URL and chosen file.
    pub key: String,
    pub name: String,
    /// "1.4 GB · 3 files · French".
    pub details: String,
    /// "4K Dolby Vision · Dolby Atmos", without the unknown parts.
    pub quality: String,
    /// "4K", "Dolby Vision", "Remux", "Atmos", "7.1"...
    pub badges: Vec<String>,
    /// Cached by the service: it plays or adds at once.
    pub instant: bool,
    /// Found by the title's ids, not only its name.
    pub exact: bool,
    /// A pack of several downloads: it is added as a whole, never played.
    pub pack: bool,
    pub action: SourceAction,
    download: RsGroupDownload,
    request: RsRequest,
}

/// The results of one source.
#[derive(Debug, Clone, PartialEq)]
pub struct SourceGroup {
    pub source_id: String,
    /// "Jackett Lookup".
    pub name: String,
    pub results: Vec<SourceResult>,
    /// It has more results: [`Sources::more`].
    pub has_more: bool,
    pub loading_more: bool,
    next_page_key: Option<String>,
}

/// What a search shows.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SourcesView {
    /// The sources that answered with results, in the order they did.
    pub groups: Vec<SourceGroup>,
    /// Sources still answering.
    pub searching: bool,
    /// The search failed: why.
    pub error: Option<String>,
    /// The result to try first, by [`SourceResult::key`].
    pub best: Option<String>,
    /// "12 results from 3 sources", "Searching…", "No sources found.".
    pub summary: String,
    /// Play Best or Add Best: what it does now, or how it ended.
    pub best_run: BestRun,
}

impl SourcesView {
    /// A result by key.
    pub fn result(&self, key: &str) -> Option<&SourceResult> {
        (self.groups.iter())
            .flat_map(|group| group.results.iter())
            .find(|result| result.key == key)
    }

    /// The results, best first ([`VideoTier::DEFAULT_ORDER`], then audio, cached,
    /// channels and size), packs left out.
    pub fn ranked(&self) -> Vec<&SourceResult> {
        let mut seen = std::collections::HashSet::new();
        let mut ranked: Vec<(&SourceResult, RankKey)> = (self.groups.iter())
            .flat_map(|group| group.results.iter())
            .filter(|result| !result.pack && seen.insert(result.key.clone()))
            .map(|result| (result, rank_key(&result.request)))
            .collect();
        ranked.sort_by_key(|(_, key)| *key);
        ranked.into_iter().map(|(result, _)| result).collect()
    }
}

/// What a best run does with the result it picks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BestAction {
    /// Play Best: the first result that streams ([`Sources::play_best`]).
    Play,
    /// Add Best: the first result the server adds ([`Sources::add_best`]).
    Add,
}

/// Where Play Best or Add Best is. The app shows [`BestRun::message`], a Cancel
/// button while it runs ([`BestRun::is_running`]), and highlights the result tried by
/// its key.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum BestRun {
    /// Not running: Play Best and Add Best.
    #[default]
    Idle,
    /// Waiting for every source to answer before choosing.
    Searching(BestAction),
    /// Trying a result of [`SourcesView::ranked`].
    Trying {
        action: BestAction,
        /// The result tried, by [`SourceResult::key`].
        key: String,
        /// Its place in the ranked results, from 0.
        index: usize,
        /// How many results the run may try.
        total: usize,
        /// "Trying source 2 of 7", "Checking source 2 of 7", "Adding it to your
        /// library…".
        status: String,
    },
    /// Add Best added a result: the server downloads it, or prepares it first
    /// (`queued`).
    Added {
        key: String,
        queued: bool,
        /// "Added 4K Dolby Vision · Dolby Atmos to your library."
        message: String,
    },
    /// Nothing could be played or added: why.
    Nothing { action: BestAction, message: String },
}

impl BestRun {
    /// What to show: `None` when idle.
    pub fn message(&self) -> Option<&str> {
        match self {
            BestRun::Idle => None,
            BestRun::Searching(_) => Some("Waiting for every source to answer…"),
            BestRun::Trying { status, .. } => Some(status),
            BestRun::Added { message, .. } | BestRun::Nothing { message, .. } => Some(message),
        }
    }

    /// It waits or tries results: Cancel stops it.
    pub fn is_running(&self) -> bool {
        matches!(self, BestRun::Searching(_) | BestRun::Trying { .. })
    }

    fn trying(action: BestAction, result: &SourceResult, index: usize, total: usize) -> BestRun {
        let verb = match action {
            BestAction::Play => "Trying",
            BestAction::Add => "Checking",
        };
        BestRun::Trying {
            action,
            key: result.key.clone(),
            index,
            total,
            status: format!("{verb} source {} of {total}", index + 1),
        }
    }

    /// Add Best's result handed to the server to download.
    fn saving(result: &SourceResult, index: usize, total: usize) -> BestRun {
        BestRun::Trying {
            action: BestAction::Add,
            key: result.key.clone(),
            index,
            total,
            status: "Adding it to your library…".to_owned(),
        }
    }

    fn added(result: &SourceResult, queued: bool) -> BestRun {
        let label = if result.quality.is_empty() {
            &result.name
        } else {
            &result.quality
        };
        let message = if queued {
            format!("The server is preparing {label}. It appears in your library when it is ready.")
        } else {
            format!("Added {label} to your library.")
        };
        BestRun::Added {
            key: result.key.clone(),
            queued,
            message,
        }
    }
}

/// What Play found.
#[derive(Debug, Clone, PartialEq)]
pub enum SourcePlay {
    /// A URL a player opens: public, or through the server (no token needed).
    Url(String),
    /// Not played: [`SourceAction::ChooseFile`] or [`SourceAction::AddToWatch`].
    NotYet,
}

/// A search of a movie's or an episode's sources, with the actions on its results.
/// Dropping it stops the search.
pub struct Sources {
    shared: Arc<Shared>,
}

struct Shared {
    copy: ServerCopy,
    library: String,
    target: Playable,
    listener: Arc<dyn Fn() + Send + Sync>,
    state: Mutex<State>,
    /// Told when the search ends and when a best run is cancelled or replaced: a run
    /// waiting for the search looks again.
    best_signal: Arc<Notify>,
}

#[derive(Default)]
struct State {
    view: SourcesView,
    /// The search, the "more" searches and Add and Add Best under way.
    tasks: Vec<Task>,
    /// Bumped by each new search: an older one's results do not land.
    generation: u64,
    /// Bumped by each best run, its cancel and each new search: an older run stops
    /// trying and sets nothing.
    best_generation: u64,
}

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

    fn api(&self) -> Result<LibraryApi> {
        (self.copy.mirror())
            .library_api(&self.library)
            .ok_or_else(not_connected)
    }

    /// Sets the best run's state when `run` is still the current one; else it was
    /// cancelled or replaced: `false`, and nothing is set.
    fn set_best(&self, run: u64, best: BestRun) -> bool {
        {
            let mut state = lock(&self.state);
            if state.best_generation != run {
                return false;
            }
            state.view.best_run = best;
        }
        self.tell();
        true
    }
}

impl Drop for Shared {
    fn drop(&mut self) {
        for task in &self
            .state
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .tasks
        {
            task.abort();
        }
    }
}

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

impl Sources {
    /// Searches the sources of `target`, a movie or an episode of `library`, at once.
    /// `listener` is called on each change, on the copy's runtime.
    pub fn new(
        copy: ServerCopy,
        library: &str,
        target: Playable,
        listener: impl Fn() + Send + Sync + 'static,
    ) -> Sources {
        let sources = Sources {
            shared: Arc::new(Shared {
                copy,
                library: library.to_owned(),
                target,
                listener: Arc::new(listener),
                state: Mutex::default(),
                best_signal: Arc::new(Notify::new()),
            }),
        };
        sources.search_again();
        sources
    }

    /// What the search found so far.
    pub fn view(&self) -> SourcesView {
        lock(&self.shared.state).view.clone()
    }

    /// Searches again from scratch. A best run under way stops.
    pub fn search_again(&self) {
        let generation = {
            let mut state = lock(&self.shared.state);
            for task in state.tasks.drain(..) {
                task.abort();
            }
            state.generation += 1;
            state.best_generation += 1;
            state.view = SourcesView {
                searching: true,
                ..Default::default()
            };
            state.view.summary = summary(&state.view);
            state.generation
        };
        self.shared.best_signal.notify_waiters();
        self.run(generation, None, None);
        self.shared.tell();
    }

    /// The next results of a source.
    pub fn more(&self, source_id: &str) {
        let (generation, page_key) = {
            let mut state = lock(&self.shared.state);
            let generation = state.generation;
            let Some(group) = (state.view.groups.iter_mut()).find(|g| g.source_id == source_id)
            else {
                return;
            };
            let Some(page_key) = group.next_page_key.clone().filter(|_| !group.loading_more) else {
                return;
            };
            group.loading_more = true;
            (generation, page_key)
        };
        self.run(generation, Some(source_id.to_owned()), Some(page_key));
        self.shared.tell();
    }

    fn run(&self, generation: u64, source: Option<String>, page_key: Option<String>) {
        let weak = Arc::downgrade(&self.shared);
        let shared = &self.shared;
        let api = shared.copy.mirror().library_api(&shared.library);
        let target = shared.target.clone();
        let future = async move {
            let result = async {
                let api = api.ok_or_else(not_connected)?;
                let sources: Vec<String> = source.iter().cloned().collect();
                let mut stream = match &target {
                    Playable::Movie(movie) => {
                        api.search_movie_medias_stream(movie, None, &sources, page_key.as_deref())
                            .await?
                    }
                    Playable::Episode {
                        serie,
                        season,
                        number,
                    } => {
                        api.search_episode_medias_stream(
                            serie,
                            *season,
                            *number,
                            None,
                            &sources,
                            page_key.as_deref(),
                        )
                        .await?
                    }
                };
                while let Some(event) = stream.next().await {
                    let event = event?;
                    let Some(shared) = weak.upgrade() else {
                        return Ok(());
                    };
                    {
                        let mut state = lock(&shared.state);
                        if state.generation != generation {
                            return Ok(());
                        }
                        apply(&mut state.view, event);
                    }
                    shared.tell();
                }
                Ok::<_, Error>(())
            }
            .await;
            let Some(shared) = weak.upgrade() else {
                return;
            };
            {
                let mut state = lock(&shared.state);
                if state.generation != generation {
                    return;
                }
                let view = &mut state.view;
                match &source {
                    Some(source) => {
                        if let Some(group) = view.groups.iter_mut().find(|g| &g.source_id == source)
                        {
                            group.loading_more = false;
                            if result.is_err() {
                                group.next_page_key = None;
                                group.has_more = false;
                            }
                        }
                    }
                    None => {
                        view.searching = false;
                        if let Err(error) = result {
                            view.error = Some(error.to_string());
                        }
                    }
                }
                view.summary = summary(view);
            }
            if source.is_none() {
                shared.best_signal.notify_waiters();
            }
            shared.tell();
        };
        let task = spawn(self.shared.copy.runtime().as_ref(), Box::pin(future));
        lock(&self.shared.state).tasks.push(task);
    }

    /// Opens a result to play it now without keeping it: the URL a player opens, or
    /// [`SourcePlay::NotYet`] with the result's action saying what it needs (a file
    /// chosen, or adding it to the library). `file` is the one chosen.
    pub async fn play(&self, key: &str, file: Option<&str>) -> Result<SourcePlay> {
        let Some(mut request) = self.request(key) else {
            return Ok(SourcePlay::NotYet);
        };
        if let Some(file) = file {
            request.selected_file = Some(file.to_owned());
        }
        self.set_action(key, SourceAction::Working("Opening…".into()));
        let api = self.api();
        let outcome = async { resolve_playable(request, &api?, &self.shared.target).await }.await;
        match outcome {
            Ok(Playable_::Play(url)) => {
                self.set_action(key, SourceAction::Idle);
                Ok(SourcePlay::Url(url))
            }
            Ok(Playable_::PickFile(files)) => {
                self.set_action(key, SourceAction::ChooseFile(files));
                Ok(SourcePlay::NotYet)
            }
            Ok(Playable_::Add) => {
                self.set_action(key, SourceAction::AddToWatch);
                Ok(SourcePlay::NotYet)
            }
            Err(error) => {
                self.set_action(key, SourceAction::Failed(error.to_string()));
                Err(error)
            }
        }
    }

    /// Adds a result to the library: the server downloads it (the file joins the
    /// title once there), or prepares it in the background first. A pack is added
    /// whole. Runs in the background; the result's action follows it.
    pub fn add(&self, key: &str, file: Option<&str>) {
        let Some(result) = self.result(key) else {
            return;
        };
        let mut request = result.request.clone();
        if let Some(file) = file {
            request.selected_file = Some(file.to_owned());
        }
        self.set_action(key, SourceAction::Working("Adding to your library…".into()));
        let weak = Arc::downgrade(&self.shared);
        let api = self.api();
        let (key, target) = (key.to_owned(), self.shared.target.clone());
        let future = async move {
            let outcome = async {
                let api = api?;
                if result.pack {
                    let group = pack_for(&result.download, &target);
                    api.download_medias_in_background(&group).await?;
                    return Ok(SourceAction::Added);
                }
                add_request(&api, request, &target).await
            }
            .await;
            let action = outcome.unwrap_or_else(|error| SourceAction::Failed(error.to_string()));
            if let Some(shared) = weak.upgrade() {
                Sources { shared }.set_action(&key, action);
            }
        };
        let task = spawn(self.shared.copy.runtime().as_ref(), Box::pin(future));
        lock(&self.shared.state).tasks.push(task);
    }

    /// Puts a result back to Play and Add to Library (after a failure, or to leave
    /// the file choice).
    pub fn reset(&self, key: &str) {
        self.set_action(key, SourceAction::Idle);
    }

    /// Play Best: once every source answered, tries the results from best to worst
    /// until one streams, and gives its URL. A source of several files plays the
    /// episode's file or a movie's main video, or is passed over, like one only the
    /// server can read. `None` when nothing streams ([`BestRun::Nothing`]) or the run
    /// was cancelled. [`SourcesView::best_run`] follows it; the results' actions stay.
    pub async fn play_best(&self) -> Option<String> {
        let run = self.start_best(BestAction::Play);
        // The future dropped before the end (the app left): the run stops showing.
        let _unfinished = Unfinished(&self.shared, run);
        let weak = Arc::downgrade(&self.shared);
        let (ranked, count) = search_over(&weak, &self.shared.best_signal, run).await?;
        if ranked.is_empty() {
            self.shared
                .set_best(run, nothing(BestAction::Play, count, 0, None));
            return None;
        }
        let total = ranked.len();
        for (index, result) in ranked.iter().enumerate() {
            let trying = BestRun::trying(BestAction::Play, result, index, total);
            if !self.shared.set_best(run, trying) {
                return None;
            }
            let api = self.api();
            let outcome = async {
                resolve_playable(result.request.clone(), &api?, &self.shared.target).await
            }
            .await;
            // No file fits, only the server can read it, or it failed: the next one.
            if let Ok(Playable_::Play(url)) = outcome {
                // Cancelled meanwhile: a late stream opens no player.
                return self.shared.set_best(run, BestRun::Idle).then_some(url);
            }
        }
        self.shared
            .set_best(run, nothing(BestAction::Play, count, total, None));
        None
    }

    /// Add Best: once every source answered, tries the results from best to worst
    /// until the server adds one (it downloads it, or prepares it first). A source of
    /// several files adds the episode's file or a movie's main video, or is passed
    /// over. Runs in the background; [`SourcesView::best_run`] follows it, the
    /// results' actions stay.
    pub fn add_best(&self) {
        let run = self.start_best(BestAction::Add);
        let weak = Arc::downgrade(&self.shared);
        let signal = Arc::clone(&self.shared.best_signal);
        let target = self.shared.target.clone();
        let future = async move { add_best(weak, signal, run, target).await };
        let task = spawn(self.shared.copy.runtime().as_ref(), Box::pin(future));
        lock(&self.shared.state).tasks.push(task);
    }

    /// Stops Play Best or Add Best, back to [`BestRun::Idle`]. A download the server
    /// already started goes on.
    pub fn cancel_best(&self) {
        {
            let mut state = lock(&self.shared.state);
            state.best_generation += 1;
            state.view.best_run = BestRun::Idle;
        }
        self.shared.best_signal.notify_waiters();
        self.shared.tell();
    }

    /// Starts a best run, replacing one under way: its number.
    fn start_best(&self, action: BestAction) -> u64 {
        let run = {
            let mut state = lock(&self.shared.state);
            state.best_generation += 1;
            state.view.best_run = if state.view.searching {
                BestRun::Searching(action)
            } else {
                BestRun::Idle
            };
            state.best_generation
        };
        self.shared.best_signal.notify_waiters();
        self.shared.tell();
        run
    }

    fn api(&self) -> Result<LibraryApi> {
        self.shared.api()
    }

    fn result(&self, key: &str) -> Option<SourceResult> {
        lock(&self.shared.state).view.result(key).cloned()
    }

    fn request(&self, key: &str) -> Option<RsRequest> {
        self.result(key).map(|result| result.request)
    }

    fn set_action(&self, key: &str, action: SourceAction) {
        {
            let mut state = lock(&self.shared.state);
            for result in (state.view.groups.iter_mut()).flat_map(|g| g.results.iter_mut()) {
                if result.key == key {
                    result.action = action.clone();
                }
            }
        }
        self.shared.tell();
    }
}

fn not_connected() -> Error {
    Error::Network {
        message: "Connect to the server to search for sources.".to_owned(),
        path: None,
    }
}

// --- Play Best and Add Best

/// Puts run `.1` back to [`BestRun::Idle`] when dropped while it still waits or
/// tries.
struct Unfinished<'a>(&'a Shared, u64);

impl Drop for Unfinished<'_> {
    fn drop(&mut self) {
        {
            let mut state = lock(&self.0.state);
            if state.best_generation != self.1 || !state.view.best_run.is_running() {
                return;
            }
            state.view.best_run = BestRun::Idle;
        }
        self.0.tell();
    }
}

/// Waits until the search is over, then gives the results to try (ranked) and how
/// many results there are. `None` once run `run` is cancelled or replaced.
async fn search_over(
    shared: &Weak<Shared>,
    signal: &Notify,
    run: u64,
) -> Option<(Vec<SourceResult>, usize)> {
    loop {
        // Made before looking: it hears the search end even if it ends meanwhile.
        let told = signal.notified();
        {
            let shared = shared.upgrade()?;
            let state = lock(&shared.state);
            if state.best_generation != run {
                return None;
            }
            if !state.view.searching {
                let view = &state.view;
                let count = view.groups.iter().map(|g| g.results.len()).sum();
                return Some((view.ranked().into_iter().cloned().collect(), count));
            }
        }
        told.await;
    }
}

/// Why a best run found nothing: no result, none to try (packs only), or none of
/// the `tried` that streamed or was added.
fn nothing(action: BestAction, count: usize, tried: usize, last_error: Option<String>) -> BestRun {
    let message = if count == 0 {
        "No sources found.".to_owned()
    } else if tried == 0 {
        format!("None of the {count} sources can be tried.")
    } else {
        match action {
            BestAction::Play => format!(
                "None of the {tried} sources could be streamed. Add one to your library instead."
            ),
            BestAction::Add => match last_error {
                Some(error) => {
                    format!("None of the {tried} sources could be added. Last error: {error}")
                }
                None => format!("None of the {tried} sources could be added."),
            },
        }
    };
    BestRun::Nothing { action, message }
}

/// Sets the best run's state when `run` is still the current one.
fn set_best(shared: &Weak<Shared>, run: u64, best: BestRun) -> bool {
    shared.upgrade().is_some_and(|s| s.set_best(run, best))
}

fn is_current(shared: &Weak<Shared>, run: u64) -> bool {
    (shared.upgrade()).is_some_and(|s| lock(&s.state).best_generation == run)
}

/// Add Best's run (see [`Sources::add_best`]).
async fn add_best(shared: Weak<Shared>, signal: Arc<Notify>, run: u64, target: Playable) {
    let Some((ranked, count)) = search_over(&shared, &signal, run).await else {
        return;
    };
    let total = ranked.len();
    let mut last_error = None;
    for (index, result) in ranked.iter().enumerate() {
        if !set_best(
            &shared,
            run,
            BestRun::trying(BestAction::Add, result, index, total),
        ) {
            return;
        }
        // Not kept while it waits on the server: a dropped `Sources` stops the run.
        let api = shared
            .upgrade()
            .map_or_else(|| Err(not_connected()), |s| s.api());
        let step = match api {
            Ok(api) => {
                (resolve_add(&api, result.request.clone(), &target).await).map(|step| (api, step))
            }
            Err(error) => Err(error),
        };
        let (api, step) = match step {
            Ok(step) => step,
            Err(error) => {
                last_error = Some(error.to_string());
                continue;
            }
        };
        let added = match step {
            // No file fits: the next one.
            AddStep::ChooseFile(_) => continue,
            AddStep::Prepare(request) => {
                if !is_current(&shared, run) {
                    return;
                }
                prepare(&api, request, &target).await.map(|()| true)
            }
            AddStep::Save(request) => {
                if !set_best(&shared, run, BestRun::saving(result, index, total)) {
                    return;
                }
                save(&api, &request, &target).await.map(|()| false)
            }
        };
        match added {
            Ok(queued) => {
                set_best(&shared, run, BestRun::added(result, queued));
                return;
            }
            Err(error) => last_error = Some(error.to_string()),
        }
    }
    set_best(
        &shared,
        run,
        nothing(BestAction::Add, count, total, last_error),
    );
}

/// Adds a search event to the view: a new source's group, or more of a source's.
fn apply(view: &mut SourcesView, event: SseLookupSearchEvent) {
    let downloads = if event.downloads.is_empty() {
        // An older server sends each request alone.
        (event.results.into_iter())
            .map(|result| RsGroupDownload {
                requests: vec![result.request],
                match_type: result.match_type,
                ..Default::default()
            })
            .collect()
    } else {
        event.downloads
    };
    let results: Vec<SourceResult> = (downloads.into_iter())
        .filter(|download| !download.requests.is_empty())
        .map(source_result)
        .collect();
    let has_more = event.next_page_key.is_some();
    match view
        .groups
        .iter_mut()
        .find(|g| g.source_id == event.source_id)
    {
        Some(group) => {
            for result in results {
                if !group.results.iter().any(|r| r.key == result.key) {
                    group.results.push(result);
                }
            }
            group.next_page_key = event.next_page_key;
            group.has_more = has_more;
            group.loading_more = false;
        }
        None if results.is_empty() => {}
        None => view.groups.push(SourceGroup {
            name: source_label(&event.source_name),
            source_id: event.source_id,
            results,
            has_more,
            loading_more: false,
            next_page_key: event.next_page_key,
        }),
    }
    view.best = view.ranked().first().map(|result| result.key.clone());
    view.summary = summary(view);
}

fn summary(view: &SourcesView) -> String {
    let count: usize = view.groups.iter().map(|g| g.results.len()).sum();
    let sources = view.groups.len();
    match (count, view.searching) {
        (0, true) => "Searching…".to_owned(),
        (0, false) if view.error.is_some() => "The search failed.".to_owned(),
        (0, false) => "No sources found.".to_owned(),
        (count, _) => {
            let results = if count == 1 {
                "1 result".to_owned()
            } else {
                format!("{count} results")
            };
            let from = if sources == 1 {
                "1 source".to_owned()
            } else {
                format!("{sources} sources")
            };
            format!("{results} from {from}")
        }
    }
}

/// "jackett_lookup" → "Jackett Lookup".
pub fn source_label(name: &str) -> String {
    name.split(['_', '-', ' '])
        .filter(|word| !word.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn source_result(download: RsGroupDownload) -> SourceResult {
    let request = download.requests[0].clone();
    let pack = download.group && download.requests.len() > 1;
    let name = if pack {
        (download.group_filename.clone()).unwrap_or_else(|| display_name(&request))
    } else {
        display_name(&request)
    };
    let video = video_tier(&request);
    let audio = audio_tiers(&request)[0];
    let mut quality = Vec::new();
    if video != VideoTier::Unknown {
        quality.push(video.label());
    }
    if audio != AudioTier::Other {
        quality.push(audio.label());
    }
    let mut badges: Vec<String> = Vec::new();
    match video {
        VideoTier::DolbyVision4k => badges.extend(["4K".into(), "Dolby Vision".into()]),
        VideoTier::Hdr4k => badges.extend(["4K".into(), "HDR".into()]),
        VideoTier::Uhd4k => badges.push("4K".into()),
        VideoTier::Remux4k => badges.extend(["4K".into(), "Remux".into()]),
        VideoTier::Remux1080p => badges.extend(["1080p".into(), "Remux".into()]),
        VideoTier::Fhd1080p => badges.push("1080p".into()),
        VideoTier::Hd720p => badges.push("720p".into()),
        VideoTier::Sd => badges.push("SD".into()),
        VideoTier::Unknown => {}
    }
    badges.extend(audio.badge().map(str::to_owned));
    match channels(&request) {
        8 => badges.push("7.1".into()),
        6 => badges.push("5.1".into()),
        _ => {}
    }
    let mut details = Vec::new();
    if pack {
        let size: u64 = download.requests.iter().filter_map(request_size).sum();
        if size > 0 {
            details.push(text::bytes(size));
        }
        details.push(format!("{} files", download.requests.len()));
    } else {
        if let Some(size) = request_size(&request) {
            details.push(text::bytes(size));
        }
        let files = request.files.as_ref().map_or(0, Vec::len);
        if files > 1 {
            details.push(format!("{files} files"));
        }
    }
    if let Some(language) = request.language.as_deref().filter(|l| !l.is_empty()) {
        details.push(language.to_owned());
    }
    if let Some(plugin) = request.plugin_name.as_deref().filter(|p| !p.is_empty()) {
        details.push(source_label(plugin));
    }
    SourceResult {
        key: format!(
            "{}\n{}",
            request.url,
            request.selected_file.as_deref().unwrap_or_default()
        ),
        name,
        details: details.join(" · "),
        quality: quality.join(" · "),
        badges,
        instant: request.instant == Some(true),
        exact: download.match_type == Some(RsLookupMatchType::ExactId),
        pack,
        action: SourceAction::Idle,
        download,
        request,
    }
}

fn request_size(request: &RsRequest) -> Option<u64> {
    request
        .size
        .or_else(|| request.files.as_ref()?.first().map(|f| f.size))
        .filter(|size| *size > 0)
}

/// The file name to show: its name, its first file's, its title, or its URL's end.
pub fn display_name(request: &RsRequest) -> String {
    (request.filename.clone())
        .filter(|name| !name.is_empty())
        .or_else(|| Some(request.files.as_ref()?.first()?.name.clone()))
        .or_else(|| request.title.clone())
        .or_else(|| {
            (request.url.rsplit('/').next())
                .filter(|end| !end.is_empty())
                .map(str::to_owned)
        })
        .unwrap_or_else(|| "Unknown".to_owned())
}

// --- Classification

/// The name in lower case with `-`, `_` and spaces as dots, as the patterns read it.
fn normalized(request: &RsRequest) -> String {
    display_name(request)
        .to_lowercase()
        .replace(['-', '_', ' '], ".")
}

/// Whether `word` starts at the start of `name` or after a dot, and `after` accepts
/// the character that follows it (`None` at the end).
fn word(name: &str, word: &str, after: impl Fn(Option<char>) -> bool) -> bool {
    name.match_indices(word).any(|(at, _)| {
        let before_ok = at == 0 || name[..at].ends_with('.');
        before_ok && after(name[at + word.len()..].chars().next())
    })
}

fn dot_or_end(c: Option<char>) -> bool {
    matches!(c, None | Some('.'))
}

fn any(_: Option<char>) -> bool {
    true
}

fn declared_audio(request: &RsRequest) -> Vec<String> {
    let first = request.files.as_ref().and_then(|files| files.first());
    (request.audio.iter().flatten())
        .chain(first.and_then(|f| f.audio.as_ref()).into_iter().flatten())
        .map(|audio| audio.to_string().to_lowercase())
        .collect()
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum Resolution {
    Uhd,
    Fhd,
    Hd,
    Sd,
}

fn resolution(request: &RsRequest, name: &str) -> Option<Resolution> {
    let first = request.files.as_ref().and_then(|files| files.first());
    let declared = (request.resolution.as_ref())
        .or_else(|| first?.resolution.as_ref())
        .map(|r| r.to_string());
    if let Some(declared) = declared.filter(|r| r != "Unknown") {
        let lower = declared.to_lowercase();
        if lower == "4k" || lower == "uhd" || lower.contains("2160") || lower.contains("4k") {
            return Some(Resolution::Uhd);
        }
        if lower.contains("1080") || lower == "fullhd" {
            return Some(Resolution::Fhd);
        }
        if lower.contains("720") || lower == "hd" {
            return Some(Resolution::Hd);
        }
    }
    if name.contains("2160p") || word(name, "4k", dot_or_end) || word(name, "uhd", dot_or_end) {
        return Some(Resolution::Uhd);
    }
    if name.contains("1080p") || name.contains("1080i") {
        return Some(Resolution::Fhd);
    }
    if name.contains("720p") {
        return Some(Resolution::Hd);
    }
    let sd = name.contains("480p")
        || name.contains("576p")
        || word(name, "dvd", dot_or_end)
        || word(name, "dvdrip", dot_or_end)
        || word(name, "sd", dot_or_end);
    sd.then_some(Resolution::Sd)
}

fn remux(name: &str) -> bool {
    word(name, "remux", dot_or_end)
        || word(name, "bdremux", dot_or_end)
        || word(name, "bdmv", dot_or_end)
        || name.contains("complete.bluray")
        || name.contains("complete.blu.ray")
        || name.contains("complete.uhd.bluray")
        || name.contains("fulldisc")
        || name.contains("full.disc")
        || name.ends_with(".iso")
}

/// The video class of a source, from the server's metadata and its name.
pub fn video_tier(request: &RsRequest) -> VideoTier {
    let name = normalized(request);
    let remux = remux(&name);
    match resolution(request, &name) {
        Some(Resolution::Uhd) => {
            if remux {
                VideoTier::Remux4k
            } else if word(&name, "dv", dot_or_end)
                || word(&name, "dovi", dot_or_end)
                || name.contains("dolby.vision")
                || name.contains("dolbyvision")
            {
                VideoTier::DolbyVision4k
            } else if name.contains("hdr") {
                VideoTier::Hdr4k
            } else {
                VideoTier::Uhd4k
            }
        }
        Some(Resolution::Fhd) if remux => VideoTier::Remux1080p,
        Some(Resolution::Fhd) => VideoTier::Fhd1080p,
        Some(Resolution::Hd) => VideoTier::Hd720p,
        Some(Resolution::Sd) => VideoTier::Sd,
        None => VideoTier::Unknown,
    }
}

/// Every audio class of a source, best first (several tracks, or Atmos over TrueHD
/// or DD+); `[Other]` when none is known.
pub fn audio_tiers(request: &RsRequest) -> Vec<AudioTier> {
    let name = normalized(request);
    let declared = declared_audio(request);
    let says = |values: &[&str]| {
        declared
            .iter()
            .any(|a| values.iter().any(|v| a.contains(v)))
    };
    let mut tiers = Vec::new();
    if name.contains("atmos") || says(&["atmos"]) {
        tiers.push(AudioTier::Atmos);
    }
    let dtsx = word(&name, "dts.x", dot_or_end)
        || word(&name, "dtsx", dot_or_end)
        || name.contains("dts:x");
    if dtsx || says(&["dtsx", "dts:x"]) {
        tiers.push(AudioTier::DtsX);
    }
    if name.contains("truehd") || says(&["truehd"]) {
        tiers.push(AudioTier::TrueHd);
    }
    let dtshd = name.contains("dtshd")
        || name.contains("dts.hd")
        || word(&name, "dts.ma", dot_or_end)
        || word(&name, "dtsma", dot_or_end);
    if dtshd || says(&["dtshd", "dts-hd"]) {
        tiers.push(AudioTier::DtsHd);
    }
    let dts = word(&name, "dts", |c| {
        matches!(c, None | Some('.')) || c.is_some_and(|c| c.is_ascii_digit())
    });
    if dts || declared.iter().any(|a| a == "dts") {
        tiers.push(AudioTier::Dts);
    }
    let ddp = word(&name, "ddp", any)
        || word(&name, "dd+", any)
        || word(&name, "eac3", any)
        || word(&name, "e.ac3", any)
        || word(&name, "e.ac.3", any)
        || word(&name, "eac.3", any);
    if ddp || says(&["ddp", "eac3"]) {
        tiers.push(AudioTier::DolbyDigitalPlus);
    }
    let dd = word(&name, "ac3", any)
        || word(&name, "dd", |c| {
            matches!(c, None | Some('.')) || c.is_some_and(|c| c.is_ascii_digit())
        });
    if dd || says(&["ac3"]) {
        tiers.push(AudioTier::DolbyDigital);
    }
    if word(&name, "aac", any) || says(&["aac"]) {
        tiers.push(AudioTier::Aac);
    }
    if tiers.is_empty() {
        tiers.push(AudioTier::Other);
    }
    tiers
}

/// Audio channels: 8 (7.1), 6 (5.1), else 0.
fn channels(request: &RsRequest) -> u32 {
    let declared = declared_audio(request);
    let name = normalized(request);
    let layout = |layout: &str| {
        declared.iter().any(|a| a.ends_with(layout))
            || name.match_indices(layout).any(|(at, _)| {
                let before = name[..at].chars().last();
                let after = name[at + layout.len()..].chars().next();
                !before.is_some_and(|c| c.is_ascii_digit())
                    && !after.is_some_and(|c| c.is_ascii_digit())
            })
    };
    if layout("7.1") {
        8
    } else if layout("5.1") {
        6
    } else {
        0
    }
}

/// Ranks: video class, audio class, cached first, more channels, larger.
type RankKey = (
    usize,
    AudioTier,
    bool,
    std::cmp::Reverse<u32>,
    std::cmp::Reverse<u64>,
);

fn rank_key(request: &RsRequest) -> RankKey {
    (
        video_tier(request).rank(),
        audio_tiers(request)[0],
        request.instant != Some(true),
        std::cmp::Reverse(channels(request)),
        std::cmp::Reverse(request_size(request).unwrap_or(0)),
    )
}

// --- Files of a source

/// The episode a file is for: from the server, else from its name (`S01E02`, `1x02`).
fn file_episode(file: &RsRequestFiles) -> Option<(u32, u32)> {
    if let (Some(season), Some(episode)) = (file.season, file.episode) {
        return Some((season, episode));
    }
    let name = file.name.to_lowercase();
    let bytes = name.as_bytes();
    let digits = |from: usize, max: usize| -> Option<(u32, usize)> {
        let len = bytes[from..]
            .iter()
            .take_while(|b| b.is_ascii_digit())
            .count();
        if len == 0 || len > max {
            return None;
        }
        Some((name[from..from + len].parse().ok()?, from + len))
    };
    for at in 0..bytes.len() {
        let starts_word = at == 0 || !bytes[at - 1].is_ascii_alphanumeric();
        if !starts_word {
            continue;
        }
        // S01E02, S01.E02
        if bytes[at] == b's'
            && let Some((season, end)) = digits(at + 1, 2)
        {
            let mut e = end;
            if e < bytes.len() && matches!(bytes[e], b' ' | b'.' | b'_' | b'-') {
                e += 1;
            }
            if e < bytes.len()
                && bytes[e] == b'e'
                && let Some((episode, after)) = digits(e + 1, 3)
                && !bytes.get(after).is_some_and(u8::is_ascii_digit)
            {
                return Some((season, episode));
            }
        }
        // 1x02
        if let Some((season, end)) = digits(at, 2)
            && bytes.get(end) == Some(&b'x')
            && let Some((episode, after)) = digits(end + 1, 3)
            && after - (end + 1) >= 2
            && !bytes.get(after).is_some_and(u8::is_ascii_digit)
        {
            return Some((season, episode));
        }
    }
    None
}

fn is_video_file(file: &RsRequestFiles) -> bool {
    match &file.mime {
        Some(mime) => mime.starts_with("video/"),
        None => {
            let name = file.name.to_lowercase();
            [
                ".mkv", ".mp4", ".m4v", ".avi", ".mov", ".ts", ".webm", ".wmv",
            ]
            .iter()
            .any(|ext| name.ends_with(ext))
        }
    }
}

/// The files of a source, the episode's video first, then videos by size.
pub fn sort_files(files: &[RsRequestFiles], target: &Playable) -> Vec<SourceFile> {
    let episode = match target {
        Playable::Episode { season, number, .. } => Some((*season, *number)),
        Playable::Movie(_) => None,
    };
    let mut files: Vec<(usize, &RsRequestFiles, bool)> = (files.iter().enumerate())
        .map(|(ix, file)| {
            let matches = episode.is_some() && file_episode(file) == episode && is_video_file(file);
            (ix, file, matches)
        })
        .collect();
    files.sort_by_key(|(ix, file, matches)| {
        (
            !matches,
            !is_video_file(file),
            std::cmp::Reverse(file.size),
            *ix,
        )
    });
    (files.into_iter())
        .map(|(_, file, matches)| {
            let mut details = Vec::new();
            if file.size > 0 {
                details.push(text::bytes(file.size));
            }
            if let Some(resolution) = &file.resolution {
                let resolution = resolution.to_string();
                if resolution != "Unknown" {
                    details.push(resolution);
                }
            }
            SourceFile {
                name: file.name.clone(),
                details: details.join(" · "),
                matches,
            }
        })
        .collect()
}

/// The file to use without asking: the episode's video, or a movie's main video.
fn best_file(files: &[RsRequestFiles], target: &Playable) -> Option<String> {
    let sorted = sort_files(files, target);
    let first = sorted.first()?;
    match target {
        Playable::Episode { .. } => first.matches.then(|| first.name.clone()),
        Playable::Movie(_) => {
            let file = files.iter().find(|f| f.name == first.name)?;
            is_video_file(file).then(|| first.name.clone())
        }
    }
}

// --- Play and add

/// What a source needs before it plays.
enum Playable_ {
    Play(String),
    PickFile(Vec<SourceFile>),
    /// Only the server can read it.
    Add,
}

/// Processes a source until it gives a URL a player opens: public URLs as they are,
/// private ones through the server (a share URL: players cannot send the token). A
/// source with several files gets one picked, or asks.
async fn resolve_playable(
    request: RsRequest,
    api: &LibraryApi,
    target: &Playable,
) -> Result<Playable_> {
    let mut current = request;
    for pass in 0.. {
        let files = current.files.clone().unwrap_or_default();
        if current.selected_file.is_none() && files.len() == 1 {
            current.selected_file = Some(files[0].name.clone());
        }
        if current.status == RsRequestStatus::RequireAdd {
            return Ok(Playable_::Add);
        }
        if current.selected_file.is_none()
            && (files.len() > 1 || current.status == RsRequestStatus::NeedFileSelection)
        {
            if files.is_empty() {
                return Err(Error::malformed(
                    "the server asked for a file but listed none",
                    None,
                ));
            }
            match best_file(&files, target) {
                Some(file) => current.selected_file = Some(file),
                None => return Ok(Playable_::PickFile(sort_files(&files, target))),
            }
        }
        // Search results are processed once at least: the URL depends on the file.
        if pass > 0 && current.status == RsRequestStatus::FinalPublic {
            return Ok(Playable_::Play(current.url));
        }
        if pass > 0 && current.status == RsRequestStatus::FinalPrivate {
            return Ok(Playable_::Play(api.request_share_url(&current.url).await?));
        }
        if pass == 3 {
            break;
        }
        let chosen = current.selected_file.clone();
        current = api.process_request(&current).await?;
        if current.selected_file.is_none() {
            current.selected_file = chosen;
        }
    }
    Err(Error::malformed("This source can’t be played.", None))
}

/// Checks a source, processes it when needed, then has the server download it into
/// the library, or prepare it first.
async fn add_request(
    api: &LibraryApi,
    request: RsRequest,
    target: &Playable,
) -> Result<SourceAction> {
    Ok(match resolve_add(api, request, target).await? {
        AddStep::Prepare(request) => {
            prepare(api, request, target).await?;
            SourceAction::Preparing
        }
        AddStep::Save(request) => {
            save(api, &request, target).await?;
            SourceAction::Added
        }
        AddStep::ChooseFile(files) => SourceAction::ChooseFile(files),
    })
}

/// What adding a checked source takes.
enum AddStep {
    /// The server prepares it in the background first: [`prepare`].
    Prepare(RsRequest),
    /// The server downloads it into the library: [`save`].
    Save(RsRequest),
    /// No file fits: the user chooses.
    ChooseFile(Vec<SourceFile>),
}

/// Checks a source and processes it when needed, its file picked: what adding it
/// takes.
async fn resolve_add(api: &LibraryApi, request: RsRequest, target: &Playable) -> Result<AddStep> {
    let chosen = request.selected_file.clone();
    let mut resolved = if request.permanent {
        request
    } else {
        api.check_request_permanent(&request).await?
    };
    if resolved.selected_file.is_none() {
        resolved.selected_file = chosen.clone();
    }
    let needs_file = |request: &RsRequest| {
        request.selected_file.is_none()
            && (request.status == RsRequestStatus::NeedFileSelection
                || request.files.as_ref().is_some_and(|f| !f.is_empty()))
    };
    let awaits_chosen = |request: &RsRequest| {
        request.status == RsRequestStatus::NeedFileSelection && request.selected_file.is_some()
    };
    if resolved.status == RsRequestStatus::RequireAdd {
        return Ok(AddStep::Prepare(resolved));
    }
    // Processing may list the files only then: a file is picked, and processed again.
    for pass in 0..2 {
        if needs_file(&resolved) {
            let files = resolved.files.clone().unwrap_or_default();
            match best_file(&files, target) {
                Some(file) => resolved.selected_file = Some(file),
                None => return Ok(AddStep::ChooseFile(sort_files(&files, target))),
            }
        } else if pass > 0 {
            break;
        }
        if resolved.status != RsRequestStatus::Unprocessed && !awaits_chosen(&resolved) {
            break;
        }
        let chosen = resolved.selected_file.clone();
        resolved = api.process_request(&resolved).await?;
        if resolved.selected_file.is_none() {
            resolved.selected_file = chosen;
        }
        if resolved.status == RsRequestStatus::RequireAdd {
            return Ok(AddStep::Prepare(resolved));
        }
    }
    if needs_file(&resolved) || awaits_chosen(&resolved) {
        return Err(Error::malformed(
            "The server could not use the chosen file. Try another source.",
            None,
        ));
    }
    Ok(AddStep::Save(resolved))
}

/// Has the server download a checked source into the library, joined to `target`.
async fn save(api: &LibraryApi, request: &RsRequest, target: &Playable) -> Result<()> {
    let _: Media = match target {
        Playable::Movie(movie) => api.add_searched_movie_media(movie, request).await?,
        Playable::Episode {
            serie,
            season,
            number,
        } => {
            api.add_searched_episode_media(serie, *season, *number, request)
                .await?
        }
    };
    Ok(())
}

/// Has a plugin prepare a request in the background. Once ready, the server downloads
/// it into the library and links it to the title the request names (`target`).
async fn prepare(api: &LibraryApi, mut request: RsRequest, target: &Playable) -> Result<()> {
    link_to(&mut request, target);
    api.add_request(&request, None).await?;
    Ok(())
}

/// Names the title a request's file joins once the server downloads it: a movie, or
/// an episode (its series as the album, with its season and number).
fn link_to(request: &mut RsRequest, target: &Playable) {
    match target {
        Playable::Movie(movie) => request.movie = Some(movie.clone()),
        Playable::Episode {
            serie,
            season,
            number,
        } => {
            request.season = Some(*season);
            request.episode = Some(*number);
            let albums = request.albums.get_or_insert_with(Vec::new);
            albums.retain(|album| album != serie);
            // First: the series the server links it to.
            albums.insert(0, serie.clone());
        }
    }
}

/// A pack added to a movie or an episode: every file linked to it.
fn pack_for(download: &RsGroupDownload, target: &Playable) -> RsGroupDownload {
    let mut group = download.clone();
    let mut infos = group.infos.take().unwrap_or_default();
    match target {
        Playable::Movie(movie) => infos.movie = Some(movie.clone()),
        Playable::Episode {
            serie,
            season,
            number,
        } => {
            let series = infos.add_series.get_or_insert_with(Vec::new);
            let linked = series.iter().any(|item| {
                &item.id == serie && item.season == Some(*season) && item.episode == Some(*number)
            });
            if !linked {
                series.push(FileEpisode {
                    id: serie.clone(),
                    season: Some(*season),
                    episode: Some(*number),
                    episode_to: None,
                });
            }
        }
    }
    for request in &mut group.requests {
        link_to(request, target);
    }
    group.infos = Some(infos);
    group
}