proxy_scraper/mtproxy.rs
1use regex::Regex;
2use url::Url;
3
4/// Represents an MTProxy, a specific type of proxy.
5#[derive(Debug)]
6pub struct MTProxy {
7 /// The host address of the MTProxy.
8 pub host: String,
9 /// The port number for the MTProxy.
10 pub port: u32,
11 /// The secret associated with the MTProxy.
12 pub secret: String,
13}
14
15impl MTProxy {
16 /// Converts the MTProxy information into a Telegram proxy URL.
17 ///
18 /// # Example
19 ///
20 /// ```
21 /// use proxy_scraper::mtproxy::MTProxy;
22 /// let proxy = MTProxy {
23 /// host: "example.com".to_string(),
24 /// port: 443,
25 /// secret: "abcdef0123456789".to_string(),
26 /// };
27 /// let url = proxy.to_url();
28 /// assert_eq!(url, "https://t.me/proxy?server=example.com&port=443&secret=abcdef0123456789");
29 /// ```
30 pub fn to_url(&self) -> String {
31 format!(
32 "https://t.me/proxy?server={}&port={}&secret={}",
33 self.host, self.port, self.secret
34 )
35 }
36
37 /// Scrapes MTProxy information from the provided source string and returns a vector of MTProxy instances.
38 ///
39 /// # Arguments
40 ///
41 /// * `source` - A string containing the source code or text from which to extract MTProxy information.
42 ///
43 /// # Returns
44 ///
45 /// A vector of `MTProxy` instances parsed from the source string.
46 pub fn scrape(source: &str) -> Vec<Self> {
47 let source = crate::utils::seperate_links(source);
48 let mut proxy_list: Vec<MTProxy> = Vec::new();
49 let regex = Regex::new(
50 r#"(\w+:\/\/.*\/proxy\?((server=.+)|(port=.+)|(secret=([A-Fa-f0-9]+|[A-Za-z0-9+\/]+))))+"#,
51 )
52 .unwrap();
53
54 for captures in regex.captures_iter(&source) {
55 let proxy = captures.get(1).map(|m| m.as_str()).unwrap_or("");
56
57 if proxy.is_empty() {
58 continue;
59 }
60
61 let proxy_url = Url::parse(proxy).unwrap();
62
63 let server = proxy_url
64 .query_pairs()
65 .find(|(key, _)| key == "server")
66 .map(|(_, value)| value);
67 let port = proxy_url
68 .query_pairs()
69 .find(|(key, _)| key == "port")
70 .map(|(_, value)| value);
71 let secret = proxy_url
72 .query_pairs()
73 .find(|(key, _)| key == "secret")
74 .map(|(_, value)| value);
75
76 match (server, port, secret) {
77 (Some(server), Some(port), Some(secret)) => proxy_list.push(MTProxy {
78 host: server.to_string(),
79 port: port.parse().unwrap_or(443),
80 secret: secret.to_string(),
81 }),
82 _ => continue,
83 };
84 }
85
86 proxy_list
87 }
88}