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
mod app;
mod ui;
pub use app::{
App, DiscoveryItem, DiscoveryRow, DownloadProgress, SettingsSection, SortOrder, StreamingState,
TmdbMetadata, TmdbSuggestion, View, WizardStep,
};
use std::io;
use std::time::Duration;
use chrono::Datelike;
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyModifiers},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{Terminal, backend::CrosstermBackend};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info};
use crate::config::Config;
use crate::doctor::{self, CheckResult};
use crate::extensions::{ExtensionManager, MediaInfo, PlaybackEvent, parse_episode_info};
use crate::history::WatchHistory;
use crate::opensubtitles::OpenSubtitlesClient;
use crate::providers::{ContentProvider, DiscoveryItem as ProviderDiscoveryItem, TraktProvider};
use crate::prowlarr::ProwlarrClient;
use crate::scrobblers::ScrobblerManager;
use crate::streaming::{self, StreamingSession, TorrentValidation, VideoFile, sort_episodes};
use crate::tmdb::{TmdbClient, parse_torrent_title};
use crate::torznab::{TorrentResult, TorznabClient};
/// Messages sent from background tasks to the UI
pub enum UiMessage {
SearchComplete {
results: Vec<TorrentResult>,
search_id: u64,
},
SearchError(String),
TmdbInfo(TmdbMetadata),
Suggestions(Vec<TmdbSuggestion>),
/// TV show details with seasons
TvDetailsLoaded(crate::tmdb::TvDetails),
/// Season episodes loaded
SeasonEpisodesLoaded(Vec<crate::tmdb::Episode>),
/// Torrent metadata received - may have multiple video files
TorrentMetadata {
torrent_info: crate::streaming::TorrentInfo,
session: std::sync::Arc<StreamingSession>,
},
/// Racing torrents - show status
RacingStatus {
count: usize,
message: String,
},
StreamReady {
file_name: String,
stream_url: String,
},
StreamError(String),
ProgressUpdate(DownloadProgress),
/// Playback position update from mpv (percent watched)
PlaybackProgress(f64),
PlayerExited,
DoctorComplete(Vec<CheckResult>),
/// Discovery data loaded
DiscoveryLoaded {
rows: Vec<DiscoveryRow>,
},
/// Discovery loading failed
DiscoveryError(String),
/// Trakt auth URL ready (Authorization Code flow)
TraktAuthReady {
auth_url: String,
},
/// Trakt auth completed successfully
TraktAuthComplete {
access_token: String,
refresh_token: String,
expires_in: u64,
},
/// Trakt auth error
TraktAuthError(String),
/// Subtitle not found warning
SubtitleWarning,
}
fn restore_terminal() {
let _ = disable_raw_mode();
let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture);
}
// Discovery row limits
const WATCHLIST_ITEM_COUNT: usize = 20;
const CALENDAR_DAYS: u32 = 7;
const RECOMMENDATIONS_ITEM_COUNT: usize = 20;
const TRENDING_ITEM_COUNT: usize = 10;
fn load_discovery_data(tx: &mpsc::Sender<UiMessage>, config: &Config) {
let tx = tx.clone();
let providers_config = config.providers.clone();
tokio::spawn(async move {
let mut rows = Vec::new();
// Check which provider to use for discovery
let provider_name = providers_config.discovery.as_deref();
match provider_name {
Some("trakt") | None => {
// Use Trakt as the discovery provider (default if no provider specified but trakt is configured)
let trakt_config = &providers_config.trakt;
// Check if we have Trakt credentials (user-provided or embedded)
let Some(client_id) = trakt_config.get_client_id().map(String::from) else {
if provider_name.is_some() {
// Only show error if Trakt was explicitly configured
let _ = tx
.send(UiMessage::DiscoveryError(
"Trakt not configured. Go to Settings → Trakt to authenticate."
.to_string(),
))
.await;
}
return;
};
if trakt_config.is_authenticated() && !trakt_config.is_token_expired() {
// Authenticated: fetch personalized content
let provider = TraktProvider::authenticated(
client_id,
trakt_config.access_token.clone().unwrap_or_default(),
);
// Fetch all data in parallel
let (watchlist_res, calendar_res, recommendations_res) = tokio::join!(
provider.watchlist(),
provider.calendar(CALENDAR_DAYS),
provider.recommendations()
);
// Row 1: Watchlist
match watchlist_res {
Ok(watchlist) => {
let items: Vec<DiscoveryItem> = watchlist
.into_iter()
.take(WATCHLIST_ITEM_COUNT)
.map(DiscoveryItem::from)
.collect();
if !items.is_empty() {
rows.push(DiscoveryRow {
title: "My Watchlist".to_string(),
items,
});
}
}
Err(e) => {
tracing::warn!(error = %e, "failed to load watchlist");
}
}
// Row 2: Up Next (calendar)
match calendar_res {
Ok(calendar) => {
let items: Vec<DiscoveryItem> =
calendar.into_iter().map(DiscoveryItem::from).collect();
if !items.is_empty() {
rows.push(DiscoveryRow {
title: "Up Next".to_string(),
items,
});
}
}
Err(e) => {
tracing::warn!(error = %e, "failed to load calendar");
}
}
// Row 3: Recommendations
match recommendations_res {
Ok(recommendations) => {
let items: Vec<DiscoveryItem> = recommendations
.into_iter()
.take(RECOMMENDATIONS_ITEM_COUNT)
.map(DiscoveryItem::from)
.collect();
if !items.is_empty() {
rows.push(DiscoveryRow {
title: "Recommended".to_string(),
items,
});
}
}
Err(e) => {
tracing::warn!(error = %e, "failed to load recommendations");
}
}
} else {
// Not authenticated: fetch public trending content
let provider = TraktProvider::new(client_id);
let (trending_shows_res, trending_movies_res) = tokio::join!(
provider.trending_shows(TRENDING_ITEM_COUNT),
provider.trending_movies(TRENDING_ITEM_COUNT)
);
let mut trending_items: Vec<DiscoveryItem> = Vec::new();
if let Ok(shows) = trending_shows_res {
trending_items.extend(shows.into_iter().map(DiscoveryItem::from));
}
if let Ok(movies) = trending_movies_res {
trending_items.extend(movies.into_iter().map(DiscoveryItem::from));
}
if !trending_items.is_empty() {
rows.push(DiscoveryRow {
title: "Trending".to_string(),
items: trending_items,
});
}
// Add a hint row about authentication
rows.push(DiscoveryRow {
title: "Connect Trakt for personalized content".to_string(),
items: vec![],
});
}
}
// Future: Some("simkl") => { ... }
Some(other) => {
let _ = tx
.send(UiMessage::DiscoveryError(format!(
"Unknown discovery provider: {}",
other
)))
.await;
return;
}
}
if rows.is_empty() {
let _ = tx
.send(UiMessage::DiscoveryError(
"Failed to load discovery data".to_string(),
))
.await;
} else {
let _ = tx.send(UiMessage::DiscoveryLoaded { rows }).await;
}
});
}
/// Start Trakt device authentication flow
/// Generate Trakt auth URL and optionally open in browser
fn start_trakt_auth(client_id: &str) -> String {
let provider = TraktProvider::new(client_id.to_string());
let auth_url = provider.get_authorize_url();
// Try to open in browser
let _ = open::that(&auth_url);
auth_url
}
/// Exchange authorization code for tokens
fn exchange_trakt_code(
tx: &mpsc::Sender<UiMessage>,
client_id: String,
client_secret: String,
code: String,
) {
let tx = tx.clone();
tokio::spawn(async move {
let provider = TraktProvider::new(client_id);
match provider.exchange_code(&code, &client_secret).await {
Ok(token) => {
let _ = tx
.send(UiMessage::TraktAuthComplete {
access_token: token.access_token,
refresh_token: token.refresh_token,
expires_in: token.expires_in,
})
.await;
}
Err(e) => {
let _ = tx
.send(UiMessage::TraktAuthError(format!(
"Failed to exchange code: {}",
e
)))
.await;
}
}
});
}
/// Spawn a background task to search for torrents across all indexers
fn spawn_torrent_search(
search_query: String,
search_id: u64,
tx: mpsc::Sender<UiMessage>,
prowlarr_url: String,
prowlarr_apikey: String,
cancel_token: CancellationToken,
) {
use futures::stream::{self, StreamExt};
const VIDEO_CATEGORIES: &[u32] = &[2000, 5000];
const MAX_CONCURRENT_SEARCHES: usize = 5; // Limit concurrent searches to avoid overwhelming the system
tokio::spawn(async move {
let prowlarr_config = crate::config::ProwlarrConfig {
url: prowlarr_url,
apikey: prowlarr_apikey,
};
let prowlarr = ProwlarrClient::new(&prowlarr_config);
let torznab = TorznabClient::new();
match prowlarr.get_usable_indexers().await {
Ok(indexers) => {
// Check if cancelled before proceeding
if cancel_token.is_cancelled() {
debug!(search_id, "search cancelled before indexer queries");
return;
}
if indexers.is_empty() {
let _ = tx
.send(UiMessage::SearchError(
"No indexers configured in Prowlarr".to_string(),
))
.await;
return;
}
// Run searches in parallel with limited concurrency
let search_futures = indexers.into_iter().map(|indexer| {
let prowlarr_url = prowlarr_config.url.clone();
let prowlarr_apikey = prowlarr_config.apikey.clone();
let search_query = search_query.clone();
let indexer_name = indexer.name.clone();
let indexer_id = indexer.id;
async move {
let torznab = TorznabClient::new();
let result = torznab
.search(
&prowlarr_url,
&prowlarr_apikey,
indexer_id,
&indexer_name,
&search_query,
Some(VIDEO_CATEGORIES),
)
.await;
(indexer_name, result)
}
});
// Collect results as they complete
let mut all_results = Vec::new();
let mut last_error: Option<String> = None;
let mut results_stream =
stream::iter(search_futures).buffer_unordered(MAX_CONCURRENT_SEARCHES);
while let Some((indexer_name, result)) = results_stream.next().await {
// Check for cancellation while collecting results
if cancel_token.is_cancelled() {
debug!(search_id, "search cancelled while collecting results");
return;
}
match result {
Ok(results) => {
debug!(
indexer = indexer_name,
count = results.len(),
"indexer search completed"
);
all_results.extend(results);
}
Err(e) => {
error!(
indexer = indexer_name,
error = %e,
"indexer search failed"
);
last_error = Some(format!("{}: {}", indexer_name, e));
}
}
}
if all_results.is_empty() {
let error_msg = last_error.unwrap_or_else(|| "No results found".to_string());
let _ = tx.send(UiMessage::SearchError(error_msg)).await;
} else {
let _ = tx
.send(UiMessage::SearchComplete {
results: all_results,
search_id,
})
.await;
}
}
Err(e) => {
let _ = tx
.send(UiMessage::SearchError(format!("Prowlarr error: {}", e)))
.await;
}
}
});
}
/// Spawn a background task to fetch TV show details
fn spawn_tv_details_fetch(tv_id: u64, tx: mpsc::Sender<UiMessage>, tmdb_apikey: Option<String>) {
tokio::spawn(async move {
if let Some(client) = TmdbClient::new(tmdb_apikey.as_deref())
&& let Ok(details) = client.get_tv_details(tv_id).await
{
let _ = tx.send(UiMessage::TvDetailsLoaded(details)).await;
}
});
}
pub async fn run(
config: Config,
ext_manager: ExtensionManager,
scrobbler_manager: ScrobblerManager,
open_settings: bool,
) -> io::Result<()> {
// Set up panic hook to restore terminal
let original_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
restore_terminal();
original_hook(panic_info);
}));
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Create app and channels
let mut app = App::new();
// Open wizard if this is a new config (needs setup)
if open_settings {
app.view = View::Wizard;
}
let (tx, mut rx) = mpsc::channel::<UiMessage>(32);
// Main loop - config is mutable for settings editing
let mut config = config;
let result = run_app(
&mut terminal,
&mut app,
&mut config,
&ext_manager,
&scrobbler_manager,
tx,
&mut rx,
)
.await;
// Shutdown extensions and scrobblers
ext_manager.shutdown();
scrobbler_manager.shutdown();
// Restore terminal
disable_raw_mode()?;
execute!(
terminal.backend_mut(),
LeaveAlternateScreen,
DisableMouseCapture
)?;
terminal.show_cursor()?;
result
}
async fn run_app(
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
app: &mut App,
config: &mut Config,
ext_manager: &ExtensionManager,
scrobbler_manager: &ScrobblerManager,
tx: mpsc::Sender<UiMessage>,
rx: &mut mpsc::Receiver<UiMessage>,
) -> io::Result<()> {
let _prowlarr = ProwlarrClient::new(&config.prowlarr);
let _torznab = TorznabClient::new();
// Video categories: Movies & TV
const VIDEO_CATEGORIES: &[u32] = &[2000, 5000];
// Watch history for resume functionality
let mut watch_history = WatchHistory::load();
// Clean up entries older than 30 days
watch_history.cleanup_old(30);
// Streaming session (created when needed)
let mut streaming_session: Option<std::sync::Arc<StreamingSession>> = None;
// Cancellation token for streaming task
let mut streaming_cancel: Option<CancellationToken> = None;
// Cancellation token for search task
let mut search_cancel: Option<CancellationToken> = None;
// Stored torrent info for file selection
let mut pending_torrent_info: Option<crate::streaming::TorrentInfo> = None;
// Load discovery data on startup (if not in wizard mode)
if app.view == View::Discovery {
app.is_loading_discovery = true;
load_discovery_data(&tx, config);
}
loop {
// Draw UI
terminal.draw(|f| ui::draw(f, app, Some(config)))?;
// Handle messages from background tasks
while let Ok(msg) = rx.try_recv() {
match msg {
UiMessage::SearchComplete { results, search_id } => {
// Ignore results from stale searches
if search_id != app.search_id {
debug!(
search_id,
current = app.search_id,
"ignoring stale search results"
);
continue;
}
app.is_searching = false;
app.results = results;
app.sort_results(); // Apply current sort order
app.selected_index = 0;
if app.results.is_empty() {
app.search_error = Some("No results found".to_string());
} else {
app.search_error = None;
// Check if auto-race is enabled
let auto_race = config.streaming.auto_race as usize;
if auto_race > 0 && !app.is_streaming {
// Copy TMDB metadata to current_* fields (same as when manually selecting from Results)
app.current_title = app
.tmdb_info
.as_ref()
.map(|t| t.title.clone())
.unwrap_or_else(|| app.search_input.clone());
app.current_tmdb_id = app.tmdb_info.as_ref().and_then(|t| t.id);
app.current_year = app.tmdb_info.as_ref().and_then(|t| t.year);
app.current_media_type =
app.tmdb_info.as_ref().and_then(|t| t.media_type.clone());
app.current_poster_url =
app.tmdb_info.as_ref().and_then(|t| t.poster_url.clone());
info!(
title = %app.current_title,
tmdb_id = ?app.current_tmdb_id,
year = ?app.current_year,
media_type = ?app.current_media_type,
"auto-race: set metadata from TMDB"
);
// Clean up any previous streaming session
if let Some(cancel) = streaming_cancel.take() {
cancel.cancel();
}
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
// Get ALL torrent URLs - we'll race through them until we find a match
let urls: Vec<String> = app
.results
.iter()
.filter_map(|r| r.get_torrent_url())
.collect();
if !urls.is_empty() {
// Clear previous streaming state
app.current_file.clear();
app.current_title.clear();
app.available_files.clear();
app.download_progress = DownloadProgress::default();
pending_torrent_info = None;
app.is_streaming = true;
app.racing_message = Some(format!(
"Racing {} torrents...",
urls.len().min(auto_race)
));
app.view = View::Streaming;
app.streaming_state = StreamingState::Connecting;
let tx = tx.clone();
let temp_dir = config.storage.temp_dir();
let cancel_token = CancellationToken::new();
streaming_cancel = Some(cancel_token.clone());
// Build validation criteria from search query and TMDB info
let mut title_keywords =
TorrentValidation::extract_keywords(&app.search_input);
let mut year: Option<u16> = None;
// Add TMDB title keywords and year if available
if let Some(ref tmdb) = app.tmdb_info {
title_keywords
.extend(TorrentValidation::extract_keywords(&tmdb.title));
year = tmdb.year;
}
// Deduplicate keywords
title_keywords.sort();
title_keywords.dedup();
let validation = if title_keywords.is_empty() && year.is_none() {
None
} else {
Some(TorrentValidation::new(title_keywords.clone(), year))
};
info!(keywords = ?title_keywords, year = ?year, "validation criteria");
let concurrent = auto_race;
tokio::spawn(async move {
let _ = tx
.send(UiMessage::RacingStatus {
count: concurrent.min(urls.len()),
message: "connecting...".to_string(),
})
.await;
let session = match StreamingSession::new(temp_dir).await {
Ok(s) => std::sync::Arc::new(s),
Err(e) => {
let _ = tx
.send(UiMessage::StreamError(e.to_string()))
.await;
return;
}
};
if cancel_token.is_cancelled() {
session.cleanup().await;
return;
}
match session
.race_torrents(
urls,
validation,
concurrent,
cancel_token.clone(),
)
.await
{
Ok((_winner_idx, torrent_info)) => {
let _ = tx
.send(UiMessage::TorrentMetadata {
torrent_info,
session,
})
.await;
}
Err(e) => {
// Don't report error if cancelled
if !cancel_token.is_cancelled() {
let _ = tx
.send(UiMessage::StreamError(e.to_string()))
.await;
}
session.cleanup().await;
}
}
});
} else {
app.view = View::Results;
}
} else {
app.view = View::Results;
}
}
}
UiMessage::SearchError(e) => {
app.is_searching = false;
app.search_error = Some(e);
}
UiMessage::TmdbInfo(info) => {
app.tmdb_info = Some(info);
}
UiMessage::Suggestions(suggestions) => {
app.suggestions = suggestions;
app.selected_suggestion = 0;
app.is_fetching_suggestions = false;
}
UiMessage::TvDetailsLoaded(details) => {
// Filter out season 0 (specials) for cleaner UI
app.tv_seasons = details
.seasons
.iter()
.filter(|s| s.season_number > 0)
.cloned()
.collect();
app.tv_details = Some(details);
app.selected_season_index = 0;
app.is_fetching_tv_details = false;
app.view = View::TvSeasons;
}
UiMessage::SeasonEpisodesLoaded(episodes) => {
app.tv_episodes = episodes;
app.selected_episode_index = 0;
app.is_fetching_tv_details = false;
app.view = View::TvEpisodes;
}
UiMessage::DoctorComplete(results) => {
app.doctor_results = results;
app.is_checking = false;
}
UiMessage::DiscoveryLoaded { rows } => {
app.discovery_rows = rows;
app.selected_row_index = 0;
app.selected_item_index = 0;
app.is_loading_discovery = false;
app.discovery_error = None;
}
UiMessage::DiscoveryError(e) => {
app.is_loading_discovery = false;
app.discovery_error = Some(e);
}
UiMessage::TraktAuthReady { auth_url } => {
app.trakt_auth_url = Some(auth_url);
app.trakt_auth_code_input = String::new();
app.trakt_auth_error = None;
}
UiMessage::TraktAuthComplete {
access_token,
refresh_token,
expires_in,
} => {
// Save tokens to config
config.providers.trakt.access_token = Some(access_token);
config.providers.trakt.refresh_token = Some(refresh_token);
// Enable both discovery and scrobbling on successful auth
config.providers.discovery = Some("trakt".to_string());
if !config.scrobblers.enabled.contains(&"trakt".to_string()) {
config.scrobblers.enabled.push("trakt".to_string());
}
// Calculate expiry timestamp
let expires_at = Some(::chrono::Utc::now().timestamp() + expires_in as i64);
config.providers.trakt.expires_at = expires_at;
// Save config
if let Err(e) = config.save() {
error!("Failed to save Trakt config: {}", e);
} else {
info!("Trakt authentication saved");
}
// Clear auth state and go back to discovery
app.trakt_auth_url = None;
app.trakt_auth_code_input = String::new();
app.trakt_auth_error = None;
app.view = View::Discovery;
// Reload discovery with Trakt data
app.is_loading_discovery = true;
load_discovery_data(&tx, config);
}
UiMessage::TraktAuthError(e) => {
app.trakt_auth_error = Some(e);
}
UiMessage::RacingStatus { count, message } => {
app.racing_message = Some(format!("Racing {} torrents: {}", count, message));
}
UiMessage::TorrentMetadata {
torrent_info,
session,
} => {
app.racing_message = None; // Clear racing message
app.pending_torrent_id = Some(torrent_info.id);
streaming_session = Some(session.clone());
pending_torrent_info = Some(torrent_info.clone());
if torrent_info.video_files.len() > 1 {
// Multiple files - show selection UI
info!(
files = torrent_info.video_files.len(),
"multiple video files, showing selection"
);
// Sort by episode number for season packs
let mut sorted_files = torrent_info.video_files.clone();
sort_episodes(&mut sorted_files);
app.available_files = sorted_files;
app.selected_file_index = 0;
app.current_episode_index = 0;
app.next_episode_ready = false;
app.view = View::FileSelection;
app.streaming_state = StreamingState::FetchingMetadata;
} else if let Some(file) = torrent_info.video_files.first().cloned() {
// Single file - proceed directly to streaming
info!(file = %file.name, "single video file, starting stream");
app.current_file = file.name.clone();
app.streaming_state = StreamingState::Ready {
stream_url: file.stream_url.clone(),
};
app.view = View::Streaming;
// Notify extensions and scrobblers
let (season, episode) = parse_episode_info(&file.name);
let media_info = MediaInfo {
title: app.current_title.clone(),
file_name: file.name.clone(),
total_bytes: file.size,
tmdb_id: app.current_tmdb_id,
year: app.current_year.map(|y| y as u32),
media_type: app.current_media_type.clone(),
poster_url: app.current_poster_url.clone(),
season,
episode,
};
ext_manager.broadcast(PlaybackEvent::Started(media_info.clone()));
scrobbler_manager.on_start(&media_info);
// Launch player task for single file
let tx = tx.clone();
let player_command = config.player.command.clone();
let player_args = config.player.args.clone();
let subtitles_enabled = config.subtitles.enabled;
let preferred_language = config.subtitles.language.clone();
let opensubtitles_key = config.subtitles.opensubtitles_api_key.clone();
let tmdb_id = app.current_tmdb_id;
let subtitle_files = torrent_info.subtitle_files.clone();
let stream_url = file.stream_url.clone();
let torrent_id = torrent_info.id;
let cancel_token = streaming_cancel.clone().unwrap_or_default();
tokio::spawn(async move {
// Spawn progress polling task
let progress_tx = tx.clone();
let progress_session = session.clone();
let progress_handle = tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(500)).await;
if let Some(stats) =
progress_session.get_stats(torrent_id).await
{
let progress = DownloadProgress {
downloaded_bytes: stats.downloaded_bytes,
total_bytes: stats.total_bytes,
download_speed: stats.download_speed,
upload_speed: stats.upload_speed,
peers_connected: stats.peers_connected,
progress_percent: if stats.total_bytes > 0 {
(stats.downloaded_bytes as f64
/ stats.total_bytes as f64)
* 100.0
} else {
0.0
},
};
if progress_tx
.send(UiMessage::ProgressUpdate(progress))
.await
.is_err()
{
break;
}
}
}
});
// Find best subtitle
let subtitle_url = if subtitles_enabled {
let from_torrent = subtitle_files
.iter()
.find(|s| {
s.language
.as_ref()
.map(|l| l == &preferred_language)
.unwrap_or(false)
})
.or_else(|| subtitle_files.first())
.map(|s| s.stream_url.clone());
if from_torrent.is_some() {
from_torrent
} else if let (Some(api_key), Some(tmdb)) =
(&opensubtitles_key, tmdb_id)
{
info!("no subtitles in torrent, trying OpenSubtitles");
let os_client = OpenSubtitlesClient::new(api_key);
match os_client.search_by_tmdb(tmdb, &preferred_language).await
{
Ok(subs) => subs.first().map(|s| s.download_url.clone()),
Err(e) => {
debug!(error = %e, "OpenSubtitles search failed");
None
}
}
} else {
None
}
} else {
None
};
if cancel_token.is_cancelled() {
progress_handle.abort();
session.cleanup().await;
let _ = tx.send(UiMessage::PlayerExited).await;
return;
}
// Warn user if subtitles are enabled but none were found
if subtitles_enabled && subtitle_url.is_none() {
info!("subtitles enabled but none found, showing warning");
let _ = tx.send(UiMessage::SubtitleWarning).await;
}
info!(player = %player_command, "launching player");
match streaming::launch_player(
&player_command,
&player_args,
&stream_url,
subtitle_url.as_deref(),
)
.await
{
Ok(mut handle) => {
// Spawn position polling task if we have IPC
let position_handle = if let Some(ref socket_path) =
handle.ipc_socket
{
let socket = socket_path.clone();
let tx_pos = tx.clone();
Some(tokio::spawn(async move {
// Wait a bit for mpv to start
tokio::time::sleep(Duration::from_secs(2)).await;
loop {
if let Some((pos, dur)) =
streaming::get_mpv_position(&socket).await
{
let progress =
streaming::calculate_progress(pos, dur);
let _ = tx_pos
.send(UiMessage::PlaybackProgress(progress))
.await;
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
}))
} else {
None
};
// Wait for either player to exit OR cancellation
tokio::select! {
_ = handle.child.wait() => {
info!("player exited normally");
}
_ = cancel_token.cancelled() => {
info!("cancellation requested, killing player");
let _ = handle.child.kill().await;
}
}
// Stop position polling
if let Some(h) = position_handle {
h.abort();
}
// Clean up IPC socket
if let Some(socket_path) = handle.ipc_socket {
let _ = std::fs::remove_file(socket_path);
}
}
Err(e) => {
error!(error = %e, "failed to launch player");
let _ = tx.send(UiMessage::StreamError(e.to_string())).await;
progress_handle.abort();
return;
}
}
progress_handle.abort();
session.cleanup().await;
let _ = tx.send(UiMessage::PlayerExited).await;
});
}
}
UiMessage::StreamReady {
file_name,
stream_url,
} => {
app.current_file = file_name.clone();
app.streaming_state = StreamingState::Ready { stream_url };
app.playback_progress = 0.0; // Reset for new playback
// Check if there's a resume point for this content
let history_key = WatchHistory::make_key(app.current_tmdb_id, &file_name);
if let Some(progress) = watch_history.has_resume_point(&history_key) {
app.show_resume_prompt = true;
app.resume_progress = progress;
}
// Notify extensions and scrobblers
let (season, episode) = parse_episode_info(&file_name);
let media_info = MediaInfo {
title: app.current_title.clone(),
file_name,
total_bytes: app.download_progress.total_bytes,
tmdb_id: app.current_tmdb_id,
year: app.current_year.map(|y| y as u32),
media_type: app.current_media_type.clone(),
poster_url: app.current_poster_url.clone(),
season,
episode,
};
ext_manager.broadcast(PlaybackEvent::Started(media_info.clone()));
scrobbler_manager.on_start(&media_info);
}
UiMessage::StreamError(e) => {
app.streaming_state = StreamingState::Error(e);
app.is_streaming = false;
}
UiMessage::ProgressUpdate(progress) => {
app.download_progress = progress;
}
UiMessage::PlaybackProgress(percent) => {
app.playback_progress = percent;
debug!(progress = percent, "playback position update");
}
UiMessage::PlayerExited => {
// Use playback progress from mpv if available, otherwise fall back to download progress
let watched_percent = if app.playback_progress > 0.0 {
app.playback_progress
} else {
app.download_progress.progress_percent
};
let (season, episode) = parse_episode_info(&app.current_file);
let media_info = MediaInfo {
title: app.current_title.clone(),
file_name: app.current_file.clone(),
total_bytes: app.download_progress.total_bytes,
tmdb_id: app.current_tmdb_id,
year: app.current_year.map(|y| y as u32),
media_type: app.current_media_type.clone(),
poster_url: app.current_poster_url.clone(),
season,
episode,
};
ext_manager.broadcast(PlaybackEvent::Stopped {
media: media_info.clone(),
watched_percent,
});
scrobbler_manager.on_stop(&media_info, watched_percent);
// Save watch progress to history
let history_key =
WatchHistory::make_key(app.current_tmdb_id, &app.current_file);
watch_history.update(history_key, app.current_title.clone(), watched_percent);
watch_history.save();
// Check if we should auto-play next episode
let has_next = app.has_next_episode();
let should_auto_play =
app.auto_play_next && has_next && app.available_files.len() > 1;
if should_auto_play {
// Advance to next episode
if let Some(next_file) = app.advance_to_next_episode().cloned() {
info!(file = %next_file.name, "auto-playing next episode");
app.current_file = next_file.name.clone();
app.streaming_state = StreamingState::Ready {
stream_url: next_file.stream_url.clone(),
};
// Notify extensions and scrobblers about new episode
let (season, episode) = parse_episode_info(&next_file.name);
let media_info = MediaInfo {
title: app.current_title.clone(),
file_name: next_file.name.clone(),
total_bytes: next_file.size,
tmdb_id: app.current_tmdb_id,
year: app.current_year.map(|y| y as u32),
media_type: app.current_media_type.clone(),
poster_url: app.current_poster_url.clone(),
season,
episode,
};
ext_manager.broadcast(PlaybackEvent::Started(media_info.clone()));
scrobbler_manager.on_start(&media_info);
// Pre-download the episode after this one
if let (Some(after_next), Some(session), Some(torrent_info)) = (
app.next_episode(),
streaming_session.as_ref(),
pending_torrent_info.as_ref(),
) {
let after_next_idx = after_next.file_idx;
let session_clone = session.clone();
let torrent_id = torrent_info.id;
info!(next_file = %after_next.name, "pre-downloading next episode");
tokio::spawn(async move {
let _ = session_clone
.prioritize_file(torrent_id, after_next_idx)
.await;
});
}
// Launch player for next episode
if let (Some(session), Some(torrent_info)) =
(streaming_session.clone(), pending_torrent_info.as_ref())
{
let tx = tx.clone();
let player_command = config.player.command.clone();
let player_args = config.player.args.clone();
let subtitles_enabled = config.subtitles.enabled;
let preferred_language = config.subtitles.language.clone();
let opensubtitles_key =
config.subtitles.opensubtitles_api_key.clone();
let tmdb_id = app.current_tmdb_id;
let subtitle_files = torrent_info.subtitle_files.clone();
let stream_url = next_file.stream_url.clone();
let torrent_id = torrent_info.id;
let cancel_token = streaming_cancel.clone().unwrap_or_default();
tokio::spawn(async move {
// Progress polling
let progress_tx = tx.clone();
let progress_session = session.clone();
let progress_handle = tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(500)).await;
if let Some(stats) =
progress_session.get_stats(torrent_id).await
{
let progress = DownloadProgress {
downloaded_bytes: stats.downloaded_bytes,
total_bytes: stats.total_bytes,
download_speed: stats.download_speed,
upload_speed: stats.upload_speed,
peers_connected: stats.peers_connected,
progress_percent: if stats.total_bytes > 0 {
(stats.downloaded_bytes as f64
/ stats.total_bytes as f64)
* 100.0
} else {
0.0
},
};
if progress_tx
.send(UiMessage::ProgressUpdate(progress))
.await
.is_err()
{
break;
}
}
}
});
// Find subtitle
let subtitle_url = if subtitles_enabled {
let from_torrent = subtitle_files
.iter()
.find(|s| {
s.language.as_deref() == Some(&preferred_language)
})
.or_else(|| subtitle_files.first())
.map(|s| s.stream_url.clone());
if from_torrent.is_some() {
from_torrent
} else if let (Some(api_key), Some(tmdb)) =
(&opensubtitles_key, tmdb_id)
{
info!(
"no subtitles in torrent for next episode, trying OpenSubtitles"
);
let os_client = OpenSubtitlesClient::new(api_key);
match os_client
.search_by_tmdb(tmdb, &preferred_language)
.await
{
Ok(subs) => {
subs.first().map(|s| s.download_url.clone())
}
Err(e) => {
debug!(error = %e, "OpenSubtitles search failed for next episode");
None
}
}
} else {
None
}
} else {
None
};
// Warn user if subtitles are enabled but none were found
if subtitles_enabled && subtitle_url.is_none() {
info!(
"subtitles enabled but none found for next episode, showing warning"
);
let _ = tx.send(UiMessage::SubtitleWarning).await;
}
// Launch player
match streaming::launch_player(
&player_command,
&player_args,
&stream_url,
subtitle_url.as_deref(),
)
.await
{
Ok(mut handle) => {
// Spawn position polling task if we have IPC
let position_handle = if let Some(ref socket_path) =
handle.ipc_socket
{
let socket = socket_path.clone();
let tx_pos = tx.clone();
Some(tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(2))
.await;
loop {
if let Some((pos, dur)) =
streaming::get_mpv_position(&socket)
.await
{
let progress =
streaming::calculate_progress(
pos, dur,
);
let _ = tx_pos
.send(UiMessage::PlaybackProgress(
progress,
))
.await;
}
tokio::time::sleep(Duration::from_secs(5))
.await;
}
}))
} else {
None
};
tokio::select! {
_ = handle.child.wait() => {
info!("player exited normally");
}
_ = cancel_token.cancelled() => {
info!("cancellation requested, killing player");
let _ = handle.child.kill().await;
}
}
if let Some(h) = position_handle {
h.abort();
}
if let Some(socket_path) = handle.ipc_socket {
let _ = std::fs::remove_file(socket_path);
}
}
Err(e) => {
error!(error = %e, "failed to launch player");
}
}
progress_handle.abort();
let _ = tx.send(UiMessage::PlayerExited).await;
});
}
}
} else if has_next && app.available_files.len() > 1 {
// Has next but auto-play disabled - go back to file selection
info!("playback ended, returning to file selection");
app.selected_file_index = app.current_episode_index + 1;
app.view = View::FileSelection;
app.streaming_state = StreamingState::FetchingMetadata;
} else {
// No next episode or single file
// Show rating prompt for movies if Trakt is authenticated and watched >50%
let is_movie = app.current_media_type.as_deref() == Some("movie");
let is_trakt_authenticated = config.providers.trakt.is_authenticated();
info!(
media_type = ?app.current_media_type,
is_movie = %is_movie,
is_trakt_authenticated = %is_trakt_authenticated,
watched_percent = %watched_percent,
"checking if should show rating prompt"
);
if is_movie && is_trakt_authenticated && watched_percent >= 50.0 {
info!("showing rating prompt for movie");
app.show_rating_prompt = true;
app.selected_rating = None;
} else {
// Mark as watched on Trakt if >80% and authenticated (but not showing rating prompt)
if is_trakt_authenticated
&& watched_percent >= 80.0
&& let (Some(client_id), Some(access_token)) = (
config.providers.trakt.get_client_id(),
config.providers.trakt.access_token.as_deref(),
)
{
let title = app.current_title.clone();
let year = app
.current_year
.unwrap_or_else(|| chrono::Utc::now().year() as u16);
let tmdb_id = app.current_tmdb_id;
let provider = TraktProvider::authenticated(
client_id.to_string(),
access_token.to_string(),
);
info!(title = %title, year = %year, tmdb_id = ?tmdb_id, "marking movie as watched on Trakt (no rating prompt)");
tokio::spawn(async move {
match provider
.mark_movie_watched(title.clone(), year, tmdb_id)
.await
{
Ok(_) => {
info!(title = %title, "Successfully marked movie as watched on Trakt")
}
Err(e) => {
error!(error = %e, title = %title, "Failed to mark as watched on Trakt")
}
}
});
}
// cleanup and go back
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
pending_torrent_info = None;
app.available_files.clear();
app.current_file.clear();
app.current_title.clear();
app.racing_message = None;
// Go back to Search if auto-race is enabled (user never saw Results)
app.view = if config.streaming.auto_race > 0 {
View::Discovery
} else {
View::Results
};
app.streaming_state = StreamingState::Connecting;
app.is_streaming = false;
}
info!("streaming ended, ready for next");
}
}
UiMessage::SubtitleWarning => {
app.show_subtitle_warning = true;
info!("showing subtitle warning to user");
}
}
}
// Handle input with timeout
if event::poll(Duration::from_millis(100))?
&& let Event::Key(key) = event::read()?
{
// Global quit
if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
app.should_quit = true;
}
match app.view {
View::Wizard => {
if app.wizard_editing {
// Text input mode
match key.code {
KeyCode::Esc => {
app.wizard_editing = false;
app.wizard_edit_buffer.clear();
}
KeyCode::Enter => {
// Save the field value
apply_wizard_edit(app, config);
app.wizard_editing = false;
app.wizard_edit_buffer.clear();
}
KeyCode::Backspace => {
app.wizard_edit_buffer.pop();
}
KeyCode::Char(c) => {
app.wizard_edit_buffer.push(c);
}
_ => {}
}
} else {
// Navigation mode
match key.code {
KeyCode::Esc => {
// Go back a step or quit wizard
if app.wizard_step == WizardStep::Welcome {
app.should_quit = true;
} else {
app.wizard_step = app.wizard_step.prev();
app.wizard_field_index = 0;
}
}
KeyCode::Enter => {
if app.wizard_step == WizardStep::Done {
// Finish wizard - save config and go to search
if let Err(e) = config.save() {
error!("Failed to save config: {}", e);
} else {
info!("Config saved from wizard");
}
app.view = View::Discovery;
} else if app.wizard_field_count() == 0 {
// No fields (Welcome) - just advance
app.wizard_step = app.wizard_step.next();
app.wizard_field_index = 0;
} else {
// Start editing current field
let current_value = get_wizard_field_value(app, config);
app.wizard_edit_buffer = current_value;
app.wizard_editing = true;
}
}
KeyCode::Tab | KeyCode::Right => {
// Next step (skip optional steps)
app.wizard_step = app.wizard_step.next();
app.wizard_field_index = 0;
}
KeyCode::BackTab | KeyCode::Left => {
app.wizard_step = app.wizard_step.prev();
app.wizard_field_index = 0;
}
KeyCode::Up | KeyCode::Char('k') => {
app.wizard_prev_field();
}
KeyCode::Down | KeyCode::Char('j') => {
app.wizard_next_field();
}
_ => {}
}
}
}
View::Discovery => match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
app.should_quit = true;
}
KeyCode::Char('/') => {
app.view = View::Search;
app.search_input.clear();
}
KeyCode::Char('r') if !app.is_loading_discovery => {
load_discovery_data(&tx, config);
app.is_loading_discovery = true;
}
KeyCode::Char('s') => {
app.view = View::Settings;
app.settings_section = SettingsSection::default();
app.settings_field_index = 0;
}
KeyCode::Char('d') => {
app.view = View::Doctor;
app.is_checking = true;
let tx = tx.clone();
let config_clone = config.clone();
tokio::spawn(async move {
let results = doctor::run_checks(&config_clone).await;
let _ = tx.send(UiMessage::DoctorComplete(results)).await;
});
}
KeyCode::Up | KeyCode::Char('k') => {
app.select_previous_row();
}
KeyCode::Down | KeyCode::Char('j') => {
app.select_next_row();
}
KeyCode::Left | KeyCode::Char('h') => {
app.select_previous_item();
}
KeyCode::Right | KeyCode::Char('l') => {
app.select_next_item();
}
KeyCode::Enter if !app.is_loading_discovery => {
if let Some(item) = app.selected_discovery_item().cloned() {
// Set metadata
app.current_title = item.title.clone();
app.current_tmdb_id = Some(item.id);
app.current_year = item.year;
app.current_media_type = Some(item.media_type.clone());
app.current_poster_url = item.poster_url.clone();
// If TV show, go to season browser
if item.media_type == "tv" {
app.is_fetching_tv_details = true;
spawn_tv_details_fetch(
item.id,
tx.clone(),
config.tmdb.as_ref().map(|t| t.apikey.clone()),
);
} else {
// Movie - start torrent search
let search_query = if let Some(year) = item.year {
format!("{} {}", item.title, year)
} else {
item.title.clone()
};
app.search_id += 1;
app.is_searching = true;
app.search_input = search_query.clone();
app.search_error = None;
// Cancel previous search if running
if let Some(cancel) = search_cancel.take() {
cancel.cancel();
debug!("cancelled previous search");
}
// Create new cancellation token for this search
let cancel_token = CancellationToken::new();
search_cancel = Some(cancel_token.clone());
spawn_torrent_search(
search_query,
app.search_id,
tx.clone(),
config.prowlarr.url.clone(),
config.prowlarr.apikey.clone(),
cancel_token,
);
// Navigate to Results view
app.view = View::Results;
}
}
}
_ => {}
},
View::Search => match key.code {
KeyCode::Esc | KeyCode::Char('q') if app.search_input.is_empty() => {
app.should_quit = true;
}
KeyCode::Esc => {
app.search_input.clear();
}
KeyCode::Enter if !app.search_input.is_empty() && !app.is_searching => {
// Check if there's a selected TV suggestion - if so, browse episodes
let selected_tv = app
.suggestions
.get(app.selected_suggestion)
.filter(|s| s.media_type == "tv")
.cloned();
if let Some(suggestion) = selected_tv {
// TV show selected - go to episode browser
let tv_id = suggestion.id;
let tv_title = suggestion.title.clone();
app.current_title = tv_title;
app.current_tmdb_id = Some(tv_id);
app.current_media_type = Some("tv".to_string());
app.is_fetching_tv_details = true;
app.suggestions.clear();
app.search_input.clear();
info!(tv_id, "fetching TV show details");
spawn_tv_details_fetch(
tv_id,
tx.clone(),
config.tmdb.as_ref().map(|t| t.apikey.clone()),
);
} else {
// Movie or no suggestion - do torrent search
info!(query = %app.search_input, "starting search");
app.search_id += 1; // Increment to invalidate any in-flight searches
app.is_searching = true;
app.search_error = None;
app.tmdb_info = None;
// Cancel previous search if running
if let Some(cancel) = search_cancel.take() {
cancel.cancel();
debug!("cancelled previous search");
}
let query = app.search_input.clone();
let current_search_id = app.search_id;
let tx = tx.clone();
let prowlarr_url = config.prowlarr.url.clone();
let prowlarr_apikey = config.prowlarr.apikey.clone();
let tmdb_apikey = config.tmdb.as_ref().map(|t| t.apikey.clone());
// Create new cancellation token for this search
let cancel_token = CancellationToken::new();
search_cancel = Some(cancel_token.clone());
// Spawn TMDB lookup task in parallel
let tmdb_tx = tx.clone();
let tmdb_query = query.clone();
tokio::spawn(async move {
if let Some(client) = TmdbClient::new(tmdb_apikey.as_deref()) {
debug!(query = %tmdb_query, "looking up TMDB info");
if let Ok(results) = client.search_multi(&tmdb_query).await
&& let Some(first) = results.first()
{
let info = TmdbMetadata {
id: Some(first.id),
title: first.display_title().to_string(),
year: first.year(),
overview: first.overview.clone(),
rating: first.vote_average,
media_type: first.media_type.clone(),
poster_url: first.poster_url("w500"),
};
let _ = tmdb_tx.send(UiMessage::TmdbInfo(info)).await;
}
}
});
// Spawn torrent search task
spawn_torrent_search(
query,
current_search_id,
tx.clone(),
prowlarr_url,
prowlarr_apikey,
cancel_token,
);
}
}
KeyCode::Char('d') if app.search_input.is_empty() && !app.is_searching => {
// Open doctor view and run checks immediately
app.view = View::Doctor;
app.doctor_results.clear();
app.is_checking = true;
let tx = tx.clone();
let config_clone = config.clone();
tokio::spawn(async move {
let results = doctor::run_checks(&config_clone).await;
let _ = tx.send(UiMessage::DoctorComplete(results)).await;
});
}
KeyCode::Char('s') if app.search_input.is_empty() && !app.is_searching => {
// Open settings view
app.view = View::Settings;
app.settings_section = SettingsSection::default();
app.settings_field_index = 0;
}
KeyCode::Tab if !app.suggestions.is_empty() => {
// Accept selected suggestion
if let Some(suggestion) = app.suggestions.get(app.selected_suggestion) {
app.search_input = if let Some(year) = suggestion.year {
format!("{} {}", suggestion.title, year)
} else {
suggestion.title.clone()
};
app.suggestions.clear();
}
}
KeyCode::Down if !app.suggestions.is_empty() => {
app.selected_suggestion =
(app.selected_suggestion + 1).min(app.suggestions.len() - 1);
}
KeyCode::Up if !app.suggestions.is_empty() => {
app.selected_suggestion = app.selected_suggestion.saturating_sub(1);
}
KeyCode::Char(c) if !app.is_searching => {
app.search_input.push(c);
app.suggestions.clear();
// Fetch suggestions if input is long enough
if app.search_input.len() >= 3 {
let tx = tx.clone();
let query = app.search_input.clone();
let tmdb_apikey = config.tmdb.as_ref().map(|t| t.apikey.clone());
app.is_fetching_suggestions = true;
tokio::spawn(async move {
if let Some(client) = TmdbClient::new(tmdb_apikey.as_deref())
&& let Ok(results) = client.search_multi(&query).await
{
let suggestions: Vec<TmdbSuggestion> = results
.into_iter()
.take(5)
.map(|r| TmdbSuggestion {
id: r.id,
title: r.display_title().to_string(),
year: r.year(),
media_type: r.media_type.unwrap_or_default(),
})
.collect();
let _ = tx.send(UiMessage::Suggestions(suggestions)).await;
}
});
}
}
KeyCode::Backspace if !app.is_searching => {
app.search_input.pop();
app.suggestions.clear();
app.selected_suggestion = 0;
// Fetch suggestions if input is still long enough
if app.search_input.len() >= 3 {
let tx = tx.clone();
let query = app.search_input.clone();
let tmdb_apikey = config.tmdb.as_ref().map(|t| t.apikey.clone());
app.is_fetching_suggestions = true;
tokio::spawn(async move {
if let Some(client) = TmdbClient::new(tmdb_apikey.as_deref())
&& let Ok(results) = client.search_multi(&query).await
{
let suggestions: Vec<TmdbSuggestion> = results
.into_iter()
.take(5)
.map(|r| TmdbSuggestion {
id: r.id,
title: r.display_title().to_string(),
year: r.year(),
media_type: r.media_type.unwrap_or_default(),
})
.collect();
let _ = tx.send(UiMessage::Suggestions(suggestions)).await;
}
});
}
}
_ => {}
},
View::TvSeasons => match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
app.view = View::Discovery;
app.tv_details = None;
app.tv_seasons.clear();
}
KeyCode::Up | KeyCode::Char('k') => {
app.select_previous_season();
}
KeyCode::Down | KeyCode::Char('j') => {
app.select_next_season();
}
KeyCode::Enter if !app.is_fetching_tv_details => {
// Fetch episodes for selected season
if let (Some(tv_id), Some(season)) =
(app.current_tmdb_id, app.selected_season())
{
let season_number = season.season_number;
let tx = tx.clone();
let tmdb_apikey = config.tmdb.as_ref().map(|t| t.apikey.clone());
app.is_fetching_tv_details = true;
tokio::spawn(async move {
if let Some(client) = TmdbClient::new(tmdb_apikey.as_deref())
&& let Ok(details) =
client.get_season_details(tv_id, season_number).await
{
let _ = tx
.send(UiMessage::SeasonEpisodesLoaded(details.episodes))
.await;
}
});
}
}
_ => {}
},
View::TvEpisodes => match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
if app.is_searching {
// Cancel search and stay in episodes view
app.is_searching = false;
app.search_error = None;
} else {
// Go back to seasons
app.view = View::TvSeasons;
app.tv_episodes.clear();
}
}
KeyCode::Up | KeyCode::Char('k') if !app.is_searching => {
app.select_previous_episode();
}
KeyCode::Down | KeyCode::Char('j') if !app.is_searching => {
app.select_next_episode();
}
KeyCode::Enter if !app.is_searching => {
// Search for this episode
if let (Some(episode), Some(tv_details)) =
(app.selected_tv_episode().cloned(), app.tv_details.clone())
{
let query = episode.search_query(&tv_details.name);
info!(query = %query, "searching for episode");
app.search_id += 1; // Increment to invalidate any in-flight searches
app.is_searching = true;
app.search_error = None;
app.current_title =
format!("{} - {}", tv_details.name, episode.display_title());
app.current_year = tv_details
.first_air_date
.as_ref()
.and_then(|d| d.split('-').next()?.parse().ok());
app.current_media_type = Some("tv".to_string());
let current_search_id = app.search_id;
let tx = tx.clone();
let prowlarr_url = config.prowlarr.url.clone();
let prowlarr_apikey = config.prowlarr.apikey.clone();
tokio::spawn(async move {
let prowlarr_config = crate::config::ProwlarrConfig {
url: prowlarr_url,
apikey: prowlarr_apikey,
};
let prowlarr = ProwlarrClient::new(&prowlarr_config);
let torznab = TorznabClient::new();
match prowlarr.get_usable_indexers().await {
Ok(indexers) => {
let mut all_results = Vec::new();
for indexer in &indexers {
if let Ok(results) = torznab
.search(
&prowlarr_config.url,
&prowlarr_config.apikey,
indexer.id,
&indexer.name,
&query,
Some(VIDEO_CATEGORIES),
)
.await
{
all_results.extend(results);
}
}
// Filter for streamable and sort by seeders
let mut streamable: Vec<_> = all_results
.into_iter()
.filter(|r| r.is_streamable())
.collect();
streamable.sort_by(|a, b| {
b.seeders.unwrap_or(0).cmp(&a.seeders.unwrap_or(0))
});
let _ = tx
.send(UiMessage::SearchComplete {
results: streamable,
search_id: current_search_id,
})
.await;
}
Err(e) => {
let _ =
tx.send(UiMessage::SearchError(e.to_string())).await;
}
}
});
}
}
_ => {}
},
View::Results => match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
app.view = View::Discovery;
}
KeyCode::Char('/') => {
app.view = View::Search;
app.search_input.clear();
}
KeyCode::Char('s') => {
app.cycle_sort();
}
KeyCode::Up | KeyCode::Char('k') => {
app.select_previous();
}
KeyCode::Down | KeyCode::Char('j') => {
app.select_next();
}
KeyCode::Enter if !app.is_streaming => {
if let Some(result) = app.selected_result()
&& let Some(url) = result.get_torrent_url()
{
info!(title = %result.title, "starting stream");
// Use TMDB title if available, otherwise torrent title
app.current_title = app
.tmdb_info
.as_ref()
.map(|t| t.title.clone())
.unwrap_or_else(|| result.title.clone());
app.current_tmdb_id = app.tmdb_info.as_ref().and_then(|t| t.id);
app.current_year = app.tmdb_info.as_ref().and_then(|t| t.year);
app.current_media_type =
app.tmdb_info.as_ref().and_then(|t| t.media_type.clone());
app.current_poster_url =
app.tmdb_info.as_ref().and_then(|t| t.poster_url.clone());
app.view = View::Streaming;
app.streaming_state = StreamingState::Connecting;
app.download_progress = DownloadProgress::default();
app.is_streaming = true;
let tx = tx.clone();
let temp_dir = config.storage.temp_dir();
// Create cancellation token
let cancel_token = CancellationToken::new();
streaming_cancel = Some(cancel_token.clone());
// Phase 1: Create session and add torrent
tokio::spawn(async move {
if cancel_token.is_cancelled() {
info!("streaming cancelled before start");
let _ = tx.send(UiMessage::PlayerExited).await;
return;
}
info!("creating streaming session");
let session = match StreamingSession::new(temp_dir).await {
Ok(s) => {
info!("session created");
std::sync::Arc::new(s)
}
Err(e) => {
error!(error = %e, "failed to create session");
let _ =
tx.send(UiMessage::StreamError(e.to_string())).await;
return;
}
};
if cancel_token.is_cancelled() {
info!("streaming cancelled");
session.cleanup().await;
let _ = tx.send(UiMessage::PlayerExited).await;
return;
}
info!("adding torrent");
let torrent_info = match session.add_torrent(&url).await {
Ok(info) => {
info!(files = info.video_files.len(), "torrent added");
info
}
Err(e) => {
error!(error = %e, "failed to add torrent");
let _ =
tx.send(UiMessage::StreamError(e.to_string())).await;
return;
}
};
// Send metadata to UI - it will decide whether to show file selection
let _ = tx
.send(UiMessage::TorrentMetadata {
torrent_info,
session,
})
.await;
});
}
}
_ => {}
},
View::FileSelection => match key.code {
KeyCode::Esc => {
// Cancel and go back to results
if let Some(cancel) = streaming_cancel.take() {
cancel.cancel();
}
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
pending_torrent_info = None;
app.available_files.clear();
app.view = View::Results;
app.is_streaming = false;
}
KeyCode::Up | KeyCode::Char('k') => {
app.select_previous_file();
}
KeyCode::Down | KeyCode::Char('j') => {
app.select_next_file();
}
KeyCode::Enter => {
// User selected a file - launch player
if let (Some(file), Some(session), Some(torrent_info)) = (
app.selected_video_file().cloned(),
streaming_session.clone(),
pending_torrent_info.as_ref(),
) {
info!(file = %file.name, "user selected file");
app.current_file = file.name.clone();
app.current_episode_index = app.selected_file_index;
app.streaming_state = StreamingState::Ready {
stream_url: file.stream_url.clone(),
};
app.view = View::Streaming;
// Notify extensions and scrobblers
let (season, episode) = parse_episode_info(&file.name);
let media_info = MediaInfo {
title: app.current_title.clone(),
file_name: file.name.clone(),
total_bytes: file.size,
tmdb_id: app.current_tmdb_id,
year: app.current_year.map(|y| y as u32),
media_type: app.current_media_type.clone(),
poster_url: app.current_poster_url.clone(),
season,
episode,
};
ext_manager.broadcast(PlaybackEvent::Started(media_info.clone()));
scrobbler_manager.on_start(&media_info);
// Pre-download next episode if available
if let Some(next_file) = app.next_episode() {
let next_file_idx = next_file.file_idx;
let session_clone = session.clone();
let torrent_id_clone = torrent_info.id;
info!(
next_file = %next_file.name,
"pre-downloading next episode"
);
tokio::spawn(async move {
let _ = session_clone
.prioritize_file(torrent_id_clone, next_file_idx)
.await;
});
app.next_episode_ready = true;
}
// Launch player task
let tx = tx.clone();
let player_command = config.player.command.clone();
let player_args = config.player.args.clone();
let subtitles_enabled = config.subtitles.enabled;
let preferred_language = config.subtitles.language.clone();
let opensubtitles_key = config.subtitles.opensubtitles_api_key.clone();
let tmdb_id = app.current_tmdb_id;
let subtitle_files = torrent_info.subtitle_files.clone();
let stream_url = file.stream_url.clone();
let torrent_id = torrent_info.id;
let cancel_token = streaming_cancel.clone().unwrap_or_default();
tokio::spawn(async move {
// Spawn progress polling task
let progress_tx = tx.clone();
let progress_session = session.clone();
let progress_handle = tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(500)).await;
if let Some(stats) =
progress_session.get_stats(torrent_id).await
{
let progress = DownloadProgress {
downloaded_bytes: stats.downloaded_bytes,
total_bytes: stats.total_bytes,
download_speed: stats.download_speed,
upload_speed: stats.upload_speed,
peers_connected: stats.peers_connected,
progress_percent: if stats.total_bytes > 0 {
(stats.downloaded_bytes as f64
/ stats.total_bytes as f64)
* 100.0
} else {
0.0
},
};
if progress_tx
.send(UiMessage::ProgressUpdate(progress))
.await
.is_err()
{
break;
}
}
}
});
// Find best subtitle
let subtitle_url = if subtitles_enabled {
let from_torrent = subtitle_files
.iter()
.find(|s| {
s.language
.as_ref()
.map(|l| l == &preferred_language)
.unwrap_or(false)
})
.or_else(|| subtitle_files.first())
.map(|s| s.stream_url.clone());
if from_torrent.is_some() {
from_torrent
} else if let (Some(api_key), Some(tmdb)) =
(&opensubtitles_key, tmdb_id)
{
info!("no subtitles in torrent, trying OpenSubtitles");
let os_client = OpenSubtitlesClient::new(api_key);
match os_client
.search_by_tmdb(tmdb, &preferred_language)
.await
{
Ok(subs) => {
subs.first().map(|s| s.download_url.clone())
}
Err(e) => {
debug!(error = %e, "OpenSubtitles search failed");
None
}
}
} else {
None
}
} else {
None
};
if cancel_token.is_cancelled() {
progress_handle.abort();
session.cleanup().await;
let _ = tx.send(UiMessage::PlayerExited).await;
return;
}
info!(player = %player_command, "launching player");
match streaming::launch_player(
&player_command,
&player_args,
&stream_url,
subtitle_url.as_deref(),
)
.await
{
Ok(mut handle) => {
// Spawn position polling task if we have IPC
let position_handle = if let Some(ref socket_path) =
handle.ipc_socket
{
let socket = socket_path.clone();
let tx_pos = tx.clone();
Some(tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(2)).await;
loop {
if let Some((pos, dur)) =
streaming::get_mpv_position(&socket).await
{
let progress =
streaming::calculate_progress(pos, dur);
let _ = tx_pos
.send(UiMessage::PlaybackProgress(
progress,
))
.await;
}
tokio::time::sleep(Duration::from_secs(5))
.await;
}
}))
} else {
None
};
// Wait for either player to exit OR cancellation
tokio::select! {
_ = handle.child.wait() => {
info!("player exited normally");
}
_ = cancel_token.cancelled() => {
info!("cancellation requested, killing player");
let _ = handle.child.kill().await;
}
}
if let Some(h) = position_handle {
h.abort();
}
if let Some(socket_path) = handle.ipc_socket {
let _ = std::fs::remove_file(socket_path);
}
}
Err(e) => {
error!(error = %e, "failed to launch player");
let _ =
tx.send(UiMessage::StreamError(e.to_string())).await;
progress_handle.abort();
return;
}
}
progress_handle.abort();
session.cleanup().await;
let _ = tx.send(UiMessage::PlayerExited).await;
});
}
}
_ => {}
},
View::Streaming => match key.code {
// Rating prompt handlers
KeyCode::Char(c @ '1'..='9') if app.show_rating_prompt => {
app.selected_rating = Some(c.to_digit(10).unwrap());
}
KeyCode::Char('0') if app.show_rating_prompt => {
app.selected_rating = Some(10);
}
KeyCode::Enter if app.show_rating_prompt && app.selected_rating.is_some() => {
// Submit rating to Trakt
if let (Some(client_id), Some(access_token)) = (
config.providers.trakt.get_client_id(),
config.providers.trakt.access_token.as_deref(),
) {
let title = app.current_title.clone();
let year = app
.current_year
.unwrap_or_else(|| chrono::Utc::now().year() as u16);
let tmdb_id = app.current_tmdb_id;
let rating = app.selected_rating.unwrap(); // Safe: checked by guard condition
let provider = TraktProvider::authenticated(
client_id.to_string(),
access_token.to_string(),
);
info!(title = %title, year = %year, rating = %rating, tmdb_id = ?tmdb_id, "submitting rating to Trakt");
tokio::spawn(async move {
// Rate and mark as watched
match provider
.rate_movie(title.clone(), year, tmdb_id, rating)
.await
{
Ok(_) => {
info!(title = %title, rating = %rating, "Successfully rated movie on Trakt")
}
Err(e) => {
error!(error = %e, title = %title, "Failed to rate on Trakt")
}
}
match provider
.mark_movie_watched(title.clone(), year, tmdb_id)
.await
{
Ok(_) => {
info!(title = %title, "Successfully marked as watched on Trakt")
}
Err(e) => {
error!(error = %e, title = %title, "Failed to mark as watched on Trakt")
}
}
});
}
app.show_rating_prompt = false;
let submitted_rating = app.selected_rating.take();
info!(rating = ?submitted_rating, "user rated content on Trakt");
// Cleanup and navigate back
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
pending_torrent_info = None;
app.available_files.clear();
app.current_file.clear();
app.current_title.clear();
app.racing_message = None;
app.view = if config.streaming.auto_race > 0 {
View::Discovery
} else {
View::Results
};
app.streaming_state = StreamingState::Connecting;
app.is_streaming = false;
}
KeyCode::Esc if app.show_rating_prompt => {
// Skip rating but still mark as watched if >80%
let watched_percent = if app.playback_progress > 0.0 {
app.playback_progress
} else {
app.download_progress.progress_percent
};
if watched_percent >= 80.0
&& let (Some(client_id), Some(access_token)) = (
config.providers.trakt.get_client_id(),
config.providers.trakt.access_token.as_deref(),
)
{
let title = app.current_title.clone();
let year = app
.current_year
.unwrap_or_else(|| chrono::Utc::now().year() as u16);
let tmdb_id = app.current_tmdb_id;
let provider = TraktProvider::authenticated(
client_id.to_string(),
access_token.to_string(),
);
info!(title = %title, year = %year, tmdb_id = ?tmdb_id, watched_percent = %watched_percent, "marking movie as watched on Trakt (skipped rating)");
tokio::spawn(async move {
match provider
.mark_movie_watched(title.clone(), year, tmdb_id)
.await
{
Ok(_) => {
info!(title = %title, "Successfully marked movie as watched on Trakt")
}
Err(e) => {
error!(error = %e, title = %title, "Failed to mark as watched on Trakt")
}
}
});
}
app.show_rating_prompt = false;
app.selected_rating = None;
info!("user skipped rating");
// Cleanup and navigate back
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
pending_torrent_info = None;
app.available_files.clear();
app.current_file.clear();
app.current_title.clear();
app.racing_message = None;
app.view = if config.streaming.auto_race > 0 {
View::Discovery
} else {
View::Results
};
app.streaming_state = StreamingState::Connecting;
app.is_streaming = false;
}
KeyCode::Char('c') if app.show_subtitle_warning => {
// Continue without subtitles
app.show_subtitle_warning = false;
info!("user chose to continue without subtitles");
}
KeyCode::Char('q') if app.show_subtitle_warning => {
// Cancel streaming - go back to file selection or results
app.show_subtitle_warning = false;
if let Some(cancel) = streaming_cancel.take() {
info!("user cancelled streaming due to missing subtitles");
cancel.cancel();
}
if let Some(session) = streaming_session.take() {
drop(session);
}
app.view = if app.selected_result().is_some() {
View::FileSelection
} else {
View::Results
};
app.streaming_state = StreamingState::Connecting;
app.is_streaming = false;
}
KeyCode::Char('r') if app.show_resume_prompt => {
// Resume from saved position
app.show_resume_prompt = false;
info!(
progress = app.resume_progress,
"user chose to resume playback"
);
// Note: Actual seeking would require mpv IPC - for now we just dismiss
// and let the user manually seek. A full implementation would pass
// --start=X% to mpv.
}
KeyCode::Char('s') if app.show_resume_prompt => {
// Start from beginning - clear the saved progress
app.show_resume_prompt = false;
let history_key =
WatchHistory::make_key(app.current_tmdb_id, &app.current_file);
watch_history.clear(&history_key);
watch_history.save();
info!("user chose to start from beginning");
}
KeyCode::Char('q') | KeyCode::Esc if !app.has_active_prompt() => {
// Cancel streaming task if running
if let Some(cancel) = streaming_cancel.take() {
info!("user cancelled streaming");
cancel.cancel();
}
// Clean up session if it exists
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
pending_torrent_info = None;
app.available_files.clear();
app.racing_message = None;
// Go back to Search if auto-race is enabled (user never saw Results)
// Otherwise go back to Results
app.view = if config.streaming.auto_race > 0 {
View::Discovery
} else {
View::Results
};
app.streaming_state = StreamingState::Connecting;
app.is_streaming = false;
}
KeyCode::Char('n') if app.has_next_episode() && !app.has_active_prompt() => {
// Skip to next episode - cancel current player
if let Some(cancel) = streaming_cancel.take() {
info!("user skipping to next episode");
cancel.cancel();
}
// PlayerExited handler will auto-play next
}
_ => {}
},
View::Doctor => match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
app.view = View::Discovery;
}
KeyCode::Char('r') if !app.is_checking => {
// Run checks
app.is_checking = true;
let tx = tx.clone();
let config_clone = config.clone();
tokio::spawn(async move {
let results = doctor::run_checks(&config_clone).await;
let _ = tx.send(UiMessage::DoctorComplete(results)).await;
});
}
_ => {}
},
View::Settings => {
if app.settings_editing {
// Editing mode - handle text input
match key.code {
KeyCode::Esc => {
// Cancel edit
app.settings_editing = false;
app.settings_edit_buffer.clear();
}
KeyCode::Enter => {
// Save edit to config
apply_settings_edit(app, config);
app.settings_editing = false;
app.settings_edit_buffer.clear();
app.settings_dirty = true;
}
KeyCode::Backspace => {
app.settings_edit_buffer.pop();
}
KeyCode::Char(c) => {
app.settings_edit_buffer.push(c);
}
_ => {}
}
} else {
// Navigation mode
match key.code {
KeyCode::Char('q') | KeyCode::Esc => {
if app.settings_dirty {
// Save config before exiting
if let Err(e) = config.save() {
error!("Failed to save config: {}", e);
} else {
info!("Config saved");
}
app.settings_dirty = false;
}
app.view = View::Discovery;
app.settings_field_index = 0;
}
KeyCode::Left | KeyCode::Char('h') => {
// Switch sections
app.settings_section = app.settings_section.prev();
app.settings_field_index = 0;
}
KeyCode::Right | KeyCode::Char('l') => {
// Switch sections
app.settings_section = app.settings_section.next();
app.settings_field_index = 0;
}
KeyCode::Up | KeyCode::Char('k') => {
// Move between fields
app.settings_prev_field();
}
KeyCode::Down | KeyCode::Char('j') => {
// Move between fields
app.settings_next_field();
}
KeyCode::Enter => {
// Try to toggle if it's a boolean field, otherwise edit
if toggle_settings_bool(app, config) {
app.settings_dirty = true;
} else if app.settings_section == SettingsSection::Trakt
&& app.settings_field_index == 3
{
// Status field - start OAuth flow if client_id is available
if let Some(client_id) =
config.providers.trakt.get_client_id().map(String::from)
{
// Save any pending changes first
if app.settings_dirty {
if let Err(e) = config.save() {
error!("Failed to save config before auth: {}", e);
}
app.settings_dirty = false;
}
// Start auth flow - generate URL and open browser
let auth_url = start_trakt_auth(&client_id);
app.view = View::TraktAuth;
app.trakt_auth_url = Some(auth_url);
app.trakt_auth_code_input = String::new();
app.trakt_auth_error = None;
}
} else if !is_readonly_field(app) {
// Start editing non-boolean field
let current_value = get_settings_field_value(app, config);
app.settings_edit_buffer = current_value;
app.settings_editing = true;
}
}
KeyCode::Char(' ') => {
// Toggle boolean fields (alternative to Enter)
if toggle_settings_bool(app, config) {
app.settings_dirty = true;
}
}
KeyCode::Char('s') => {
// Save now
if let Err(e) = config.save() {
error!("Failed to save config: {}", e);
} else {
info!("Config saved");
app.settings_dirty = false;
}
}
_ => {}
}
}
}
View::TraktAuth => {
match key.code {
KeyCode::Esc => {
// Cancel auth and go back to settings
app.trakt_auth_url = None;
app.trakt_auth_code_input = String::new();
app.trakt_auth_error = None;
app.view = View::Settings;
}
KeyCode::Enter => {
// Submit the code
if !app.trakt_auth_code_input.is_empty()
&& let Some(client_id) =
config.providers.trakt.get_client_id().map(String::from)
{
let client_secret = config
.providers
.trakt
.client_secret
.clone()
.unwrap_or_default();
let code = app.trakt_auth_code_input.trim().to_string();
exchange_trakt_code(&tx, client_id, client_secret, code);
}
}
KeyCode::Char(c) => {
// Type characters into code input
app.trakt_auth_code_input.push(c);
app.trakt_auth_error = None; // Clear error on new input
}
KeyCode::Backspace => {
app.trakt_auth_code_input.pop();
}
_ => {}
}
}
}
}
if app.should_quit {
// Cleanup before exit
if let Some(session) = streaming_session.take() {
session.cleanup().await;
}
break;
}
}
Ok(())
}
/// Get the current value of the selected settings field
fn get_settings_field_value(app: &App, config: &Config) -> String {
match app.settings_section {
SettingsSection::Prowlarr => match app.settings_field_index {
0 => config.prowlarr.url.clone(),
1 => config.prowlarr.apikey.clone(),
2 => String::new(), // Status field is read-only
_ => String::new(),
},
SettingsSection::Tmdb => match app.settings_field_index {
0 => config
.tmdb
.as_ref()
.map(|t| t.apikey.clone())
.unwrap_or_default(),
_ => String::new(),
},
SettingsSection::Player => match app.settings_field_index {
0 => config.player.command.clone(),
1 => config.player.args.join(" "),
_ => String::new(),
},
SettingsSection::Streaming => match app.settings_field_index {
0 => config.streaming.auto_race.to_string(),
_ => String::new(),
},
SettingsSection::Subtitles => match app.settings_field_index {
0 => config.subtitles.enabled.to_string(),
1 => config.subtitles.language.clone(),
2 => config
.subtitles
.opensubtitles_api_key
.clone()
.unwrap_or_default(),
_ => String::new(),
},
SettingsSection::Discord => match app.settings_field_index {
0 => config.extensions.discord.enabled.to_string(),
1 => config.extensions.discord.app_id.clone().unwrap_or_default(),
_ => String::new(),
},
SettingsSection::Trakt => match app.settings_field_index {
0 => {
// Return current enable status for editing
let discovery = config.providers.discovery.as_deref() == Some("trakt");
let scrobbling = config.scrobblers.enabled.contains(&"trakt".to_string());
(discovery || scrobbling).to_string()
}
1 => config.providers.trakt.client_id.clone().unwrap_or_default(),
2 => config
.providers
.trakt
.client_secret
.clone()
.unwrap_or_default(),
3 => String::new(), // Status field is read-only
_ => String::new(),
},
}
}
/// Apply the edit buffer to the config field
fn apply_settings_edit(app: &App, config: &mut Config) {
let value = app.settings_edit_buffer.trim().to_string();
match app.settings_section {
SettingsSection::Prowlarr => match app.settings_field_index {
0 => config.prowlarr.url = value,
1 => config.prowlarr.apikey = value,
_ => {}
},
SettingsSection::Tmdb => {
if app.settings_field_index == 0 {
if value.is_empty() {
config.tmdb = None;
} else {
config.tmdb = Some(crate::config::TmdbConfig { apikey: value });
}
}
}
SettingsSection::Player => match app.settings_field_index {
0 => config.player.command = value,
1 => {
config.player.args = if value.is_empty() {
Vec::new()
} else {
value.split_whitespace().map(String::from).collect()
};
}
_ => {}
},
SettingsSection::Streaming => {
if app.settings_field_index == 0
&& let Ok(v) = value.parse::<u8>()
{
config.streaming.auto_race = v;
}
}
SettingsSection::Subtitles => match app.settings_field_index {
0 => config.subtitles.enabled = value.to_lowercase() == "true",
1 => config.subtitles.language = value,
2 => {
config.subtitles.opensubtitles_api_key =
if value.is_empty() { None } else { Some(value) };
}
_ => {}
},
SettingsSection::Discord => match app.settings_field_index {
0 => config.extensions.discord.enabled = value.to_lowercase() == "true",
1 => {
config.extensions.discord.app_id =
if value.is_empty() { None } else { Some(value) };
}
_ => {}
},
SettingsSection::Trakt => match app.settings_field_index {
0 => {
// Toggle both discovery and scrobbling together
let enable = value.to_lowercase() == "true";
if enable {
config.providers.discovery = Some("trakt".to_string());
if !config.scrobblers.enabled.contains(&"trakt".to_string()) {
config.scrobblers.enabled.push("trakt".to_string());
}
} else {
if config.providers.discovery.as_deref() == Some("trakt") {
config.providers.discovery = None;
}
config.scrobblers.enabled.retain(|s| s != "trakt");
}
}
1 => {
config.providers.trakt.client_id =
if value.is_empty() { None } else { Some(value) };
}
2 => {
config.providers.trakt.client_secret =
if value.is_empty() { None } else { Some(value) };
}
3 => {} // Status field is read-only
_ => {}
},
}
}
/// Toggle boolean fields with spacebar, returns true if a toggle happened
fn toggle_settings_bool(app: &App, config: &mut Config) -> bool {
match app.settings_section {
SettingsSection::Subtitles if app.settings_field_index == 0 => {
config.subtitles.enabled = !config.subtitles.enabled;
true
}
SettingsSection::Discord if app.settings_field_index == 0 => {
config.extensions.discord.enabled = !config.extensions.discord.enabled;
true
}
SettingsSection::Trakt if app.settings_field_index == 0 => {
// Toggle both discovery and scrobbling together
let currently_enabled = config.providers.discovery.as_deref() == Some("trakt")
|| config.scrobblers.enabled.contains(&"trakt".to_string());
if currently_enabled {
// Disable both
if config.providers.discovery.as_deref() == Some("trakt") {
config.providers.discovery = None;
}
config.scrobblers.enabled.retain(|s| s != "trakt");
} else {
// Enable both
config.providers.discovery = Some("trakt".to_string());
if !config.scrobblers.enabled.contains(&"trakt".to_string()) {
config.scrobblers.enabled.push("trakt".to_string());
}
}
true
}
_ => false,
}
}
/// Check if the current settings field is read-only (can't be edited)
fn is_readonly_field(app: &App) -> bool {
match app.settings_section {
// Prowlarr "Status" field (index 2) is read-only
SettingsSection::Prowlarr => app.settings_field_index == 2,
// Trakt "Status" field (index 3) is read-only
SettingsSection::Trakt => app.settings_field_index == 3,
_ => false,
}
}
/// Get the current value of the selected wizard field
fn get_wizard_field_value(app: &App, config: &Config) -> String {
match app.wizard_step {
WizardStep::Prowlarr => match app.wizard_field_index {
0 => config.prowlarr.url.clone(),
1 => config.prowlarr.apikey.clone(),
_ => String::new(),
},
WizardStep::Tmdb => match app.wizard_field_index {
0 => config
.tmdb
.as_ref()
.map(|t| t.apikey.clone())
.unwrap_or_default(),
_ => String::new(),
},
WizardStep::Player => match app.wizard_field_index {
0 => config.player.command.clone(),
_ => String::new(),
},
_ => String::new(),
}
}
/// Apply the wizard edit buffer to the config field
fn apply_wizard_edit(app: &App, config: &mut Config) {
let value = app.wizard_edit_buffer.trim().to_string();
match app.wizard_step {
WizardStep::Prowlarr => match app.wizard_field_index {
0 => config.prowlarr.url = value,
1 => config.prowlarr.apikey = value,
_ => {}
},
WizardStep::Tmdb => {
if app.wizard_field_index == 0 {
if value.is_empty() {
config.tmdb = None;
} else {
config.tmdb = Some(crate::config::TmdbConfig { apikey: value });
}
}
}
WizardStep::Player => {
if app.wizard_field_index == 0 {
config.player.command = value;
}
}
_ => {}
}
}