fx-torrent 0.10.3

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

/// Represents a list of URLs, which can be single, multiple, or ignored.
pub type UrlList = Vec<String>;

/// Represents the piece layers as a dictionary of strings.
pub type PieceLayers = HashMap<String, String>;

/// The file attributes of a torrent file.
/// See BEP47 for more info.
#[bitmask(u8)]
#[bitmask_config(vec_debug, flags_iter)]
pub enum FileAttributeFlags {
    Symlink = 0b0001,
    Executable = 0b0010,
    Hidden = 0b0100,
    PaddingFile = 0b1000,
}

impl Default for FileAttributeFlags {
    fn default() -> Self {
        FileAttributeFlags::none()
    }
}

impl Display for FileAttributeFlags {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut flags = Vec::new();

        if self.contains(FileAttributeFlags::Symlink) {
            flags.push('l');
        }
        if self.contains(FileAttributeFlags::Executable) {
            flags.push('x');
        }
        if self.contains(FileAttributeFlags::Hidden) {
            flags.push('h');
        }
        if self.contains(FileAttributeFlags::PaddingFile) {
            flags.push('p');
        }

        write!(f, "{}", flags.into_iter().collect::<String>())
    }
}

impl FromStr for FileAttributeFlags {
    type Err = TorrentError;

    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        let mut flags = FileAttributeFlags::none();

        for ch in value.to_lowercase().chars() {
            flags = match ch {
                'l' => flags | FileAttributeFlags::Symlink,
                'x' => flags | FileAttributeFlags::Executable,
                'h' => flags | FileAttributeFlags::Hidden,
                'p' => flags | FileAttributeFlags::PaddingFile,
                _ => {
                    return Err(TorrentError::TorrentParse(
                        "Invalid character in file attributes".to_string(),
                    ))
                }
            };
        }

        Ok(flags)
    }
}

impl Serialize for FileAttributeFlags {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.to_string().as_str())
    }
}

impl<'de> Deserialize<'de> for FileAttributeFlags {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Deserializer::deserialize_any(deserializer, FileAttributeFlagVisitor {})
    }
}

struct FileAttributeFlagVisitor;

impl<'de> Visitor<'de> for FileAttributeFlagVisitor {
    type Value = FileAttributeFlags;

    fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "expected a string")
    }

    fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
    where
        E: Error,
    {
        FileAttributeFlags::from_str(v).map_err(|e| Error::custom(e))
    }

    fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E>
    where
        E: Error,
    {
        FileAttributeFlags::from_str(String::from_utf8_lossy(v).as_ref())
            .map_err(|e| Error::custom(e))
    }
}

/// The file info metadata information of a file within a torrent.
/// This information is specific to a single file inside the [TorrentMetadataInfo].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TorrentFileInfo {
    /// Length of the file in bytes.
    pub length: u64,
    /// Path of the file within the torrent.
    /// This is never present in a single torrent file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<Vec<String>>,
    /// The utf-8 representation path to the file.
    /// This is never present in a single torrent file.
    #[serde(
        rename = "path.utf-8",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub path_utf8: Option<Vec<String>>,
    /// MD5 checksum of the file, if available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub md5sum: Option<String>,
    /// When present the characters each represent a file attribute. l = symlink, x = executable, h = hidden, p = padding file.
    /// See BEP47
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attr: Option<FileAttributeFlags>,
    /// Path of the symlink target relative to the torrent root directory.
    /// See BEP47
    #[serde(
        rename = "symlink path",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub symlink_path: Option<Vec<String>>,
    /// The SHA1 digest calculated over the contents of the file itself, without any additional padding. Can be used to aid file deduplication.
    /// See BEP47
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha1: Option<String>,
}

impl TorrentFileInfo {
    /// Get the filename of the torrent file.
    /// If the file information belongs to a [TorrentFiles::Single], the returned string will be empty.
    pub fn filename(&self) -> String {
        self.path()
            .file_name()
            .map(|e| e.to_string_lossy().to_string())
            .unwrap_or_default()
    }

    /// Get the path to the file within the torrent.
    /// If the file information belongs to a [TorrentFiles::Single], the returned path will be empty.
    pub fn path(&self) -> PathBuf {
        let empty_vec = Vec::with_capacity(0);
        let segments = self
            .path_utf8
            .as_ref()
            .unwrap_or_else(|| self.path.as_ref().unwrap_or(&empty_vec));

        let mut path = PathBuf::new();
        for segment in segments {
            path.push(segment);
        }

        path
    }

    /// Get the segments of the path to the torrent file.
    /// If the file information belongs to a [TorrentFiles::Single], the returned path will be empty.
    ///
    /// # Returns
    ///
    /// Returns either the utf8 representation of the path or the normal path.
    pub fn path_segments(&self) -> &[String] {
        self.path_utf8
            .as_deref()
            .or(self.path.as_deref())
            .unwrap_or(&[])
    }

    /// Check if the file is a padding file (see BEP47).
    pub fn is_padding_file(&self) -> bool {
        self.attr
            .as_ref()
            .map(|e| e.contains(FileAttributeFlags::PaddingFile))
            .unwrap_or(false)
    }
}

/// The torrent files information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum TorrentFiles {
    Single {
        #[serde(flatten)]
        file: TorrentFileInfo,
    },
    Multiple {
        /// List of files within the directory.
        files: Vec<TorrentFileInfo>,
    },
    FileTree {
        /// A tree of dictionaries where dictionary keys represent UTF-8 encoded path elements.
        /// See BEP52 for more info
        #[serde(rename = "file tree")]
        file_tree: FileTree,
    },
}

/// The file tree of a torrent.
/// These are the merkle roots of a v2 torrent.
#[derive(Debug, Clone, PartialEq)]
pub enum FileTree {
    File(FileNode),
    Dir(HashMap<String, FileTree>),
}

impl FileTree {
    /// Get the total size/length of all files in the tree.
    pub fn len(&self) -> usize {
        match self {
            FileTree::File(node) => node.length as usize,
            FileTree::Dir(nodes) => nodes.iter().map(|(_, value)| value.len()).sum(),
        }
    }

    /// Get the total amount of files in the file tree.
    pub fn total_files(&self) -> usize {
        match self {
            FileTree::File(_) => 1,
            FileTree::Dir(nodes) => nodes.iter().map(|(_, value)| value.total_files()).sum(),
        }
    }

    /// Get the files information of the file tree.
    pub fn files(&self) -> Vec<TorrentFileInfo> {
        self.create_files(Vec::new())
    }

    fn create_files(&self, path: Vec<String>) -> Vec<TorrentFileInfo> {
        match self {
            FileTree::Dir(nodes) => nodes
                .iter()
                .flat_map(|(key, value)| {
                    let mut new_path = path.clone();
                    new_path.push(key.clone());
                    value.create_files(new_path)
                })
                .collect(),
            FileTree::File(node) => {
                let path = if !path.is_empty() { Some(path) } else { None };

                vec![TorrentFileInfo {
                    length: node.length,
                    path: path.clone(),
                    path_utf8: path,
                    md5sum: None,
                    attr: None,
                    symlink_path: None,
                    sha1: None,
                }]
            }
        }
    }
}

impl Serialize for FileTree {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serde_file_tree::serialize(&self, serializer)
    }
}

impl<'de> Deserialize<'de> for FileTree {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        serde_file_tree::deserialize(deserializer)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FileNode {
    /// Length of the file in bytes.
    pub length: u64,
    /// For non-empty files this is the root hash of a merkle tree with a branching factor of 2, constructed from 16KiB blocks of the file.
    #[serde(
        rename = "pieces root",
        default,
        with = "serde_bytes",
        skip_serializing_if = "Option::is_none"
    )]
    pub pieces_root: Option<Vec<u8>>,
}

/// Metadata of a torrent, including pieces, piece length, file info, etc.
#[derive(Clone, Serialize, Deserialize, PartialEq)]
pub struct TorrentMetadataInfo {
    /// Length of each piece in bytes.
    #[serde(rename = "piece length")]
    pub piece_length: u64,
    /// Pieces bytes of the torrent.
    /// Can be empty when the torrent only supports v2, see BEP52.
    #[serde(with = "serde_bytes", default, skip_serializing_if = "Vec::is_empty")]
    pub pieces: Vec<u8>,
    /// Name of the torrent.
    /// This either represents the name of the file or the name of the directory.
    pub name: String,
    /// Name of the torrent in UTF-8 format.
    #[serde(
        rename = "name.utf-8",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub name_utf8: Option<String>,
    /// Flag indicating if the torrent is private, see BEP27.
    #[serde(
        default,
        skip_serializing_if = "std::ops::Not::not",
        with = "crate::serde::int_bool"
    )]
    pub private: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    /// An integer value, set to 2 to indicate compatibility with the current revision of BEP52.
    /// Version 1 is not assigned to avoid confusion with BEP3.
    #[serde(
        rename = "meta version",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub meta_version: Option<u64>,
    /// Information about the torrent files.
    #[serde(flatten)]
    pub files: TorrentFiles,
}

impl TorrentMetadataInfo {
    /// Create a new builder instance for the metadata info of the torrent.
    pub fn builder() -> TorrentMetadataInfoBuilder {
        TorrentMetadataInfoBuilder::builder()
    }

    /// Get the name of the torrent.
    ///
    /// # Returns
    ///
    /// Returns the utf8 representation of the name if available, else the name field.
    pub fn name(&self) -> String {
        self.name_utf8.clone().unwrap_or(self.name.clone())
    }

    /// Converts the pieces of the torrent into a vector of SHA1 hashes.
    ///
    /// # Returns
    ///
    /// A vector containing the SHA1 hashes of each piece.
    pub fn sha1_pieces(&self) -> Vec<Sha1Hash> {
        self.pieces
            .as_slice()
            .chunks_exact(20)
            .map(|e| e.try_into().unwrap())
            .collect()
    }

    /// Converts the pieces of the torrent into a vector of SHA256 hashes.
    ///
    /// # Returns
    ///
    /// A vector containing the SHA256 hashes of each piece.
    pub fn sha256_pieces(&self) -> Vec<Sha256Hash> {
        self.pieces
            .as_slice()
            .chunks_exact(32)
            .map(|e| e.try_into().unwrap())
            .collect()
    }

    /// Returns the total amount of bytes in the torrent.
    pub fn len(&self) -> usize {
        match &self.files {
            TorrentFiles::Single { file } => file.length.clone() as usize,
            TorrentFiles::Multiple { files, .. } => files.iter().map(|f| f.length as usize).sum(),
            TorrentFiles::FileTree { file_tree } => file_tree.len(),
        }
    }

    /// Get the total number of files in the torrent.
    ///
    /// # Returns
    ///
    /// Returns the total number of files in the torrent.
    pub fn total_files(&self) -> usize {
        match &self.files {
            TorrentFiles::Single { .. } => 1,
            TorrentFiles::Multiple { files } => files.len(),
            TorrentFiles::FileTree { file_tree } => file_tree.total_files(),
        }
    }

    /// Get the files of the torrent.
    ///
    /// # Returns
    ///
    /// Returns an array of the files of the torrent.
    pub fn files(&self) -> Vec<TorrentFileInfo> {
        match &self.files {
            TorrentFiles::Single { file } => vec![file.clone()],
            TorrentFiles::Multiple { files } => files.clone(),
            TorrentFiles::FileTree { file_tree } => file_tree.files(),
        }
    }

    /// Calculate the info hash of this metadata.
    ///
    /// # Returns
    ///
    /// Returns the calculated info hash, or returns an error when the info hash could not be calculated.
    pub fn info_hash(&self) -> Result<InfoHash> {
        let metadata_bytes = bencode::to_bytes(&self)?;
        let is_v2 = self.meta_version.filter(|e| *e == 2).is_some();

        if is_v2 {
            Ok(InfoHash::from_metadata_v2(metadata_bytes))
        } else {
            Ok(InfoHash::from_metadata_v1(metadata_bytes))
        }
    }

    /// Get the path of the given file within the torrent.
    /// This will calculate the torrent path based on the file path segments.
    ///
    /// # Returns
    ///
    /// It returns the torrent filepath of the given file.
    pub fn path(&self, file: &TorrentFileInfo) -> PathBuf {
        let mut path = PathBuf::new().join(self.name());
        for path_section in file.path_segments() {
            path = path.join(path_section);
        }
        path
    }
}

impl Debug for TorrentMetadataInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TorrentMetadata")
            .field("piece_length", &self.piece_length)
            .field("pieces", &self.pieces.len())
            .field("name", &self.name)
            .field("name_utf8", &self.name_utf8)
            .field("private", &self.private)
            .field("source", &self.source)
            .field("meta_version", &self.meta_version)
            .field("files", &self.files)
            .finish()
    }
}

#[derive(Debug, Default)]
pub struct TorrentMetadataInfoBuilder {
    pieces: Option<Vec<u8>>,
    piece_length: Option<u64>,
    name: Option<String>,
    name_utf8: Option<String>,
    private: Option<bool>,
    source: Option<String>,
    files: Option<TorrentFiles>,
}

impl TorrentMetadataInfoBuilder {
    pub fn builder() -> TorrentMetadataInfoBuilder {
        TorrentMetadataInfoBuilder::default()
    }

    pub fn pieces(&mut self, pieces: Vec<u8>) -> &mut Self {
        self.pieces = Some(pieces);
        self
    }

    pub fn piece_length(&mut self, piece_length: u64) -> &mut Self {
        self.piece_length = Some(piece_length);
        self
    }

    pub fn name(&mut self, name: String) -> &mut Self {
        self.name = Some(name);
        self
    }

    pub fn name_utf8(&mut self, name_utf8: String) -> &mut Self {
        self.name_utf8 = Some(name_utf8);
        self
    }

    /// Set if the torrent is private (see BEP27).
    pub fn private(&mut self, private: bool) -> &mut Self {
        self.private = Some(private);
        self
    }

    pub fn source(&mut self, source: String) -> &mut Self {
        self.source = Some(source);
        self
    }

    pub fn files(&mut self, files: TorrentFiles) -> &mut Self {
        self.files = Some(files);
        self
    }

    pub fn build(&mut self) -> Result<TorrentMetadataInfo> {
        let name = self.name.take().ok_or(TorrentError::InvalidMetadata(
            "name must be set".to_string(),
        ))?;
        let files = self.files.take().ok_or(TorrentError::InvalidMetadata(
            "files must be set".to_string(),
        ))?;
        let pieces = self.pieces.take().unwrap_or_default();
        let piece_length = self.piece_length.take().unwrap_or_default();

        Ok(TorrentMetadataInfo {
            pieces,
            piece_length,
            name,
            name_utf8: self.name_utf8.take(),
            private: self.private.take().unwrap_or_default(),
            source: self.source.take(),
            meta_version: None,
            files,
        })
    }
}

/// Detailed information from a .torrent file, akin to `add_torrent_params` in `libtorrent`.
///
/// This struct facilitates adding a new [crate::Torrent] to a session.
///
/// # Examples
///
/// ```rust,no_run
/// # use fx_torrent::MagnetResult;
/// # use fx_torrent::TorrentError;
/// # use fx_torrent::TorrentMetadata;
/// # use std::convert::TryInto;
///
/// fn parse_torrent_data(data: &[u8]) -> MagnetResult<TorrentMetadata> {
///     let torrent_info: TorrentMetadata = data.try_into()?;
///     Ok(torrent_info)
/// }
/// ```
///
/// # Remarks
///
/// Either the `info` field or `info_hash` field must be set for the struct to be valid.
/// If only the info-hash is specified, the torrent file will be downloaded from peers,
/// requiring support for the metadata extension.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TorrentMetadata {
    /// The display name of the torrent.
    #[serde(skip)]
    name: Option<String>,
    /// URL of the tracker for the torrent.
    pub announce: Option<String>,
    /// Metadata specific to the torrent, equivalent to `ti` field in `add_torrent_params`.
    pub info: Option<TorrentMetadataInfo>,
    /// The size of the info [TorrentMetadataInfo] in bytes.
    #[serde(skip)]
    pub info_byte_size: Option<usize>,
    /// A dictionary of strings. For each file in the file tree that is larger than the piece size it contains one string value.
    /// See BEP52.
    #[serde(rename = "piece layers", default, with = "serde_piece_layers")]
    pub piece_layers: Option<PieceLayers>,
    #[serde(rename = "magnet-uri")]
    pub magnet_uri: Option<String>,
    #[serde(rename = "announce-list")]
    pub announce_list: Option<Vec<Vec<String>>>,
    /// The DHT nodes for this torrent.
    pub nodes: Option<Vec<TorrentNode>>,
    /// Optional creation date of the torrent.
    #[serde(rename = "creation date")]
    pub creation_date: Option<u64>,
    /// Optional comment associated with the torrent.
    pub comment: Option<String>,
    /// Optional creator of the torrent.
    #[serde(rename = "created by")]
    pub created_by: Option<String>,
    /// Optional encoding format of the torrent.
    pub encoding: Option<String>,
    /// Optional list of URLs associated with the torrent.
    #[serde(rename = "url-list")]
    pub url_list: Option<UrlList>,
    /// Optional list of http webseeds of the torrent.
    #[serde(default, rename = "httpseeds")]
    pub http_seeds: Option<Vec<String>>,
    /// When metadata (.torrent file) isn't available, this uniquely identifies the torrent
    /// and validates the info-dict when received from the swarm.
    #[serde(skip)]
    pub info_hash: InfoHash,
}

impl TorrentMetadata {
    /// Creates a new `TorrentInfoBuilder` instance.
    pub fn builder() -> TorrentMetadataBuilder {
        TorrentMetadataBuilder::builder()
    }

    /// Get the display name of the torrent if known.
    pub fn name(&self) -> Option<&str> {
        self.name
            .as_ref()
            .filter(|e| !e.is_empty())
            .map(|e| e.as_str())
    }

    pub fn update_name<T: Into<String>>(&mut self, name: T) {
        self.name = Some(name.into());
    }

    /// Get the metadata version of the torrent if known.
    ///
    /// If the protocol version is v1, it will return `1`.
    /// If the protocol version is v2, it will return `2`.
    ///
    /// # Returns
    ///
    /// Returns the metadata version of the torrent info if known, else [None].
    pub fn metadata_version(&self) -> Option<u64> {
        self.info.as_ref().map(|e| e.meta_version.unwrap_or(1))
    }

    /// Get the trackers in a tiered order for this torrent.
    /// It makes use of a [BTreeMap] to sort the trackers by tier index.
    ///
    /// The key is the index of the tier and the value is the list of trackers in that tier.
    ///
    /// # Returns
    ///
    /// Returns an ordered list, by tier, of trackers for this torrent.
    pub fn tiered_trackers(&self) -> BTreeMap<u8, Vec<Url>> {
        let mut tiered_trackers = BTreeMap::<u8, Vec<Url>>::new();
        let mut tier = 0u8;

        // add the announce tracker info to the tiered trackers if present
        if let Some(announce) = self.announce.as_ref() {
            match Url::parse(announce) {
                Ok(url) => {
                    tiered_trackers.insert(tier, vec![url]);
                }
                Err(e) => warn!("Failed to parse announce url: {}", e),
            }
        }

        // loop over the announce list and add the trackers to the tiered trackers
        // based on the order they appear in the announce list
        if let Some(announce_list) = self.announce_list.as_ref() {
            for trackers in announce_list {
                for tracker in trackers {
                    match Url::parse(tracker) {
                        Ok(url) => {
                            tiered_trackers
                                .entry(tier)
                                .or_insert_with(Vec::new)
                                .push(url);
                        }
                        Err(e) => warn!("Failed to parse announce url: {}", e),
                    }
                }

                tier += 1;
            }
        }

        tiered_trackers
    }

    /// Get the trackers that don't contain any order for this torrent.
    ///
    /// # Returns
    ///
    /// Returns the trackers from the `announce` field for this torrent.
    pub fn trackers(&self) -> Vec<Url> {
        self.announce
            .as_ref()
            .iter()
            .filter_map(|url| Url::parse(url).ok())
            .collect()
    }

    /// Returns the total number of pieces in the torrent,
    /// or [None] if the [TorrentMetadataInfo] is unknown.
    ///
    /// The total number of pieces can only be calculated if the [TorrentMetadataInfo] is known.
    pub fn total_pieces(&self) -> Option<usize> {
        self.info
            .as_ref()
            .map(|metadata| {
                let file_size = metadata.len();
                let piece_length = metadata.piece_length as usize;
                let num_pieces = (file_size + piece_length - 1) / piece_length;

                let expected_pieces = if self.info_hash.has_v2() {
                    metadata.sha256_pieces().len()
                } else {
                    metadata.sha1_pieces().len()
                };

                if expected_pieces == num_pieces {
                    Some(num_pieces)
                } else {
                    warn!(
                        "Unable to determine pieces, expected {} but got {} instead",
                        expected_pieces, num_pieces
                    );
                    None
                }
            })
            .unwrap_or(None)
    }

    /// Calculate the info hash from the metadata of the torrent.
    /// This can only be done when the metadata is available.
    ///
    /// # Returns
    ///
    /// Returns the calculated info hash of the metadata.
    pub fn calculate_info_hash(&self) -> Result<InfoHash> {
        match &self.info {
            Some(metadata) => metadata.info_hash(),
            None => Err(TorrentError::InvalidMetadata(
                "info dictionary is empty".to_string(),
            )),
        }
    }

    /// Returns the metadata of the torrent as bencoded bytes.
    pub fn as_bytes(&self) -> Result<Vec<u8>> {
        Vec::<u8>::try_from(self)
    }

    /// Saves the metadata of the torrent to the given file location.
    /// If the target path already exists, it will be overridden.
    pub async fn save(&self, filepath: impl AsRef<Path>) -> Result<()> {
        let bytes = self.as_bytes()?;
        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(filepath)
            .await?;

        file.write_all(&bytes).await?;
        file.flush().await?;

        Ok(())
    }
}

impl TryFrom<&[u8]> for TorrentMetadata {
    type Error = TorrentError;

    /// Attempts to parse torrent metadata from the given bytes.
    /// The bytes should be encoded in the `bencode` format.
    ///
    /// # Arguments
    ///
    /// * `value` - Byte slice containing the torrent metadata.
    ///
    /// # Returns
    ///
    /// A Result containing the parsed TorrentInfo if successful,
    /// or a TorrentError if parsing fails.
    fn try_from(value: &[u8]) -> Result<Self> {
        let mut torrent_info = bencode::from_bytes::<Self>(value)
            .map_err(|e| TorrentError::TorrentParse(e.to_string()))?;
        // retrieve the metadata version from the metadata info, default to version 1 if unknown
        let metadata_version = torrent_info.metadata_version().unwrap_or(1);
        // calculate the info hash from the info dict
        let info_bytes = bencode::to_bytes(&torrent_info.info)
            .map_err(|e| TorrentError::TorrentParse(e.to_string()))?;
        let info_len = info_bytes.len();
        // calculate the info hash based on the metadata version
        let info_hash = if metadata_version == 2 {
            InfoHash::from_metadata_v2(info_bytes)
        } else {
            InfoHash::from_metadata_v1(info_bytes)
        };

        torrent_info.info_hash = info_hash;
        torrent_info.info_byte_size = Some(info_len);
        Ok(torrent_info)
    }
}

impl TryFrom<&TorrentMetadata> for Vec<u8> {
    type Error = TorrentError;

    fn try_from(value: &TorrentMetadata) -> Result<Self> {
        bencode::to_bytes(&value).map_err(|e| TorrentError::InvalidMetadata(e.to_string()))
    }
}

impl TryFrom<Magnet> for TorrentMetadata {
    type Error = TorrentError;

    fn try_from(value: Magnet) -> Result<Self> {
        let mut builder = TorrentMetadataBuilder::builder();

        // extract the display name
        if let Some(name) = value.display_name.as_ref() {
            builder.name(name);
        }
        // extract the trackers
        for tracker in value.trackers() {
            builder.tracker(tracker);
        }
        // extract webseeds
        let webseeds: UrlList = value.ws().into_iter().map(|e| e.clone()).collect();
        if !webseeds.is_empty() {
            builder.url_list(webseeds);
        }
        // extract the info hash
        builder.info_hash(InfoHash::try_from_str_slice(value.xt().as_slice())?);

        Ok(builder.build())
    }
}

impl TryFrom<&TorrentMetadata> for Magnet {
    type Error = error::MagnetError;

    fn try_from(value: &TorrentMetadata) -> error::MagnetResult<Self> {
        if let Some(uri) = value.magnet_uri.as_ref() {
            Magnet::from_str(uri)
        } else {
            let topic_version = if value.info_hash.has_v2() {
                "btmh"
            } else {
                "btih"
            };
            let mut builder = Magnet::builder();

            builder
                .exact_topic(format!("urn:{}:{}", topic_version, value.info_hash))
                .address_trackers(
                    value
                        .announce_list
                        .iter()
                        .flat_map(|e| (*e).clone())
                        .flat_map(|e| e)
                        .collect(),
                );

            if let Some(name) = value.name() {
                builder.display_name(name);
            }
            if let Some(web_seeds) = value.url_list.as_ref() {
                builder.web_seeds(web_seeds.clone());
            }
            if let Some(metadata) = value.info.as_ref() {
                if let Some(source) = metadata.source.as_ref() {
                    builder.exact_source(source);
                }
            }

            builder.build()
        }
    }
}

/// A builder for constructing a `TorrentInfo` struct with optional fields.
///
/// The `TorrentInfoBuilder` allows for the creation of a `TorrentInfo` instance with flexible configuration of its fields.
#[derive(Debug, Default)]
pub struct TorrentMetadataBuilder {
    name: Option<String>,
    announce: Option<String>,
    info: Option<TorrentMetadataInfo>,
    announce_list: Option<Vec<Vec<String>>>,
    nodes: Option<Vec<TorrentNode>>,
    creation_date: Option<u64>,
    comment: Option<String>,
    created_by: Option<String>,
    encoding: Option<String>,
    url_list: Option<UrlList>,
    http_seeds: Option<Vec<String>>,
    info_hash: Option<InfoHash>,
    piece_layers: Option<HashMap<String, String>>,
}

impl TorrentMetadataBuilder {
    /// Creates a new `TorrentInfoBuilder` instance.
    ///
    /// # Returns
    ///
    /// A new instance of `TorrentInfoBuilder`.
    pub fn builder() -> Self {
        Self::default()
    }

    /// Sets the name of the torrent.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the torrent.
    ///
    /// # Returns
    ///
    /// The updated `TorrentInfoBuilder` instance.
    pub fn name<T: Into<String>>(&mut self, name: T) -> &mut Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the announce URL for the torrent.
    ///
    /// # Arguments
    ///
    /// * `announce` - The URL of the announce tracker.
    ///
    /// # Returns
    ///
    /// The updated `TorrentInfoBuilder` instance.
    pub fn announce<T: Into<String>>(&mut self, announce: T) -> &mut Self {
        self.announce = Some(announce.into());
        self
    }

    /// Sets the metadata for the torrent.
    ///
    /// # Arguments
    ///
    /// * `info` - The `TorrentMetadata` for the torrent.
    ///
    /// # Returns
    ///
    /// The updated `TorrentInfoBuilder` instance.
    pub fn info(&mut self, info: TorrentMetadataInfo) -> &mut Self {
        self.info = Some(info);
        self
    }

    /// Sets the list of announce URLs for the torrent.
    ///
    /// # Arguments
    ///
    /// * `announce_list` - A list of lists of announce URLs.
    ///
    /// # Returns
    ///
    /// The updated `TorrentInfoBuilder` instance.
    pub fn announce_list(&mut self, announce_list: Vec<Vec<String>>) -> &mut Self {
        self.announce_list = Some(announce_list);
        self
    }

    /// Set the given nodes for the torrent to use within the DHT discovery.
    ///
    /// # Arguments
    ///
    /// * `nodes` - The DHT nodes to add.
    pub fn nodes(&mut self, nodes: Vec<TorrentNode>) -> &mut Self {
        let builder_nodes = &mut self.nodes.get_or_insert(Vec::new());
        for node in nodes {
            builder_nodes.push(node);
        }
        self
    }

    /// Add the given node to the torrent DHT nodes for discovery.
    ///
    /// # Arguments
    ///
    /// * `node` - The DHT node info to add.
    pub fn node(&mut self, node: TorrentNode) -> &mut Self {
        self.nodes.get_or_insert(Vec::new()).push(node);
        self
    }

    /// Adds a single tracker URL to the announce list.
    ///
    /// # Arguments
    ///
    /// * `tracker_uri` - The URL of the tracker to add.
    pub fn tracker<T: Into<String>>(&mut self, tracker_uri: T) -> &mut Self {
        let announce_list = self.announce_list.get_or_insert(Vec::new());
        announce_list.push(vec![tracker_uri.into()]);
        self
    }

    /// Sets the creation date of the torrent.
    ///
    /// # Arguments
    ///
    /// * `creation_date` - The creation date as a Unix timestamp.
    pub fn creation_date(&mut self, creation_date: u64) -> &mut Self {
        self.creation_date = Some(creation_date);
        self
    }

    /// Sets a comment for the torrent.
    ///
    /// # Arguments
    ///
    /// * `comment` - A comment associated with the torrent.
    pub fn comment<T: Into<String>>(&mut self, comment: T) -> &mut Self {
        self.comment = Some(comment.into());
        self
    }

    /// Sets the creator of the torrent.
    ///
    /// # Arguments
    ///
    /// * `created_by` - The name of the creator.
    pub fn created_by(&mut self, created_by: String) -> &mut Self {
        self.created_by = Some(created_by);
        self
    }

    /// Sets the encoding format of the torrent.
    ///
    /// # Arguments
    ///
    /// * `encoding` - The encoding format.
    pub fn encoding(&mut self, encoding: String) -> &mut Self {
        self.encoding = Some(encoding);
        self
    }

    /// Sets the list of URLs associated with the torrent.
    /// This will replace any existing url within the list.
    ///
    /// # Arguments
    ///
    /// * `url_list` - The `UrlList` containing associated URLs.
    pub fn url_list(&mut self, url_list: UrlList) -> &mut Self {
        self.url_list = Some(url_list);
        self
    }

    /// Set the list of HTTP webseeds for the torrent.
    /// This will replace any existing http seeds within the list.
    ///
    /// # Arguments
    ///
    /// * `seeds` - The http webseeds.
    pub fn http_seeds(&mut self, seeds: Vec<String>) -> &mut Self {
        self.http_seeds = Some(seeds);
        self
    }

    /// Sets the info hash for the torrent.
    ///
    /// # Arguments
    ///
    /// * `info_hash` - The `InfoHash` for the torrent.
    pub fn info_hash(&mut self, info_hash: InfoHash) -> &mut Self {
        self.info_hash = Some(info_hash);
        self
    }

    /// Sets the piece layers for the torrent.
    ///
    /// # Arguments
    ///
    /// * `piece_layers` - A `HashMap` of piece layers.
    pub fn piece_layers(&mut self, piece_layers: HashMap<String, String>) -> &mut Self {
        self.piece_layers = Some(piece_layers);
        self
    }

    /// Constructs and returns a `TorrentInfo` instance based on the configured builder settings.
    ///
    /// # Returns
    ///
    /// A `TorrentInfo` instance containing the fields set in the builder.
    /// Panics if the `info_hash` field is not set.
    pub fn build(&mut self) -> TorrentMetadata {
        TorrentMetadata {
            name: self.name.take(),
            announce: self.announce.take(),
            info: self.info.take(),
            info_byte_size: None,
            piece_layers: self.piece_layers.take(),
            magnet_uri: None,
            announce_list: self.announce_list.take(),
            nodes: self.nodes.take(),
            creation_date: self.creation_date.take(),
            comment: self.comment.take(),
            created_by: self.created_by.take(),
            encoding: self.encoding.take(),
            url_list: self.url_list.take(),
            http_seeds: self.http_seeds.take(),
            info_hash: self
                .info_hash
                .take()
                .expect("expected the info hash to be present"),
        }
    }
}

/// The DHT node information for a torrent.
#[derive(Debug, Clone, PartialEq)]
pub struct TorrentNode {
    /// The host address of the node.
    /// This can either be a DNS-, IPv4 or IPv6 address.
    pub host: String,
    pub port: u16,
}

impl TorrentNode {
    /// Get the socket address for the torrent node.
    pub fn socket_addr(&self) -> Result<SocketAddr> {
        match IpAddr::from_str(&self.host) {
            Ok(ip) => Ok(SocketAddr::new(ip, self.port)),
            Err(e) => Err(TorrentError::AddressParse(e.to_string())),
        }
    }
}

impl Serialize for TorrentNode {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        HashMap::from([(&self.host, self.port)]).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for TorrentNode {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let map = HashMap::<String, u16>::deserialize(deserializer)?;
        if let Some((host, port)) = map.into_iter().next() {
            Ok(Self { host, port })
        } else {
            Err(Error::custom("expected a torrent node pair"))
        }
    }
}

mod serde_torrent {
    use super::*;

    #[derive(Debug)]
    pub struct FileTreeVisitor;

    impl<'de> Visitor<'de> for FileTreeVisitor {
        type Value = FileTree;

        fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
            write!(f, "expected a valid bencoded file tree")
        }

        fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut file_tree = None;

            while let Some(key) = map.next_key::<String>()? {
                if key == "" {
                    let file_node = map.next_value::<FileNode>()?;
                    file_tree = Some(FileTree::File(file_node));
                } else {
                    let tree = map.next_value::<FileTree>()?;
                    if let FileTree::Dir(file_tree_dir) =
                        file_tree.get_or_insert(FileTree::Dir(Default::default()))
                    {
                        file_tree_dir.insert(key, tree);
                    } else {
                        return Err(Error::custom(
                            "unexpected FileTree value, expected FileTree::Dir",
                        ));
                    }
                }
            }

            match file_tree {
                Some(e) => Ok(e),
                None => Err(Error::custom("file tree map is empty")),
            }
        }
    }

    #[derive(Debug)]
    struct StringBytes(String);

    impl<'de> Deserialize<'de> for StringBytes {
        fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_any(StringBytesVisitor {})
        }
    }

    #[derive(Debug)]
    struct StringBytesVisitor;

    impl<'de> Visitor<'de> for StringBytesVisitor {
        type Value = StringBytes;

        fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
            write!(f, "expected a string byte array")
        }

        fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E>
        where
            E: Error,
        {
            Ok(StringBytes(String::from_utf8_lossy(v).to_string()))
        }
    }

    #[derive(Debug)]
    pub struct PieceLayersVisitor;

    impl<'de> Visitor<'de> for PieceLayersVisitor {
        type Value = PieceLayers;

        fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
            write!(f, "expected a dictionary of bytes representing strings")
        }

        fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut result = HashMap::new();

            while let Some((key, value)) = map.next_entry::<StringBytes, StringBytes>()? {
                let key_str = key.0;
                let value_str = value.0;
                result.insert(key_str, value_str);
            }

            Ok(result)
        }
    }
}

pub mod serde_file_tree {
    use super::*;
    use serde::ser::SerializeMap;

    pub fn serialize<S>(file_tree: &FileTree, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match file_tree {
            FileTree::File(node) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("", node)?;
                map.end()
            }
            FileTree::Dir(nodes) => {
                let mut map = serializer.serialize_map(Some(nodes.len()))?;
                for (key, value) in nodes {
                    map.serialize_entry(key, value)?;
                }
                map.end()
            }
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> std::result::Result<FileTree, D::Error>
    where
        D: Deserializer<'de>,
    {
        D::deserialize_map(deserializer, serde_torrent::FileTreeVisitor {})
    }
}

pub mod serde_piece_layers {
    use super::*;
    use serde::ser::SerializeMap;

    pub fn serialize<S>(
        value: &Option<PieceLayers>,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(value) => {
                let mut map = serializer.serialize_map(Some(value.len()))?;
                for (k, v) in value {
                    map.serialize_entry(k, v)?;
                }
                map.end()
            }
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(
        deserializer: D,
    ) -> std::result::Result<Option<PieceLayers>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(
            Some(deserializer.deserialize_map(serde_torrent::PieceLayersVisitor {})?)
                .filter(|e| !e.is_empty()),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::str::FromStr;

    #[test]
    fn test_file_attribute_flags_from_str() {
        let result = FileAttributeFlags::from_str("x").unwrap();
        assert_eq!(FileAttributeFlags::Executable, result);

        let result = FileAttributeFlags::from_str("H").unwrap();
        assert_eq!(FileAttributeFlags::Hidden, result);

        let result = FileAttributeFlags::from_str("p").unwrap();
        assert_eq!(FileAttributeFlags::PaddingFile, result);

        let result = FileAttributeFlags::from_str("l").unwrap();
        assert_eq!(FileAttributeFlags::Symlink, result);
    }

    #[test]
    fn test_file_attribute_flags_deserialize() {
        let expected_result = FileAttributeFlags::Executable | FileAttributeFlags::PaddingFile;
        let bytes = bencode::to_bytes(&expected_result).unwrap();
        let result: FileAttributeFlags = bencode::from_bytes(bytes.as_ref()).unwrap();
        assert_eq!(expected_result, result);

        let expected_result = FileAttributeFlags::Symlink;
        let bytes = bencode::to_bytes(&expected_result).unwrap();
        let result: FileAttributeFlags = bencode::from_bytes(bytes.as_ref()).unwrap();
        assert_eq!(expected_result, result);
    }

    mod torrent_metadata {
        use super::*;
        use crate::tests::read_test_file_to_bytes;
        use tempfile::tempdir;
        use tokio::fs::read;

        #[test]
        fn test_tiered_trackers() {
            init_logger!();
            let announce = "udp://example.tracker.org:6969/announce";
            let info = TorrentMetadataBuilder::builder()
                .announce(announce)
                .announce_list(vec![
                    vec![
                        "http://foobar.tracker.org:6970/announce".to_string(),
                        "http://foobar.tracker.org:6971/announce".to_string(),
                    ],
                    vec!["udp://first_tier.tracker.org:6900/announce".to_string()],
                ])
                .info_hash(
                    InfoHash::from_str(
                        "urn:btmh:1220cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
                    )
                        .unwrap(),
                )
                .build();
            let expected_result: BTreeMap<u8, Vec<Url>> = vec![
                (
                    0u8,
                    vec![
                        Url::parse(announce).unwrap(),
                        Url::parse("http://foobar.tracker.org:6970/announce").unwrap(),
                        Url::parse("http://foobar.tracker.org:6971/announce").unwrap(),
                    ],
                ),
                (
                    1u8,
                    vec![Url::parse("udp://first_tier.tracker.org:6900/announce").unwrap()],
                ),
            ]
            .into_iter()
            .collect();

            let result = info.tiered_trackers();

            assert_eq!(expected_result, result);
        }

        #[test]
        fn test_try_from_bytes_v1() {
            init_logger!();
            let announce = "http://bttracker.debian.org:6969/announce";
            let data = read_test_file_to_bytes("debian.torrent");
            let expected_name = "debian-11.6.0-amd64-netinst.iso";
            let expected_piece_length = 262144;
            let expected_files = TorrentFiles::Single {
                file: TorrentFileInfo {
                    length: 406847488,
                    path: None,
                    path_utf8: None,
                    md5sum: None,
                    attr: None,
                    symlink_path: None,
                    sha1: None,
                },
            };

            let info = TorrentMetadata::try_from(data.as_slice()).unwrap();

            assert_eq!(announce, info.announce.expect("expected announce").as_str());
            assert_ne!(
                None, info.info,
                "expected the metadata to have been present"
            );
            let metadata = info.info.unwrap();
            assert_eq!(
                expected_name, metadata.name,
                "expected the piece length to match"
            );
            assert_eq!(
                expected_piece_length, metadata.piece_length,
                "expected the piece length to match"
            );
            assert_eq!(expected_files, metadata.files);
        }

        #[test]
        fn test_try_from_bytes_v2() {
            init_logger!();
            let data = read_test_file_to_bytes("v2.torrent");
            let expected_name = "bittorrent-v2-test";
            let expected_piece_length = 4194304;
            let expected_total_files = 11;

            let info = TorrentMetadata::try_from(data.as_slice())
                .expect("expected the v2 torrent to parse");

            assert_ne!(
                None, info.info,
                "expected the metadata to have been present"
            );
            let metadata = info.info.unwrap();
            assert_eq!(
                expected_name, metadata.name,
                "expected the piece length to match"
            );
            assert_eq!(
                expected_piece_length, metadata.piece_length,
                "expected the piece length to match"
            );
            assert_eq!(expected_total_files, metadata.total_files());
        }

        #[test]
        fn test_files_v2() {
            init_logger!();
            let data = read_test_file_to_bytes("v2.torrent");

            let info = TorrentMetadata::try_from(data.as_slice())
                .expect("expected the v2 torrent to parse");
            assert_ne!(
                None, info.info,
                "expected the metadata to have been present"
            );

            let metadata = info.info.unwrap();
            let result = metadata.files();
            assert_eq!(11, result.len());
        }

        #[test]
        fn test_try_from_magnet() {
            init_logger!();
            let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce";
            let magnet = Magnet::from_str(uri).unwrap();

            let result = TorrentMetadata::try_from(magnet).unwrap();

            let info_hash = &result.info_hash;
            assert_eq!(
                Some("eadaf0efea39406914414d359e0ea16416409bd7".to_uppercase()),
                info_hash.v1_as_str()
            );
            assert_eq!(Some("debian-12.4.0-amd64-DVD-1.iso"), result.name());
        }

        #[test]
        fn test_magnet_try_from() {
            init_logger!();
            let data = read_test_file_to_bytes("debian-udp.torrent");
            let expected_result = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce";
            let info = TorrentMetadata::try_from(data.as_slice()).unwrap();

            let magnet = Magnet::try_from(&info).unwrap();

            let result = magnet.to_string();
            assert_eq!(
                vec!["urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7"],
                magnet.xt()
            );
            assert_eq!(expected_result, result.as_str());
        }

        #[test]
        fn test_create_info_hash() {
            init_logger!();
            let torrent = read_test_file_to_bytes("debian-udp.torrent");
            let info = TorrentMetadata::try_from(torrent.as_slice()).unwrap();

            let result = info.calculate_info_hash().unwrap();

            assert_eq!(info.info_hash, result);
        }

        #[test]
        fn as_bytes() {
            init_logger!();
            let original_data = read_test_file_to_bytes("debian-udp.torrent");
            let metadata = TorrentMetadata::try_from(original_data.as_slice()).unwrap();

            let result = metadata.as_bytes().unwrap();
            assert_eq!(original_data, result);
        }

        #[tokio::test]
        async fn test_save() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let target_filepath = temp_dir.path().join("test.torrent");
            let original_data = read_test_file_to_bytes("debian-udp.torrent");
            let metadata = TorrentMetadata::try_from(original_data.as_slice()).unwrap();

            // write the file to the given location
            let result = metadata.save(&target_filepath).await;
            assert_eq!(Ok(()), result, "expected the metadata to have been saved");

            // read the written file and verify that the data matches the original file
            let result = read(&target_filepath).await.unwrap();
            assert_eq!(
                original_data, result,
                "expected the savec metadata to match"
            );
        }
    }

    mod torrent_file_info {
        use super::*;

        #[test]
        fn test_filename() {
            let filename = "MyMovieFilename.mp4";

            let file_with_path = TorrentFileInfo {
                length: 0,
                path: Some(vec!["foo".to_string(), filename.to_string()]),
                path_utf8: None,
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let result = file_with_path.filename();
            assert_eq!(
                filename,
                result.as_str(),
                "expected the filename to have been retrieved from the path"
            );

            let file_with_path_utf8 = TorrentFileInfo {
                length: 0,
                path: None,
                path_utf8: Some(vec!["foo".to_string(), filename.to_string()]),
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let result = file_with_path_utf8.filename();
            assert_eq!(
                filename,
                result.as_str(),
                "expected the filename to have been retrieved from the path_utf8"
            );
        }

        #[test]
        fn test_torrent_file_path() {
            let expected_result = PathBuf::from("foo/bar");
            let file = TorrentFileInfo {
                length: 0,
                path: Some(vec!["foo".to_string(), "bar".to_string()]),
                path_utf8: None,
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let result = file.path();
            assert_eq!(expected_result, result);

            let expected_result = PathBuf::from("esta/dolor");
            let file = TorrentFileInfo {
                length: 0,
                path: Some(vec!["this".to_string(), "is invalid".to_string()]),
                path_utf8: Some(vec!["esta".to_string(), "dolor".to_string()]),
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let result = file.path();
            assert_eq!(expected_result, result);
        }

        #[test]
        fn test_torrent_file_path_segments() {
            let expected_result = vec!["foo".to_string(), "bar".to_string()];
            let file = TorrentFileInfo {
                length: 0,
                path: Some(expected_result.clone()),
                path_utf8: None,
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let result = file.path_segments();
            assert_eq!(expected_result, result);

            let expected_result = vec!["esta".to_string(), "dolor".to_string()];
            let file = TorrentFileInfo {
                length: 0,
                path: Some(vec!["this".to_string(), "is invalid".to_string()]),
                path_utf8: Some(expected_result.clone()),
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let result = file.path_segments();
            assert_eq!(expected_result, result);
        }

        #[test]
        fn test_torrent_metadata_info_path() {
            let file_info = TorrentFileInfo {
                length: 0,
                path: Some(vec!["TorrentFile.mp4".to_string()]),
                path_utf8: None,
                md5sum: None,
                attr: None,
                symlink_path: None,
                sha1: None,
            };
            let metadata = TorrentMetadataInfo {
                piece_length: 0,
                pieces: vec![],
                name: "MyTorrentDir".to_string(),
                name_utf8: None,
                private: false,
                source: None,
                meta_version: None,
                files: TorrentFiles::Multiple {
                    files: vec![file_info.clone()],
                },
            };
            let expected_result = PathBuf::from("MyTorrentDir/TorrentFile.mp4");

            let result = metadata.path(&file_info);

            assert_eq!(expected_result, result);
        }
    }
}