Skip to main content

fx_torrent/
torrent_metadata.rs

1use crate::info_hash::InfoHash;
2use crate::{bencode, error, Magnet, Sha1Hash, Sha256Hash};
3use crate::{Result, TorrentError};
4use bitmask_enum::bitmask;
5use log::warn;
6use serde::de::{Error, MapAccess, Visitor};
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8use std::collections::{BTreeMap, HashMap};
9use std::fmt::{Debug, Display, Formatter};
10use std::net::{IpAddr, SocketAddr};
11use std::path::{Path, PathBuf};
12use std::str::FromStr;
13use tokio::fs::OpenOptions;
14use tokio::io::AsyncWriteExt;
15use url::Url;
16
17/// Represents a list of URLs, which can be single, multiple, or ignored.
18pub type UrlList = Vec<String>;
19
20/// Represents the piece layers as a dictionary of strings.
21pub type PieceLayers = HashMap<String, String>;
22
23/// The file attributes of a torrent file.
24/// See BEP47 for more info.
25#[bitmask(u8)]
26#[bitmask_config(vec_debug, flags_iter)]
27pub enum FileAttributeFlags {
28    Symlink = 0b0001,
29    Executable = 0b0010,
30    Hidden = 0b0100,
31    PaddingFile = 0b1000,
32}
33
34impl Default for FileAttributeFlags {
35    fn default() -> Self {
36        FileAttributeFlags::none()
37    }
38}
39
40impl Display for FileAttributeFlags {
41    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42        let mut flags = Vec::new();
43
44        if self.contains(FileAttributeFlags::Symlink) {
45            flags.push('l');
46        }
47        if self.contains(FileAttributeFlags::Executable) {
48            flags.push('x');
49        }
50        if self.contains(FileAttributeFlags::Hidden) {
51            flags.push('h');
52        }
53        if self.contains(FileAttributeFlags::PaddingFile) {
54            flags.push('p');
55        }
56
57        write!(f, "{}", flags.into_iter().collect::<String>())
58    }
59}
60
61impl FromStr for FileAttributeFlags {
62    type Err = TorrentError;
63
64    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
65        let mut flags = FileAttributeFlags::none();
66
67        for ch in value.to_lowercase().chars() {
68            flags = match ch {
69                'l' => flags | FileAttributeFlags::Symlink,
70                'x' => flags | FileAttributeFlags::Executable,
71                'h' => flags | FileAttributeFlags::Hidden,
72                'p' => flags | FileAttributeFlags::PaddingFile,
73                _ => {
74                    return Err(TorrentError::TorrentParse(
75                        "Invalid character in file attributes".to_string(),
76                    ))
77                }
78            };
79        }
80
81        Ok(flags)
82    }
83}
84
85impl Serialize for FileAttributeFlags {
86    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
87    where
88        S: Serializer,
89    {
90        serializer.serialize_str(self.to_string().as_str())
91    }
92}
93
94impl<'de> Deserialize<'de> for FileAttributeFlags {
95    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
96    where
97        D: Deserializer<'de>,
98    {
99        Deserializer::deserialize_any(deserializer, FileAttributeFlagVisitor {})
100    }
101}
102
103struct FileAttributeFlagVisitor;
104
105impl<'de> Visitor<'de> for FileAttributeFlagVisitor {
106    type Value = FileAttributeFlags;
107
108    fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
109        write!(f, "expected a string")
110    }
111
112    fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
113    where
114        E: Error,
115    {
116        FileAttributeFlags::from_str(v).map_err(|e| Error::custom(e))
117    }
118
119    fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E>
120    where
121        E: Error,
122    {
123        FileAttributeFlags::from_str(String::from_utf8_lossy(v).as_ref())
124            .map_err(|e| Error::custom(e))
125    }
126}
127
128/// The file info metadata information of a file within a torrent.
129/// This information is specific to a single file inside the [TorrentMetadataInfo].
130#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
131pub struct TorrentFileInfo {
132    /// Length of the file in bytes.
133    pub length: u64,
134    /// Path of the file within the torrent.
135    /// This is never present in a single torrent file.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub path: Option<Vec<String>>,
138    /// The utf-8 representation path to the file.
139    /// This is never present in a single torrent file.
140    #[serde(
141        rename = "path.utf-8",
142        default,
143        skip_serializing_if = "Option::is_none"
144    )]
145    pub path_utf8: Option<Vec<String>>,
146    /// MD5 checksum of the file, if available.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub md5sum: Option<String>,
149    /// When present the characters each represent a file attribute. l = symlink, x = executable, h = hidden, p = padding file.
150    /// See BEP47
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub attr: Option<FileAttributeFlags>,
153    /// Path of the symlink target relative to the torrent root directory.
154    /// See BEP47
155    #[serde(
156        rename = "symlink path",
157        default,
158        skip_serializing_if = "Option::is_none"
159    )]
160    pub symlink_path: Option<Vec<String>>,
161    /// The SHA1 digest calculated over the contents of the file itself, without any additional padding. Can be used to aid file deduplication.
162    /// See BEP47
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub sha1: Option<String>,
165}
166
167impl TorrentFileInfo {
168    /// Get the filename of the torrent file.
169    /// If the file information belongs to a [TorrentFiles::Single], the returned string will be empty.
170    pub fn filename(&self) -> String {
171        self.path()
172            .file_name()
173            .map(|e| e.to_string_lossy().to_string())
174            .unwrap_or_default()
175    }
176
177    /// Get the path to the file within the torrent.
178    /// If the file information belongs to a [TorrentFiles::Single], the returned path will be empty.
179    pub fn path(&self) -> PathBuf {
180        let empty_vec = Vec::with_capacity(0);
181        let segments = self
182            .path_utf8
183            .as_ref()
184            .unwrap_or_else(|| self.path.as_ref().unwrap_or(&empty_vec));
185
186        let mut path = PathBuf::new();
187        for segment in segments {
188            path.push(segment);
189        }
190
191        path
192    }
193
194    /// Get the segments of the path to the torrent file.
195    /// If the file information belongs to a [TorrentFiles::Single], the returned path will be empty.
196    ///
197    /// # Returns
198    ///
199    /// Returns either the utf8 representation of the path or the normal path.
200    pub fn path_segments(&self) -> &[String] {
201        self.path_utf8
202            .as_deref()
203            .or(self.path.as_deref())
204            .unwrap_or(&[])
205    }
206
207    /// Check if the file is a padding file (see BEP47).
208    pub fn is_padding_file(&self) -> bool {
209        self.attr
210            .as_ref()
211            .map(|e| e.contains(FileAttributeFlags::PaddingFile))
212            .unwrap_or(false)
213    }
214}
215
216/// The torrent files information
217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
218#[serde(untagged)]
219pub enum TorrentFiles {
220    Single {
221        #[serde(flatten)]
222        file: TorrentFileInfo,
223    },
224    Multiple {
225        /// List of files within the directory.
226        files: Vec<TorrentFileInfo>,
227    },
228    FileTree {
229        /// A tree of dictionaries where dictionary keys represent UTF-8 encoded path elements.
230        /// See BEP52 for more info
231        #[serde(rename = "file tree")]
232        file_tree: FileTree,
233    },
234}
235
236/// The file tree of a torrent.
237/// These are the merkle roots of a v2 torrent.
238#[derive(Debug, Clone, PartialEq)]
239pub enum FileTree {
240    File(FileNode),
241    Dir(HashMap<String, FileTree>),
242}
243
244impl FileTree {
245    /// Get the total size/length of all files in the tree.
246    pub fn len(&self) -> usize {
247        match self {
248            FileTree::File(node) => node.length as usize,
249            FileTree::Dir(nodes) => nodes.iter().map(|(_, value)| value.len()).sum(),
250        }
251    }
252
253    /// Get the total amount of files in the file tree.
254    pub fn total_files(&self) -> usize {
255        match self {
256            FileTree::File(_) => 1,
257            FileTree::Dir(nodes) => nodes.iter().map(|(_, value)| value.total_files()).sum(),
258        }
259    }
260
261    /// Get the files information of the file tree.
262    pub fn files(&self) -> Vec<TorrentFileInfo> {
263        self.create_files(Vec::new())
264    }
265
266    fn create_files(&self, path: Vec<String>) -> Vec<TorrentFileInfo> {
267        match self {
268            FileTree::Dir(nodes) => nodes
269                .iter()
270                .flat_map(|(key, value)| {
271                    let mut new_path = path.clone();
272                    new_path.push(key.clone());
273                    value.create_files(new_path)
274                })
275                .collect(),
276            FileTree::File(node) => {
277                let path = if !path.is_empty() { Some(path) } else { None };
278
279                vec![TorrentFileInfo {
280                    length: node.length,
281                    path: path.clone(),
282                    path_utf8: path,
283                    md5sum: None,
284                    attr: None,
285                    symlink_path: None,
286                    sha1: None,
287                }]
288            }
289        }
290    }
291}
292
293impl Serialize for FileTree {
294    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
295    where
296        S: Serializer,
297    {
298        serde_file_tree::serialize(&self, serializer)
299    }
300}
301
302impl<'de> Deserialize<'de> for FileTree {
303    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
304    where
305        D: Deserializer<'de>,
306    {
307        serde_file_tree::deserialize(deserializer)
308    }
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
312pub struct FileNode {
313    /// Length of the file in bytes.
314    pub length: u64,
315    /// 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.
316    #[serde(
317        rename = "pieces root",
318        default,
319        with = "serde_bytes",
320        skip_serializing_if = "Option::is_none"
321    )]
322    pub pieces_root: Option<Vec<u8>>,
323}
324
325/// Metadata of a torrent, including pieces, piece length, file info, etc.
326#[derive(Clone, Serialize, Deserialize, PartialEq)]
327pub struct TorrentMetadataInfo {
328    /// Length of each piece in bytes.
329    #[serde(rename = "piece length")]
330    pub piece_length: u64,
331    /// Pieces bytes of the torrent.
332    /// Can be empty when the torrent only supports v2, see BEP52.
333    #[serde(with = "serde_bytes", default, skip_serializing_if = "Vec::is_empty")]
334    pub pieces: Vec<u8>,
335    /// Name of the torrent.
336    /// This either represents the name of the file or the name of the directory.
337    pub name: String,
338    /// Name of the torrent in UTF-8 format.
339    #[serde(
340        rename = "name.utf-8",
341        default,
342        skip_serializing_if = "Option::is_none"
343    )]
344    pub name_utf8: Option<String>,
345    /// Flag indicating if the torrent is private, see BEP27.
346    #[serde(
347        default,
348        skip_serializing_if = "std::ops::Not::not",
349        with = "crate::serde::int_bool"
350    )]
351    pub private: bool,
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub source: Option<String>,
354    /// An integer value, set to 2 to indicate compatibility with the current revision of BEP52.
355    /// Version 1 is not assigned to avoid confusion with BEP3.
356    #[serde(
357        rename = "meta version",
358        default,
359        skip_serializing_if = "Option::is_none"
360    )]
361    pub meta_version: Option<u64>,
362    /// Information about the torrent files.
363    #[serde(flatten)]
364    pub files: TorrentFiles,
365}
366
367impl TorrentMetadataInfo {
368    /// Create a new builder instance for the metadata info of the torrent.
369    pub fn builder() -> TorrentMetadataInfoBuilder {
370        TorrentMetadataInfoBuilder::builder()
371    }
372
373    /// Get the name of the torrent.
374    ///
375    /// # Returns
376    ///
377    /// Returns the utf8 representation of the name if available, else the name field.
378    pub fn name(&self) -> String {
379        self.name_utf8.clone().unwrap_or(self.name.clone())
380    }
381
382    /// Converts the pieces of the torrent into a vector of SHA1 hashes.
383    ///
384    /// # Returns
385    ///
386    /// A vector containing the SHA1 hashes of each piece.
387    pub fn sha1_pieces(&self) -> Vec<Sha1Hash> {
388        self.pieces
389            .as_slice()
390            .chunks_exact(20)
391            .map(|e| e.try_into().unwrap())
392            .collect()
393    }
394
395    /// Converts the pieces of the torrent into a vector of SHA256 hashes.
396    ///
397    /// # Returns
398    ///
399    /// A vector containing the SHA256 hashes of each piece.
400    pub fn sha256_pieces(&self) -> Vec<Sha256Hash> {
401        self.pieces
402            .as_slice()
403            .chunks_exact(32)
404            .map(|e| e.try_into().unwrap())
405            .collect()
406    }
407
408    /// Returns the total amount of bytes in the torrent.
409    pub fn len(&self) -> usize {
410        match &self.files {
411            TorrentFiles::Single { file } => file.length.clone() as usize,
412            TorrentFiles::Multiple { files, .. } => files.iter().map(|f| f.length as usize).sum(),
413            TorrentFiles::FileTree { file_tree } => file_tree.len(),
414        }
415    }
416
417    /// Get the total number of files in the torrent.
418    ///
419    /// # Returns
420    ///
421    /// Returns the total number of files in the torrent.
422    pub fn total_files(&self) -> usize {
423        match &self.files {
424            TorrentFiles::Single { .. } => 1,
425            TorrentFiles::Multiple { files } => files.len(),
426            TorrentFiles::FileTree { file_tree } => file_tree.total_files(),
427        }
428    }
429
430    /// Get the files of the torrent.
431    ///
432    /// # Returns
433    ///
434    /// Returns an array of the files of the torrent.
435    pub fn files(&self) -> Vec<TorrentFileInfo> {
436        match &self.files {
437            TorrentFiles::Single { file } => vec![file.clone()],
438            TorrentFiles::Multiple { files } => files.clone(),
439            TorrentFiles::FileTree { file_tree } => file_tree.files(),
440        }
441    }
442
443    /// Calculate the info hash of this metadata.
444    ///
445    /// # Returns
446    ///
447    /// Returns the calculated info hash, or returns an error when the info hash could not be calculated.
448    pub fn info_hash(&self) -> Result<InfoHash> {
449        let metadata_bytes = bencode::to_bytes(&self)?;
450        let is_v2 = self.meta_version.filter(|e| *e == 2).is_some();
451
452        if is_v2 {
453            Ok(InfoHash::from_metadata_v2(metadata_bytes))
454        } else {
455            Ok(InfoHash::from_metadata_v1(metadata_bytes))
456        }
457    }
458
459    /// Get the path of the given file within the torrent.
460    /// This will calculate the torrent path based on the file path segments.
461    ///
462    /// # Returns
463    ///
464    /// It returns the torrent filepath of the given file.
465    pub fn path(&self, file: &TorrentFileInfo) -> PathBuf {
466        let mut path = PathBuf::new().join(self.name());
467        for path_section in file.path_segments() {
468            path = path.join(path_section);
469        }
470        path
471    }
472}
473
474impl Debug for TorrentMetadataInfo {
475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
476        f.debug_struct("TorrentMetadata")
477            .field("piece_length", &self.piece_length)
478            .field("pieces", &self.pieces.len())
479            .field("name", &self.name)
480            .field("name_utf8", &self.name_utf8)
481            .field("private", &self.private)
482            .field("source", &self.source)
483            .field("meta_version", &self.meta_version)
484            .field("files", &self.files)
485            .finish()
486    }
487}
488
489#[derive(Debug, Default)]
490pub struct TorrentMetadataInfoBuilder {
491    pieces: Option<Vec<u8>>,
492    piece_length: Option<u64>,
493    name: Option<String>,
494    name_utf8: Option<String>,
495    private: Option<bool>,
496    source: Option<String>,
497    files: Option<TorrentFiles>,
498}
499
500impl TorrentMetadataInfoBuilder {
501    pub fn builder() -> TorrentMetadataInfoBuilder {
502        TorrentMetadataInfoBuilder::default()
503    }
504
505    pub fn pieces(&mut self, pieces: Vec<u8>) -> &mut Self {
506        self.pieces = Some(pieces);
507        self
508    }
509
510    pub fn piece_length(&mut self, piece_length: u64) -> &mut Self {
511        self.piece_length = Some(piece_length);
512        self
513    }
514
515    pub fn name(&mut self, name: String) -> &mut Self {
516        self.name = Some(name);
517        self
518    }
519
520    pub fn name_utf8(&mut self, name_utf8: String) -> &mut Self {
521        self.name_utf8 = Some(name_utf8);
522        self
523    }
524
525    /// Set if the torrent is private (see BEP27).
526    pub fn private(&mut self, private: bool) -> &mut Self {
527        self.private = Some(private);
528        self
529    }
530
531    pub fn source(&mut self, source: String) -> &mut Self {
532        self.source = Some(source);
533        self
534    }
535
536    pub fn files(&mut self, files: TorrentFiles) -> &mut Self {
537        self.files = Some(files);
538        self
539    }
540
541    pub fn build(&mut self) -> Result<TorrentMetadataInfo> {
542        let name = self.name.take().ok_or(TorrentError::InvalidMetadata(
543            "name must be set".to_string(),
544        ))?;
545        let files = self.files.take().ok_or(TorrentError::InvalidMetadata(
546            "files must be set".to_string(),
547        ))?;
548        let pieces = self.pieces.take().unwrap_or_default();
549        let piece_length = self.piece_length.take().unwrap_or_default();
550
551        Ok(TorrentMetadataInfo {
552            pieces,
553            piece_length,
554            name,
555            name_utf8: self.name_utf8.take(),
556            private: self.private.take().unwrap_or_default(),
557            source: self.source.take(),
558            meta_version: None,
559            files,
560        })
561    }
562}
563
564/// Detailed information from a .torrent file, akin to `add_torrent_params` in `libtorrent`.
565///
566/// This struct facilitates adding a new [crate::Torrent] to a session.
567///
568/// # Examples
569///
570/// ```rust,no_run
571/// # use fx_torrent::MagnetResult;
572/// # use fx_torrent::TorrentError;
573/// # use fx_torrent::TorrentMetadata;
574/// # use std::convert::TryInto;
575///
576/// fn parse_torrent_data(data: &[u8]) -> MagnetResult<TorrentMetadata> {
577///     let torrent_info: TorrentMetadata = data.try_into()?;
578///     Ok(torrent_info)
579/// }
580/// ```
581///
582/// # Remarks
583///
584/// Either the `info` field or `info_hash` field must be set for the struct to be valid.
585/// If only the info-hash is specified, the torrent file will be downloaded from peers,
586/// requiring support for the metadata extension.
587#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
588pub struct TorrentMetadata {
589    /// The display name of the torrent.
590    #[serde(skip)]
591    name: Option<String>,
592    /// URL of the tracker for the torrent.
593    pub announce: Option<String>,
594    /// Metadata specific to the torrent, equivalent to `ti` field in `add_torrent_params`.
595    pub info: Option<TorrentMetadataInfo>,
596    /// The size of the info [TorrentMetadataInfo] in bytes.
597    #[serde(skip)]
598    pub info_byte_size: Option<usize>,
599    /// A dictionary of strings. For each file in the file tree that is larger than the piece size it contains one string value.
600    /// See BEP52.
601    #[serde(rename = "piece layers", default, with = "serde_piece_layers")]
602    pub piece_layers: Option<PieceLayers>,
603    #[serde(rename = "magnet-uri")]
604    pub magnet_uri: Option<String>,
605    #[serde(rename = "announce-list")]
606    pub announce_list: Option<Vec<Vec<String>>>,
607    /// The DHT nodes for this torrent.
608    pub nodes: Option<Vec<TorrentNode>>,
609    /// Optional creation date of the torrent.
610    #[serde(rename = "creation date")]
611    pub creation_date: Option<u64>,
612    /// Optional comment associated with the torrent.
613    pub comment: Option<String>,
614    /// Optional creator of the torrent.
615    #[serde(rename = "created by")]
616    pub created_by: Option<String>,
617    /// Optional encoding format of the torrent.
618    pub encoding: Option<String>,
619    /// Optional list of URLs associated with the torrent.
620    #[serde(rename = "url-list")]
621    pub url_list: Option<UrlList>,
622    /// Optional list of http webseeds of the torrent.
623    #[serde(default, rename = "httpseeds")]
624    pub http_seeds: Option<Vec<String>>,
625    /// When metadata (.torrent file) isn't available, this uniquely identifies the torrent
626    /// and validates the info-dict when received from the swarm.
627    #[serde(skip)]
628    pub info_hash: InfoHash,
629}
630
631impl TorrentMetadata {
632    /// Creates a new `TorrentInfoBuilder` instance.
633    pub fn builder() -> TorrentMetadataBuilder {
634        TorrentMetadataBuilder::builder()
635    }
636
637    /// Get the display name of the torrent if known.
638    pub fn name(&self) -> Option<&str> {
639        self.name
640            .as_ref()
641            .filter(|e| !e.is_empty())
642            .map(|e| e.as_str())
643    }
644
645    pub fn update_name<T: Into<String>>(&mut self, name: T) {
646        self.name = Some(name.into());
647    }
648
649    /// Get the metadata version of the torrent if known.
650    ///
651    /// If the protocol version is v1, it will return `1`.
652    /// If the protocol version is v2, it will return `2`.
653    ///
654    /// # Returns
655    ///
656    /// Returns the metadata version of the torrent info if known, else [None].
657    pub fn metadata_version(&self) -> Option<u64> {
658        self.info.as_ref().map(|e| e.meta_version.unwrap_or(1))
659    }
660
661    /// Get the trackers in a tiered order for this torrent.
662    /// It makes use of a [BTreeMap] to sort the trackers by tier index.
663    ///
664    /// The key is the index of the tier and the value is the list of trackers in that tier.
665    ///
666    /// # Returns
667    ///
668    /// Returns an ordered list, by tier, of trackers for this torrent.
669    pub fn tiered_trackers(&self) -> BTreeMap<u8, Vec<Url>> {
670        let mut tiered_trackers = BTreeMap::<u8, Vec<Url>>::new();
671        let mut tier = 0u8;
672
673        // add the announce tracker info to the tiered trackers if present
674        if let Some(announce) = self.announce.as_ref() {
675            match Url::parse(announce) {
676                Ok(url) => {
677                    tiered_trackers.insert(tier, vec![url]);
678                }
679                Err(e) => warn!("Failed to parse announce url: {}", e),
680            }
681        }
682
683        // loop over the announce list and add the trackers to the tiered trackers
684        // based on the order they appear in the announce list
685        if let Some(announce_list) = self.announce_list.as_ref() {
686            for trackers in announce_list {
687                for tracker in trackers {
688                    match Url::parse(tracker) {
689                        Ok(url) => {
690                            tiered_trackers
691                                .entry(tier)
692                                .or_insert_with(Vec::new)
693                                .push(url);
694                        }
695                        Err(e) => warn!("Failed to parse announce url: {}", e),
696                    }
697                }
698
699                tier += 1;
700            }
701        }
702
703        tiered_trackers
704    }
705
706    /// Get the trackers that don't contain any order for this torrent.
707    ///
708    /// # Returns
709    ///
710    /// Returns the trackers from the `announce` field for this torrent.
711    pub fn trackers(&self) -> Vec<Url> {
712        self.announce
713            .as_ref()
714            .iter()
715            .filter_map(|url| Url::parse(url).ok())
716            .collect()
717    }
718
719    /// Returns the total number of pieces in the torrent,
720    /// or [None] if the [TorrentMetadataInfo] is unknown.
721    ///
722    /// The total number of pieces can only be calculated if the [TorrentMetadataInfo] is known.
723    pub fn total_pieces(&self) -> Option<usize> {
724        self.info
725            .as_ref()
726            .map(|metadata| {
727                let file_size = metadata.len();
728                let piece_length = metadata.piece_length as usize;
729                let num_pieces = (file_size + piece_length - 1) / piece_length;
730
731                let expected_pieces = if self.info_hash.has_v2() {
732                    metadata.sha256_pieces().len()
733                } else {
734                    metadata.sha1_pieces().len()
735                };
736
737                if expected_pieces == num_pieces {
738                    Some(num_pieces)
739                } else {
740                    warn!(
741                        "Unable to determine pieces, expected {} but got {} instead",
742                        expected_pieces, num_pieces
743                    );
744                    None
745                }
746            })
747            .unwrap_or(None)
748    }
749
750    /// Calculate the info hash from the metadata of the torrent.
751    /// This can only be done when the metadata is available.
752    ///
753    /// # Returns
754    ///
755    /// Returns the calculated info hash of the metadata.
756    pub fn calculate_info_hash(&self) -> Result<InfoHash> {
757        match &self.info {
758            Some(metadata) => metadata.info_hash(),
759            None => Err(TorrentError::InvalidMetadata(
760                "info dictionary is empty".to_string(),
761            )),
762        }
763    }
764
765    /// Returns the metadata of the torrent as bencoded bytes.
766    pub fn as_bytes(&self) -> Result<Vec<u8>> {
767        Vec::<u8>::try_from(self)
768    }
769
770    /// Saves the metadata of the torrent to the given file location.
771    /// If the target path already exists, it will be overridden.
772    pub async fn save(&self, filepath: impl AsRef<Path>) -> Result<()> {
773        let bytes = self.as_bytes()?;
774        let mut file = OpenOptions::new()
775            .write(true)
776            .truncate(true)
777            .create(true)
778            .open(filepath)
779            .await?;
780
781        file.write_all(&bytes).await?;
782        file.flush().await?;
783
784        Ok(())
785    }
786}
787
788impl TryFrom<&[u8]> for TorrentMetadata {
789    type Error = TorrentError;
790
791    /// Attempts to parse torrent metadata from the given bytes.
792    /// The bytes should be encoded in the `bencode` format.
793    ///
794    /// # Arguments
795    ///
796    /// * `value` - Byte slice containing the torrent metadata.
797    ///
798    /// # Returns
799    ///
800    /// A Result containing the parsed TorrentInfo if successful,
801    /// or a TorrentError if parsing fails.
802    fn try_from(value: &[u8]) -> Result<Self> {
803        let mut torrent_info = bencode::from_bytes::<Self>(value)
804            .map_err(|e| TorrentError::TorrentParse(e.to_string()))?;
805        // retrieve the metadata version from the metadata info, default to version 1 if unknown
806        let metadata_version = torrent_info.metadata_version().unwrap_or(1);
807        // calculate the info hash from the info dict
808        let info_bytes = bencode::to_bytes(&torrent_info.info)
809            .map_err(|e| TorrentError::TorrentParse(e.to_string()))?;
810        let info_len = info_bytes.len();
811        // calculate the info hash based on the metadata version
812        let info_hash = if metadata_version == 2 {
813            InfoHash::from_metadata_v2(info_bytes)
814        } else {
815            InfoHash::from_metadata_v1(info_bytes)
816        };
817
818        torrent_info.info_hash = info_hash;
819        torrent_info.info_byte_size = Some(info_len);
820        Ok(torrent_info)
821    }
822}
823
824impl TryFrom<&TorrentMetadata> for Vec<u8> {
825    type Error = TorrentError;
826
827    fn try_from(value: &TorrentMetadata) -> Result<Self> {
828        bencode::to_bytes(&value).map_err(|e| TorrentError::InvalidMetadata(e.to_string()))
829    }
830}
831
832impl TryFrom<Magnet> for TorrentMetadata {
833    type Error = TorrentError;
834
835    fn try_from(value: Magnet) -> Result<Self> {
836        let mut builder = TorrentMetadataBuilder::builder();
837
838        // extract the display name
839        if let Some(name) = value.display_name.as_ref() {
840            builder.name(name);
841        }
842        // extract the trackers
843        for tracker in value.trackers() {
844            builder.tracker(tracker);
845        }
846        // extract webseeds
847        let webseeds: UrlList = value.ws().into_iter().map(|e| e.clone()).collect();
848        if !webseeds.is_empty() {
849            builder.url_list(webseeds);
850        }
851        // extract the info hash
852        builder.info_hash(InfoHash::try_from_str_slice(value.xt().as_slice())?);
853
854        Ok(builder.build())
855    }
856}
857
858impl TryFrom<&TorrentMetadata> for Magnet {
859    type Error = error::MagnetError;
860
861    fn try_from(value: &TorrentMetadata) -> error::MagnetResult<Self> {
862        if let Some(uri) = value.magnet_uri.as_ref() {
863            Magnet::from_str(uri)
864        } else {
865            let topic_version = if value.info_hash.has_v2() {
866                "btmh"
867            } else {
868                "btih"
869            };
870            let mut builder = Magnet::builder();
871
872            builder
873                .exact_topic(format!("urn:{}:{}", topic_version, value.info_hash))
874                .address_trackers(
875                    value
876                        .announce_list
877                        .iter()
878                        .flat_map(|e| (*e).clone())
879                        .flat_map(|e| e)
880                        .collect(),
881                );
882
883            if let Some(name) = value.name() {
884                builder.display_name(name);
885            }
886            if let Some(web_seeds) = value.url_list.as_ref() {
887                builder.web_seeds(web_seeds.clone());
888            }
889            if let Some(metadata) = value.info.as_ref() {
890                if let Some(source) = metadata.source.as_ref() {
891                    builder.exact_source(source);
892                }
893            }
894
895            builder.build()
896        }
897    }
898}
899
900/// A builder for constructing a `TorrentInfo` struct with optional fields.
901///
902/// The `TorrentInfoBuilder` allows for the creation of a `TorrentInfo` instance with flexible configuration of its fields.
903#[derive(Debug, Default)]
904pub struct TorrentMetadataBuilder {
905    name: Option<String>,
906    announce: Option<String>,
907    info: Option<TorrentMetadataInfo>,
908    announce_list: Option<Vec<Vec<String>>>,
909    nodes: Option<Vec<TorrentNode>>,
910    creation_date: Option<u64>,
911    comment: Option<String>,
912    created_by: Option<String>,
913    encoding: Option<String>,
914    url_list: Option<UrlList>,
915    http_seeds: Option<Vec<String>>,
916    info_hash: Option<InfoHash>,
917    piece_layers: Option<HashMap<String, String>>,
918}
919
920impl TorrentMetadataBuilder {
921    /// Creates a new `TorrentInfoBuilder` instance.
922    ///
923    /// # Returns
924    ///
925    /// A new instance of `TorrentInfoBuilder`.
926    pub fn builder() -> Self {
927        Self::default()
928    }
929
930    /// Sets the name of the torrent.
931    ///
932    /// # Arguments
933    ///
934    /// * `name` - The name of the torrent.
935    ///
936    /// # Returns
937    ///
938    /// The updated `TorrentInfoBuilder` instance.
939    pub fn name<T: Into<String>>(&mut self, name: T) -> &mut Self {
940        self.name = Some(name.into());
941        self
942    }
943
944    /// Sets the announce URL for the torrent.
945    ///
946    /// # Arguments
947    ///
948    /// * `announce` - The URL of the announce tracker.
949    ///
950    /// # Returns
951    ///
952    /// The updated `TorrentInfoBuilder` instance.
953    pub fn announce<T: Into<String>>(&mut self, announce: T) -> &mut Self {
954        self.announce = Some(announce.into());
955        self
956    }
957
958    /// Sets the metadata for the torrent.
959    ///
960    /// # Arguments
961    ///
962    /// * `info` - The `TorrentMetadata` for the torrent.
963    ///
964    /// # Returns
965    ///
966    /// The updated `TorrentInfoBuilder` instance.
967    pub fn info(&mut self, info: TorrentMetadataInfo) -> &mut Self {
968        self.info = Some(info);
969        self
970    }
971
972    /// Sets the list of announce URLs for the torrent.
973    ///
974    /// # Arguments
975    ///
976    /// * `announce_list` - A list of lists of announce URLs.
977    ///
978    /// # Returns
979    ///
980    /// The updated `TorrentInfoBuilder` instance.
981    pub fn announce_list(&mut self, announce_list: Vec<Vec<String>>) -> &mut Self {
982        self.announce_list = Some(announce_list);
983        self
984    }
985
986    /// Set the given nodes for the torrent to use within the DHT discovery.
987    ///
988    /// # Arguments
989    ///
990    /// * `nodes` - The DHT nodes to add.
991    pub fn nodes(&mut self, nodes: Vec<TorrentNode>) -> &mut Self {
992        let builder_nodes = &mut self.nodes.get_or_insert(Vec::new());
993        for node in nodes {
994            builder_nodes.push(node);
995        }
996        self
997    }
998
999    /// Add the given node to the torrent DHT nodes for discovery.
1000    ///
1001    /// # Arguments
1002    ///
1003    /// * `node` - The DHT node info to add.
1004    pub fn node(&mut self, node: TorrentNode) -> &mut Self {
1005        self.nodes.get_or_insert(Vec::new()).push(node);
1006        self
1007    }
1008
1009    /// Adds a single tracker URL to the announce list.
1010    ///
1011    /// # Arguments
1012    ///
1013    /// * `tracker_uri` - The URL of the tracker to add.
1014    pub fn tracker<T: Into<String>>(&mut self, tracker_uri: T) -> &mut Self {
1015        let announce_list = self.announce_list.get_or_insert(Vec::new());
1016        announce_list.push(vec![tracker_uri.into()]);
1017        self
1018    }
1019
1020    /// Sets the creation date of the torrent.
1021    ///
1022    /// # Arguments
1023    ///
1024    /// * `creation_date` - The creation date as a Unix timestamp.
1025    pub fn creation_date(&mut self, creation_date: u64) -> &mut Self {
1026        self.creation_date = Some(creation_date);
1027        self
1028    }
1029
1030    /// Sets a comment for the torrent.
1031    ///
1032    /// # Arguments
1033    ///
1034    /// * `comment` - A comment associated with the torrent.
1035    pub fn comment<T: Into<String>>(&mut self, comment: T) -> &mut Self {
1036        self.comment = Some(comment.into());
1037        self
1038    }
1039
1040    /// Sets the creator of the torrent.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// * `created_by` - The name of the creator.
1045    pub fn created_by(&mut self, created_by: String) -> &mut Self {
1046        self.created_by = Some(created_by);
1047        self
1048    }
1049
1050    /// Sets the encoding format of the torrent.
1051    ///
1052    /// # Arguments
1053    ///
1054    /// * `encoding` - The encoding format.
1055    pub fn encoding(&mut self, encoding: String) -> &mut Self {
1056        self.encoding = Some(encoding);
1057        self
1058    }
1059
1060    /// Sets the list of URLs associated with the torrent.
1061    /// This will replace any existing url within the list.
1062    ///
1063    /// # Arguments
1064    ///
1065    /// * `url_list` - The `UrlList` containing associated URLs.
1066    pub fn url_list(&mut self, url_list: UrlList) -> &mut Self {
1067        self.url_list = Some(url_list);
1068        self
1069    }
1070
1071    /// Set the list of HTTP webseeds for the torrent.
1072    /// This will replace any existing http seeds within the list.
1073    ///
1074    /// # Arguments
1075    ///
1076    /// * `seeds` - The http webseeds.
1077    pub fn http_seeds(&mut self, seeds: Vec<String>) -> &mut Self {
1078        self.http_seeds = Some(seeds);
1079        self
1080    }
1081
1082    /// Sets the info hash for the torrent.
1083    ///
1084    /// # Arguments
1085    ///
1086    /// * `info_hash` - The `InfoHash` for the torrent.
1087    pub fn info_hash(&mut self, info_hash: InfoHash) -> &mut Self {
1088        self.info_hash = Some(info_hash);
1089        self
1090    }
1091
1092    /// Sets the piece layers for the torrent.
1093    ///
1094    /// # Arguments
1095    ///
1096    /// * `piece_layers` - A `HashMap` of piece layers.
1097    pub fn piece_layers(&mut self, piece_layers: HashMap<String, String>) -> &mut Self {
1098        self.piece_layers = Some(piece_layers);
1099        self
1100    }
1101
1102    /// Constructs and returns a `TorrentInfo` instance based on the configured builder settings.
1103    ///
1104    /// # Returns
1105    ///
1106    /// A `TorrentInfo` instance containing the fields set in the builder.
1107    /// Panics if the `info_hash` field is not set.
1108    pub fn build(&mut self) -> TorrentMetadata {
1109        TorrentMetadata {
1110            name: self.name.take(),
1111            announce: self.announce.take(),
1112            info: self.info.take(),
1113            info_byte_size: None,
1114            piece_layers: self.piece_layers.take(),
1115            magnet_uri: None,
1116            announce_list: self.announce_list.take(),
1117            nodes: self.nodes.take(),
1118            creation_date: self.creation_date.take(),
1119            comment: self.comment.take(),
1120            created_by: self.created_by.take(),
1121            encoding: self.encoding.take(),
1122            url_list: self.url_list.take(),
1123            http_seeds: self.http_seeds.take(),
1124            info_hash: self
1125                .info_hash
1126                .take()
1127                .expect("expected the info hash to be present"),
1128        }
1129    }
1130}
1131
1132/// The DHT node information for a torrent.
1133#[derive(Debug, Clone, PartialEq)]
1134pub struct TorrentNode {
1135    /// The host address of the node.
1136    /// This can either be a DNS-, IPv4 or IPv6 address.
1137    pub host: String,
1138    pub port: u16,
1139}
1140
1141impl TorrentNode {
1142    /// Get the socket address for the torrent node.
1143    pub fn socket_addr(&self) -> Result<SocketAddr> {
1144        match IpAddr::from_str(&self.host) {
1145            Ok(ip) => Ok(SocketAddr::new(ip, self.port)),
1146            Err(e) => Err(TorrentError::AddressParse(e.to_string())),
1147        }
1148    }
1149}
1150
1151impl Serialize for TorrentNode {
1152    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1153    where
1154        S: Serializer,
1155    {
1156        HashMap::from([(&self.host, self.port)]).serialize(serializer)
1157    }
1158}
1159
1160impl<'de> Deserialize<'de> for TorrentNode {
1161    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1162    where
1163        D: Deserializer<'de>,
1164    {
1165        let map = HashMap::<String, u16>::deserialize(deserializer)?;
1166        if let Some((host, port)) = map.into_iter().next() {
1167            Ok(Self { host, port })
1168        } else {
1169            Err(Error::custom("expected a torrent node pair"))
1170        }
1171    }
1172}
1173
1174mod serde_torrent {
1175    use super::*;
1176
1177    #[derive(Debug)]
1178    pub struct FileTreeVisitor;
1179
1180    impl<'de> Visitor<'de> for FileTreeVisitor {
1181        type Value = FileTree;
1182
1183        fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1184            write!(f, "expected a valid bencoded file tree")
1185        }
1186
1187        fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
1188        where
1189            A: MapAccess<'de>,
1190        {
1191            let mut file_tree = None;
1192
1193            while let Some(key) = map.next_key::<String>()? {
1194                if key == "" {
1195                    let file_node = map.next_value::<FileNode>()?;
1196                    file_tree = Some(FileTree::File(file_node));
1197                } else {
1198                    let tree = map.next_value::<FileTree>()?;
1199                    if let FileTree::Dir(file_tree_dir) =
1200                        file_tree.get_or_insert(FileTree::Dir(Default::default()))
1201                    {
1202                        file_tree_dir.insert(key, tree);
1203                    } else {
1204                        return Err(Error::custom(
1205                            "unexpected FileTree value, expected FileTree::Dir",
1206                        ));
1207                    }
1208                }
1209            }
1210
1211            match file_tree {
1212                Some(e) => Ok(e),
1213                None => Err(Error::custom("file tree map is empty")),
1214            }
1215        }
1216    }
1217
1218    #[derive(Debug)]
1219    struct StringBytes(String);
1220
1221    impl<'de> Deserialize<'de> for StringBytes {
1222        fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1223        where
1224            D: Deserializer<'de>,
1225        {
1226            deserializer.deserialize_any(StringBytesVisitor {})
1227        }
1228    }
1229
1230    #[derive(Debug)]
1231    struct StringBytesVisitor;
1232
1233    impl<'de> Visitor<'de> for StringBytesVisitor {
1234        type Value = StringBytes;
1235
1236        fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1237            write!(f, "expected a string byte array")
1238        }
1239
1240        fn visit_bytes<E>(self, v: &[u8]) -> std::result::Result<Self::Value, E>
1241        where
1242            E: Error,
1243        {
1244            Ok(StringBytes(String::from_utf8_lossy(v).to_string()))
1245        }
1246    }
1247
1248    #[derive(Debug)]
1249    pub struct PieceLayersVisitor;
1250
1251    impl<'de> Visitor<'de> for PieceLayersVisitor {
1252        type Value = PieceLayers;
1253
1254        fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1255            write!(f, "expected a dictionary of bytes representing strings")
1256        }
1257
1258        fn visit_map<A>(self, mut map: A) -> std::result::Result<Self::Value, A::Error>
1259        where
1260            A: MapAccess<'de>,
1261        {
1262            let mut result = HashMap::new();
1263
1264            while let Some((key, value)) = map.next_entry::<StringBytes, StringBytes>()? {
1265                let key_str = key.0;
1266                let value_str = value.0;
1267                result.insert(key_str, value_str);
1268            }
1269
1270            Ok(result)
1271        }
1272    }
1273}
1274
1275pub mod serde_file_tree {
1276    use super::*;
1277    use serde::ser::SerializeMap;
1278
1279    pub fn serialize<S>(file_tree: &FileTree, serializer: S) -> std::result::Result<S::Ok, S::Error>
1280    where
1281        S: Serializer,
1282    {
1283        match file_tree {
1284            FileTree::File(node) => {
1285                let mut map = serializer.serialize_map(Some(1))?;
1286                map.serialize_entry("", node)?;
1287                map.end()
1288            }
1289            FileTree::Dir(nodes) => {
1290                let mut map = serializer.serialize_map(Some(nodes.len()))?;
1291                for (key, value) in nodes {
1292                    map.serialize_entry(key, value)?;
1293                }
1294                map.end()
1295            }
1296        }
1297    }
1298
1299    pub fn deserialize<'de, D>(deserializer: D) -> std::result::Result<FileTree, D::Error>
1300    where
1301        D: Deserializer<'de>,
1302    {
1303        D::deserialize_map(deserializer, serde_torrent::FileTreeVisitor {})
1304    }
1305}
1306
1307pub mod serde_piece_layers {
1308    use super::*;
1309    use serde::ser::SerializeMap;
1310
1311    pub fn serialize<S>(
1312        value: &Option<PieceLayers>,
1313        serializer: S,
1314    ) -> std::result::Result<S::Ok, S::Error>
1315    where
1316        S: Serializer,
1317    {
1318        match value {
1319            Some(value) => {
1320                let mut map = serializer.serialize_map(Some(value.len()))?;
1321                for (k, v) in value {
1322                    map.serialize_entry(k, v)?;
1323                }
1324                map.end()
1325            }
1326            None => serializer.serialize_none(),
1327        }
1328    }
1329
1330    pub fn deserialize<'de, D>(
1331        deserializer: D,
1332    ) -> std::result::Result<Option<PieceLayers>, D::Error>
1333    where
1334        D: Deserializer<'de>,
1335    {
1336        Ok(
1337            Some(deserializer.deserialize_map(serde_torrent::PieceLayersVisitor {})?)
1338                .filter(|e| !e.is_empty()),
1339        )
1340    }
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345    use super::*;
1346    use std::str::FromStr;
1347
1348    #[test]
1349    fn test_file_attribute_flags_from_str() {
1350        let result = FileAttributeFlags::from_str("x").unwrap();
1351        assert_eq!(FileAttributeFlags::Executable, result);
1352
1353        let result = FileAttributeFlags::from_str("H").unwrap();
1354        assert_eq!(FileAttributeFlags::Hidden, result);
1355
1356        let result = FileAttributeFlags::from_str("p").unwrap();
1357        assert_eq!(FileAttributeFlags::PaddingFile, result);
1358
1359        let result = FileAttributeFlags::from_str("l").unwrap();
1360        assert_eq!(FileAttributeFlags::Symlink, result);
1361    }
1362
1363    #[test]
1364    fn test_file_attribute_flags_deserialize() {
1365        let expected_result = FileAttributeFlags::Executable | FileAttributeFlags::PaddingFile;
1366        let bytes = bencode::to_bytes(&expected_result).unwrap();
1367        let result: FileAttributeFlags = bencode::from_bytes(bytes.as_ref()).unwrap();
1368        assert_eq!(expected_result, result);
1369
1370        let expected_result = FileAttributeFlags::Symlink;
1371        let bytes = bencode::to_bytes(&expected_result).unwrap();
1372        let result: FileAttributeFlags = bencode::from_bytes(bytes.as_ref()).unwrap();
1373        assert_eq!(expected_result, result);
1374    }
1375
1376    mod torrent_metadata {
1377        use super::*;
1378        use crate::tests::read_test_file_to_bytes;
1379        use tempfile::tempdir;
1380        use tokio::fs::read;
1381
1382        #[test]
1383        fn test_tiered_trackers() {
1384            init_logger!();
1385            let announce = "udp://example.tracker.org:6969/announce";
1386            let info = TorrentMetadataBuilder::builder()
1387                .announce(announce)
1388                .announce_list(vec![
1389                    vec![
1390                        "http://foobar.tracker.org:6970/announce".to_string(),
1391                        "http://foobar.tracker.org:6971/announce".to_string(),
1392                    ],
1393                    vec!["udp://first_tier.tracker.org:6900/announce".to_string()],
1394                ])
1395                .info_hash(
1396                    InfoHash::from_str(
1397                        "urn:btmh:1220cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
1398                    )
1399                        .unwrap(),
1400                )
1401                .build();
1402            let expected_result: BTreeMap<u8, Vec<Url>> = vec![
1403                (
1404                    0u8,
1405                    vec![
1406                        Url::parse(announce).unwrap(),
1407                        Url::parse("http://foobar.tracker.org:6970/announce").unwrap(),
1408                        Url::parse("http://foobar.tracker.org:6971/announce").unwrap(),
1409                    ],
1410                ),
1411                (
1412                    1u8,
1413                    vec![Url::parse("udp://first_tier.tracker.org:6900/announce").unwrap()],
1414                ),
1415            ]
1416            .into_iter()
1417            .collect();
1418
1419            let result = info.tiered_trackers();
1420
1421            assert_eq!(expected_result, result);
1422        }
1423
1424        #[test]
1425        fn test_try_from_bytes_v1() {
1426            init_logger!();
1427            let announce = "http://bttracker.debian.org:6969/announce";
1428            let data = read_test_file_to_bytes("debian.torrent");
1429            let expected_name = "debian-11.6.0-amd64-netinst.iso";
1430            let expected_piece_length = 262144;
1431            let expected_files = TorrentFiles::Single {
1432                file: TorrentFileInfo {
1433                    length: 406847488,
1434                    path: None,
1435                    path_utf8: None,
1436                    md5sum: None,
1437                    attr: None,
1438                    symlink_path: None,
1439                    sha1: None,
1440                },
1441            };
1442
1443            let info = TorrentMetadata::try_from(data.as_slice()).unwrap();
1444
1445            assert_eq!(announce, info.announce.expect("expected announce").as_str());
1446            assert_ne!(
1447                None, info.info,
1448                "expected the metadata to have been present"
1449            );
1450            let metadata = info.info.unwrap();
1451            assert_eq!(
1452                expected_name, metadata.name,
1453                "expected the piece length to match"
1454            );
1455            assert_eq!(
1456                expected_piece_length, metadata.piece_length,
1457                "expected the piece length to match"
1458            );
1459            assert_eq!(expected_files, metadata.files);
1460        }
1461
1462        #[test]
1463        fn test_try_from_bytes_v2() {
1464            init_logger!();
1465            let data = read_test_file_to_bytes("v2.torrent");
1466            let expected_name = "bittorrent-v2-test";
1467            let expected_piece_length = 4194304;
1468            let expected_total_files = 11;
1469
1470            let info = TorrentMetadata::try_from(data.as_slice())
1471                .expect("expected the v2 torrent to parse");
1472
1473            assert_ne!(
1474                None, info.info,
1475                "expected the metadata to have been present"
1476            );
1477            let metadata = info.info.unwrap();
1478            assert_eq!(
1479                expected_name, metadata.name,
1480                "expected the piece length to match"
1481            );
1482            assert_eq!(
1483                expected_piece_length, metadata.piece_length,
1484                "expected the piece length to match"
1485            );
1486            assert_eq!(expected_total_files, metadata.total_files());
1487        }
1488
1489        #[test]
1490        fn test_files_v2() {
1491            init_logger!();
1492            let data = read_test_file_to_bytes("v2.torrent");
1493
1494            let info = TorrentMetadata::try_from(data.as_slice())
1495                .expect("expected the v2 torrent to parse");
1496            assert_ne!(
1497                None, info.info,
1498                "expected the metadata to have been present"
1499            );
1500
1501            let metadata = info.info.unwrap();
1502            let result = metadata.files();
1503            assert_eq!(11, result.len());
1504        }
1505
1506        #[test]
1507        fn test_try_from_magnet() {
1508            init_logger!();
1509            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";
1510            let magnet = Magnet::from_str(uri).unwrap();
1511
1512            let result = TorrentMetadata::try_from(magnet).unwrap();
1513
1514            let info_hash = &result.info_hash;
1515            assert_eq!(
1516                Some("eadaf0efea39406914414d359e0ea16416409bd7".to_uppercase()),
1517                info_hash.v1_as_str()
1518            );
1519            assert_eq!(Some("debian-12.4.0-amd64-DVD-1.iso"), result.name());
1520        }
1521
1522        #[test]
1523        fn test_magnet_try_from() {
1524            init_logger!();
1525            let data = read_test_file_to_bytes("debian-udp.torrent");
1526            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";
1527            let info = TorrentMetadata::try_from(data.as_slice()).unwrap();
1528
1529            let magnet = Magnet::try_from(&info).unwrap();
1530
1531            let result = magnet.to_string();
1532            assert_eq!(
1533                vec!["urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7"],
1534                magnet.xt()
1535            );
1536            assert_eq!(expected_result, result.as_str());
1537        }
1538
1539        #[test]
1540        fn test_create_info_hash() {
1541            init_logger!();
1542            let torrent = read_test_file_to_bytes("debian-udp.torrent");
1543            let info = TorrentMetadata::try_from(torrent.as_slice()).unwrap();
1544
1545            let result = info.calculate_info_hash().unwrap();
1546
1547            assert_eq!(info.info_hash, result);
1548        }
1549
1550        #[test]
1551        fn as_bytes() {
1552            init_logger!();
1553            let original_data = read_test_file_to_bytes("debian-udp.torrent");
1554            let metadata = TorrentMetadata::try_from(original_data.as_slice()).unwrap();
1555
1556            let result = metadata.as_bytes().unwrap();
1557            assert_eq!(original_data, result);
1558        }
1559
1560        #[tokio::test]
1561        async fn test_save() {
1562            init_logger!();
1563            let temp_dir = tempdir().unwrap();
1564            let target_filepath = temp_dir.path().join("test.torrent");
1565            let original_data = read_test_file_to_bytes("debian-udp.torrent");
1566            let metadata = TorrentMetadata::try_from(original_data.as_slice()).unwrap();
1567
1568            // write the file to the given location
1569            let result = metadata.save(&target_filepath).await;
1570            assert_eq!(Ok(()), result, "expected the metadata to have been saved");
1571
1572            // read the written file and verify that the data matches the original file
1573            let result = read(&target_filepath).await.unwrap();
1574            assert_eq!(
1575                original_data, result,
1576                "expected the savec metadata to match"
1577            );
1578        }
1579    }
1580
1581    mod torrent_file_info {
1582        use super::*;
1583
1584        #[test]
1585        fn test_filename() {
1586            let filename = "MyMovieFilename.mp4";
1587
1588            let file_with_path = TorrentFileInfo {
1589                length: 0,
1590                path: Some(vec!["foo".to_string(), filename.to_string()]),
1591                path_utf8: None,
1592                md5sum: None,
1593                attr: None,
1594                symlink_path: None,
1595                sha1: None,
1596            };
1597            let result = file_with_path.filename();
1598            assert_eq!(
1599                filename,
1600                result.as_str(),
1601                "expected the filename to have been retrieved from the path"
1602            );
1603
1604            let file_with_path_utf8 = TorrentFileInfo {
1605                length: 0,
1606                path: None,
1607                path_utf8: Some(vec!["foo".to_string(), filename.to_string()]),
1608                md5sum: None,
1609                attr: None,
1610                symlink_path: None,
1611                sha1: None,
1612            };
1613            let result = file_with_path_utf8.filename();
1614            assert_eq!(
1615                filename,
1616                result.as_str(),
1617                "expected the filename to have been retrieved from the path_utf8"
1618            );
1619        }
1620
1621        #[test]
1622        fn test_torrent_file_path() {
1623            let expected_result = PathBuf::from("foo/bar");
1624            let file = TorrentFileInfo {
1625                length: 0,
1626                path: Some(vec!["foo".to_string(), "bar".to_string()]),
1627                path_utf8: None,
1628                md5sum: None,
1629                attr: None,
1630                symlink_path: None,
1631                sha1: None,
1632            };
1633            let result = file.path();
1634            assert_eq!(expected_result, result);
1635
1636            let expected_result = PathBuf::from("esta/dolor");
1637            let file = TorrentFileInfo {
1638                length: 0,
1639                path: Some(vec!["this".to_string(), "is invalid".to_string()]),
1640                path_utf8: Some(vec!["esta".to_string(), "dolor".to_string()]),
1641                md5sum: None,
1642                attr: None,
1643                symlink_path: None,
1644                sha1: None,
1645            };
1646            let result = file.path();
1647            assert_eq!(expected_result, result);
1648        }
1649
1650        #[test]
1651        fn test_torrent_file_path_segments() {
1652            let expected_result = vec!["foo".to_string(), "bar".to_string()];
1653            let file = TorrentFileInfo {
1654                length: 0,
1655                path: Some(expected_result.clone()),
1656                path_utf8: None,
1657                md5sum: None,
1658                attr: None,
1659                symlink_path: None,
1660                sha1: None,
1661            };
1662            let result = file.path_segments();
1663            assert_eq!(expected_result, result);
1664
1665            let expected_result = vec!["esta".to_string(), "dolor".to_string()];
1666            let file = TorrentFileInfo {
1667                length: 0,
1668                path: Some(vec!["this".to_string(), "is invalid".to_string()]),
1669                path_utf8: Some(expected_result.clone()),
1670                md5sum: None,
1671                attr: None,
1672                symlink_path: None,
1673                sha1: None,
1674            };
1675            let result = file.path_segments();
1676            assert_eq!(expected_result, result);
1677        }
1678
1679        #[test]
1680        fn test_torrent_metadata_info_path() {
1681            let file_info = TorrentFileInfo {
1682                length: 0,
1683                path: Some(vec!["TorrentFile.mp4".to_string()]),
1684                path_utf8: None,
1685                md5sum: None,
1686                attr: None,
1687                symlink_path: None,
1688                sha1: None,
1689            };
1690            let metadata = TorrentMetadataInfo {
1691                piece_length: 0,
1692                pieces: vec![],
1693                name: "MyTorrentDir".to_string(),
1694                name_utf8: None,
1695                private: false,
1696                source: None,
1697                meta_version: None,
1698                files: TorrentFiles::Multiple {
1699                    files: vec![file_info.clone()],
1700                },
1701            };
1702            let expected_result = PathBuf::from("MyTorrentDir/TorrentFile.mp4");
1703
1704            let result = metadata.path(&file_info);
1705
1706            assert_eq!(expected_result, result);
1707        }
1708    }
1709}