Skip to main content

bencode_read_torrent_files/common/
torrent.rs

1use babbel_bencode::{FileSource, Node, parse};
2use std::collections::HashMap;
3use std::path::Path;
4
5/// Represents details about a single file within a torrent
6///
7/// # Fields
8/// * `path` - The file path relative to the torrent root directory
9/// * `length` - Size of the file in bytes
10#[derive(Debug, PartialEq)]
11pub struct FileDetails {
12    pub path: String,
13    pub length: u64,
14}
15
16/// Represents the metadata contained in a .torrent file
17///
18/// # Fields
19/// * `announce` - The tracker URL
20/// * `announce_list` - List of backup tracker URLs
21/// * `encoding` - Character encoding used for strings
22/// * `attribute` - Optional attribute field
23/// * `comment` - Optional comment about the torrent
24/// * `creation_date` - Unix timestamp of when the torrent was created
25/// * `created_by` - Name/version of the program that created the torrent
26/// * `length` - Total size of all files in bytes
27/// * `name` - Name of the torrent (usually the directory name)
28/// * `piece_length` - Size of each piece in bytes
29/// * `pieces` - String of concatenated 20-byte SHA1 piece hashes
30/// * `private_flag` - Whether the torrent is private (1) or public (0)
31/// * `source` - Source of the torrent
32/// * `files` - List of files included in the torrent
33#[derive(Debug, PartialEq)]
34pub struct TorrentFile {
35    pub announce: String,
36    pub announce_list: Vec<String>,
37    pub encoding: String,
38    pub attribute: u64,
39    pub comment: String,
40    pub creation_date: u64,
41    pub created_by: String,
42    pub length: u64,
43    pub name: String,
44    pub piece_length: u64,
45    pub pieces: String,
46    pub private_flag: u64,
47    pub source: String,
48    pub files: Vec<FileDetails>,
49}
50
51impl TorrentFile {
52    /// Helper method to get an integer value from a dictionary
53    ///
54    /// # Arguments
55    /// * `dict` - Dictionary to search in
56    /// * `key` - Key to look up
57    /// * `default` - Default value if key is not found
58    ///
59    /// # Returns
60    /// Integer value or default if not found
61    fn get_integer(dict: &HashMap<String, Node>, key: &str, default: u64) -> u64 {
62        if let Some(Node::Integer(n)) = dict.get(key) {
63            return *n as u64;
64        }
65        default
66    }
67
68    /// Helper method to get a string value from a dictionary
69    ///
70    /// # Arguments
71    /// * `dict` - Dictionary to search in
72    /// * `key` - Key to look up
73    /// * `default` - Default value if key is not found
74    ///
75    /// # Returns
76    /// String value or default if not found
77    fn get_string(dict: &HashMap<String, Node>, key: &str, default: &str) -> String {
78        if let Some(Node::Str(s)) = dict.get(key) {
79            return s.clone();
80        }
81        default.to_string()
82    }
83
84    /// Helper method to get an integer from the info dictionary
85    ///
86    /// # Arguments
87    /// * `dict` - Root dictionary containing info dict
88    /// * `key` - Key to look up in info dict
89    /// * `default` - Default value if key is not found
90    ///
91    /// # Returns
92    /// Integer value or default if not found
93    fn get_info_integer(dict: &HashMap<String, Node>, key: &str, default: u64) -> u64 {
94        if let Some(Node::Dictionary(info_dict)) = dict.get("info") {
95            if let Some(Node::Integer(n)) = info_dict.get(key) {
96                return *n as u64;
97            }
98        }
99        default
100    }
101
102    /// Helper method to get a string from the info dictionary
103    ///
104    /// # Arguments
105    /// * `dict` - Root dictionary containing info dict
106    /// * `key` - Key to look up in info dict
107    /// * `default` - Default value if key is not found
108    ///
109    /// # Returns
110    /// String value or default if not found
111    fn get_info_string(dict: &HashMap<String, Node>, key: &str, default: &str) -> String {
112        if let Some(Node::Dictionary(info_dict)) = dict.get("info") {
113            if let Some(Node::Str(s)) = info_dict.get(key) {
114                return s.clone();
115            }
116        }
117        default.to_string()
118    }
119
120    /// Helper method to extract the announce-list from the torrent
121    ///
122    /// # Arguments
123    /// * `dict` - Root dictionary containing the announce-list
124    ///
125    /// # Returns
126    /// Vector of tracker URLs from the announce-list or empty vector if not found
127    fn get_announce_list(dict: &HashMap<String, Node>) -> Vec<String> {
128        match dict.get("announce-list") {
129            Some(Node::List(list)) => list
130                .iter()
131                .filter_map(|item| match item {
132                    Node::List(sublist) => sublist.first().and_then(|url| match url {
133                        Node::Str(s) => Some(s.clone()),
134                        _ => None,
135                    }),
136                    _ => None,
137                })
138                .collect(),
139            _ => Vec::new(),
140        }
141    }
142
143    /// Helper method to extract the file list from the info dictionary
144    ///
145    /// # Arguments
146    /// * `dict` - Root dictionary containing info dict with files
147    ///
148    /// # Returns
149    /// Vector of FileDetails or empty vector if not found
150    fn get_file_list(dict: &HashMap<String, Node>) -> Vec<FileDetails> {
151        if let Some(Node::Dictionary(info_dict)) = dict.get("info") {
152            if let Some(Node::List(files_list)) = info_dict.get("files") {
153                files_list
154                    .iter()
155                    .filter_map(|file| {
156                        if let Node::Dictionary(file_dict) = file {
157                            let length = Self::get_integer(file_dict, "length", 0);
158                            let path = match file_dict.get("path") {
159                                Some(Node::List(path_list)) => path_list
160                                    .iter()
161                                    .filter_map(|p| match p {
162                                        Node::Str(s) => Some(s.clone()),
163                                        _ => None,
164                                    })
165                                    .collect::<Vec<String>>()
166                                    .join("/"),
167                                _ => return None,
168                            };
169                            Some(FileDetails { path, length })
170                        } else {
171                            None
172                        }
173                    })
174                    .collect()
175            } else {
176                Vec::new()
177            }
178        } else {
179            Vec::new()
180        }
181    }
182
183    /// Creates a new TorrentFile instance by parsing a .torrent file
184    ///
185    /// # Arguments
186    /// * `path` - Path to the .torrent file to parse
187    ///
188    /// # Returns
189    /// Result containing either the parsed TorrentFile or an error message
190    pub fn from_file(path: &Path) -> Result<TorrentFile, String> {
191        match FileSource::new(path.to_str().unwrap()) {
192            Ok(mut file) => match parse(&mut file) {
193                Ok(Node::Dictionary(dict)) => {
194                    Self::validate_required_keys(&dict)?;
195                    Ok(TorrentFile {
196                        announce: Self::get_string(&dict, "announce", ""),
197                        announce_list: Self::get_announce_list(&dict),
198                        encoding: Self::get_string(&dict, "encoding", "UTF-8"),
199                        attribute: Self::get_info_integer(&dict, "attribute", 0),
200                        comment: Self::get_string(&dict, "comment", ""),
201                        creation_date: Self::get_integer(&dict, "creation date", 0),
202                        created_by: Self::get_string(&dict, "created by", ""),
203                        length: Self::get_info_integer(&dict, "length", 0),
204                        name: Self::get_info_string(&dict, "name", ""),
205                        piece_length: Self::get_info_integer(&dict, "piece length", 0),
206                        pieces: Self::get_info_string(&dict, "pieces", ""),
207                        private_flag: Self::get_info_integer(&dict, "private", 0),
208                        source: Self::get_info_string(&dict, "source", ""),
209                        files: Self::get_file_list(&dict),
210                    })
211                }
212                Err(s) => Err(s),
213                _ => Err("Invalid torrent file format".to_string()),
214            },
215            Err(e) => Err(format!("Failed to open file: {}", e)),
216        }
217    }
218
219    /// Validates that all required keys are present in the torrent dictionary
220    ///
221    /// # Arguments
222    /// * `dict` - Dictionary to validate
223    ///
224    /// # Returns
225    /// Ok if all required keys are present, Err with the message if any are missing
226    pub fn validate_required_keys(dict: &HashMap<String, Node>) -> Result<(), String> {
227        let required_keys = ["announce", "info"];
228        for key in required_keys {
229            if !dict.contains_key(key) {
230                return Err(format!("Missing required key: {}", key));
231            }
232        }
233
234        if let Some(Node::Dictionary(info)) = dict.get("info") {
235            let required_info_keys = ["name", "piece length", "pieces"];
236            for key in required_info_keys {
237                if !info.contains_key(key) {
238                    return Err(format!("Missing required info key: {}", key));
239                }
240            }
241        }
242        Ok(())
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use std::collections::HashMap;
250
251    #[test]
252    fn test_get_integer() {
253        let mut dict = HashMap::new();
254        dict.insert("test".to_string(), Node::Integer(42));
255
256        assert_eq!(TorrentFile::get_integer(&dict, "test", 0), 42);
257        assert_eq!(TorrentFile::get_integer(&dict, "nonexistent", 100), 100);
258    }
259
260    #[test]
261    fn test_get_string() {
262        let mut dict = HashMap::new();
263        dict.insert("test".to_string(), Node::Str("value".to_string()));
264
265        assert_eq!(TorrentFile::get_string(&dict, "test", "default"), "value");
266        assert_eq!(
267            TorrentFile::get_string(&dict, "nonexistent", "default"),
268            "default"
269        );
270    }
271
272    #[test]
273    fn test_get_info_integer() {
274        let mut info_dict = HashMap::new();
275        info_dict.insert("attr".to_string(), Node::Integer(42));
276
277        let mut dict = HashMap::new();
278        dict.insert("info".to_string(), Node::Dictionary(info_dict));
279
280        assert_eq!(TorrentFile::get_info_integer(&dict, "attr", 0), 42);
281        assert_eq!(
282            TorrentFile::get_info_integer(&dict, "nonexistent", 100),
283            100
284        );
285    }
286
287    #[test]
288    fn test_validate_required_keys() {
289        let mut info_dict = HashMap::new();
290        info_dict.insert("name".to_string(), Node::Str("test".to_string()));
291        info_dict.insert("piece length".to_string(), Node::Integer(1));
292        info_dict.insert("pieces".to_string(), Node::Str("test".to_string()));
293
294        let mut dict = HashMap::new();
295        dict.insert("announce".to_string(), Node::Str("test".to_string()));
296        dict.insert("info".to_string(), Node::Dictionary(info_dict));
297
298        assert!(TorrentFile::validate_required_keys(&dict).is_ok());
299    }
300
301    #[test]
302    fn test_validate_required_keys_missing() {
303        let dict = HashMap::new();
304        assert!(TorrentFile::validate_required_keys(&dict).is_err());
305    }
306
307    #[test]
308    fn test_get_announce_list() {
309        let mut announce_list = Vec::new();
310        announce_list.push(Node::List(vec![Node::Str("test1".to_string())]));
311        announce_list.push(Node::List(vec![Node::Str("test2".to_string())]));
312
313        let mut dict = HashMap::new();
314        dict.insert("announce-list".to_string(), Node::List(announce_list));
315
316        let result = TorrentFile::get_announce_list(&dict);
317        assert_eq!(result, vec!["test1".to_string(), "test2".to_string()]);
318    }
319}