1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
use atom_syndication::Feed as AtomFeed;
use base64;
use chrono::DateTime;
use crossterm::terminal;
use html2text;
use log::{debug, error, info, warn};
use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, BytesText, Event};
use quick_xml::{Reader, Writer};
use reqwest;
use rss::Channel;
use serde::{Deserialize, Serialize};
use std::io::{Cursor, Write};
use std::{
collections::HashMap, collections::HashSet, error, fs, path::PathBuf, time::Duration,
time::SystemTime,
};
/// Default HTTP request timeout in seconds
const DEFAULT_HTTP_TIMEOUT_SECS: u64 = 30;
/// Default auto-refresh interval in minutes (0 = disabled)
const DEFAULT_AUTO_REFRESH_MINS: u64 = 0;
/// Default cache duration in minutes (60 = 1 hour)
const DEFAULT_CACHE_DURATION_MINS: u64 = 60;
/// Default notifications enabled setting (false = disabled)
const DEFAULT_NOTIFICATIONS_ENABLED: bool = false;
/// Default mark read on scroll setting (false = disabled)
const DEFAULT_MARK_READ_ON_SCROLL: bool = false;
/// Copies text to clipboard using OSC 52 escape sequence.
/// This works over SSH and through tmux, unlike native clipboard APIs.
/// Returns Ok(()) on success, Err with message on failure.
pub fn copy_to_clipboard_osc52(text: &str) -> Result<(), String> {
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
let encoded = STANDARD.encode(text);
// OSC 52 sequence: \x1b]52;c;<base64>\x07
// 'c' = clipboard selection
let osc52_seq = format!("\x1b]52;c;{}\x07", encoded);
// Write directly to stdout
let mut stdout = std::io::stdout();
stdout
.write_all(osc52_seq.as_bytes())
.map_err(|e| format!("Failed to write OSC 52: {}", e))?;
stdout
.flush()
.map_err(|e| format!("Failed to flush stdout: {}", e))?;
debug!("Copied {} bytes to clipboard via OSC 52", text.len());
Ok(())
}
/// Color theme for the application UI
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Theme {
/// Primary accent color (titles, headers)
#[serde(default = "default_primary")]
pub primary: String,
/// Secondary accent color (selected items, section headers)
#[serde(default = "default_secondary")]
pub secondary: String,
/// Default text color
#[serde(default = "default_text")]
pub text: String,
/// Muted text color (read items, inactive elements)
#[serde(default = "default_muted")]
pub muted: String,
/// Error message color
#[serde(default = "default_error")]
pub error: String,
/// Highlight color (unread counts, links)
#[serde(default = "default_highlight")]
pub highlight: String,
/// Description/secondary text color
#[serde(default = "default_description")]
pub description: String,
/// Category header color
#[serde(default = "default_category")]
pub category: String,
}
fn default_primary() -> String {
"green".to_string()
}
fn default_secondary() -> String {
"yellow".to_string()
}
fn default_text() -> String {
"white".to_string()
}
fn default_muted() -> String {
"dark_gray".to_string()
}
fn default_error() -> String {
"red".to_string()
}
fn default_highlight() -> String {
"cyan".to_string()
}
fn default_description() -> String {
"gray".to_string()
}
fn default_category() -> String {
"magenta".to_string()
}
impl Default for Theme {
fn default() -> Self {
Self {
primary: default_primary(),
secondary: default_secondary(),
text: default_text(),
muted: default_muted(),
error: default_error(),
highlight: default_highlight(),
description: default_description(),
category: default_category(),
}
}
}
impl Theme {
/// Returns a light theme suitable for light terminal backgrounds
pub fn light() -> Self {
Self {
primary: "blue".to_string(),
secondary: "magenta".to_string(),
text: "black".to_string(),
muted: "dark_gray".to_string(),
error: "red".to_string(),
highlight: "blue".to_string(),
description: "dark_gray".to_string(),
category: "magenta".to_string(),
}
}
}
/// Customizable keyboard shortcuts
/// Each field contains a comma-separated list of keys that trigger the action.
/// Supported formats: single characters (e.g., "j"), special keys (e.g., "Up", "Enter", "Esc"),
/// and multiple keys (e.g., "j,Down" for vim-style + arrow key navigation).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Keybindings {
// Navigation
#[serde(default = "default_move_up")]
pub move_up: String,
#[serde(default = "default_move_down")]
pub move_down: String,
#[serde(default = "default_page_up")]
pub page_up: String,
#[serde(default = "default_page_down")]
pub page_down: String,
#[serde(default = "default_scroll_to_top")]
pub scroll_to_top: String,
#[serde(default = "default_scroll_to_bottom")]
pub scroll_to_bottom: String,
// Actions
#[serde(default = "default_select")]
pub select: String,
#[serde(default = "default_open_in_browser")]
pub open_in_browser: String,
#[serde(default = "default_copy_link")]
pub copy_link: String,
#[serde(default = "default_toggle_read")]
pub toggle_read: String,
#[serde(default = "default_mark_all_read")]
pub mark_all_read: String,
#[serde(default = "default_toggle_favorite")]
pub toggle_favorite: String,
#[serde(default = "default_toggle_favorites_view")]
pub toggle_favorites_view: String,
#[serde(default = "default_refresh")]
pub refresh: String,
// Search & Filter
#[serde(default = "default_start_search")]
pub start_search: String,
#[serde(default = "default_toggle_unread_only")]
pub toggle_unread_only: String,
// Preview
#[serde(default = "default_open_preview")]
pub open_preview: String,
// Feed Manager
#[serde(default = "default_open_feed_manager")]
pub open_feed_manager: String,
#[serde(default = "default_add_feed")]
pub add_feed: String,
#[serde(default = "default_delete_feed")]
pub delete_feed: String,
#[serde(default = "default_set_category")]
pub set_category: String,
#[serde(default = "default_export_clipboard")]
pub export_clipboard: String,
#[serde(default = "default_export_opml")]
pub export_opml: String,
#[serde(default = "default_import_clipboard")]
pub import_clipboard: String,
#[serde(default = "default_import_opml")]
pub import_opml: String,
// UI
#[serde(default = "default_help")]
pub help: String,
#[serde(default = "default_quit")]
pub quit: String,
// Export
#[serde(default = "default_export_article")]
pub export_article: String,
}
// Default keybinding functions
fn default_move_up() -> String {
"k,Up".to_string()
}
fn default_move_down() -> String {
"j,Down".to_string()
}
fn default_page_up() -> String {
"PageUp".to_string()
}
fn default_page_down() -> String {
"PageDown".to_string()
}
fn default_scroll_to_top() -> String {
"g".to_string()
}
fn default_scroll_to_bottom() -> String {
"G".to_string()
}
fn default_select() -> String {
"Enter".to_string()
}
fn default_open_in_browser() -> String {
"o".to_string()
}
fn default_copy_link() -> String {
"O".to_string()
}
fn default_toggle_read() -> String {
"r".to_string()
}
fn default_mark_all_read() -> String {
"R".to_string()
}
fn default_toggle_favorite() -> String {
"f".to_string()
}
fn default_toggle_favorites_view() -> String {
"F".to_string()
}
fn default_refresh() -> String {
"c".to_string()
}
fn default_start_search() -> String {
"/".to_string()
}
fn default_toggle_unread_only() -> String {
"u".to_string()
}
fn default_open_preview() -> String {
"p".to_string()
}
fn default_open_feed_manager() -> String {
"m".to_string()
}
fn default_add_feed() -> String {
"a".to_string()
}
fn default_delete_feed() -> String {
"d".to_string()
}
fn default_set_category() -> String {
"t".to_string()
}
fn default_export_clipboard() -> String {
"e".to_string()
}
fn default_export_opml() -> String {
"E".to_string()
}
fn default_import_clipboard() -> String {
"i".to_string()
}
fn default_import_opml() -> String {
"I".to_string()
}
fn default_help() -> String {
"?".to_string()
}
fn default_quit() -> String {
"q".to_string()
}
fn default_export_article() -> String {
"s".to_string()
}
impl Default for Keybindings {
fn default() -> Self {
Self {
move_up: default_move_up(),
move_down: default_move_down(),
page_up: default_page_up(),
page_down: default_page_down(),
scroll_to_top: default_scroll_to_top(),
scroll_to_bottom: default_scroll_to_bottom(),
select: default_select(),
open_in_browser: default_open_in_browser(),
copy_link: default_copy_link(),
toggle_read: default_toggle_read(),
mark_all_read: default_mark_all_read(),
toggle_favorite: default_toggle_favorite(),
toggle_favorites_view: default_toggle_favorites_view(),
refresh: default_refresh(),
start_search: default_start_search(),
toggle_unread_only: default_toggle_unread_only(),
open_preview: default_open_preview(),
open_feed_manager: default_open_feed_manager(),
add_feed: default_add_feed(),
delete_feed: default_delete_feed(),
set_category: default_set_category(),
export_clipboard: default_export_clipboard(),
export_opml: default_export_opml(),
import_clipboard: default_import_clipboard(),
import_opml: default_import_opml(),
help: default_help(),
quit: default_quit(),
export_article: default_export_article(),
}
}
}
/// Application configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// HTTP request timeout in seconds (default: 30)
#[serde(default = "default_http_timeout")]
pub http_timeout_secs: u64,
/// Auto-refresh interval in minutes (default: 0 = disabled)
#[serde(default = "default_auto_refresh")]
pub auto_refresh_mins: u64,
/// Cache duration in minutes (default: 60 = 1 hour)
#[serde(default = "default_cache_duration")]
pub cache_duration_mins: u64,
/// Desktop notifications for new articles (default: false)
#[serde(default = "default_notifications_enabled")]
pub notifications_enabled: bool,
/// Auto-mark items as read when scrolling past them (default: false)
#[serde(default = "default_mark_read_on_scroll")]
pub mark_read_on_scroll: bool,
/// Color theme (default: dark theme)
#[serde(default)]
pub theme: Theme,
/// Custom keyboard shortcuts (default: vim-style bindings)
#[serde(default)]
pub keybindings: Keybindings,
}
fn default_http_timeout() -> u64 {
DEFAULT_HTTP_TIMEOUT_SECS
}
fn default_auto_refresh() -> u64 {
DEFAULT_AUTO_REFRESH_MINS
}
fn default_cache_duration() -> u64 {
DEFAULT_CACHE_DURATION_MINS
}
fn default_notifications_enabled() -> bool {
DEFAULT_NOTIFICATIONS_ENABLED
}
fn default_mark_read_on_scroll() -> bool {
DEFAULT_MARK_READ_ON_SCROLL
}
impl Default for Config {
fn default() -> Self {
Self {
http_timeout_secs: DEFAULT_HTTP_TIMEOUT_SECS,
auto_refresh_mins: DEFAULT_AUTO_REFRESH_MINS,
cache_duration_mins: DEFAULT_CACHE_DURATION_MINS,
notifications_enabled: DEFAULT_NOTIFICATIONS_ENABLED,
mark_read_on_scroll: DEFAULT_MARK_READ_ON_SCROLL,
theme: Theme::default(),
keybindings: Keybindings::default(),
}
}
}
/// Creates a reqwest client with a configured timeout to prevent hanging on slow/unresponsive feeds
fn create_http_client(timeout_secs: u64) -> reqwest::Client {
reqwest::Client::builder()
.timeout(Duration::from_secs(timeout_secs))
.build()
.unwrap_or_else(|_| reqwest::Client::new())
}
pub type AppResult<T> = std::result::Result<T, Box<dyn error::Error>>;
#[derive(Debug, PartialEq)]
pub enum InputMode {
Normal,
Adding,
Deleting,
FeedManager,
Help,
Searching,
Importing,
SettingCategory,
Preview,
Command,
}
#[derive(Debug, PartialEq)]
pub enum PageMode {
FeedList,
FeedManager,
Favorites,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeedItem {
pub title: String,
pub description: String,
pub link: String,
pub published: Option<SystemTime>,
pub id: String,
#[serde(default)]
pub feed_url: String,
}
/// Represents a feed subscription with its URL, title, and optional category
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeedInfo {
pub url: String,
pub title: String,
#[serde(default)]
pub category: Option<String>,
}
/// Feed health status
#[derive(Debug, Clone, PartialEq)]
pub enum FeedStatus {
/// Feed is healthy and responding normally
Healthy,
/// Feed responded but took longer than expected (>5 seconds)
Slow,
/// Feed failed to load or parse
Broken,
/// Feed has not been checked yet
Unknown,
}
/// Tracks the health status of a feed
#[derive(Debug, Clone)]
pub struct FeedHealth {
/// Current status of the feed
pub status: FeedStatus,
/// Time of the last successful fetch
pub last_success: Option<SystemTime>,
/// Response time of the last fetch attempt (in milliseconds)
pub last_response_time_ms: Option<u64>,
/// Error message from the last failed attempt
pub last_error: Option<String>,
/// Number of consecutive failures
pub consecutive_failures: u32,
}
impl Default for FeedHealth {
fn default() -> Self {
Self {
status: FeedStatus::Unknown,
last_success: None,
last_response_time_ms: None,
last_error: None,
consecutive_failures: 0,
}
}
}
impl FeedHealth {
/// Returns a display string for the health status
pub fn status_indicator(&self) -> &'static str {
match self.status {
FeedStatus::Healthy => "●", // Green dot
FeedStatus::Slow => "◐", // Half-filled circle (slow)
FeedStatus::Broken => "✗", // X mark (broken)
FeedStatus::Unknown => "○", // Empty circle (unknown)
}
}
/// Returns a human-readable status description
pub fn status_description(&self) -> String {
match self.status {
FeedStatus::Healthy => {
if let Some(ms) = self.last_response_time_ms {
format!("OK ({}ms)", ms)
} else {
"OK".to_string()
}
}
FeedStatus::Slow => {
if let Some(ms) = self.last_response_time_ms {
format!("Slow ({}ms)", ms)
} else {
"Slow".to_string()
}
}
FeedStatus::Broken => {
if let Some(ref err) = self.last_error {
format!("Error: {}", err)
} else {
"Broken".to_string()
}
}
FeedStatus::Unknown => "Not checked".to_string(),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct SavedState {
feeds: Vec<FeedInfo>,
read_items: HashSet<String>,
favorites: HashSet<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct CachedFeed {
url: String,
content: Vec<FeedItem>,
last_updated: SystemTime,
}
#[derive(Debug)]
pub struct App {
pub running: bool,
pub input_mode: InputMode,
pub page_mode: PageMode,
pub input_buffer: String,
pub rss_feeds: Vec<FeedInfo>,
pub selected_index: Option<usize>,
pub current_feed_content: Vec<FeedItem>,
pub error_message: Option<String>,
/// Status message shown at bottom (for success notifications)
pub status_message: Option<String>,
save_path: PathBuf,
read_items: HashSet<String>,
pub favorites: HashSet<String>,
pub scroll: u16,
pub terminal_width: u16,
pub terminal_height: u16,
pub search_query: String,
pub filtered_indices: Option<Vec<usize>>,
pub import_result: Option<String>,
pub config: Config,
/// Timestamp of the last feed refresh
pub last_refresh: Option<SystemTime>,
/// Flag indicating an auto-refresh is pending (set by tick, consumed by main loop)
pub auto_refresh_pending: bool,
/// Scroll position for the article preview pane
pub preview_scroll: u16,
/// Buffer for vi-style command mode (e.g., :q, :w, :wq)
pub command_buffer: String,
/// Health status for each feed (keyed by URL)
pub feed_health: HashMap<String, FeedHealth>,
/// Item IDs that have already been seen (for notification tracking)
seen_items: HashSet<String>,
/// Filter to show only unread items
pub show_unread_only: bool,
}
impl Default for App {
fn default() -> Self {
Self {
running: true,
input_mode: InputMode::Normal,
page_mode: PageMode::FeedList,
input_buffer: String::new(),
rss_feeds: Vec::new(),
selected_index: None,
current_feed_content: Vec::new(),
error_message: None,
status_message: None,
save_path: Self::get_save_path(),
read_items: HashSet::new(),
favorites: HashSet::new(),
scroll: 0,
terminal_width: 80,
terminal_height: 24,
search_query: String::new(),
filtered_indices: None,
import_result: None,
config: Config::default(),
last_refresh: None,
auto_refresh_pending: false,
preview_scroll: 0,
command_buffer: String::new(),
feed_health: HashMap::new(),
seen_items: HashSet::new(),
show_unread_only: false,
}
}
}
impl App {
pub async fn new() -> Self {
let mut app = Self {
config: Self::load_config(),
..Default::default()
};
// Get initial terminal size
if let Ok((width, height)) = terminal::size() {
app.terminal_width = width;
app.terminal_height = height;
}
app.load_feeds().unwrap_or_else(|e| {
error!("Failed to load feeds: {}", e);
app.error_message = Some(format!("Failed to load feeds: {}", e));
});
// Cache all feeds and load all cached content
if !app.rss_feeds.is_empty() {
app.selected_index = Some(0);
// Load cached content first to populate seen_items (prevents notifications on startup)
let mut all_items = Vec::new();
for feed in &app.rss_feeds {
if let Some(cached_items) = app.load_feed_cache(&feed.url) {
all_items.extend(cached_items);
}
}
// Populate seen_items with cached item IDs to avoid startup notifications
for item in &all_items {
app.seen_items.insert(item.id.clone());
}
app.current_feed_content = all_items;
// Now refresh feeds (notifications will only fire for truly new items)
let _ = app.refresh_all_feeds().await;
app.cache_all_feeds().await;
// Reload and combine all cached feed content
let mut all_items = Vec::new();
for feed in &app.rss_feeds {
if let Some(cached_items) = app.load_feed_cache(&feed.url) {
all_items.extend(cached_items);
}
}
// Sort all items by date, newest first
all_items.sort_by(|a, b| b.published.cmp(&a.published));
app.current_feed_content = all_items;
}
// Record the initial refresh time
app.last_refresh = Some(SystemTime::now());
app
}
/// Handles the tick event of the terminal.
/// Checks if auto-refresh is due and sets the auto_refresh_pending flag.
pub fn tick(&mut self) {
// Skip auto-refresh check if disabled or no feeds
if self.config.auto_refresh_mins == 0 || self.rss_feeds.is_empty() {
return;
}
// Skip if we're not in a view that should auto-refresh (e.g., not in help or input modes)
if self.input_mode != InputMode::Normal {
return;
}
// Check if it's time for an auto-refresh
if let Some(last_refresh) = self.last_refresh {
if let Ok(elapsed) = last_refresh.elapsed() {
let refresh_interval = Duration::from_secs(self.config.auto_refresh_mins * 60);
if elapsed >= refresh_interval {
debug!(
"Auto-refresh triggered after {} minutes",
self.config.auto_refresh_mins
);
self.auto_refresh_pending = true;
}
}
}
}
/// Performs the auto-refresh if pending. Called from the main loop.
pub async fn perform_auto_refresh(&mut self) {
if !self.auto_refresh_pending {
return;
}
self.auto_refresh_pending = false;
// Only auto-refresh in FeedList or Favorites mode
match self.page_mode {
PageMode::FeedList => {
info!("Auto-refreshing feeds...");
if let Err(e) = self.refresh_all_feeds().await {
error!("Auto-refresh failed: {}", e);
} else {
self.last_refresh = Some(SystemTime::now());
}
}
PageMode::Favorites => {
// For favorites, refresh all feeds then re-filter to favorites
info!("Auto-refreshing feeds (favorites view)...");
if let Err(e) = self.refresh_all_feeds().await {
error!("Auto-refresh failed: {}", e);
} else {
// Re-filter to show only favorites
let favorites: Vec<FeedItem> = self
.current_feed_content
.iter()
.filter(|item| self.favorites.contains(&item.id))
.cloned()
.collect();
self.current_feed_content = favorites;
// Reset selection state after content change
self.selected_index = if self.current_feed_content.is_empty() {
None
} else {
Some(0)
};
self.filtered_indices = None;
self.scroll = 0;
self.last_refresh = Some(SystemTime::now());
}
}
PageMode::FeedManager => {
// Don't auto-refresh in feed manager mode
self.last_refresh = Some(SystemTime::now());
}
}
}
/// Returns the time until the next auto-refresh, or None if auto-refresh is disabled.
pub fn time_until_next_refresh(&self) -> Option<Duration> {
if self.config.auto_refresh_mins == 0 {
return None;
}
let refresh_interval = Duration::from_secs(self.config.auto_refresh_mins * 60);
if let Some(last_refresh) = self.last_refresh {
if let Ok(elapsed) = last_refresh.elapsed() {
if elapsed < refresh_interval {
return Some(refresh_interval - elapsed);
}
}
}
Some(Duration::from_secs(0))
}
/// Set running to false to quit the application.
pub fn quit(&mut self) {
self.running = false;
}
pub fn get_save_path() -> PathBuf {
let mut path = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
if let Err(e) = fs::create_dir_all(&path) {
error!("Failed to create config directory {:?}: {}", path, e);
}
path.push("feeds.json");
path
}
pub fn get_log_path() -> PathBuf {
let mut path = dirs::data_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
path.push("logs");
if let Err(e) = fs::create_dir_all(&path) {
eprintln!("Failed to create log directory {:?}: {}", path, e);
}
path.push("reedy.log");
path
}
pub fn get_config_path() -> PathBuf {
let mut path = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
if let Err(e) = fs::create_dir_all(&path) {
error!("Failed to create config directory {:?}: {}", path, e);
}
path.push("config.json");
path
}
pub fn load_config() -> Config {
let config_path = Self::get_config_path();
if config_path.exists() {
match fs::read_to_string(&config_path) {
Ok(contents) => match serde_json::from_str::<Config>(&contents) {
Ok(config) => return config,
Err(e) => {
warn!(
"Failed to parse config file {}: {}. Using defaults.",
config_path.display(),
e
);
}
},
Err(e) => {
warn!(
"Failed to read config file {}: {}. Using defaults.",
config_path.display(),
e
);
}
}
}
// Return default config if file doesn't exist or can't be parsed
Config::default()
}
pub fn save_config(&self) -> AppResult<()> {
let config_path = Self::get_config_path();
let json = serde_json::to_string_pretty(&self.config)?;
fs::write(config_path, json)?;
Ok(())
}
fn create_item_id(title: &str, published: Option<SystemTime>, feed_url: &str) -> String {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
feed_url.hash(&mut hasher);
let url_hash = hasher.finish();
let title_slug = title
.to_lowercase()
.replace(|c: char| !c.is_alphanumeric(), "_");
if let Some(time) = published {
let nanos = time
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
format!("{}_{:x}_{}", title_slug, url_hash, nanos)
} else {
format!("{}_{:x}", title_slug, url_hash)
}
}
pub fn is_item_read(&self, item: &FeedItem) -> bool {
self.read_items.contains(&item.id)
}
/// Returns the count of unread items for a given feed URL.
/// Uses cached feed content to determine the count.
pub fn count_unread_for_feed(&self, url: &str) -> usize {
if let Some(items) = self.load_feed_cache(url) {
items.iter().filter(|item| !self.is_item_read(item)).count()
} else {
0
}
}
/// Returns the total count of items for a given feed URL.
/// Uses cached feed content to determine the count.
pub fn count_total_for_feed(&self, url: &str) -> usize {
if let Some(items) = self.load_feed_cache(url) {
items.len()
} else {
0
}
}
/// Returns the health status for a given feed URL.
/// Returns a default Unknown status if the feed hasn't been checked yet.
pub fn get_feed_health(&self, url: &str) -> FeedHealth {
self.feed_health.get(url).cloned().unwrap_or_default()
}
pub fn toggle_read_status(&mut self) {
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
if let Some(item) = self.current_feed_content.get(actual_index) {
if self.read_items.contains(&item.id) {
self.read_items.remove(&item.id);
debug!("Marked item as unread: {}", item.title);
} else {
self.read_items.insert(item.id.clone());
debug!("Marked item as read: {}", item.title);
}
self.save_state().unwrap_or_else(|e| {
error!("Failed to save read status: {}", e);
});
}
}
}
}
/// Marks the currently selected item as read if mark_read_on_scroll is enabled.
/// This is called when navigating away from an item (scrolling to the next one).
/// Does not save state immediately to avoid excessive disk writes during rapid scrolling;
/// state will be saved on quit or next explicit save action.
fn mark_current_as_read_on_scroll(&mut self) {
if !self.config.mark_read_on_scroll {
return;
}
// Only mark read in FeedList or Favorites mode
if self.page_mode != PageMode::FeedList && self.page_mode != PageMode::Favorites {
return;
}
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
if let Some(item) = self.current_feed_content.get(actual_index) {
if !self.read_items.contains(&item.id) {
self.read_items.insert(item.id.clone());
debug!("Auto-marked item as read on scroll: {}", item.title);
}
}
}
}
}
fn save_state(&self) -> AppResult<()> {
let saved = SavedState {
feeds: self.rss_feeds.clone(),
read_items: self.read_items.clone(),
favorites: self.favorites.clone(),
};
let content = serde_json::to_string_pretty(&saved)?;
fs::write(&self.save_path, content)?;
debug!(
"Saved {} feeds, {} read items, and {} favorites to {}",
self.rss_feeds.len(),
self.read_items.len(),
self.favorites.len(),
self.save_path.display()
);
Ok(())
}
fn load_feeds(&mut self) -> AppResult<()> {
if self.save_path.exists() {
let content = match fs::read_to_string(&self.save_path) {
Ok(c) => c,
Err(e) => {
error!("Failed to read feeds file: {}. Clearing corrupted data.", e);
if let Err(e) = fs::remove_file(&self.save_path) {
error!("Failed to remove corrupted file: {}", e);
}
self.error_message = Some(
"Feeds data was corrupted and has been cleared. Starting fresh."
.to_string(),
);
return Ok(());
}
};
// Try to parse with new format first (Vec<FeedInfo>)
match serde_json::from_str::<SavedState>(&content) {
Ok(saved) => {
self.rss_feeds = saved.feeds;
self.read_items = saved.read_items;
self.favorites = saved.favorites;
debug!(
"Loaded {} feeds and {} favorites from {}",
self.rss_feeds.len(),
self.favorites.len(),
self.save_path.display()
);
}
Err(_) => {
// Try parsing middle format (with favorites, but Vec<String> for feeds)
#[derive(Debug, Serialize, Deserialize)]
struct MiddleSavedState {
feeds: Vec<String>,
read_items: HashSet<String>,
favorites: HashSet<String>,
}
if let Ok(middle_saved) = serde_json::from_str::<MiddleSavedState>(&content) {
// Convert Vec<String> to Vec<FeedInfo> using URL as title
self.rss_feeds = middle_saved
.feeds
.into_iter()
.map(|url| FeedInfo {
title: url.clone(),
url,
category: None,
})
.collect();
self.read_items = middle_saved.read_items;
self.favorites = middle_saved.favorites;
debug!(
"Loaded {} feeds from middle format state file {}",
self.rss_feeds.len(),
self.save_path.display()
);
} else {
// Try parsing oldest format (without favorites)
#[derive(Debug, Serialize, Deserialize)]
struct OldSavedState {
feeds: Vec<String>,
read_items: HashSet<String>,
}
if let Ok(old_saved) = serde_json::from_str::<OldSavedState>(&content) {
// Convert Vec<String> to Vec<FeedInfo> using URL as title
self.rss_feeds = old_saved
.feeds
.into_iter()
.map(|url| FeedInfo {
title: url.clone(),
url,
category: None,
})
.collect();
self.read_items = old_saved.read_items;
self.favorites = HashSet::new(); // Initialize empty favorites
debug!(
"Loaded {} feeds from old format state file {}",
self.rss_feeds.len(),
self.save_path.display()
);
} else {
// All parsing attempts failed - clear the corrupted file and start fresh
error!(
"Failed to parse feeds file: {}. Clearing corrupted data.",
self.save_path.display()
);
if let Err(e) = fs::remove_file(&self.save_path) {
error!("Failed to remove corrupted file: {}", e);
}
self.error_message = Some(
"Feeds data was corrupted and has been cleared. Starting fresh."
.to_string(),
);
}
}
}
}
}
Ok(())
}
pub fn toggle_feed_manager(&mut self) {
match self.page_mode {
PageMode::FeedList => {
self.page_mode = PageMode::FeedManager;
self.selected_index = Some(0);
self.scroll = 0; // Reset scroll position
}
PageMode::FeedManager => {
self.page_mode = PageMode::FeedList;
// Reset selection and trigger refresh
self.selected_index = Some(0);
self.scroll = 0; // Reset scroll position
}
PageMode::Favorites => {
self.page_mode = PageMode::FeedManager;
self.selected_index = Some(0);
self.scroll = 0; // Reset scroll position
}
}
}
pub fn select_previous(&mut self) {
self.status_message = None; // Clear status on navigation
if let Some(current) = self.selected_index {
let len = match self.page_mode {
PageMode::FeedList | PageMode::Favorites => self.visible_item_count(),
PageMode::FeedManager => self.rss_feeds.len(),
};
if len == 0 {
return;
}
self.selected_index = Some(if current > 0 { current - 1 } else { len - 1 });
self.ensure_selection_visible();
}
}
pub fn select_next(&mut self) {
self.status_message = None; // Clear status on navigation
if let Some(current) = self.selected_index {
let len = match self.page_mode {
PageMode::FeedList | PageMode::Favorites => self.visible_item_count(),
PageMode::FeedManager => self.rss_feeds.len(),
};
if len == 0 {
return;
}
// Mark current item as read before moving to the next (if enabled)
self.mark_current_as_read_on_scroll();
self.selected_index = Some((current + 1) % len);
self.ensure_selection_visible();
}
}
/// Calculates the number of visible items based on terminal height and page mode.
/// This accounts for UI chrome (title bar, command bar, borders, etc.)
pub fn items_per_page(&self) -> usize {
// Terminal layout: 3 lines title + 3 lines command bar = 6 lines of chrome
// Content area has 2 lines for borders
let content_height = self.terminal_height.saturating_sub(8) as usize;
match self.page_mode {
// FeedList/Favorites: each item takes 3 lines (title, description snippet, metadata)
PageMode::FeedList | PageMode::Favorites => (content_height / 3).max(1),
// FeedManager: each item takes 1 line, minus 1 for status line
PageMode::FeedManager => content_height.saturating_sub(1).max(1),
}
}
/// Ensures that the currently selected item is visible in the view
pub fn ensure_selection_visible(&mut self) {
if let Some(index) = self.selected_index {
// Make sure selection is not above the current scroll position
if (index as u16) < self.scroll {
self.scroll = index as u16;
}
// Calculate the number of visible items in the current view
let items_per_page = self.items_per_page();
// Make sure selection is not below the visible area
if index >= (self.scroll as usize + items_per_page) {
self.scroll = (index - items_per_page + 1) as u16;
}
}
}
pub fn start_adding(&mut self) {
self.input_mode = InputMode::Adding;
self.input_buffer.clear();
}
pub fn cancel_adding(&mut self) {
self.input_mode = InputMode::Normal;
self.input_buffer.clear();
self.clear_error();
}
pub fn toggle_help(&mut self) {
match self.input_mode {
InputMode::Help => self.input_mode = InputMode::Normal,
_ => self.input_mode = InputMode::Help,
}
}
pub fn start_deleting(&mut self) {
if !self.rss_feeds.is_empty() {
self.input_mode = InputMode::Deleting;
self.selected_index = Some(0);
}
}
pub fn cancel_deleting(&mut self) {
self.input_mode = InputMode::Normal;
}
pub fn delete_feed(&mut self, index: usize) {
if index < self.rss_feeds.len() {
self.rss_feeds.remove(index);
self.selected_index = None;
self.current_feed_content.clear();
if let Err(e) = self.save_feeds() {
error!("Failed to save feeds after deletion: {}", e);
self.error_message = Some("Failed to save feeds".to_string());
}
}
}
/// Exports all feed URLs to the clipboard using OSC 52, one URL per line
pub fn export_feeds_to_clipboard(&mut self) {
if self.rss_feeds.is_empty() {
self.error_message = Some("No feeds to export".to_string());
return;
}
let feed_list: String = self
.rss_feeds
.iter()
.map(|f| f.url.as_str())
.collect::<Vec<_>>()
.join("\n");
match copy_to_clipboard_osc52(&feed_list) {
Ok(()) => {
info!("Exported {} feeds to clipboard", self.rss_feeds.len());
self.status_message = Some(format!(
"Exported {} feeds to clipboard",
self.rss_feeds.len()
));
}
Err(e) => {
error!("Failed to copy to clipboard: {}", e);
self.error_message = Some(format!("Failed to copy to clipboard: {}", e));
}
}
}
/// Starts the import mode
pub fn start_importing(&mut self) {
self.input_mode = InputMode::Importing;
self.input_buffer.clear();
self.import_result = None;
// Try to pre-fill from clipboard
if let Ok(mut clipboard) = arboard::Clipboard::new() {
if let Ok(text) = clipboard.get_text() {
self.input_buffer = text;
}
}
}
/// Cancels the import mode
pub fn cancel_importing(&mut self) {
self.input_mode = InputMode::Normal;
self.input_buffer.clear();
self.import_result = None;
self.clear_error();
}
/// Exports feeds to OPML format and saves to a file
/// Returns the path where the file was saved
pub fn export_opml(&mut self) -> AppResult<PathBuf> {
if self.rss_feeds.is_empty() {
self.error_message = Some("No feeds to export".to_string());
return Err("No feeds to export".into());
}
let opml_content = self.generate_opml()?;
// Save to the config directory
let mut path = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
fs::create_dir_all(&path)?;
path.push("feeds.opml");
fs::write(&path, opml_content)?;
info!(
"Exported {} feeds to OPML: {}",
self.rss_feeds.len(),
path.display()
);
self.error_message = Some(format!(
"Exported {} feeds to {}",
self.rss_feeds.len(),
path.display()
));
Ok(path)
}
/// Generates OPML XML content from current feeds
fn generate_opml(&self) -> AppResult<String> {
let mut writer = Writer::new(Cursor::new(Vec::new()));
// XML declaration
writer.write_event(Event::Decl(BytesDecl::new("1.0", Some("UTF-8"), None)))?;
// OPML root element
let mut opml = BytesStart::new("opml");
opml.push_attribute(("version", "2.0"));
writer.write_event(Event::Start(opml))?;
// Head section
writer.write_event(Event::Start(BytesStart::new("head")))?;
writer.write_event(Event::Start(BytesStart::new("title")))?;
writer.write_event(Event::Text(BytesText::new("Reedy RSS Feeds")))?;
writer.write_event(Event::End(BytesEnd::new("title")))?;
writer.write_event(Event::End(BytesEnd::new("head")))?;
// Body section
writer.write_event(Event::Start(BytesStart::new("body")))?;
// Group feeds by category
let feeds_by_category = self.get_feeds_by_category();
for (category, feeds) in feeds_by_category {
match category {
Some(cat_name) => {
// Create a category outline
let mut cat_outline = BytesStart::new("outline");
cat_outline.push_attribute(("text", cat_name.as_str()));
cat_outline.push_attribute(("title", cat_name.as_str()));
writer.write_event(Event::Start(cat_outline))?;
// Write feeds in this category
for feed in feeds {
let mut outline = BytesStart::new("outline");
outline.push_attribute(("type", "rss"));
outline.push_attribute(("text", feed.title.as_str()));
outline.push_attribute(("title", feed.title.as_str()));
outline.push_attribute(("xmlUrl", feed.url.as_str()));
writer.write_event(Event::Empty(outline))?;
}
writer.write_event(Event::End(BytesEnd::new("outline")))?;
}
None => {
// Write uncategorized feeds at the top level
for feed in feeds {
let mut outline = BytesStart::new("outline");
outline.push_attribute(("type", "rss"));
outline.push_attribute(("text", feed.title.as_str()));
outline.push_attribute(("title", feed.title.as_str()));
outline.push_attribute(("xmlUrl", feed.url.as_str()));
writer.write_event(Event::Empty(outline))?;
}
}
}
}
writer.write_event(Event::End(BytesEnd::new("body")))?;
writer.write_event(Event::End(BytesEnd::new("opml")))?;
let result = writer.into_inner().into_inner();
Ok(String::from_utf8(result)?)
}
/// Imports feeds from an OPML file
pub async fn import_opml(&mut self, path: &PathBuf) -> AppResult<()> {
let content = fs::read_to_string(path)?;
self.parse_and_import_opml(&content).await
}
/// Imports feeds from OPML content string
pub async fn import_opml_content(&mut self, content: &str) -> AppResult<()> {
self.parse_and_import_opml(content).await
}
/// Parses OPML content and imports feeds
async fn parse_and_import_opml(&mut self, content: &str) -> AppResult<()> {
let mut reader = Reader::from_str(content);
reader.config_mut().trim_text(true);
let mut added = 0;
let mut skipped_duplicate = 0;
let mut category_stack: Vec<String> = Vec::new();
loop {
match reader.read_event() {
Ok(Event::Start(ref e)) if e.name().as_ref() == b"outline" => {
// This is a start tag (has children) - could be a category or a feed
let mut xml_url: Option<String> = None;
let mut title: Option<String> = None;
for attr in e.attributes().flatten() {
match attr.key.as_ref() {
b"xmlUrl" | b"xmlurl" => {
xml_url = Some(String::from_utf8_lossy(&attr.value).to_string());
}
b"text" | b"title" => {
if title.is_none() {
title = Some(String::from_utf8_lossy(&attr.value).to_string());
}
}
_ => {}
}
}
if xml_url.is_some() {
// It's a feed with a start tag (unusual but valid)
let url = xml_url.unwrap();
if self.rss_feeds.iter().any(|f| f.url == url) {
skipped_duplicate += 1;
} else {
let feed_title = title
.filter(|t| !t.is_empty())
.unwrap_or_else(|| url.clone());
let category = category_stack.last().cloned();
info!("Adding feed from OPML: {} ({})", feed_title, url);
self.rss_feeds.push(FeedInfo {
url,
title: feed_title,
category,
});
added += 1;
}
} else if let Some(cat_name) = title {
// It's a category - push to stack
category_stack.push(cat_name);
}
}
Ok(Event::Empty(ref e)) if e.name().as_ref() == b"outline" => {
// Self-closing tag - this is a feed
let mut xml_url: Option<String> = None;
let mut title: Option<String> = None;
for attr in e.attributes().flatten() {
match attr.key.as_ref() {
b"xmlUrl" | b"xmlurl" => {
xml_url = Some(String::from_utf8_lossy(&attr.value).to_string());
}
b"text" | b"title" => {
if title.is_none() {
title = Some(String::from_utf8_lossy(&attr.value).to_string());
}
}
_ => {}
}
}
if let Some(url) = xml_url {
// Skip duplicates
if self.rss_feeds.iter().any(|f| f.url == url) {
skipped_duplicate += 1;
continue;
}
// Use the title from OPML or use the URL as fallback
let feed_title = title
.filter(|t| !t.is_empty())
.unwrap_or_else(|| url.clone());
let category = category_stack.last().cloned();
info!("Adding feed from OPML: {} ({})", feed_title, url);
self.rss_feeds.push(FeedInfo {
url,
title: feed_title,
category,
});
added += 1;
}
}
Ok(Event::End(ref e)) if e.name().as_ref() == b"outline" => {
// Exiting an outline - pop category if we have one
category_stack.pop();
}
Ok(Event::Eof) => break,
Err(e) => {
error!("Error parsing OPML: {}", e);
return Err(format!("Error parsing OPML: {}", e).into());
}
_ => {}
}
}
// Save if we added any feeds
if added > 0 {
self.save_feeds()?;
}
// Build result message
let mut result_parts = Vec::new();
if added > 0 {
result_parts.push(format!("{} added", added));
}
if skipped_duplicate > 0 {
result_parts.push(format!("{} duplicate", skipped_duplicate));
}
let result_msg = if result_parts.is_empty() {
"OPML Import: No feeds found".to_string()
} else {
format!("OPML Import: {}", result_parts.join(", "))
};
self.import_result = Some(result_msg.clone());
self.error_message = Some(result_msg);
Ok(())
}
/// Gets the default OPML file path for import
pub fn get_opml_path() -> PathBuf {
let mut path = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
path.push("feeds.opml");
path
}
/// Starts category setting mode for the currently selected feed
pub fn start_setting_category(&mut self) {
if self.selected_index.is_some() && !self.rss_feeds.is_empty() {
self.input_mode = InputMode::SettingCategory;
// Pre-fill with current category if it exists
if let Some(index) = self.selected_index {
if let Some(feed) = self.rss_feeds.get(index) {
self.input_buffer = feed.category.clone().unwrap_or_default();
}
}
}
}
/// Cancels category setting mode
pub fn cancel_setting_category(&mut self) {
self.input_mode = InputMode::Normal;
self.input_buffer.clear();
self.clear_error();
}
/// Sets the category for the currently selected feed
pub fn set_category(&mut self) {
if let Some(index) = self.selected_index {
if let Some(feed) = self.rss_feeds.get_mut(index) {
let category = self.input_buffer.trim().to_string();
if category.is_empty() {
feed.category = None;
info!("Cleared category for feed: {}", feed.title);
} else {
feed.category = Some(category.clone());
info!("Set category '{}' for feed: {}", category, feed.title);
}
if let Err(e) = self.save_feeds() {
error!("Failed to save feeds after setting category: {}", e);
self.error_message = Some("Failed to save category".to_string());
}
}
}
self.input_mode = InputMode::Normal;
self.input_buffer.clear();
}
/// Returns a sorted list of unique categories used by feeds
pub fn get_categories(&self) -> Vec<String> {
let mut categories: Vec<String> = self
.rss_feeds
.iter()
.filter_map(|f| f.category.clone())
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect();
categories.sort();
categories
}
/// Returns feeds grouped by category. Uncategorized feeds are grouped under None.
pub fn get_feeds_by_category(&self) -> Vec<(Option<String>, Vec<&FeedInfo>)> {
use std::collections::BTreeMap;
let mut grouped: BTreeMap<Option<String>, Vec<&FeedInfo>> = BTreeMap::new();
for feed in &self.rss_feeds {
grouped.entry(feed.category.clone()).or_default().push(feed);
}
// Convert to Vec and sort: None (uncategorized) first, then alphabetically by category
let mut result: Vec<(Option<String>, Vec<&FeedInfo>)> = grouped.into_iter().collect();
result.sort_by(|a, b| match (&a.0, &b.0) {
(None, None) => std::cmp::Ordering::Equal,
(None, Some(_)) => std::cmp::Ordering::Less,
(Some(_), None) => std::cmp::Ordering::Greater,
(Some(a), Some(b)) => a.cmp(b),
});
result
}
/// Imports feeds from the input buffer (one URL per line)
pub async fn import_feeds(&mut self) -> AppResult<()> {
let urls: Vec<String> = self
.input_buffer
.lines()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if urls.is_empty() {
self.error_message = Some("No URLs to import".to_string());
return Ok(());
}
let mut added = 0;
let mut skipped_duplicate = 0;
let mut skipped_invalid = 0;
for url in urls {
// Skip duplicates
if self.rss_feeds.iter().any(|f| f.url == url) {
skipped_duplicate += 1;
continue;
}
// Validate the URL and get title
match Self::validate_and_get_feed_title(&url, self.config.http_timeout_secs).await {
Ok(Some(title)) => {
info!("Successfully validated and added feed: {} ({})", title, url);
self.rss_feeds.push(FeedInfo {
url,
title,
category: None,
});
added += 1;
}
Ok(None) => {
debug!("Invalid RSS feed URL during import: {}", url);
skipped_invalid += 1;
}
Err(e) => {
debug!("Error validating feed during import: {} - {}", url, e);
skipped_invalid += 1;
}
}
}
// Save if we added any feeds
if added > 0 {
self.save_feeds()?;
}
// Build result message
let mut result_parts = Vec::new();
if added > 0 {
result_parts.push(format!("{} added", added));
}
if skipped_duplicate > 0 {
result_parts.push(format!("{} duplicate", skipped_duplicate));
}
if skipped_invalid > 0 {
result_parts.push(format!("{} invalid", skipped_invalid));
}
let result_msg = format!("Import: {}", result_parts.join(", "));
self.import_result = Some(result_msg.clone());
self.error_message = Some(result_msg);
self.input_mode = InputMode::Normal;
self.input_buffer.clear();
Ok(())
}
/// Validates a URL as a valid RSS/Atom feed and returns its title if valid.
/// Returns Ok(Some(title)) if valid, Ok(None) if invalid, or Err on failure.
pub async fn validate_and_get_feed_title(
url: &str,
timeout_secs: u64,
) -> AppResult<Option<String>> {
// First validate URL format
let url = reqwest::Url::parse(url)?;
if url.scheme() != "http" && url.scheme() != "https" {
return Ok(None);
}
// Try to fetch and parse the feed
let client = create_http_client(timeout_secs);
match client.get(url.as_str()).send().await {
Ok(response) => {
// Check for HTTP errors before trying to parse
if !response.status().is_success() {
error!(
"HTTP error {} when fetching feed: {}",
response.status(),
url
);
return Ok(None);
}
let bytes = response.bytes().await?;
// Try RSS first
if let Ok(channel) = Channel::read_from(&bytes[..]) {
let title = channel.title().to_string();
return Ok(Some(if title.is_empty() {
url.to_string()
} else {
title
}));
}
// Try Atom if RSS fails
if let Ok(feed) = AtomFeed::read_from(&bytes[..]) {
let title = feed.title().value.clone();
return Ok(Some(if title.is_empty() {
url.to_string()
} else {
title
}));
}
Ok(None)
}
Err(_) => Ok(None),
}
}
pub async fn add_feed(&mut self) -> AppResult<()> {
debug!("Attempting to add feed: {}", self.input_buffer);
match Self::validate_and_get_feed_title(&self.input_buffer, self.config.http_timeout_secs)
.await
{
Ok(Some(title)) => {
info!(
"Successfully validated feed: {} ({})",
title, self.input_buffer
);
self.rss_feeds.push(FeedInfo {
url: self.input_buffer.clone(),
title,
category: None,
});
self.save_feeds()?;
self.input_buffer.clear();
self.input_mode = InputMode::Normal;
Ok(())
}
Ok(None) => {
error!("Invalid RSS feed URL: {}", self.input_buffer);
self.error_message = Some("Invalid RSS feed URL".to_string());
Ok(())
}
Err(e) => {
error!("Error validating feed: {}", e);
self.error_message = Some(format!("Error: {}", e));
Ok(())
}
}
}
pub async fn select_feed(&mut self, index: usize) -> AppResult<()> {
if index < self.rss_feeds.len() {
debug!("Loading feed content from index {}", index);
self.selected_index = Some(index);
self.load_feed_content().await?;
}
Ok(())
}
pub async fn load_feed_content(&mut self) -> AppResult<()> {
if let Some(index) = self.selected_index {
if let Some(feed_info) = self.rss_feeds.get(index) {
let url = &feed_info.url;
let feed_title = &feed_info.title;
debug!("Checking cache for URL: {}", url);
// Try to load from cache first
if let Some(cached_content) = self.load_feed_cache(url) {
debug!("Using cached content for {}", url);
self.current_feed_content = cached_content;
return Ok(());
}
debug!("Fetching feed content from URL: {}", url);
let client = create_http_client(self.config.http_timeout_secs);
let response = client.get(url.as_str()).send().await?;
// Check for HTTP errors
if !response.status().is_success() {
self.error_message = Some(format!(
"HTTP error {}: {}",
response.status(),
response
.status()
.canonical_reason()
.unwrap_or("Unknown error")
));
return Ok(());
}
let content = response.bytes().await?;
let feed_title_clone = feed_title.clone();
let mut feed_items: Vec<FeedItem> = match Channel::read_from(&content[..]) {
Ok(channel) => {
// Handle RSS feed
channel
.items()
.iter()
.map(|item| {
let description = item
.description()
.unwrap_or("No description")
.replace(|c| ['\n', '\r'].contains(&c), " ");
let clean_description =
html2text::from_read(description.as_bytes(), 80);
let published = item.pub_date().and_then(|date| {
DateTime::parse_from_rfc2822(date).ok().map(|dt| dt.into())
});
FeedItem {
title: format!(
"{} | {}",
item.title().unwrap_or("No title"),
feed_title_clone
),
description: clean_description,
link: item.link().unwrap_or("").to_string(),
published,
id: Self::create_item_id(
item.title().unwrap_or("No title"),
published,
url,
),
feed_url: url.clone(),
}
})
.collect()
}
Err(_) => {
// Try parsing as Atom feed
match AtomFeed::read_from(&content[..]) {
Ok(feed) => feed
.entries()
.iter()
.map(|entry| {
let description = entry
.content()
.and_then(|c| c.value.clone())
.or_else(|| entry.summary().map(|s| s.value.clone()))
.unwrap_or_else(|| "No description".to_string());
let clean_description =
html2text::from_read(description.as_bytes(), 80);
let published = entry
.published()
.or_else(|| Some(entry.updated()))
.map(|date| date.to_owned().into());
FeedItem {
title: format!(
"{} | {}",
entry.title().value,
feed_title_clone
),
description: clean_description,
link: entry
.links()
.first()
.map(|l| l.href().to_string())
.unwrap_or_default(),
published,
id: Self::create_item_id(
&entry.title().value,
published,
url,
),
feed_url: url.clone(),
}
})
.collect(),
Err(e) => {
error!("Failed to parse feed as either RSS or Atom: {}", e);
return Err(Box::new(e));
}
}
}
};
// Sort by date, newest first
feed_items.sort_by(|a, b| b.published.cmp(&a.published));
// Save to cache
if let Err(e) = self.save_feed_cache(url, &feed_items) {
error!("Failed to cache feed content: {}", e);
}
self.current_feed_content = feed_items;
Ok(())
} else {
debug!("No feed URL found at index {}", index);
Ok(())
}
} else {
debug!("No feed selected");
Ok(())
}
}
fn save_feeds(&self) -> AppResult<()> {
let saved = SavedState {
feeds: self.rss_feeds.clone(),
read_items: self.read_items.clone(),
favorites: self.favorites.clone(),
};
let content = serde_json::to_string_pretty(&saved)?;
fs::write(&self.save_path, content)?;
debug!(
"Saved {} feeds, {} read items, and {} favorites to {}",
self.rss_feeds.len(),
self.read_items.len(),
self.favorites.len(),
self.save_path.display()
);
Ok(())
}
pub fn open_selected_feed(&self) {
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
if let Some(item) = self.current_feed_content.get(actual_index) {
if !item.link.is_empty() {
let _ = open::that(&item.link);
}
}
}
}
}
/// Copies the selected item's link to the clipboard using OSC 52
pub fn copy_selected_link(&mut self) {
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
if let Some(item) = self.current_feed_content.get(actual_index) {
if !item.link.is_empty() {
match copy_to_clipboard_osc52(&item.link) {
Ok(()) => {
self.status_message = Some("Link copied!".to_string());
debug!("Copied link to clipboard: {}", item.link);
}
Err(e) => {
error!("Failed to copy to clipboard: {}", e);
self.error_message = Some(format!("Failed to copy: {}", e));
}
}
}
}
}
}
}
pub fn clear_error(&mut self) {
self.error_message = None;
}
/// Clears both status and error messages
pub fn clear_messages(&mut self) {
self.status_message = None;
self.error_message = None;
}
pub fn scroll_up(&mut self) {
if self.scroll > 0 {
self.scroll = self.scroll.saturating_sub(1);
}
}
pub fn scroll_down(&mut self) {
let max_scroll = match self.page_mode {
PageMode::FeedList | PageMode::Favorites => {
if self.current_feed_content.is_empty() {
0
} else {
self.current_feed_content.len().saturating_sub(1)
}
}
PageMode::FeedManager => {
if self.rss_feeds.is_empty() {
0
} else {
self.rss_feeds.len().saturating_sub(1)
}
}
};
if (self.scroll as usize) < max_scroll {
self.scroll += 1;
}
}
pub fn page_up(&mut self) {
let page_size = self.items_per_page() as u16;
// Scroll up by page size
self.scroll = self.scroll.saturating_sub(page_size);
// Update selection to follow scrolling
if let Some(index) = self.selected_index {
if (index as u16) >= self.scroll + page_size {
self.selected_index = Some(self.scroll as usize);
}
}
}
pub fn page_down(&mut self) {
let page_size = self.items_per_page();
// Get the appropriate list length based on page mode
let list_len = match self.page_mode {
PageMode::FeedList | PageMode::Favorites => self.current_feed_content.len(),
PageMode::FeedManager => self.rss_feeds.len(),
};
// Calculate maximum possible scroll value
let max_scroll = if list_len == 0 {
0
} else {
list_len
.saturating_sub(1)
.saturating_sub(page_size.saturating_sub(1))
};
// Calculate new scroll position, capped at maximum scroll
let new_scroll = (self.scroll as usize + page_size).min(max_scroll);
self.scroll = new_scroll as u16;
// If the selected index is now above the visible area, update it
if let Some(index) = self.selected_index {
if index < new_scroll {
self.selected_index = Some(new_scroll);
}
}
}
/// Scrolls to the top of the feed and selects the first item
pub fn scroll_to_top(&mut self) {
self.scroll = 0;
// Select the first item if there are any items
match self.page_mode {
PageMode::FeedList | PageMode::Favorites => {
if !self.current_feed_content.is_empty() {
self.selected_index = Some(0);
}
}
PageMode::FeedManager => {
if !self.rss_feeds.is_empty() {
self.selected_index = Some(0);
}
}
}
}
/// Scrolls to the bottom of the feed and selects the last item
pub fn scroll_to_bottom(&mut self) {
let len = match self.page_mode {
PageMode::FeedList | PageMode::Favorites => self.visible_item_count(),
PageMode::FeedManager => self.rss_feeds.len(),
};
if len == 0 {
return;
}
// Select the last item
self.selected_index = Some(len - 1);
// Ensure the selection is visible by scrolling to show it
self.ensure_selection_visible();
}
/// Opens the article preview pane for the currently selected item
pub fn open_preview(&mut self) {
if let Some(visible_index) = self.selected_index {
if self.get_actual_index(visible_index).is_some() {
self.input_mode = InputMode::Preview;
self.preview_scroll = 0;
}
}
}
/// Closes the article preview pane
pub fn close_preview(&mut self) {
self.input_mode = InputMode::Normal;
self.preview_scroll = 0;
}
/// Scrolls the preview pane up by one line
pub fn preview_scroll_up(&mut self) {
self.preview_scroll = self.preview_scroll.saturating_sub(1);
}
/// Scrolls the preview pane down by one line
pub fn preview_scroll_down(&mut self) {
self.preview_scroll = self.preview_scroll.saturating_add(1);
}
/// Scrolls the preview pane up by a page
pub fn preview_page_up(&mut self) {
let page_size = self.terminal_height.saturating_sub(10);
self.preview_scroll = self.preview_scroll.saturating_sub(page_size);
}
/// Scrolls the preview pane down by a page
pub fn preview_page_down(&mut self) {
let page_size = self.terminal_height.saturating_sub(10);
self.preview_scroll = self.preview_scroll.saturating_add(page_size);
}
/// Gets the currently selected feed item for preview
pub fn get_preview_item(&self) -> Option<&FeedItem> {
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
return self.current_feed_content.get(actual_index);
}
}
None
}
/// Formats a feed item as markdown for export
fn format_article_markdown(&self, item: &FeedItem) -> String {
let mut output = String::new();
// Title
output.push_str(&format!("# {}\n\n", item.title));
// Metadata
if let Some(published) = item.published {
if let Ok(duration) = published.duration_since(SystemTime::UNIX_EPOCH) {
let secs = duration.as_secs() as i64;
if let Some(dt) = chrono::DateTime::from_timestamp(secs, 0) {
output.push_str(&format!("**Date:** {}\n\n", dt.format("%Y-%m-%d %H:%M")));
}
}
}
if !item.link.is_empty() {
output.push_str(&format!("**Link:** {}\n\n", item.link));
}
// Status
let read_status = if self.read_items.contains(&item.id) {
"Read"
} else {
"Unread"
};
let fav_status = if self.favorites.contains(&item.id) {
"★ Favorited"
} else {
""
};
if !fav_status.is_empty() {
output.push_str(&format!("**Status:** {} | {}\n\n", read_status, fav_status));
} else {
output.push_str(&format!("**Status:** {}\n\n", read_status));
}
output.push_str("---\n\n");
// Content - convert HTML to plain text
let plain_text = html2text::from_read(item.description.as_bytes(), 80);
output.push_str(&plain_text);
output
}
/// Exports the currently selected article to clipboard using OSC 52
pub fn export_article_to_clipboard(&mut self) {
let item = if let Some(item) = self.get_preview_item() {
item.clone()
} else {
self.error_message = Some("No article selected".to_string());
return;
};
let content = self.format_article_markdown(&item);
match copy_to_clipboard_osc52(&content) {
Ok(()) => {
info!("Exported article to clipboard: {}", item.title);
self.status_message = Some("Article copied!".to_string());
}
Err(e) => {
error!("Failed to copy to clipboard: {}", e);
self.error_message = Some(format!("Failed to copy: {}", e));
}
}
}
/// Exports the currently selected article to a file
pub fn export_article_to_file(&mut self) {
let item = if let Some(item) = self.get_preview_item() {
item.clone()
} else {
self.error_message = Some("No article selected".to_string());
return;
};
let content = self.format_article_markdown(&item);
// Create a safe filename from the title
let safe_title: String = item
.title
.chars()
.take(50)
.map(|c| {
if c.is_alphanumeric() || c == ' ' || c == '-' {
c
} else {
'_'
}
})
.collect::<String>()
.trim()
.replace(' ', "_");
// Get export directory
let mut path = dirs::data_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
path.push("exports");
if let Err(e) = fs::create_dir_all(&path) {
error!("Failed to create export directory: {}", e);
self.error_message = Some(format!("Failed to create export directory: {}", e));
return;
}
// Add timestamp to filename to avoid collisions
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
path.push(format!("{}_{}.md", safe_title, timestamp));
match fs::write(&path, content) {
Ok(()) => {
info!("Exported article to: {}", path.display());
self.error_message = Some(format!("Saved to: {}", path.display()));
}
Err(e) => {
error!("Failed to write file: {}", e);
self.error_message = Some(format!("Failed to save article: {}", e));
}
}
}
/// Enters vi-style command mode (triggered by ':')
pub fn start_command_mode(&mut self) {
self.input_mode = InputMode::Command;
self.command_buffer.clear();
}
/// Cancels command mode without executing
pub fn cancel_command_mode(&mut self) {
self.input_mode = InputMode::Normal;
self.command_buffer.clear();
}
/// Executes the current command buffer and returns to normal mode.
/// Returns Ok(true) if the command was executed successfully,
/// Ok(false) if the command was not recognized,
/// or an error if execution failed.
pub fn execute_command(&mut self) -> AppResult<bool> {
let command = self.command_buffer.trim().to_lowercase();
self.input_mode = InputMode::Normal;
self.command_buffer.clear();
match command.as_str() {
// Quit commands
"q" | "quit" => {
self.quit();
Ok(true)
}
// Write/save commands
"w" | "write" | "save" => {
self.save_state()?;
self.error_message = Some("State saved".to_string());
Ok(true)
}
// Write and quit
"wq" | "x" => {
self.save_state()?;
self.quit();
Ok(true)
}
// Force quit (without save - but we always save state anyway)
"q!" => {
self.quit();
Ok(true)
}
// Refresh feeds
"refresh" | "r" => {
// Set a flag to indicate refresh is needed (actual refresh is async)
self.auto_refresh_pending = true;
Ok(true)
}
// Help
"help" | "h" => {
self.toggle_help();
Ok(true)
}
// Open feed manager
"feeds" | "manage" => {
self.toggle_feed_manager();
Ok(true)
}
// Toggle favorites view
"favorites" | "fav" => {
// Return false to indicate async action needed
// The handler will call toggle_favorites_page().await
self.error_message = Some("__toggle_favorites__".to_string());
Ok(true)
}
// Mark all as read
"read" | "markread" => {
self.mark_all_as_read();
Ok(true)
}
// Scroll to top
"0" | "top" | "gg" => {
self.scroll_to_top();
Ok(true)
}
// Scroll to bottom
"$" | "bottom" => {
self.scroll_to_bottom();
Ok(true)
}
// Empty command - just cancel
"" => Ok(true),
// Unknown command
_ => {
self.error_message = Some(format!("Unknown command: {}", command));
Ok(false)
}
}
}
/// Starts search mode
pub fn start_search(&mut self) {
self.input_mode = InputMode::Searching;
self.search_query.clear();
self.filtered_indices = None;
}
/// Cancels search mode and clears the filter
pub fn cancel_search(&mut self) {
self.input_mode = InputMode::Normal;
self.search_query.clear();
self.filtered_indices = None;
self.scroll = 0;
// Reset selection to first item if available
if !self.current_feed_content.is_empty() {
self.selected_index = Some(0);
}
}
/// Confirms the search and stays in filtered mode
pub fn confirm_search(&mut self) {
self.input_mode = InputMode::Normal;
// Keep the filter active, selection remains on current filtered item
}
/// Updates the search filter based on the current query
pub fn update_search_filter(&mut self) {
self.apply_filters();
}
/// Applies all active filters (search query and unread-only)
fn apply_filters(&mut self) {
let has_search = !self.search_query.is_empty();
let has_unread_filter = self.show_unread_only;
// If no filters active, clear filtered_indices
if !has_search && !has_unread_filter {
self.filtered_indices = None;
self.scroll = 0;
if !self.current_feed_content.is_empty() {
self.selected_index = Some(0);
}
return;
}
let query_lower = self.search_query.to_lowercase();
let filtered: Vec<usize> = self
.current_feed_content
.iter()
.enumerate()
.filter(|(_, item)| {
// Apply search filter if active
let matches_search = !has_search
|| item.title.to_lowercase().contains(&query_lower)
|| item.description.to_lowercase().contains(&query_lower);
// Apply unread filter if active
let matches_unread = !has_unread_filter || !self.read_items.contains(&item.id);
matches_search && matches_unread
})
.map(|(i, _)| i)
.collect();
self.scroll = 0;
if filtered.is_empty() {
self.selected_index = None;
} else {
self.selected_index = Some(0);
}
self.filtered_indices = Some(filtered);
}
/// Toggles the unread-only filter
pub fn toggle_unread_only(&mut self) {
self.show_unread_only = !self.show_unread_only;
self.apply_filters();
debug!(
"Toggled unread-only filter: {}",
if self.show_unread_only { "ON" } else { "OFF" }
);
}
/// Clears all filters (search and unread-only) when pressing Esc
pub fn clear_search(&mut self) {
self.search_query.clear();
self.show_unread_only = false;
self.apply_filters();
}
/// Returns the items to display based on the current filter
pub fn get_visible_items(&self) -> Vec<(usize, &FeedItem)> {
match &self.filtered_indices {
Some(indices) => indices
.iter()
.map(|&i| (i, &self.current_feed_content[i]))
.collect(),
None => self.current_feed_content.iter().enumerate().collect(),
}
}
/// Returns the number of visible items (filtered or all)
pub fn visible_item_count(&self) -> usize {
match &self.filtered_indices {
Some(indices) => indices.len(),
None => self.current_feed_content.len(),
}
}
/// Gets the actual index in current_feed_content for a visible index
pub fn get_actual_index(&self, visible_index: usize) -> Option<usize> {
match &self.filtered_indices {
Some(indices) => indices.get(visible_index).copied(),
None => {
if visible_index < self.current_feed_content.len() {
Some(visible_index)
} else {
None
}
}
}
}
fn get_cache_dir() -> PathBuf {
let mut path = dirs::cache_dir().unwrap_or_else(|| PathBuf::from("."));
path.push("reedy");
path.push("feed_cache");
if let Err(e) = fs::create_dir_all(&path) {
error!("Failed to create cache directory {:?}: {}", path, e);
}
path
}
fn get_cache_path(url: &str) -> PathBuf {
let mut path = Self::get_cache_dir();
// Create a filename from the URL (sanitized)
let filename = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, url);
path.push(filename);
path.set_extension("json");
path
}
fn save_feed_cache(&self, url: &str, content: &[FeedItem]) -> AppResult<()> {
let cache = CachedFeed {
url: url.to_string(),
content: content.to_vec(),
last_updated: SystemTime::now(),
};
let cache_path = Self::get_cache_path(url);
let content = serde_json::to_string_pretty(&cache)?;
fs::write(cache_path, content)?;
Ok(())
}
fn load_feed_cache(&self, url: &str) -> Option<Vec<FeedItem>> {
let cache_path = Self::get_cache_path(url);
if let Ok(content) = fs::read_to_string(&cache_path) {
match serde_json::from_str::<CachedFeed>(&content) {
Ok(cache) => {
// Check if cache is within the configured duration
let cache_duration_secs = self.config.cache_duration_mins * 60;
if let Ok(duration) = cache.last_updated.elapsed() {
if duration.as_secs() < cache_duration_secs {
return Some(cache.content);
}
}
}
Err(e) => {
// Cache file is corrupted, delete it
error!(
"Failed to parse cache file for {}: {}. Removing corrupted cache.",
url, e
);
match fs::remove_file(&cache_path) {
Ok(_) => info!("Removed corrupted cache file for {}", url),
Err(e) => error!("Failed to remove corrupted cache file: {}", e),
}
}
}
}
None
}
/// Caches content from all configured RSS/Atom feeds.
///
/// This method iterates through all feed URLs and:
/// - Checks if a valid cache already exists for each feed
/// - Skips feeds that are already cached
/// - Fetches and parses new content for uncached feeds
/// - Attempts to parse feeds as both RSS and Atom formats
/// - Stores the parsed content in the local cache
///
/// The cached content includes feed items with their titles, descriptions,
/// links, and publication dates. Cache entries are stored in the application's
/// cache directory with base64-encoded URLs as filenames.
///
/// # Errors
///
/// While this method doesn't return errors, it logs error messages when:
/// - Network requests fail
/// - Feed parsing fails
/// - Cache operations fail
pub async fn cache_all_feeds(&mut self) {
for feed_info in self.rss_feeds.clone() {
debug!("Checking cache for URL: {}", feed_info.url);
// Skip if already cached
if self.load_feed_cache(&feed_info.url).is_some() {
debug!("Using existing cache for {}", feed_info.url);
continue;
}
debug!("Fetching feed content from URL: {}", feed_info.url);
let client = create_http_client(self.config.http_timeout_secs);
match client.get(&feed_info.url).send().await {
Ok(response) => {
// Check for HTTP errors
if !response.status().is_success() {
error!(
"HTTP error {} when fetching {}: {}",
response.status(),
feed_info.url,
response.status().canonical_reason().unwrap_or("Unknown")
);
continue;
}
if let Ok(content) = response.bytes().await {
// Try RSS first
let feed_items = match Channel::read_from(&content[..]) {
Ok(channel) => {
convert_rss_items(channel, &feed_info.title, &feed_info.url)
}
Err(_) => {
// Try Atom if RSS fails
match AtomFeed::read_from(&content[..]) {
Ok(feed) => {
convert_atom_items(feed, &feed_info.title, &feed_info.url)
}
Err(e) => {
error!("Failed to parse feed as either RSS or Atom: {}", e);
continue;
}
}
}
};
if let Err(e) = self.save_feed_cache(&feed_info.url, &feed_items) {
error!("Failed to cache feed content for {}: {}", feed_info.url, e);
}
}
}
Err(e) => {
error!("Failed to fetch feed {}: {}", feed_info.url, e);
}
}
}
}
/// Refreshes all RSS/Atom feeds by fetching their latest content.
///
/// This method:
/// - Fetches the latest content from all configured feed URLs
/// - Parses both RSS and Atom feed formats
/// - Caches the fetched content for each feed
/// - Combines all feed items into a single sorted list
/// - Updates the application's current feed content
/// - Tracks feed health status (healthy, slow, broken)
///
/// # Errors
///
/// Returns an error if:
/// - Network requests fail
/// - Feed parsing fails
/// - Cache operations fail
pub async fn refresh_all_feeds(&mut self) -> AppResult<()> {
use std::time::Instant;
let mut all_items = Vec::new();
let client = create_http_client(self.config.http_timeout_secs);
// Clone feed info to avoid borrow issues
let feeds: Vec<FeedInfo> = self.rss_feeds.clone();
for feed_info in feeds {
debug!("Refreshing feed: {}", feed_info.url);
// Record start time for health tracking
let start_time = Instant::now();
match client.get(&feed_info.url).send().await {
Ok(response) => {
let response_time_ms = start_time.elapsed().as_millis() as u64;
// Check for HTTP errors
if !response.status().is_success() {
error!(
"HTTP error {} when refreshing {}: {}",
response.status(),
feed_info.url,
response.status().canonical_reason().unwrap_or("Unknown")
);
let existing = self.feed_health.get(&feed_info.url);
let consecutive = existing.map(|h| h.consecutive_failures + 1).unwrap_or(1);
self.feed_health.insert(
feed_info.url.clone(),
FeedHealth {
status: FeedStatus::Broken,
last_success: existing.and_then(|h| h.last_success),
last_error: Some(format!("HTTP {}", response.status())),
last_response_time_ms: Some(response_time_ms),
consecutive_failures: consecutive,
},
);
continue;
}
match response.bytes().await {
Ok(content) => {
// Try RSS first
let parse_result = match Channel::read_from(&content[..]) {
Ok(channel) => Some(convert_rss_items(
channel,
&feed_info.title,
&feed_info.url,
)),
Err(_) => {
// Try Atom if RSS fails
match AtomFeed::read_from(&content[..]) {
Ok(feed) => Some(convert_atom_items(
feed,
&feed_info.title,
&feed_info.url,
)),
Err(_) => None,
}
}
};
match parse_result {
Some(feed_items) => {
// Save to cache
if let Err(e) =
self.save_feed_cache(&feed_info.url, &feed_items)
{
error!(
"Failed to cache feed content for {}: {}",
feed_info.url, e
);
}
all_items.extend(feed_items);
// Update health status - slow if > 5000ms, healthy otherwise
let status = if response_time_ms > 5000 {
FeedStatus::Slow
} else {
FeedStatus::Healthy
};
self.feed_health.insert(
feed_info.url.clone(),
FeedHealth {
status,
last_success: Some(SystemTime::now()),
last_response_time_ms: Some(response_time_ms),
last_error: None,
consecutive_failures: 0,
},
);
}
None => {
error!(
"Failed to parse feed as either RSS or Atom: {}",
feed_info.url
);
// Update health status as broken (parse error)
let health =
self.feed_health.entry(feed_info.url.clone()).or_default();
health.status = FeedStatus::Broken;
health.last_error = Some("Failed to parse feed".to_string());
health.last_response_time_ms = Some(response_time_ms);
health.consecutive_failures += 1;
}
}
}
Err(e) => {
error!("Failed to read response body for {}: {}", feed_info.url, e);
// Update health status as broken
let health = self.feed_health.entry(feed_info.url.clone()).or_default();
health.status = FeedStatus::Broken;
health.last_error = Some(format!("Read error: {}", e));
health.consecutive_failures += 1;
}
}
}
Err(e) => {
error!("Failed to fetch feed {}: {}", feed_info.url, e);
// Update health status as broken (network error)
let health = self.feed_health.entry(feed_info.url.clone()).or_default();
health.status = FeedStatus::Broken;
health.last_error = Some(format!("{}", e));
health.consecutive_failures += 1;
}
}
}
// Sort all items by date, newest first
all_items.sort_by(|a, b| b.published.cmp(&a.published));
// Check for new items and send notifications if enabled
if self.config.notifications_enabled {
let new_items: Vec<&FeedItem> = all_items
.iter()
.filter(|item| !self.seen_items.contains(&item.id))
.collect();
if !new_items.is_empty() {
self.send_new_articles_notification(&new_items);
}
}
// Update seen items with all current item IDs
for item in &all_items {
self.seen_items.insert(item.id.clone());
}
// Update the current feed content
self.current_feed_content = all_items;
Ok(())
}
/// Sends a desktop notification for new articles
fn send_new_articles_notification(&self, new_items: &[&FeedItem]) {
use notify_rust::Notification;
let count = new_items.len();
let summary = if count == 1 {
"1 new article".to_string()
} else {
format!("{} new articles", count)
};
// Build body with up to 3 article titles
let body: String = new_items
.iter()
.take(3)
.map(|item| format!("• {}", item.title))
.collect::<Vec<_>>()
.join("\n");
let body_with_more = if count > 3 {
format!("{}\n...and {} more", body, count - 3)
} else {
body
};
if let Err(e) = Notification::new()
.summary(&summary)
.body(&body_with_more)
.appname("Reedy")
.timeout(5000)
.show()
{
error!("Failed to send notification: {}", e);
} else {
info!("Sent notification for {} new article(s)", count);
}
}
pub fn mark_as_read(&mut self) {
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
if let Some(item) = self.current_feed_content.get(actual_index) {
if !self.read_items.contains(&item.id) {
self.read_items.insert(item.id.clone());
debug!("Marked item as read: {}", item.title);
self.save_state().unwrap_or_else(|e| {
error!("Failed to save read status: {}", e);
});
}
}
}
}
}
pub fn mark_all_as_read(&mut self) {
// Get items to mark - either filtered items or all items
let items_to_mark: Vec<String> = match &self.filtered_indices {
Some(indices) => indices
.iter()
.filter_map(|&i| self.current_feed_content.get(i))
.filter(|item| !self.read_items.contains(&item.id))
.map(|item| item.id.clone())
.collect(),
None => self
.current_feed_content
.iter()
.filter(|item| !self.read_items.contains(&item.id))
.map(|item| item.id.clone())
.collect(),
};
for id in items_to_mark {
self.read_items.insert(id.clone());
debug!("Marked item as read: {}", id);
}
self.save_state().unwrap_or_else(|e| {
error!("Failed to save read status: {}", e);
});
}
pub fn is_item_favorite(&self, item: &FeedItem) -> bool {
self.favorites.contains(&item.id)
}
pub fn toggle_favorite(&mut self) {
if let Some(visible_index) = self.selected_index {
if let Some(actual_index) = self.get_actual_index(visible_index) {
if let Some(item) = self.current_feed_content.get(actual_index) {
let was_favorite = self.favorites.contains(&item.id);
if was_favorite {
self.favorites.remove(&item.id);
debug!("Removed item from favorites: {}", item.title);
} else {
self.favorites.insert(item.id.clone());
debug!("Added item to favorites: {}", item.title);
}
self.save_state().unwrap_or_else(|e| {
error!("Failed to save favorites: {}", e);
});
// If we're in Favorites view and just unfavorited an item, remove it from the list
if was_favorite && self.page_mode == PageMode::Favorites {
self.current_feed_content.remove(actual_index);
// Rebuild filters to handle all active filter combinations correctly
self.apply_filters();
// Clamp selected index to valid range
let visible_count = self.visible_item_count();
if visible_count == 0 {
self.selected_index = None;
} else if visible_index >= visible_count {
self.selected_index = Some(visible_count - 1);
}
}
}
}
}
}
pub async fn toggle_favorites_page(&mut self) {
match self.page_mode {
PageMode::Favorites => {
self.page_mode = PageMode::FeedList;
// Reset scroll position
self.scroll = 0;
// Reset selection and reload all feeds like at startup
let _ = self.refresh_all_feeds().await;
self.cache_all_feeds().await;
// Load and combine all cached feed content
let mut all_items = Vec::new();
for feed_info in &self.rss_feeds {
if let Some(cached_items) = self.load_feed_cache(&feed_info.url) {
all_items.extend(cached_items);
}
}
// Sort all items by date, newest first
all_items.sort_by(|a, b| b.published.cmp(&a.published));
self.current_feed_content = all_items;
self.selected_index = Some(0);
}
_ => {
self.page_mode = PageMode::Favorites;
// Reset scroll position
self.scroll = 0;
// Filter current feed content to show only favorites
let favorites: Vec<FeedItem> = self
.current_feed_content
.iter()
.filter(|item| self.favorites.contains(&item.id))
.cloned()
.collect();
self.current_feed_content = favorites;
self.selected_index = if self.current_feed_content.is_empty() {
None
} else {
Some(0)
};
}
}
}
}
pub async fn fetch_feed(url: &str, timeout_secs: Option<u64>) -> AppResult<Vec<FeedItem>> {
debug!("Fetching feed from URL: {}", url);
let client = create_http_client(timeout_secs.unwrap_or(DEFAULT_HTTP_TIMEOUT_SECS));
let resp = client.get(url).send().await?;
// Check for HTTP errors
if !resp.status().is_success() {
return Err(format!(
"HTTP error {}: {}",
resp.status(),
resp.status().canonical_reason().unwrap_or("Unknown")
)
.into());
}
let response = resp.bytes().await?;
// Try parsing as RSS first
match Channel::read_from(&response[..]) {
Ok(channel) => {
debug!("Successfully parsed RSS feed");
Ok(convert_rss_items(channel, url, url))
}
Err(_) => {
// Try parsing as Atom
debug!("RSS parsing failed, attempting Atom format");
match AtomFeed::read_from(&response[..]) {
Ok(feed) => {
debug!("Successfully parsed Atom feed");
Ok(convert_atom_items(feed, url, url))
}
Err(e) => {
error!("Failed to parse feed as either RSS or Atom: {}", e);
Err(Box::new(e))
}
}
}
}
}
fn convert_rss_items(channel: Channel, feed_title: &str, feed_url: &str) -> Vec<FeedItem> {
channel
.items()
.iter()
.map(|item| {
let description = item
.description()
.unwrap_or("No description")
.replace(|c| ['\n', '\r'].contains(&c), " ");
let clean_description = html2text::from_read(description.as_bytes(), 80);
let published = item
.pub_date()
.and_then(|date| DateTime::parse_from_rfc2822(date).ok().map(|dt| dt.into()));
FeedItem {
title: format!("{} | {}", item.title().unwrap_or("No title"), feed_title),
description: clean_description,
link: item.link().unwrap_or("").to_string(),
published,
id: App::create_item_id(item.title().unwrap_or("No title"), published, feed_url),
feed_url: feed_url.to_string(),
}
})
.collect()
}
fn convert_atom_items(feed: AtomFeed, feed_title: &str, feed_url: &str) -> Vec<FeedItem> {
feed.entries()
.iter()
.map(|entry| {
let description = entry
.content()
.and_then(|c| c.value.clone())
.or_else(|| entry.summary().map(|s| s.value.clone()))
.unwrap_or_else(|| "No description".to_string());
let clean_description = html2text::from_read(description.as_bytes(), 80);
let published = entry
.published()
.or_else(|| Some(entry.updated()))
.map(|date| date.to_owned().into());
FeedItem {
title: format!("{} | {}", entry.title().value, feed_title),
description: clean_description,
link: entry
.links()
.first()
.map(|l| l.href().to_string())
.unwrap_or_default(),
published,
id: App::create_item_id(&entry.title().value, published, feed_url),
feed_url: feed_url.to_string(),
}
})
.collect()
}