ferristream 0.1.0

A TUI app for streaming torrents on-the-fly
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
use quick_xml::Reader;
use quick_xml::events::Event;
use reqwest::Client;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum TorznabError {
    #[error("request failed: {0}")]
    RequestError(#[from] reqwest::Error),
    #[error("xml parse error: {0}")]
    XmlError(#[from] quick_xml::Error),
    #[error("invalid response: {0}")]
    InvalidResponse(String),
}

#[derive(Debug, Clone)]
pub struct TorrentResult {
    pub title: String,
    pub link: Option<String>,
    pub magnet_url: Option<String>,
    pub infohash: Option<String>,
    pub size: Option<u64>,
    pub seeders: Option<u32>,
    pub leechers: Option<u32>,
    pub indexer: String,
}

impl TorrentResult {
    pub fn size_human(&self) -> String {
        match self.size {
            Some(bytes) => {
                const GB: u64 = 1024 * 1024 * 1024;
                const MB: u64 = 1024 * 1024;
                if bytes >= GB {
                    format!("{:.2} GB", bytes as f64 / GB as f64)
                } else {
                    format!("{:.1} MB", bytes as f64 / MB as f64)
                }
            }
            None => "?".to_string(),
        }
    }

    /// Get a URL that librqbit can use
    /// magnet, infohash-based magnet, or .torrent URL
    pub fn get_torrent_url(&self) -> Option<String> {
        // prefer magnet url if available
        if let Some(ref magnet) = self.magnet_url {
            return Some(magnet.clone());
        }

        // check if link is a magnet url
        if let Some(ref link) = self.link
            && link.starts_with("magnet:")
        {
            return Some(link.clone());
        }

        // construct magnet from infohash if available
        if let Some(ref hash) = self.infohash {
            let encoded_name = urlencoding::encode(&self.title);
            return Some(format!("magnet:?xt=urn:btih:{}&dn={}", hash, encoded_name));
        }

        // fall back to .torrent download link (prowlarr proxy URL)
        if let Some(ref link) = self.link {
            return Some(link.clone());
        }

        None
    }

    /// Check if this result can be streamed
    pub fn is_streamable(&self) -> bool {
        self.magnet_url.is_some() || self.infohash.is_some() || self.link.is_some()
    }
}

pub struct TorznabClient {
    client: Client,
}

impl Default for TorznabClient {
    fn default() -> Self {
        Self::new()
    }
}

impl TorznabClient {
    pub fn new() -> Self {
        Self {
            client: Client::new(),
        }
    }

    /// Search with optional category filter
    /// Categories: 2000 = Movies, 5000 = TV
    pub async fn search(
        &self,
        base_url: &str,
        api_key: &str,
        indexer_id: i32,
        indexer_name: &str,
        query: &str,
        categories: Option<&[u32]>,
    ) -> Result<Vec<TorrentResult>, TorznabError> {
        let cat_param = categories
            .map(|cats| {
                format!(
                    "&cat={}",
                    cats.iter()
                        .map(|c| c.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                )
            })
            .unwrap_or_default();

        let url = format!(
            "{}/{}/api?t=search&apikey={}&q={}&limit=100{}",
            base_url.trim_end_matches('/'),
            indexer_id,
            api_key,
            urlencoding::encode(query),
            cat_param
        );

        let response = self.client.get(&url).send().await?;

        if !response.status().is_success() {
            return Err(TorznabError::InvalidResponse(format!(
                "status: {}",
                response.status()
            )));
        }

        let xml = response.text().await?;
        self.parse_response(&xml, indexer_name)
    }

    fn parse_response(
        &self,
        xml: &str,
        indexer_name: &str,
    ) -> Result<Vec<TorrentResult>, TorznabError> {
        let mut reader = Reader::from_str(xml);
        reader.config_mut().trim_text(true);

        let mut results = Vec::new();
        let mut current_item: Option<TorrentResult> = None;
        let mut current_element = String::new();

        loop {
            match reader.read_event() {
                Ok(Event::Start(ref e)) => {
                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();
                    current_element = name.clone();

                    if name == "item" {
                        current_item = Some(TorrentResult {
                            title: String::new(),
                            link: None,
                            magnet_url: None,
                            infohash: None,
                            size: None,
                            seeders: None,
                            leechers: None,
                            indexer: indexer_name.to_string(),
                        });
                    }
                }
                Ok(Event::Empty(ref e)) => {
                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();

                    // handle <torznab:attr name="X" value="Y" /> elements
                    if (name == "torznab:attr" || name == "attr")
                        && let Some(ref mut item) = current_item
                    {
                        let mut attr_name = String::new();
                        let mut attr_value = String::new();

                        for attr in e.attributes().flatten() {
                            let key = String::from_utf8_lossy(attr.key.as_ref()).to_string();
                            let val = String::from_utf8_lossy(&attr.value).to_string();

                            if key == "name" {
                                attr_name = val;
                            } else if key == "value" {
                                attr_value = val;
                            }
                        }

                        match attr_name.as_str() {
                            "seeders" => item.seeders = attr_value.parse().ok(),
                            "leechers" => item.leechers = attr_value.parse().ok(),
                            "size" => item.size = attr_value.parse().ok(),
                            "magneturl" => {
                                if !attr_value.trim().is_empty() {
                                    item.magnet_url = Some(attr_value);
                                }
                            }
                            "infohash" => {
                                if !attr_value.trim().is_empty() {
                                    item.infohash = Some(attr_value);
                                }
                            }
                            _ => {}
                        }
                    }
                }
                Ok(Event::Text(ref e)) => {
                    if let Some(ref mut item) = current_item {
                        let text = e.decode().unwrap_or_default().to_string();

                        match current_element.as_str() {
                            "title" => item.title = text,
                            "link" => item.link = Some(text),
                            "size" => {
                                if item.size.is_none() {
                                    item.size = text.parse().ok();
                                }
                            }
                            _ => {}
                        }
                    }
                }
                Ok(Event::End(ref e)) => {
                    let name = String::from_utf8_lossy(e.name().as_ref()).to_string();

                    if name == "item"
                        && let Some(item) = current_item.take()
                        && !item.title.is_empty()
                    {
                        results.push(item);
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(TorznabError::XmlError(e)),
                _ => {}
            }
        }

        Ok(results)
    }
}

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

    #[test]
    fn test_size_human() {
        let result = TorrentResult {
            title: "Test".to_string(),
            link: None,
            magnet_url: None,
            infohash: None,
            size: Some(1024 * 1024 * 1024), // 1 GB
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert_eq!(result.size_human(), "1.00 GB");

        let result = TorrentResult {
            size: Some(500 * 1024 * 1024), // 500 MB
            ..result.clone()
        };
        assert_eq!(result.size_human(), "500.0 MB");

        let result = TorrentResult {
            size: Some(2 * 1024 * 1024 * 1024 + 512 * 1024 * 1024), // 2.5 GB
            ..result.clone()
        };
        assert_eq!(result.size_human(), "2.50 GB");

        let result = TorrentResult {
            size: None,
            ..result.clone()
        };
        assert_eq!(result.size_human(), "?");
    }

    #[test]
    fn test_get_torrent_url_magnet_priority() {
        // Magnet URL should be preferred
        let result = TorrentResult {
            title: "Test".to_string(),
            link: Some("http://example.com/torrent".to_string()),
            magnet_url: Some("magnet:?xt=urn:btih:abc123".to_string()),
            infohash: Some("def456".to_string()),
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert_eq!(
            result.get_torrent_url(),
            Some("magnet:?xt=urn:btih:abc123".to_string())
        );
    }

    #[test]
    fn test_get_torrent_url_link_is_magnet() {
        // Link that is a magnet URL
        let result = TorrentResult {
            title: "Test".to_string(),
            link: Some("magnet:?xt=urn:btih:fromlink".to_string()),
            magnet_url: None,
            infohash: None,
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert_eq!(
            result.get_torrent_url(),
            Some("magnet:?xt=urn:btih:fromlink".to_string())
        );
    }

    #[test]
    fn test_get_torrent_url_infohash_fallback() {
        // Construct magnet from infohash
        let result = TorrentResult {
            title: "Test Movie".to_string(),
            link: None,
            magnet_url: None,
            infohash: Some("abc123hash".to_string()),
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        let url = result.get_torrent_url().unwrap();
        assert!(url.starts_with("magnet:?xt=urn:btih:abc123hash"));
        assert!(url.contains("dn=Test%20Movie"));
    }

    #[test]
    fn test_get_torrent_url_link_fallback() {
        // Fall back to regular link
        let result = TorrentResult {
            title: "Test".to_string(),
            link: Some("http://example.com/download.torrent".to_string()),
            magnet_url: None,
            infohash: None,
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert_eq!(
            result.get_torrent_url(),
            Some("http://example.com/download.torrent".to_string())
        );
    }

    #[test]
    fn test_get_torrent_url_none() {
        let result = TorrentResult {
            title: "Test".to_string(),
            link: None,
            magnet_url: None,
            infohash: None,
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert_eq!(result.get_torrent_url(), None);
    }

    #[test]
    fn test_is_streamable() {
        let streamable = TorrentResult {
            title: "Test".to_string(),
            link: None,
            magnet_url: Some("magnet:?xt=...".to_string()),
            infohash: None,
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert!(streamable.is_streamable());

        let not_streamable = TorrentResult {
            title: "Test".to_string(),
            link: None,
            magnet_url: None,
            infohash: None,
            size: None,
            seeders: None,
            leechers: None,
            indexer: "test".to_string(),
        };
        assert!(!not_streamable.is_streamable());
    }

    #[test]
    fn test_parse_response_basic() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <item>
      <title>Test Movie 2024 1080p</title>
      <link>http://example.com/download</link>
      <size>1073741824</size>
      <torznab:attr name="seeders" value="50"/>
      <torznab:attr name="leechers" value="10"/>
      <torznab:attr name="magneturl" value="magnet:?xt=urn:btih:abc123"/>
    </item>
  </channel>
</rss>"#;

        let client = TorznabClient::new();
        let results = client.parse_response(xml, "TestIndexer").unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].title, "Test Movie 2024 1080p");
        assert_eq!(
            results[0].link,
            Some("http://example.com/download".to_string())
        );
        assert_eq!(results[0].size, Some(1073741824));
        assert_eq!(results[0].seeders, Some(50));
        assert_eq!(results[0].leechers, Some(10));
        assert_eq!(
            results[0].magnet_url,
            Some("magnet:?xt=urn:btih:abc123".to_string())
        );
        assert_eq!(results[0].indexer, "TestIndexer");
    }

    #[test]
    fn test_parse_response_multiple_items() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <item>
      <title>Movie One</title>
      <torznab:attr name="seeders" value="100"/>
    </item>
    <item>
      <title>Movie Two</title>
      <torznab:attr name="seeders" value="50"/>
    </item>
    <item>
      <title>Movie Three</title>
      <torznab:attr name="seeders" value="25"/>
    </item>
  </channel>
</rss>"#;

        let client = TorznabClient::new();
        let results = client.parse_response(xml, "Test").unwrap();

        assert_eq!(results.len(), 3);
        assert_eq!(results[0].title, "Movie One");
        assert_eq!(results[0].seeders, Some(100));
        assert_eq!(results[1].title, "Movie Two");
        assert_eq!(results[2].title, "Movie Three");
    }

    #[test]
    fn test_parse_response_with_infohash() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <item>
      <title>Test</title>
      <torznab:attr name="infohash" value="abcdef1234567890"/>
    </item>
  </channel>
</rss>"#;

        let client = TorznabClient::new();
        let results = client.parse_response(xml, "Test").unwrap();

        assert_eq!(results[0].infohash, Some("abcdef1234567890".to_string()));
    }

    #[test]
    fn test_parse_response_empty() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
  </channel>
</rss>"#;

        let client = TorznabClient::new();
        let results = client.parse_response(xml, "Test").unwrap();

        assert!(results.is_empty());
    }

    #[test]
    fn test_empty_magneturl_should_not_override_valid_link() {
        // When magneturl attribute is present but empty, it should not
        // take priority over a valid download link
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <item>
      <title>Test Movie 2024</title>
      <link>http://example.com/download.torrent</link>
      <torznab:attr name="magneturl" value=""/>
    </item>
  </channel>
</rss>"#;

        let client = TorznabClient::new();
        let results = client.parse_response(xml, "TestIndexer").unwrap();

        assert_eq!(results.len(), 1);
        let result = &results[0];

        // magnet_url should be None, not Some("")
        assert_eq!(result.magnet_url, None);
        assert_eq!(
            result.link,
            Some("http://example.com/download.torrent".to_string())
        );

        // Get the torrent URL - this should return the valid link
        let url = result.get_torrent_url();
        assert_eq!(
            url,
            Some("http://example.com/download.torrent".to_string()),
            "Expected to get the valid download link, not empty string"
        );
    }

    #[test]
    fn test_empty_infohash_should_not_create_invalid_magnet() {
        // When infohash attribute is present but empty, it should not
        // create an invalid magnet URL
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <item>
      <title>Test Movie 2024</title>
      <link>http://example.com/download.torrent</link>
      <torznab:attr name="infohash" value=""/>
    </item>
  </channel>
</rss>"#;

        let client = TorznabClient::new();
        let results = client.parse_response(xml, "TestIndexer").unwrap();

        assert_eq!(results.len(), 1);
        let result = &results[0];

        // infohash should be None, not Some("")
        assert_eq!(result.infohash, None);

        // Get the torrent URL - should fall back to the valid link
        let url = result.get_torrent_url();
        assert_eq!(
            url,
            Some("http://example.com/download.torrent".to_string()),
            "Expected to get the valid download link, not construct invalid magnet"
        );
    }
}