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
use anyhow::Result;
use clap::{Parser, Subcommand};
use colored::*;
#[derive(Debug, Clone)]
enum UploadMode {
SingleAlbum,
MaintainStructure,
}
fn print_logo() {
println!(
"{}",
r#"
____ __ __ ____ _ ___
/ ___| _ __ ___ _ _ ___ | \/ |_ _ __ _ / ___| | |_ _|
\___ \| '_ ` _ \| | | |/ _ `| |\/| | | | |/ _` | | | | | |
___) | | | | | | |_| | (_| | | | | |_| | (_| | |___| |___ | |
|____/|_| |_| |_|\__,_|\__, |_| |_|\__,_|\__, |\____|_____|___|
|___/ |___/
"#
.bright_cyan()
.bold()
);
}
// Helper functions for consistent colored output
fn success(msg: &str) -> String {
format!("{} {}", "✓".green().bold(), msg.green())
}
fn error(msg: &str) -> String {
format!("{} {}", "✗".red().bold(), msg.red())
}
fn warning(msg: &str) -> String {
format!("{} {}", "⚠".yellow().bold(), msg.yellow())
}
fn info(msg: &str) -> String {
msg.cyan().to_string()
}
fn highlight(msg: &str) -> String {
msg.bright_white().bold().to_string()
}
fn print_tree(node: &api::NodeTree, prefix: &str, is_last: bool) {
// Print the current node
let connector = if is_last { "└── " } else { "├── " };
let type_indicator = match node.node_type.as_str() {
"Folder" => "📁",
"Album" => "📷",
_ => "📄",
};
println!("{}{}{} {}", prefix, connector, type_indicator, node.name);
// Prepare prefix for children
let child_prefix = format!("{}{}", prefix, if is_last { " " } else { "│ " });
// Print children
let child_count = node.children.len();
for (i, child) in node.children.iter().enumerate() {
let is_last_child = i == child_count - 1;
print_tree(child, &child_prefix, is_last_child);
}
}
/// Where uploads keep their cache (the hash store and file index).
fn upload_cache_dir() -> Result<std::path::PathBuf> {
cache::get_cache_path()
}
/// Format a number with thousands separators
fn format_number(n: usize) -> String {
let s = n.to_string();
let mut result = String::new();
let chars: Vec<char> = s.chars().collect();
for (i, ch) in chars.iter().enumerate() {
if i > 0 && (chars.len() - i) % 3 == 0 {
result.push(',');
}
result.push(*ch);
}
result
}
/// Format bytes into a human-readable string
fn format_size(bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
const GB: u64 = MB * 1024;
if bytes >= GB {
format!("{:.2} GB", bytes as f64 / GB as f64)
} else if bytes >= MB {
format!("{:.2} MB", bytes as f64 / MB as f64)
} else if bytes >= KB {
format!("{:.2} KB", bytes as f64 / KB as f64)
} else {
format!("{} bytes", bytes)
}
}
/// Format duration in seconds into a human-readable string
fn format_duration(seconds: u64) -> String {
let hours = seconds / 3600;
let minutes = (seconds % 3600) / 60;
let secs = seconds % 60;
if hours > 0 {
format!("{}h {}m {}s", hours, minutes, secs)
} else if minutes > 0 {
format!("{}m {}s", minutes, secs)
} else {
format!("{}s", secs)
}
}
mod api;
mod backup;
mod cache;
mod config;
mod dated;
mod downloader;
mod raw;
mod scanner;
mod sort;
mod uploader;
#[derive(Parser)]
#[command(name = "smugmug-cli")]
#[command(about = "A CLI tool for uploading photos to SmugMug", long_about = None)]
#[command(version)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize configuration and authenticate with SmugMug
Init,
/// Sign in through your browser to get (or refresh) an access token
Auth,
/// Test authentication credentials
TestAuth,
/// Album management
Albums {
#[command(subcommand)]
command: AlbumCommands,
},
/// Image management
Images {
#[command(subcommand)]
command: ImageCommands,
},
/// Comment management
Comments {
#[command(subcommand)]
command: CommentCommands,
},
/// Upload photos to SmugMug
Upload {
/// Path to photos directory or file
path: String,
/// Number of concurrent upload threads
#[arg(short, long, default_value = "4")]
threads: usize,
/// Album name (creates if doesn't exist). Without it, files go into
/// albums by the day they were taken (YEAR/MONTH/YEAR-MONTH-DAY) in
/// the configured default folder ("Uploads" unless changed), or in
/// --parent if given
#[arg(short, long)]
album: Option<String>,
/// Parent folder path (e.g., "2024/Travel" creates album in Travel folder)
#[arg(short, long)]
parent: Option<String>,
/// Leave out paths matching this pattern (.gitignore syntax,
/// relative to PATH; e.g. "old_backup/" or "*.png"). Repeatable.
/// Only for uploads by date (no --album or --structure)
#[arg(short = 'x', long = "exclude", value_name = "PATTERN")]
excludes: Vec<String>,
/// Recreate the directory structure as SmugMug folders and albums
#[arg(long, conflicts_with_all = ["album", "parent", "interactive"])]
structure: bool,
/// Ask how to upload (single album or folder structure) instead of
/// using the default destination
#[arg(short, long, conflicts_with = "album")]
interactive: bool,
/// Dry run - don't actually upload
#[arg(short = 'n', long)]
dry_run: bool,
/// Also match existing SmugMug images by content hash regardless of
/// filename, to skip re-uploading the same content under a
/// different name (in addition to the default same-filename
/// skip/replace behavior, which always runs)
#[arg(long)]
check_remote: bool,
/// Disable local cache (always check files, even if previously uploaded)
#[arg(long)]
no_cache: bool,
/// How to handle RAW files, overriding `raw_mode` in the config:
/// upload originals (needs SmugMug Source), JPEGs rendered from
/// their embedded previews, or nothing. Default: auto
#[arg(long, value_enum)]
raw: Option<config::RawMode>,
},
/// Set how a folder lists its contents or an album lists its photos,
/// optionally for everything under it. Folders and albums are sorted
/// by different settings: give --folders-by, --albums-by, or both. A
/// repeat run only changes what's no longer right.
Sort {
/// Folder or album, as a path of names from the top of your account
/// (e.g. Backup, Backup/2014/07, Backup/2014/07/2014-07-12)
path: String,
/// How folders list their contents (name, date-added, date-modified,
/// manual). SmugMug's default for a new folder is date-modified,
/// newest first
#[arg(long, value_enum)]
folders_by: Option<sort::FolderSort>,
/// How albums list their photos (manual, caption, filename,
/// date-uploaded, date-modified, date-taken)
#[arg(long, value_enum)]
albums_by: Option<sort::AlbumSort>,
/// Ascending or descending
#[arg(short, long, value_enum, default_value = "asc")]
direction: sort::Direction,
/// Also set every folder (with --folders-by) and album (with
/// --albums-by) under the path
#[arg(short, long)]
recursive: bool,
/// Show what would change without changing it
#[arg(short = 'n', long)]
dry_run: bool,
},
/// Back up directories into albums by the day photos were taken
/// (FOLDER/YEAR/MONTH/YEAR-MONTH-DAY), again every --interval. Settings
/// come from the [backup] section of the config; options override them.
Backup {
/// Directories to back up (default: [backup] sources)
#[arg(env = "SMUGMUG_BACKUP_SOURCES", value_delimiter = ',')]
sources: Vec<std::path::PathBuf>,
/// SmugMug folder to back up into (default: [backup] folder, "Backup")
#[arg(short, long, env = "SMUGMUG_BACKUP_FOLDER")]
folder: Option<String>,
/// Leave out paths matching this pattern (.gitignore syntax,
/// relative to each source). Repeatable; adds to [backup] exclude
#[arg(
short = 'x',
long = "exclude",
value_name = "PATTERN",
env = "SMUGMUG_BACKUP_EXCLUDE",
value_delimiter = ','
)]
excludes: Vec<String>,
/// Time between the end of one run and the start of the next, e.g.
/// "6h", "30m", "1d" (default: [backup] interval; without one, runs
/// once)
#[arg(short, long, env = "SMUGMUG_BACKUP_INTERVAL")]
interval: Option<String>,
/// Run once even if an interval is configured
#[arg(long)]
once: bool,
/// Concurrent uploads
// Text so a blank SMUGMUG_BACKUP_THREADS (an unset template field)
// means "not given" rather than an error.
#[arg(short, long, env = "SMUGMUG_BACKUP_THREADS")]
threads: Option<String>,
/// Files read (hashed, dated, RAWs rendered) at once
#[arg(long)]
read_threads: Option<usize>,
/// Show what would be uploaded, by date, without reading files in
/// full or touching SmugMug
#[arg(short = 'n', long)]
dry_run: bool,
/// How to handle RAW files, overriding `raw_mode` in the config
#[arg(long, value_enum)]
raw: Option<config::RawMode>,
},
/// Show cache status and statistics
Status,
/// Cache management
Cache {
#[command(subcommand)]
command: CacheCommands,
},
/// Raw API probes for exploring undocumented endpoints
#[command(hide = true)]
Debug {
#[command(subcommand)]
command: DebugCommands,
},
}
#[derive(Subcommand)]
enum AlbumCommands {
/// List all albums
List,
/// Create a new album
Create {
/// Album name
name: String,
/// Privacy level (private, unlisted, public) - defaults to private
#[arg(long, default_value = "private")]
privacy: String,
},
/// Delete an album
Delete {
/// Album name or key
album: String,
/// Force deletion without confirmation
#[arg(short, long)]
force: bool,
},
/// Download all images from an album
Download {
/// Album name or key
album: String,
/// Output directory
#[arg(short, long, default_value = ".")]
output: String,
/// Number of concurrent download threads
#[arg(short, long, default_value = "4")]
threads: usize,
},
/// Show folder/album tree structure
Tree,
/// Update album settings
Settings {
/// Album name or key
album: String,
/// Set privacy (public, unlisted, private)
#[arg(long)]
privacy: Option<String>,
/// Set description
#[arg(long)]
description: Option<String>,
/// Set keywords (semicolon-separated)
#[arg(long)]
keywords: Option<String>,
/// Set sort method (Position, Caption, FileName, DateTimeOriginal, DateTimeUploaded)
#[arg(long)]
sort_method: Option<String>,
/// Set sort direction (asc, desc)
#[arg(long)]
sort_direction: Option<String>,
},
/// Get album download link (ZIP file)
GetDownloadLink {
/// Album name or key
album: String,
/// Wait for download generation (polls until ready)
#[arg(short, long)]
wait: bool,
},
}
#[derive(Subcommand)]
enum DebugCommands {
/// Authenticated GET of an API path (e.g. "/api/v2!authuser"); prints status and raw JSON
Get {
/// API path or absolute URL, query string allowed
path: String,
/// HTTP method to send instead of GET (e.g. OPTIONS)
#[arg(short = 'X', long, default_value = "GET")]
method: String,
/// JSON body to send (e.g. for -X POST)
#[arg(short, long)]
data: Option<String>,
},
/// Upload one file to the Library (no album); prints status and raw JSON
LibraryUpload {
/// File to upload
file: String,
/// Value for the Filepath field (defaults to the file name)
#[arg(long)]
filepath: Option<String>,
},
}
#[derive(Subcommand)]
enum CacheCommands {
/// Clear the deduplication cache
Clear,
}
#[derive(Subcommand)]
enum ImageCommands {
/// List images in an album
List {
/// Album name or key
album: String,
},
/// Show detailed information about an image
Info {
/// Album name or key
album: String,
/// Image key to view
image_key: String,
},
/// Delete an image
Delete {
/// Album name or key
album: String,
/// Image key to delete
image_key: String,
/// Force deletion without confirmation
#[arg(short, long)]
force: bool,
},
/// Update image metadata
Update {
/// Album name or key
album: String,
/// Image key to update
image_key: String,
/// Set image caption
#[arg(long)]
caption: Option<String>,
/// Set image title
#[arg(long)]
title: Option<String>,
/// Set keywords (semicolon-separated)
#[arg(long)]
keywords: Option<String>,
/// Set latitude
#[arg(long)]
latitude: Option<f64>,
/// Set longitude
#[arg(long)]
longitude: Option<f64>,
},
/// Move image to a different album
Move {
/// Source album name or key
source_album: String,
/// Image key to move
image_key: String,
/// Target album name or key
target_album: String,
/// Force move without confirmation
#[arg(short, long)]
force: bool,
},
}
#[derive(Subcommand)]
enum CommentCommands {
/// List comments on an image
List {
/// Album name or key
album: String,
/// Image key
image_key: String,
},
/// Create a new comment on an image
Create {
/// Album name or key
album: String,
/// Image key
image_key: String,
/// Comment text
#[arg(short, long)]
text: String,
/// Commenter name
#[arg(short, long)]
name: Option<String>,
/// Commenter email
#[arg(short, long)]
email: Option<String>,
/// Rating (0-5)
#[arg(short, long)]
rating: Option<u8>,
},
}
#[tokio::main]
async fn main() -> Result<()> {
print_logo();
let cli = Cli::parse();
// Check if auth is configured for commands that require it
if !matches!(cli.command, Commands::Init | Commands::Auth) && !config::is_auth_configured() {
println!("\n{}", warning("Authentication not configured!"));
println!(
"\n{}",
info("To get started, you'll need to set up your SmugMug API credentials.")
);
println!("\n{}", highlight("Run the following command to configure:"));
println!(" {}\n", "smugmug-cli init".bright_white().bold());
println!("{}", info("You'll need:"));
println!(
" • API Key and Secret from {}",
"https://api.smugmug.com/api/developer/apply".bright_cyan()
);
println!(" • Access Token and Secret from your SmugMug Account Settings\n");
return Ok(());
}
match cli.command {
Commands::Init => {
println!("Initializing SmugMug CLI...");
config::init_config().await?;
}
Commands::Auth => {
config::auth_command().await?;
}
Commands::TestAuth => {
println!("Testing authentication...");
let cfg = config::load_config()?;
let client = api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
);
match client.get_auth_user().await {
Ok(user_info) => {
println!("\n{}", success("Authentication successful!"));
println!("\n{}", info("User info:"));
println!("{}", serde_json::to_string_pretty(&user_info)?);
// Try to fetch features
if let Some(user_uri) = user_info["Response"]["User"]["Uri"].as_str() {
println!("\n{}", info("Fetching user features..."));
match client.get_user_features(user_uri).await {
Ok(features) => {
println!("\n{}", info("User features:"));
println!("{}", serde_json::to_string_pretty(&features)?);
}
Err(e) => {
println!(
"\n{}",
error(&format!("Failed to fetch features: {}", e))
);
}
}
}
}
Err(e) => {
println!("\n{}", error(&format!("Authentication failed: {}", e)));
println!(
"\n{}",
warning("Please check your credentials and run 'smugmug-cli init' again.")
);
}
}
}
Commands::Albums { command } => {
let cfg = config::load_config()?;
let client = std::sync::Arc::new(api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
));
match command {
AlbumCommands::List => {
println!("Fetching albums...");
match client.list_albums().await {
Ok(albums) => {
println!("\n✓ Found {} albums:\n", albums.len());
for album in albums {
println!(" • {} (Key: {})", album.name, album.album_key);
println!(" URL Name: {}", album.url_name);
println!(" Node ID: {}", album.node_id);
println!();
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
}
}
}
AlbumCommands::Create { name, privacy } => {
// Validate and normalize privacy value
let normalized_privacy = match privacy.to_lowercase().as_str() {
"public" => "Public",
"unlisted" => "Unlisted",
"private" => "Private",
_ => {
println!(
"\n{}",
error(&format!("Invalid privacy value: {}", privacy))
);
println!(" Valid values: public, unlisted, private");
return Ok(());
}
};
println!(
"Creating album: {} ({})",
name,
normalized_privacy.to_lowercase()
);
match client.create_album(&name, None, normalized_privacy).await {
Ok(album) => {
println!("\n{}", success("Album created successfully!"));
println!(" Name: {}", album.name);
println!(" Privacy: {}", normalized_privacy);
println!(" Key: {}", album.album_key);
println!(" URL Name: {}", album.url_name);
println!(" Node ID: {}", album.node_id);
if let Some(web_uri) = album.web_uri {
println!(" Web URL: {}", web_uri);
}
}
Err(e) => {
println!("\n{}", error(&format!("Failed to create album: {}", e)));
}
}
}
AlbumCommands::Delete { album, force } => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let (album_key, album_info) = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
(found.album_key.clone(), Some(found.clone()))
} else {
// Album not found by name, try using the input as key directly
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Show album details
if let Some(info) = album_info {
println!("\n Album to delete:");
println!(" Name: {}", info.name);
println!(" Key: {}", info.album_key);
if let Some(web_uri) = &info.web_uri {
println!(" URL: {}", web_uri);
}
}
// Confirm deletion unless --force is used
if !force {
use dialoguer::Confirm;
let confirmed = Confirm::new()
.with_prompt("\nAre you sure you want to delete this album? This cannot be undone.")
.default(false)
.interact()?;
if !confirmed {
println!("\n Deletion cancelled.");
return Ok(());
}
}
// Delete the album
println!("\nDeleting album...");
match client.delete_album(&album_key).await {
Ok(()) => {
println!("\n✓ Album deleted successfully!");
}
Err(e) => {
println!("\n✗ Failed to delete album: {}", e);
}
}
}
AlbumCommands::Download {
album,
output,
threads,
} => {
println!("Downloading album: {}", album);
println!("Output directory: {}", output);
println!("Threads: {}\n", threads);
// Try to find album by name or use as key
let album_key = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("✗ Album not found: {}", album);
return Ok(());
}
}
Err(e) => {
println!("✗ Failed to list albums: {}", e);
return Ok(());
}
};
let download_options = downloader::DownloadOptions {
album_key,
output_dir: std::path::PathBuf::from(output),
client,
threads,
};
match downloader::download_album(download_options).await {
Ok(stats) => {
println!("\n✓ Download complete!");
println!(" Total images: {}", stats.total_images);
println!(" Downloaded: {}", stats.downloaded);
println!(" Failed: {}", stats.failed);
println!(
" Total size: {:.2} MB",
stats.total_bytes as f64 / 1024.0 / 1024.0
);
}
Err(e) => {
println!("\n✗ Download failed: {}", e);
}
}
}
AlbumCommands::Tree => {
println!("Fetching folder structure...\n");
match client.get_node_tree().await {
Ok(tree) => {
print_tree(&tree, "", true);
}
Err(e) => {
println!("✗ Failed to fetch folder structure: {}", e);
}
}
}
AlbumCommands::Settings {
album,
privacy,
description,
keywords,
sort_method,
sort_direction,
} => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let (album_key, album_info) = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
(found.album_key.clone(), Some(found.clone()))
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Check if any settings were provided
if privacy.is_none()
&& description.is_none()
&& keywords.is_none()
&& sort_method.is_none()
&& sort_direction.is_none()
{
println!("\n✗ No settings specified to update");
println!(
" Use --privacy, --description, --keywords, --sort-method, or --sort-direction"
);
return Ok(());
}
// Validate and normalize privacy value
let privacy = if let Some(p) = privacy {
let normalized = match p.to_lowercase().as_str() {
"public" => "Public",
"unlisted" => "Unlisted",
"private" => "Private",
_ => {
println!("\n✗ Invalid privacy value: {}", p);
println!(" Valid values: public, unlisted, private");
return Ok(());
}
};
Some(normalized.to_string())
} else {
None
};
// Validate and normalize sort direction
let sort_direction = if let Some(d) = sort_direction {
let normalized = match d.to_lowercase().as_str() {
"asc" | "ascending" => "Ascending",
"desc" | "descending" => "Descending",
_ => {
println!("\n✗ Invalid sort direction: {}", d);
println!(" Valid values: asc, desc");
return Ok(());
}
};
Some(normalized.to_string())
} else {
None
};
// Show current album info
if let Some(info) = album_info {
println!("\nAlbum: {}", info.name);
println!(" Key: {}", info.album_key);
if let Some(web_uri) = &info.web_uri {
println!(" URL: {}", web_uri);
}
}
// Show what will be updated
println!("\nSettings to update:");
if let Some(ref p) = privacy {
println!(" Privacy: {}", p);
}
if let Some(ref d) = description {
println!(" Description: {}", d);
}
if let Some(ref k) = keywords {
println!(" Keywords: {}", k);
}
if let Some(ref sm) = sort_method {
println!(" Sort Method: {}", sm);
}
if let Some(ref sd) = sort_direction {
println!(" Sort Direction: {}", sd);
}
// Create settings update struct
let settings = api::albums::AlbumSettingsUpdate {
privacy,
description,
keywords,
sort_method,
sort_direction,
};
println!("\nUpdating album settings...");
match client.update_album_settings(&album_key, settings).await {
Ok(()) => {
println!("\n✓ Album settings updated successfully!");
}
Err(e) => {
println!("\n✗ Failed to update album settings: {}", e);
}
}
}
AlbumCommands::GetDownloadLink { album, wait } => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
if wait {
println!("Requesting album download...");
println!("(This may take a few minutes for large albums)\n");
match client.get_album_download_link(&album_key).await {
Ok(url) => {
println!("\n✓ Download Ready!");
println!(" URL: {}", url);
println!("\nDownload with:");
println!(" wget \"{}\"", url);
println!(" curl -O \"{}\"", url);
}
Err(e) => {
println!("\n✗ Failed to get download link: {}", e);
}
}
} else {
println!("Requesting album download...\n");
match client.request_album_download(&album_key).await {
Ok(info) => {
println!("✓ Download requested successfully!");
if let Some(status) = &info.status {
println!(" Status: {}", status);
}
if let Some(uri) = &info.uri {
println!(" Status URI: {}", uri);
}
println!("\nTo wait for completion, use:");
println!(
" smugmug-cli albums get-download-link \"{}\" --wait",
album
);
}
Err(e) => {
println!("\n✗ Failed to request download: {}", e);
}
}
}
}
}
}
Commands::Images { command } => {
let cfg = config::load_config()?;
let client = std::sync::Arc::new(api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
));
match command {
ImageCommands::List { album } => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
println!("Fetching images from album...\n");
match client.list_album_images(&album_key).await {
Ok(images) => {
if images.is_empty() {
println!("No images found in this album.");
} else {
println!("✓ Found {} images:\n", format_number(images.len()));
for image in images {
println!(" Image Key: {}", image.image_key);
println!(" File: {}", image.file_name);
println!(" Size: {}", format_size(image.file_size));
println!(" Format: {}", image.format);
if let Some(title) = &image.title {
println!(" Title: {}", title);
}
if let Some(md5) = &image.archived_md5 {
println!(" MD5: {}", md5);
}
println!();
}
}
}
Err(e) => {
println!("\n✗ Failed to list images: {}", e);
}
}
}
ImageCommands::Info { album, image_key } => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key_resolved = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Verify the image exists in the album
println!("Verifying image exists in album...");
let image_exists = match client.list_album_images(&album_key_resolved).await {
Ok(images) => images.iter().any(|img| img.image_key == image_key),
Err(e) => {
println!("\n✗ Failed to verify image: {}", e);
return Ok(());
}
};
if !image_exists {
println!("\n✗ Image not found in album: {}", image_key);
println!(
" Use 'smugmug-cli images list {}' to see available images",
album
);
return Ok(());
}
// Fetch detailed image information
println!("Fetching image details...\n");
match client.get_image_details(&image_key).await {
Ok(details) => {
println!("✓ Image Details\n");
println!("Basic Information:");
println!(" Image Key: {}", details.image_key);
println!(" File Name: {}", details.file_name);
println!(" Format: {}", details.format);
println!(" File Size: {}", format_size(details.file_size));
println!();
println!("Metadata:");
println!(
" Title: {}",
details.title.as_deref().unwrap_or("N/A")
);
println!(
" Caption: {}",
details.caption.as_deref().unwrap_or("N/A")
);
println!(
" Keywords: {}",
details.keywords.as_deref().unwrap_or("N/A")
);
println!();
println!("Location:");
if let Some(lat) = details.latitude {
println!(" Latitude: {}", lat);
} else {
println!(" Latitude: N/A");
}
if let Some(lon) = details.longitude {
println!(" Longitude: {}", lon);
} else {
println!(" Longitude: N/A");
}
if let Some(alt) = details.altitude {
println!(" Altitude: {} m", alt);
} else {
println!(" Altitude: N/A");
}
println!();
println!("Technical:");
println!(" Archived URI: {}", details.archived_uri);
println!(
" Archived MD5: {}",
details.archived_md5.as_deref().unwrap_or("N/A")
);
println!(
" Upload Key: {}",
details.upload_key.as_deref().unwrap_or("N/A")
);
println!(" API URI: {}", details.uri);
if let Some(web_uri) = &details.web_uri {
println!(" Web URL: {}", web_uri);
}
}
Err(e) => {
println!("\n✗ Failed to fetch image details: {}", e);
}
}
}
ImageCommands::Delete {
album,
image_key,
force,
} => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key_resolved = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Verify the image exists in the album
println!("Verifying image exists...");
let image_info = match client.list_album_images(&album_key_resolved).await {
Ok(images) => {
if let Some(found) =
images.iter().find(|img| img.image_key == image_key)
{
found.clone()
} else {
println!("\n✗ Image not found in album: {}", image_key);
println!(
" Use 'smugmug-cli images list {}' to see available images",
album
);
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list images: {}", e);
return Ok(());
}
};
// Show confirmation prompt unless --force is specified
if !force {
use dialoguer::Confirm;
println!("\nImage details:");
println!(" File: {}", image_info.file_name);
println!(" Key: {}", image_info.image_key);
println!(" Size: {}", format_size(image_info.file_size));
println!(" Format: {}", image_info.format);
let confirmed = Confirm::new()
.with_prompt("Are you sure you want to delete this image?")
.default(false)
.interact()?;
if !confirmed {
println!("\nDeletion cancelled.");
return Ok(());
}
}
println!("\nDeleting image...");
match client.delete_image(&image_key).await {
Ok(()) => {
println!("\n✓ Image deleted successfully!");
}
Err(e) => {
println!("\n✗ Failed to delete image: {}", e);
}
}
}
ImageCommands::Update {
album,
image_key,
caption,
title,
keywords,
latitude,
longitude,
} => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key_resolved = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Verify the image exists in the album
println!("Verifying image exists...");
let image_info = match client.list_album_images(&album_key_resolved).await {
Ok(images) => {
if let Some(found) =
images.iter().find(|img| img.image_key == image_key)
{
found.clone()
} else {
println!("\n✗ Image not found in album: {}", image_key);
println!(
" Use 'smugmug-cli images list {}' to see available images",
album
);
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list images: {}", e);
return Ok(());
}
};
// Check if any updates were provided
if caption.is_none()
&& title.is_none()
&& keywords.is_none()
&& latitude.is_none()
&& longitude.is_none()
{
println!("\n✗ No metadata fields specified to update");
println!(
" Use --caption, --title, --keywords, --latitude, or --longitude"
);
return Ok(());
}
// Show current image info
println!("\nImage details:");
println!(" File: {}", image_info.file_name);
println!(" Key: {}", image_info.image_key);
println!(" Size: {}", format_size(image_info.file_size));
println!(" Format: {}", image_info.format);
// Show what will be updated
println!("\nMetadata updates:");
if let Some(ref c) = caption {
println!(" Caption: {}", c);
}
if let Some(ref t) = title {
println!(" Title: {}", t);
}
if let Some(ref k) = keywords {
println!(" Keywords: {}", k);
}
if let Some(lat) = latitude {
println!(" Latitude: {}", lat);
}
if let Some(lon) = longitude {
println!(" Longitude: {}", lon);
}
// Create metadata update struct
let metadata = api::images::ImageMetadataUpdate {
caption,
title,
keywords,
latitude,
longitude,
};
println!("\nUpdating image metadata...");
match client.update_image_metadata(&image_key, metadata).await {
Ok(()) => {
println!("\n✓ Image metadata updated successfully!");
}
Err(e) => {
println!("\n✗ Failed to update image metadata: {}", e);
}
}
}
ImageCommands::Move {
source_album,
image_key,
target_album,
force,
} => {
println!("Looking up source album: {}", source_album);
// Try to find source album by name or use as key
let (source_album_key, source_album_name) = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == source_album || a.album_key == source_album)
{
(found.album_key.clone(), found.name.clone())
} else {
println!("\n✗ Source album not found: {}", source_album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Verify the image exists in the source album
println!("Verifying image exists in source album...");
let image_info = match client.list_album_images(&source_album_key).await {
Ok(images) => {
if let Some(found) =
images.iter().find(|img| img.image_key == image_key)
{
found.clone()
} else {
println!("\n✗ Image not found in source album: {}", image_key);
println!(
" Use 'smugmug-cli images list {}' to see available images",
source_album
);
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list images in source album: {}", e);
return Ok(());
}
};
// Try to find target album by name or use as key
println!("Looking up target album: {}", target_album);
let (target_album_key, target_album_name) = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == target_album || a.album_key == target_album)
{
(found.album_key.clone(), found.name.clone())
} else {
println!("\n✗ Target album not found: {}", target_album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Show confirmation prompt unless --force is specified
if !force {
use dialoguer::Confirm;
println!("\nImage details:");
println!(" File: {}", image_info.file_name);
println!(" Key: {}", image_info.image_key);
println!(" Size: {}", format_size(image_info.file_size));
println!(" Format: {}", image_info.format);
if let Some(title) = &image_info.title {
println!(" Title: {}", title);
}
println!();
println!("Move from:");
println!(" Album: {} (Key: {})", source_album_name, source_album_key);
println!("To:");
println!(" Album: {} (Key: {})", target_album_name, target_album_key);
let confirmed = Confirm::new()
.with_prompt("Are you sure you want to move this image?")
.default(false)
.interact()?;
if !confirmed {
println!("\nMove cancelled.");
return Ok(());
}
}
println!("\nMoving image...");
match client.move_image(&image_key, &target_album_key).await {
Ok(()) => {
println!("\n✓ Image moved successfully!");
println!(" From: {}", source_album_name);
println!(" To: {}", target_album_name);
}
Err(e) => {
println!("\n✗ Failed to move image: {}", e);
}
}
}
}
}
Commands::Comments { command } => {
let cfg = config::load_config()?;
let client = std::sync::Arc::new(api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
));
match command {
CommentCommands::List { album, image_key } => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key_resolved = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Verify the image exists in the album
println!("Verifying image exists...");
let image_exists = match client.list_album_images(&album_key_resolved).await {
Ok(images) => images.iter().any(|img| img.image_key == image_key),
Err(e) => {
println!("\n✗ Failed to verify image: {}", e);
return Ok(());
}
};
if !image_exists {
println!("\n✗ Image not found in album: {}", image_key);
println!(
" Use 'smugmug-cli images list {}' to see available images",
album
);
return Ok(());
}
// List comments
println!("Fetching comments...\n");
match client.list_image_comments(&image_key).await {
Ok(comments) => {
if comments.is_empty() {
println!("No comments found for this image.");
} else {
println!(
"✓ Found {} comments for image {}:\n",
format_number(comments.len()),
image_key
);
for comment in comments {
if let Some(key) = &comment.comment_key {
println!(" Comment Key: {}", key);
}
if let Some(name) = &comment.name {
println!(" Author: {}", name);
} else {
println!(" Author: Anonymous");
}
if let Some(rating) = comment.rating {
let stars = "★".repeat(rating as usize)
+ &"☆".repeat((5 - rating) as usize);
println!(" Rating: {} ({}/5)", stars, rating);
}
println!(" Text: {}", comment.text);
if let Some(date) = &comment.date {
println!(" Date: {}", date);
}
println!();
}
}
}
Err(e) => {
println!("\n✗ Failed to list comments: {}", e);
}
}
}
CommentCommands::Create {
album,
image_key,
text,
name,
email,
rating,
} => {
println!("Looking up album: {}", album);
// Try to find album by name or use as key
let album_key_resolved = match client.list_albums().await {
Ok(albums) => {
if let Some(found) = albums
.iter()
.find(|a| a.name == album || a.album_key == album)
{
found.album_key.clone()
} else {
println!("\n✗ Album not found: {}", album);
println!(" Use 'smugmug-cli albums list' to see available albums");
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list albums: {}", e);
return Ok(());
}
};
// Verify the image exists in the album
println!("Verifying image exists...");
let image_info = match client.list_album_images(&album_key_resolved).await {
Ok(images) => {
if let Some(found) =
images.iter().find(|img| img.image_key == image_key)
{
found.clone()
} else {
println!("\n✗ Image not found in album: {}", image_key);
println!(
" Use 'smugmug-cli images list {}' to see available images",
album
);
return Ok(());
}
}
Err(e) => {
println!("\n✗ Failed to list images: {}", e);
return Ok(());
}
};
// Show image details and comment preview
println!("\nImage: {}", image_info.file_name);
println!("Comment preview:");
println!(" Author: {}", name.as_deref().unwrap_or("Anonymous"));
println!(" Text: {}", text);
if let Some(r) = rating {
println!(" Rating: {}/5", r);
}
// Confirm
use dialoguer::Confirm;
let confirmed = Confirm::new()
.with_prompt("Post this comment?")
.default(true)
.interact()?;
if !confirmed {
println!("\nComment cancelled.");
return Ok(());
}
// Create comment
println!("\nPosting comment...");
let request = api::comments::CreateCommentRequest {
text,
name,
email,
rating,
link: None,
};
match client.create_image_comment(&image_key, request).await {
Ok(comment) => {
println!("\n✓ Comment posted successfully!");
if let Some(key) = comment.comment_key {
println!(" Comment Key: {}", key);
}
}
Err(e) => {
println!("\n✗ Failed to post comment: {}", e);
}
}
}
}
}
Commands::Sort {
path,
folders_by,
albums_by,
direction,
recursive,
dry_run,
} => {
let cfg = config::load_config()?;
let client = api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
);
let options = sort::SortOptions {
path,
folders: folders_by,
albums: albums_by,
direction,
recursive,
dry_run,
};
let summary = sort::run(&client, &options).await?;
sort::print_summary(&summary, &options);
if !summary.failed.is_empty() {
anyhow::bail!("{} could not be updated", summary.failed.len());
}
}
Commands::Backup {
sources,
folder,
excludes,
interval,
once,
threads,
read_threads,
dry_run,
raw,
} => {
let cfg = config::load_config()?;
let backup = &cfg.backup;
// Blank values (an unset field in a container template) count as
// not given.
let sources: Vec<std::path::PathBuf> = sources
.into_iter()
.filter(|s| !s.as_os_str().is_empty())
.collect();
let excludes: Vec<String> = excludes
.into_iter()
.map(|e| e.trim().to_string())
.filter(|e| !e.is_empty())
.collect();
let folder = folder.filter(|f| !f.trim().is_empty());
let interval = interval.filter(|i| !i.trim().is_empty());
let threads: Option<usize> = threads
.filter(|t| !t.trim().is_empty())
.map(|t| {
t.trim()
.parse()
.map_err(|_| anyhow::anyhow!("Invalid thread count '{}'", t))
})
.transpose()?;
let sources = if sources.is_empty() {
backup.sources.clone()
} else {
sources
};
if sources.is_empty() {
anyhow::bail!(
"Nothing to back up: give directories on the command line or set sources in the [backup] section of the config"
);
}
let interval = if once {
None
} else {
interval
.or_else(|| backup.interval.clone())
.map(|i| backup::parse_interval(&i))
.transpose()?
};
let raw_mode = raw.unwrap_or(cfg.upload.raw_mode);
let options = dated::RunOptions {
sources,
excludes: backup.exclude.iter().cloned().chain(excludes).collect(),
root_folder: folder.unwrap_or_else(|| backup.folder.clone()),
root_privacy: Some("Private"),
upload_threads: threads
.or(backup.upload_threads)
.unwrap_or(cfg.upload.threads),
read_threads: read_threads
.or(backup.read_threads)
.unwrap_or(cfg.upload.read_threads),
dry_run,
no_cache: false,
raw_handling: raw_mode.handling(cfg.upload.has_smugmug_source),
live_photo_videos: backup
.live_photo_videos
.unwrap_or(cfg.upload.live_photo_videos),
retry_attempts: cfg.upload.retry_attempts,
cache_path: upload_cache_dir()?,
};
let client = std::sync::Arc::new(api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
));
backup::run(client, options, interval).await?;
}
Commands::Upload {
path,
threads,
album,
parent,
excludes,
structure,
interactive,
dry_run,
check_remote,
no_cache,
raw,
} => {
let cfg = config::load_config()?;
let raw_mode = raw.unwrap_or(cfg.upload.raw_mode);
let client = std::sync::Arc::new(api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
));
// With no album, folder or mode given, upload into albums by the
// day each file was taken, in the default folder.
let use_default_destination = album.is_none() && !structure && !interactive;
if use_default_destination {
let options = dated::RunOptions {
sources: vec![std::path::PathBuf::from(&path)],
excludes,
root_folder: parent
.clone()
.unwrap_or_else(|| cfg.upload.default_folder.clone()),
// The default folder is created private; a --parent
// folder keeps SmugMug's default privacy, as before.
root_privacy: parent.is_none().then_some("Private"),
upload_threads: threads,
read_threads: cfg.upload.read_threads,
dry_run,
no_cache,
raw_handling: raw_mode.handling(cfg.upload.has_smugmug_source),
live_photo_videos: cfg.upload.live_photo_videos,
retry_attempts: cfg.upload.retry_attempts,
cache_path: upload_cache_dir()?,
};
println!("Uploading from: {}", path);
println!(
"Into: {}/YYYY/MM/YYYY-MM-DD (by the day each was taken)",
options.root_folder
);
if dry_run {
println!("DRY RUN - nothing will be uploaded");
}
let stop = dated::stop_on_signal();
let stats = dated::run(client, &options, &stop).await?;
dated::print_summary(&stats, &options);
println!(" Duration: {}", format_duration(stats.duration_secs));
return Ok(());
}
if !excludes.is_empty() {
anyhow::bail!(
"--exclude only works for uploads by date (without --album or --structure)"
);
}
// Determine upload mode and album name
let (upload_mode, album_name) = if structure {
(UploadMode::MaintainStructure, String::new())
} else if let Some(name) = album {
// Album specified via CLI, use single album mode
(UploadMode::SingleAlbum, name)
} else {
// --interactive: prompt user
use dialoguer::{Input, Select};
println!("\nNo album specified. How would you like to upload?");
let choices = vec![
"Single album - flatten all images into one album",
"Maintain folder structure - create albums/folders matching your directory structure",
];
let selection = Select::new().items(&choices).default(0).interact()?;
match selection {
0 => {
// Single album mode
let path_obj = std::path::Path::new(&path);
let default_name = path_obj
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("Uploads")
.to_string();
let album_name: String = Input::new()
.with_prompt("Album name")
.default(default_name)
.interact_text()?;
(UploadMode::SingleAlbum, album_name)
}
1 => {
// Maintain structure mode
println!("\nFolder structure will be preserved in SmugMug.");
(UploadMode::MaintainStructure, String::new())
}
_ => unreachable!(),
}
};
// Folder the album series lives in, if any
let folder_path = parent.clone();
println!("Uploading from: {}", path);
if matches!(upload_mode, UploadMode::SingleAlbum) {
match &folder_path {
Some(folder) => println!("Album: {}/{}", folder, album_name),
None => println!("Album: {}", album_name),
}
}
println!("Threads: {}", threads);
if dry_run {
println!("DRY RUN - no files will be uploaded\n");
} else {
println!();
}
let cache_path = upload_cache_dir()?;
// Handle upload based on mode
match upload_mode {
UploadMode::SingleAlbum => {
use uploader::album_series::{
AlbumScope, AlbumSeries, ClientAlbumSeries, MAX_ALBUM_IMAGES,
};
// Work out what will actually be uploaded before touching
// SmugMug at all.
let files: Vec<std::path::PathBuf> =
match scanner::scan_directory(std::path::Path::new(&path)) {
Ok(scanned) => scanned.into_iter().map(|f| f.path).collect(),
Err(e) => {
println!("✗ Failed to scan {}: {}", path, e);
return Ok(());
}
};
let raw_handling = raw_mode.handling(cfg.upload.has_smugmug_source);
let (files, raw_selection) = uploader::select_raw_files(files, raw_handling);
uploader::print_raw_selection(
&raw_selection,
raw_mode,
cfg.upload.has_smugmug_source,
);
if files.is_empty() {
println!("No files to upload.");
return Ok(());
}
// Find or create the folder the albums live in (a dry run
// only looks). The default folder is created private; a
// --parent folder keeps SmugMug's default privacy, as
// before.
let scope = if let Some(ref folder) = folder_path {
println!("Finding/creating folder path: {}", folder);
let privacy = None;
let found = if dry_run {
client.find_folder_path(folder).await
} else {
client
.find_or_create_folder_path(folder, privacy)
.await
.map(Some)
};
match found {
Ok(Some(uri)) => {
println!("✓ Using folder: {}\n", folder);
AlbumScope::Folder(uri)
}
Ok(None) => {
println!("• Would create folder: {}\n", folder);
AlbumScope::MissingFolder
}
Err(e) => {
println!("✗ Failed to find/create folder path: {}", e);
return Ok(());
}
}
} else {
AlbumScope::Anywhere
};
// The album and any overflow albums ("Name (2)", ...) are
// created only when a file actually needs uploading, so
// SmugMug's per-album limit is respected without making
// albums that would stay empty.
println!("Looking up album...");
let series = match AlbumSeries::load(
ClientAlbumSeries::new(client.clone(), scope),
&album_name,
MAX_ALBUM_IMAGES,
dry_run,
)
.await
{
Ok(series) => std::sync::Arc::new(series),
Err(e) => {
println!("✗ Failed to look up album: {}", e);
return Ok(());
}
};
let existing = series.existing_albums().await;
if existing.is_empty() {
println!(
"• Album {} will be created when the first file uploads\n",
album_name
);
} else {
for a in &existing {
println!(
"✓ Found album: {} (Key: {}) — {} of {} images used",
a.album.name, a.album.album_key, a.count, MAX_ALBUM_IMAGES
);
}
println!();
}
// Set up upload options
let upload_options = uploader::UploadOptions {
files,
raw_handling,
series: series.clone(),
client,
threads,
dry_run,
check_remote,
no_cache,
cache_path,
retry_attempts: cfg.upload.retry_attempts,
};
// Perform upload
match uploader::upload_files(upload_options).await {
Ok(stats) => {
println!("\n{}", success("Upload complete!"));
println!(
" {}: {}",
info("Total files"),
highlight(&stats.total_files.to_string())
);
println!(
" {}: {}",
"Uploaded".green(),
highlight(&stats.uploaded.to_string())
);
println!(" {}: {}", "Replaced (modified)".cyan(), stats.replaced);
if stats.collected > 0 {
println!(
" {}: {}",
"Added from SmugMug (already uploaded)".cyan(),
stats.collected
);
}
println!(" {}: {}", "Skipped (duplicates)".yellow(), stats.skipped);
let raw_skipped =
raw_selection.skipped + raw_selection.skipped_with_sibling;
if raw_skipped > 0 {
println!(" {}: {}", "Skipped (RAW)".yellow(), raw_skipped);
}
println!(" {}: {}", "Failed".red(), stats.failed);
println!(
" {}: {}",
info("Total size"),
highlight(&format!(
"{:.2} MB",
stats.total_bytes as f64 / 1024.0 / 1024.0
))
);
println!(
" {}: {}",
info("Duration"),
highlight(&format_duration(stats.duration_secs))
);
}
Err(e) => {
println!("\n{}", error(&format!("Upload failed: {}", e)));
}
}
// Where new images went
let used: Vec<_> = series
.albums()
.await
.into_iter()
.filter(|a| a.claimed > 0 || a.created)
.collect();
if !used.is_empty() {
println!("\n {}:", info("Albums"));
for a in used {
let verb = if dry_run { "would get" } else { "got" };
let status = match (a.created, dry_run) {
(true, true) => " (would be created, private)",
(true, false) => " (created, private)",
_ => "",
};
println!(" {}: {} {} new{}", a.album.name, verb, a.claimed, status);
if let Some(ref web_uri) = a.album.web_uri {
println!(" {}", web_uri);
}
}
}
}
UploadMode::MaintainStructure => {
// Upload with folder structure preservation
match uploader::upload_with_structure(uploader::UploadStructureOptions {
path: std::path::PathBuf::from(path),
client: client.clone(),
dry_run,
check_remote,
no_cache,
cache_path,
retry_attempts: cfg.upload.retry_attempts,
has_smugmug_source: cfg.upload.has_smugmug_source,
raw_mode,
})
.await
{
Ok(stats) => {
println!("\n{}", success("Upload complete!"));
println!(
" {}: {}",
info("Total files"),
highlight(&stats.total_files.to_string())
);
println!(
" {}: {}",
"Uploaded".green(),
highlight(&stats.uploaded.to_string())
);
println!(" {}: {}", "Replaced (modified)".cyan(), stats.replaced);
println!(" {}: {}", "Skipped (duplicates)".yellow(), stats.skipped);
println!(" {}: {}", "Failed".red(), stats.failed);
println!(
" {}: {}",
info("Folders created"),
highlight(&stats.folders_created.to_string())
);
println!(
" {}: {}",
info("Albums created"),
highlight(&stats.albums_created.to_string())
);
println!(
" {}: {}",
info("Total size"),
highlight(&format!(
"{:.2} MB",
stats.total_bytes as f64 / 1024.0 / 1024.0
))
);
println!(
" {}: {}",
info("Duration"),
highlight(&format_duration(stats.duration_secs))
);
}
Err(e) => {
println!("\n{}", error(&format!("Upload failed: {}", e)));
}
}
}
}
}
Commands::Debug { command } => {
let cfg = config::load_config()?;
let client = api::SmugMugClient::new(
cfg.auth.api_key,
cfg.auth.api_secret,
cfg.auth.access_token,
cfg.auth.access_token_secret,
);
let is_upload = matches!(command, DebugCommands::LibraryUpload { .. });
let (status, body) = match command {
DebugCommands::Get { path, method, data } => {
let body = data
.map(|d| serde_json::from_str(&d))
.transpose()
.map_err(|e| anyhow::anyhow!("--data is not valid JSON: {e}"))?;
client
.request_raw(&method.to_uppercase(), &path, body)
.await?
}
DebugCommands::LibraryUpload { file, filepath } => {
let file_path = std::path::Path::new(&file);
let filepath = filepath.unwrap_or_else(|| {
file_path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("image")
.to_string()
});
api::upload::send_library_upload(
&client,
api::upload::LIBRARY_UPLOAD_URL,
file_path,
&filepath,
)
.await?
}
};
println!("HTTP {}", status);
match serde_json::from_str::<serde_json::Value>(&body) {
Ok(json) => println!("{}", serde_json::to_string_pretty(&json)?),
Err(_) => println!("{}", body),
}
if is_upload {
match api::upload::parse_library_upload_response(status, &body) {
Ok(result) => println!(
"\n{}",
success(&format!(
"Parsed: image key {} ({})",
result.image_key, result.image_uri
))
),
Err(e) => println!("\n{}", error(&format!("Could not parse: {}", e))),
}
}
}
Commands::Status => {
let cache_path = cache::get_cache_path()?;
println!("Cache Status:");
println!(" Location: {}", cache_path.display());
match cache::HashStore::new(cache_path.to_str().unwrap()) {
Ok(store) => match store.stats() {
Ok(stats) => {
println!(" Total entries: {}", format_number(stats.total_entries));
println!(" Cache size: {}", format_size(stats.total_size));
if let Some(oldest) = stats.oldest_entry {
println!(" Oldest entry: {}", oldest.format("%Y-%m-%d"));
} else {
println!(" Oldest entry: N/A");
}
if let Some(newest) = stats.newest_entry {
println!(" Newest entry: {}", newest.format("%Y-%m-%d"));
} else {
println!(" Newest entry: N/A");
}
}
Err(e) => {
println!(" Error retrieving stats: {}", e);
}
},
Err(e) => {
println!(" Error opening cache: {}", e);
}
}
}
Commands::Cache { command } => match command {
CacheCommands::Clear => {
println!("Clearing cache...");
cache::clear_cache()?;
}
},
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_number_zero() {
assert_eq!(format_number(0), "0");
}
#[test]
fn test_format_number_small() {
assert_eq!(format_number(123), "123");
assert_eq!(format_number(999), "999");
}
#[test]
fn test_format_number_thousands() {
assert_eq!(format_number(1000), "1,000");
assert_eq!(format_number(1234), "1,234");
assert_eq!(format_number(9999), "9,999");
}
#[test]
fn test_format_number_millions() {
assert_eq!(format_number(1000000), "1,000,000");
assert_eq!(format_number(1234567), "1,234,567");
}
#[test]
fn test_format_number_large() {
assert_eq!(format_number(1234567890), "1,234,567,890");
}
#[test]
fn test_format_size_bytes() {
assert_eq!(format_size(0), "0 bytes");
assert_eq!(format_size(1), "1 bytes");
assert_eq!(format_size(512), "512 bytes");
assert_eq!(format_size(1023), "1023 bytes");
}
#[test]
fn test_format_size_kb() {
assert_eq!(format_size(1024), "1.00 KB");
assert_eq!(format_size(1536), "1.50 KB");
assert_eq!(format_size(10240), "10.00 KB");
assert_eq!(format_size(1024 * 1024 - 1), "1024.00 KB");
}
#[test]
fn test_format_size_mb() {
assert_eq!(format_size(1024 * 1024), "1.00 MB");
assert_eq!(format_size(1024 * 1024 * 5), "5.00 MB");
assert_eq!(format_size(1024 * 1024 + 512 * 1024), "1.50 MB");
assert_eq!(format_size(1024 * 1024 * 1024 - 1), "1024.00 MB");
}
#[test]
fn test_format_size_gb() {
assert_eq!(format_size(1024 * 1024 * 1024), "1.00 GB");
assert_eq!(format_size(1024u64 * 1024 * 1024 * 5), "5.00 GB");
assert_eq!(
format_size(1024u64 * 1024 * 1024 + 512 * 1024 * 1024),
"1.50 GB"
);
}
#[test]
fn test_format_size_precision() {
// Test that we maintain 2 decimal places
assert_eq!(format_size(1536), "1.50 KB");
assert_eq!(format_size(1587), "1.55 KB");
assert_eq!(format_size(1024 + 10), "1.01 KB");
}
#[test]
fn test_format_duration_seconds() {
assert_eq!(format_duration(0), "0s");
assert_eq!(format_duration(1), "1s");
assert_eq!(format_duration(30), "30s");
assert_eq!(format_duration(59), "59s");
}
#[test]
fn test_format_duration_minutes() {
assert_eq!(format_duration(60), "1m 0s");
assert_eq!(format_duration(90), "1m 30s");
assert_eq!(format_duration(3599), "59m 59s");
}
#[test]
fn test_format_duration_hours() {
assert_eq!(format_duration(3600), "1h 0m 0s");
assert_eq!(format_duration(3661), "1h 1m 1s");
assert_eq!(format_duration(7200), "2h 0m 0s");
assert_eq!(format_duration(7265), "2h 1m 5s");
}
}