hightorrent 0.4.1

High-level torrent library which supports Bittorrent v1, v2 and hybrid torrents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use fluent_uri::pct_enc::{encoder::Query, EStr};
use fluent_uri::{ParseError as UriParseError, Uri};

use crate::{InfoHash, InfoHashError, TorrentID, Tracker, TrackerError};

use std::str::FromStr;

/// Error occurred during parsing a [`MagnetLink`](crate::magnet::MagnetLink).
#[derive(Clone, Debug, PartialEq)]
pub enum MagnetLinkError {
    /// The URI was not valid according to [`Uri::parse`](fluent_uri::Uri::parse).
    InvalidURI { source: UriParseError },
    /// The URI does not contain a query.
    InvalidURINoQuery,
    /// The URI query contains non-UTF8 chars
    InvalidURIQueryUnicode,
    /// The URI query contains a key without a value
    InvalidURIQueryEmptyValue { key: String },
    /// The URI query contains a non-urlencoded `?` beyond the query declaration
    InvalidURIQueryInterrogation,
    /// The URI contains a newline
    InvalidURINewLine,
    /// The URI scheme was not `magnet`
    InvalidScheme { scheme: String },
    /// No Bittorrent v1/v2 hash was found in the magnet URI
    NoHashFound,
    /// A Bittorrent v1/v2 hash found in magnet URI was not a valid
    /// [`InfoHash`](crate::hash::InfoHash::new), or conflicting hashes were found
    /// (eg. two infohash v1 in the same URI).
    InvalidHash { source: InfoHashError },
    /// Too many hashes were found in the magnet URI, expected two at most.
    TooManyHashes { number: usize },
    /// There were two or more `dn` declarations in the magnet query.
    DuplicateName,
    /// No name was contained in the magnet URI. This is technically allowed by
    /// some implementations, but should not be encouraged/supported.
    #[cfg(feature = "magnet_force_name")]
    NoNameFound,
    /// The tracker declared could not be parsed.
    InvalidTracker {
        tracker: String,
        source: TrackerError,
    },
}

impl std::fmt::Display for MagnetLinkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MagnetLinkError::InvalidURI { source } => {
                write!(f, "Invalid URI: {source}")
            }
            MagnetLinkError::InvalidURINoQuery => {
                write!(f, "Invalid URI: no query string")
            }
            MagnetLinkError::InvalidURIQueryEmptyValue { key } => {
                write!(f, "Invalid URI: query has key {key} with no value")
            }
            MagnetLinkError::InvalidURIQueryUnicode => {
                write!(f, "Invalid URI: the query part contains non-utf8 chars")
            }
            MagnetLinkError::InvalidURIQueryInterrogation => {
                write!(f, "Invalid URI: the query part should only contain one `?`")
            }
            MagnetLinkError::InvalidURINewLine => {
                write!(f, "Invalid URI: newlines are not allowed in magnet links")
            }
            MagnetLinkError::InvalidScheme { scheme } => {
                write!(f, "Invalid URI scheme: {scheme}")
            }
            MagnetLinkError::NoHashFound => {
                write!(f, "No hash found (only btih/btmh hashes are supported)")
            }
            MagnetLinkError::InvalidHash { source } => {
                write!(f, "Invalid hash: {source}")
            }
            MagnetLinkError::TooManyHashes { number } => {
                write!(f, "Too many hashes ({number})")
            }
            MagnetLinkError::DuplicateName => {
                write!(
                    f,
                    "Too many name declarations for the magnet, only expecting one."
                )
            }
            #[cfg(feature = "magnet_force_name")]
            MagnetLinkError::NoNameFound => {
                write!(f, "No name found")
            }
            MagnetLinkError::InvalidTracker { tracker, .. } => {
                write!(f, "Invalid tracker: {tracker}")
            }
        }
    }
}

impl From<InfoHashError> for MagnetLinkError {
    fn from(e: InfoHashError) -> MagnetLinkError {
        MagnetLinkError::InvalidHash { source: e }
    }
}

impl<Input> From<(UriParseError, Input)> for MagnetLinkError {
    fn from(e: (UriParseError, Input)) -> MagnetLinkError {
        MagnetLinkError::InvalidURI { source: e.0 }
    }
}

impl std::error::Error for MagnetLinkError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            MagnetLinkError::InvalidURI { source } => Some(source),
            MagnetLinkError::InvalidHash { source } => Some(source),
            MagnetLinkError::InvalidTracker { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// A Magnet URI, which contains the infohash(es) but not the entire meta info.
///
/// More information is specified in [BEP-0009](https://bittorrent.org/beps/bep_0009.html), and
/// even more appears in the wild, as explained [on Wikipedia](https://en.wikipedia.org/wiki/Magnet_URI_scheme).
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(feature = "sea_orm", derive(sea_orm::DeriveValueType))]
#[cfg_attr(feature = "sea_orm", sea_orm(value_type = "String"))]
#[serde(try_from = "String")]
#[serde(into = "String")]
pub struct MagnetLink {
    /// Only mandatory field for magnet link parsing, unless the
    /// `magnet_force_name` crate feature is enabled.
    hash: InfoHash,
    /// Original query string from which the magnet was parsed.
    /// Used to format the magnet link back to a string.
    query: String,
    /// Name of the torrent, which may be empty unless
    /// `magnet_force_name` crate feature is enabled.
    name: String,
    /// Trackers contained in the magnet link
    ///
    /// The trackers are url-encoded in the magnet link, but are presented here
    /// in their decoded form which can is human-readable.
    trackers: Vec<Tracker>,
}

impl MagnetLink {
    /// Generates a new MagnetLink from a string. Will fail if the string is not a valid URL, and
    /// in the conditions defined in [`MagnetLink::from_url`](crate::magnet::MagnetLink::from_url).
    pub fn new(s: &str) -> Result<MagnetLink, MagnetLinkError> {
        // The error returned by Uri::parse when there is a newline is not very obvious, so we
        // sacrifice performance to save neurons from fellow developers.
        if s.contains('\n') {
            return Err(MagnetLinkError::InvalidURINewLine);
        }

        let u = Uri::parse(s.to_string())?;
        MagnetLink::from_url(&u)
    }

    /// Generates a new MagnetLink from a parsed URL.
    /// Will generate a weird name if multiple "dn" params are contained in the URL.
    /// Will fail if:
    ///   - the scheme is not `magnet`
    ///   - there is no name (`dn` URL param)
    ///   - no hash was found (`xt` URL param, with `urn:btih:` prefix for v1 infohash,
    ///     `urn:btmh:1220` for v2 infohash)
    ///   - more than one hash of the same type was found
    ///   - the hashes were not valid according to [`InfoHash::new`](crate::hash::InfoHash::new)
    pub fn from_url(u: &Uri<String>) -> Result<MagnetLink, MagnetLinkError> {
        if u.scheme().as_str() != "magnet" {
            return Err(MagnetLinkError::InvalidScheme {
                scheme: u.scheme().to_string(),
            });
        }

        let mut name = String::new();
        let mut hashes: Vec<String> = Vec::new();
        let mut trackers: Vec<Tracker> = Vec::new();

        let query = u.query().ok_or(MagnetLinkError::InvalidURINoQuery)?;
        for (key, val) in Self::unsafe_parse_query(query)? {
            // magnets should not allow unescaped ? in query value
            if val.as_str().contains('?') {
                return Err(MagnetLinkError::InvalidURIQueryInterrogation);
            }

            // magnets should not allow empty query values
            if val.is_empty() {
                return Err(MagnetLinkError::InvalidURIQueryEmptyValue {
                    key: key.as_str().to_string(),
                });
            }

            match key.as_str() {
                "xt" => {
                    let val = val.as_str();
                    if val.starts_with("urn:btih:") {
                        // Infohash v1
                        hashes.push(val.strip_prefix("urn:btih:").unwrap().to_string());
                    } else if val.starts_with("urn:btmh:1220") {
                        // Infohash v2
                        hashes.push(val.strip_prefix("urn:btmh:1220").unwrap().to_string());
                    }
                }
                "dn" => {
                    if !name.is_empty() {
                        return Err(MagnetLinkError::DuplicateName);
                    }
                    name = val
                        .decode()
                        .to_string()
                        .map_err(|_| MagnetLinkError::InvalidURIQueryUnicode)?
                        // fluent_uri explicitly does not decode U+002B (`+`) as a space
                        .replace('+', " ")
                        .to_owned();
                }
                "tr" => {
                    let tracker_uri = val
                        .decode()
                        .to_string()
                        .map_err(|_| MagnetLinkError::InvalidURIQueryUnicode)?;
                    trackers.push(Tracker::new(&tracker_uri).map_err(|e| {
                        MagnetLinkError::InvalidTracker {
                            source: e,
                            tracker: tracker_uri.to_string(),
                        }
                    })?);
                }
                _ => {
                    continue;
                }
            }
        }

        #[cfg(feature = "magnet_force_name")]
        if name.is_empty() {
            return Err(MagnetLinkError::NoNameFound);
        }

        let hashes_len = hashes.len();

        if hashes_len == 0 {
            return Err(MagnetLinkError::NoHashFound);
        }

        if hashes_len > 2 {
            return Err(MagnetLinkError::TooManyHashes { number: hashes_len });
        }

        // Check hashes sanity
        let mut valid_hashes: Vec<InfoHash> = Vec::new();
        for hash in hashes {
            let valid_hash = InfoHash::new(&hash)?;
            valid_hashes.push(valid_hash);
        }

        // If we still have two hashes not just one, we should combine them into hybrid
        // Otherwise we just return the first and only infohash found
        let final_hash = if valid_hashes.len() == 1 {
            valid_hashes.first().unwrap().clone()
        } else {
            let (hash1, hash2) = (valid_hashes.first().unwrap(), valid_hashes.get(1).unwrap());
            hash1.hybrid(hash2)?
        };

        // Reorder the trackers to provide equality
        trackers.sort_unstable();
        // Remove duplicates
        trackers.dedup();

        Ok(MagnetLink {
            hash: final_hash,
            name: name.to_string(),
            query: query.as_str().to_string(),
            trackers,
        })
    }

    /// Parse the query in a list of key->value entries with a percent-decoder attached.
    ///
    /// The results can be accessed raw with [EStr::as_str] and percent-decoded with [EStr::decode].
    ///
    /// This method only fails if the magnet query is empty (`magnet:`), but may produce unexpected
    /// results because it does not apply magnet-specific sanitation.
    ///
    /// This method has a dangerous-sounding name because of percent-encoding.
    /// If you aren't careful, you may end up with garbage data. This method
    /// is not actually memory-unsafe.
    ///
    /// For example:
    ///
    /// - a key without a value may be returned
    /// - duplicate entries may be returned (such as a double magnet name)
    /// - a value with an unencoded `?` may be returned
    #[allow(clippy::type_complexity)]
    pub fn unsafe_parse_query(
        query: &EStr<Query>,
    ) -> Result<Vec<(&EStr<Query>, &EStr<Query>)>, MagnetLinkError> {
        let pairs: Vec<(&EStr<Query>, &EStr<Query>)> = query
            .split('&')
            .map(|s| s.split_once('=').unwrap_or((s, EStr::EMPTY)))
            .collect();

        Ok(pairs)
    }

    /// Returns the [`InfoHash`](crate::hash::InfoHash) contained in the MagnetLink
    pub fn hash(&self) -> &InfoHash {
        &self.hash
    }

    /// Returns the torrent name contained in the MagnetLink. If multiple names are contained in the URL,
    /// they will all be appended. If no name is contained in the magnet link, the result of this function will be empty.
    /// However, when the `magnet_force_name` feature is enabled, the `MagnetLink` creation will have errored when the name
    /// is not provided and so this function is guaranteed to return an actual name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the [`TorrentID`](crate::id::TorrentID) for the MagnetLink
    pub fn id(&self) -> TorrentID {
        self.hash.id()
    }

    /// Returns the list of [`Tracker`](crate::tracker::Tracker) for the MagnetLink.
    ///
    /// The list is guaranteed to be sorted in a specific order and deduplicated,
    /// but the order is not specified.
    pub fn trackers(&self) -> &[Tracker] {
        &self.trackers
    }
}

impl std::fmt::Display for MagnetLink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "magnet:?{}", self.query)
    }
}

impl PartialEq for MagnetLink {
    fn eq(&self, other: &Self) -> bool {
        // Here we may have different ordering of the URL params so we check the
        // values. This is more expensive but more correct.
        //
        // In the future, we may optimize this by reproducing a normalized query.
        self.name == other.name
            && self.hash == other.hash
            // Trackers have been sorted in the constructor
            && self.trackers == other.trackers
    }
}

impl FromStr for MagnetLink {
    type Err = MagnetLinkError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}

impl TryFrom<String> for MagnetLink {
    type Error = MagnetLinkError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(&s)
    }
}

impl From<MagnetLink> for String {
    fn from(m: MagnetLink) -> Self {
        m.to_string()
    }
}

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

    #[test]
    fn can_load_v1() {
        let magnet_source =
            std::fs::read_to_string("tests/bittorrent-v1-emma-goldman.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_source).unwrap();
        assert_eq!(
            magnet.name,
            "Goldman, Emma - Essential Works of Anarchism".to_string()
        );
        assert_eq!(
            magnet.hash,
            InfoHash::V1("c811b41641a09d192b8ed81b14064fff55d85ce3".to_string())
        );
    }

    #[test]
    fn can_load_hybrid() {
        let magnet_source =
            std::fs::read_to_string("tests/bittorrent-v2-hybrid-test.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_source).unwrap();
        assert_eq!(magnet.name, "bittorrent-v1-v2-hybrid-test");
        assert_eq!(
            magnet.hash,
            InfoHash::Hybrid((
                "631a31dd0a46257d5078c0dee4e66e26f73e42ac".to_string(),
                "d8dd32ac93357c368556af3ac1d95c9d76bd0dff6fa9833ecdac3d53134efabb".to_string()
            ))
        );
    }

    #[test]
    fn can_load_v2() {
        let magnet_source = std::fs::read_to_string("tests/bittorrent-v2-test.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_source).unwrap();
        assert_eq!(magnet.name, "bittorrent-v2-test".to_string());
        assert_eq!(
            magnet.hash,
            InfoHash::V2(
                "caf1e1c30e81cb361b9ee167c4aa64228a7fa4fa9f6105232b28ad099f3a302e".to_string()
            )
        );
    }

    #[test]
    #[cfg(not(feature = "magnet_force_name"))]
    fn can_load_without_name() {
        let magnet =
            MagnetLink::new("magnet:?xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce3")
                .unwrap();
        assert_eq!(magnet.name, "".to_string());
        assert_eq!(
            magnet.hash,
            InfoHash::V1("c811b41641a09d192b8ed81b14064fff55d85ce3".to_string())
        );
    }

    #[test]
    fn fails_load_no_hash() {
        let res = MagnetLink::new(
            "magnet:?dn=Goldman%2c%20Emma%20-%20Essential%20Works%20of%20Anarchism",
        );
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(err, MagnetLinkError::NoHashFound);
    }

    #[test]
    fn fails_load_too_many_hashes() {
        let res = MagnetLink::new("magnet:?xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce3&dn=Goldman%2c%20Emma%20-%20Essential%20Works%20of%20Anarchism&xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce4&xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce5");
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(err, MagnetLinkError::TooManyHashes { number: 3 });
    }

    #[test]
    fn fails_load_conflicting_hash() {
        let res = MagnetLink::new("magnet:?xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce3&dn=Goldman%2c%20Emma%20-%20Essential%20Works%20of%20Anarchism&xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce4");
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(
            err,
            MagnetLinkError::InvalidHash {
                source: InfoHashError::FailedHybrid {
                    hashtype: "V1".to_string()
                }
            }
        );
    }

    #[test]
    fn fails_load_illegal_uri_chars() {
        let res = MagnetLink::new("magnet:?xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce3&dn=Goldman%2c%20Emma%20-%20Essential%20Works%20of%20Anarchism&xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce4&xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce5");
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(err, MagnetLinkError::TooManyHashes { number: 3 });
    }

    #[test]
    fn fails_load_invalid_hash_chars() {
        let res = MagnetLink::new("magnet:?xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85WWW&dn=Goldman%2c%20Emma%20-%20Essential%20Works%20of%20Anarchism");
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(
            err,
            MagnetLinkError::InvalidHash {
                source: InfoHashError::InvalidChars {
                    hash: "c811b41641a09d192b8ed81b14064fff55d85WWW".to_string()
                }
            }
        );
    }

    #[test]
    fn fails_load_invalid_hash_length() {
        let res = MagnetLink::new("magnet:?xt=urn:btih:c811b41641a09d192b8ed81b14064fff55d85ce311&dn=Goldman%2c%20Emma%20-%20Essential%20Works%20of%20Anarchism");
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(
            err,
            MagnetLinkError::InvalidHash {
                source: InfoHashError::InvalidLength {
                    len: 42,
                    hash: "c811b41641a09d192b8ed81b14064fff55d85ce311".to_string()
                }
            }
        );
    }

    #[test]
    fn fails_load_not_magnet() {
        let res = MagnetLink::new("https://fr.wikipedia.org");
        assert!(res.is_err());
        let err = res.unwrap_err();
        assert_eq!(
            err,
            MagnetLinkError::InvalidScheme {
                scheme: "https".to_string()
            }
        );
    }

    #[test]
    fn fails_newline_in_magnet() {
        let mut magnet_url = std::fs::read_to_string("tests/bittorrent-v2-test.magnet").unwrap();
        magnet_url.push('\n');

        let res = MagnetLink::new(&magnet_url);
        assert!(res.is_err());

        assert_eq!(res.unwrap_err(), MagnetLinkError::InvalidURINewLine,);
    }

    #[test]
    fn survives_roundtrip() {
        // Here we test that parsing a magnet then displaying it again
        // will produce exactly the same output.
        let magnet_url =
            Uri::parse(std::fs::read_to_string("tests/bittorrent-v2-test.magnet").unwrap())
                .unwrap();
        let magnet = MagnetLink::from_url(&magnet_url).unwrap();

        let magnet_str = magnet.to_string();
        assert_eq!(&magnet_url.to_string(), &magnet_str);
    }

    #[test]
    fn survives_roundtrip_tracker_urlencoding() {
        // Test that tracker URLs are properly url-decoded and re-encoded.
        let magnet_str =
            std::fs::read_to_string("tests/bittorrent-v1-emma-goldman.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_str).unwrap();

        assert_eq!(&magnet.to_string(), &magnet_str);
    }

    #[test]
    fn can_parse_magnet_trackers() {
        let expected = &[
            "http://tracker.tfile.co:80/announce",
            "udp://9.rarbg.me:2730/announce",
            "udp://9.rarbg.me:2740/announce",
            "udp://9.rarbg.me:2770/announce",
            "udp://9.rarbg.to:2710/announce",
            "udp://9.rarbg.to:2720/announce",
            "udp://9.rarbg.to:2730/announce",
            "udp://9.rarbg.to:2740/announce",
            "udp://9.rarbg.to:2770/announce",
            "udp://bt.xxx-tracker.com:2710/announce",
            "udp://denis.stalker.upeer.me:6969/announce",
            "udp://eddie4.nl:6969/announce",
            "udp://exodus.desync.com:6969/announce",
            "udp://ipv4.tracker.harry.lu:80/announce",
            "udp://ipv6.tracker.harry.lu:80/announce",
            "udp://open.demonii.si:1337/announce",
            "udp://open.stealth.si:80/announce",
            "udp://retracker.lanta-net.ru:2710/announce",
            "udp://torrentclub.tech:6969/announce",
            "udp://tracker.coppersurfer.tk:6969/announce",
            "udp://tracker.cyberia.is:6969/announce",
            "udp://tracker.internetwarriors.net:1337/announce",
            "udp://tracker.justseed.it:1337/announce",
            "udp://tracker.leechers-paradise.org:6969/announce",
            "udp://tracker.mg64.net:6969/announce",
            "udp://tracker.moeking.me:6969/announce",
            "udp://tracker.open-internet.nl:6969/announce",
            "udp://tracker.opentrackr.org:1337/announce",
            "udp://tracker.pirateparty.gr:6969/announce",
            "udp://tracker.port443.xyz:6969/announce",
            "udp://tracker.tiny-vps.com:6969/announce",
            "udp://tracker.torrent.eu.org:451/announce",
            "udp://tracker.zer0day.to:1337/announce",
        ];

        let magnet_url =
            std::fs::read_to_string("tests/bittorrent-v1-emma-goldman.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_url).unwrap();
        let found = magnet
            .trackers
            .clone()
            .into_iter()
            .map(|tracker| tracker.url().to_string())
            .collect::<Vec<_>>();

        assert_eq!(found, expected);

        let magnet_url = std::fs::read_to_string("tests/bittorrent-v2-test.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_url).unwrap();
        let found = magnet
            .trackers
            .into_iter()
            .map(|tracker| tracker.url().to_string())
            .collect::<Vec<_>>();
        assert!(found.is_empty());

        let magnet_url = std::fs::read_to_string("tests/bittorrent-v2-hybrid-test.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_url).unwrap();
        let found = magnet
            .trackers
            .into_iter()
            .map(|tracker| tracker.url().to_string())
            .collect::<Vec<_>>();
        assert!(found.is_empty());
    }

    #[test]
    fn serialization_roundtrip() {
        let magnet_url = std::fs::read_to_string("tests/bittorrent-v2-test.magnet").unwrap();
        let magnet = MagnetLink::new(&magnet_url).unwrap();
        let json_url = serde_json::to_string(&magnet_url).unwrap();
        let deserialized_magnet: MagnetLink = serde_json::from_str(&json_url).unwrap();
        assert_eq!(deserialized_magnet, magnet,);
    }
}