bencode_read_torrent_files/common/
torrent.rs1use babbel_bencode::{FileSource, Node, parse};
2use std::collections::HashMap;
3use std::path::Path;
4
5#[derive(Debug, PartialEq)]
11pub struct FileDetails {
12 pub path: String,
13 pub length: u64,
14}
15
16#[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 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 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 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 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 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 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 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 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}