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
// Tivilsta - A different whitelisting mechanism
//
// Author:
//      Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom
//
// License:
//      Copyright (c) 2022 Nissar Chababy
//
//      Licensed under the Apache License, Version 2.0 (the "License");
//      you may not use this file except in compliance with the License.
//      You may obtain a copy of the License at
//
//          http://www.apache.org/licenses/LICENSE-2.0
//
//      Unless required by applicable law or agreed to in writing, software
//      distributed under the License is distributed on an "AS IS" BASIS,
//      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//      See the License for the specific language governing permissions and
//      limitations under the License.

use fancy_regex::escape as regex_escape;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use std::env;
use std::fs::File;
use std::io;
use std::path::Path;
use urlparse::urlparse;

/// A helper function that fetches a remote URL.
///
/// # Arguments
///
/// * `url` - The URL to fetch.
///
/// * `error_message` - A Message to return if the fetch fails.
///
/// # Returns
///
/// A `reqwest::blocking::Response` object to work with.
pub fn fetch_url(
    url: &String,
    error_message: String,
) -> Result<reqwest::blocking::Response, Box<dyn std::error::Error>> {
    let response = reqwest::blocking::get(url)?;

    if response.status().is_success() {
        Ok(response)
    } else {
        Err(Box::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            error_message,
        )))
    }
}

/// A function that will fetch the content of the given `url` into the given `destination`.
///
/// # Arguments
///
/// * `url` - The URL to fetch.
///
/// * `destination` - The path to the destination file.
///
/// # Returns
///
/// The path of the file where the content was copied into.
pub fn fetch_file(
    url: &String,
    destination: &String,
) -> Result<String, Box<dyn std::error::Error>> {
    let response = fetch_url(url, String::from("Couldn't reach the remote server."))?;

    let body = response.text().expect("Invalid body.");

    let mut output_file = File::create(destination).expect("Couldn't create file.");
    io::copy(&mut body.as_bytes(), &mut output_file).expect("Couldn't write content.");
    Ok(destination.to_string())
}

/// A function that download a presumed `user_input`.
///
/// # Arguments
///
/// * `user_input` - The presumed user input.
/// If it contains `://`, it will be treated as a URL, and downloaded.
/// Otherwise, the given `user_input` will be the direct return value of this function.
///
/// # Returns
///
/// A tuple containing the downloaded file and a boolean informing the end-user
/// whether the the `user_input` was a URL that has been downloaded by this function.
/// In the later case, a path to a file with a random name will be provided as the
/// first part or the tuple.
pub fn download_file(user_input: &String) -> (String, bool) {
    if !user_input.contains("://") {
        return (user_input.clone(), false);
    }

    let filename: String = thread_rng()
        .sample_iter(&Alphanumeric)
        .take(30)
        .map(char::from)
        .collect();

    let temp_file = Path::new(&env::temp_dir().as_os_str()).join(filename);

    let tmp_path = temp_file.to_str().unwrap().to_string();

    return (fetch_file(user_input, &tmp_path).unwrap_or(tmp_path), true);
}

/// A function that will escape a given `extensions` before joining them into
/// a regex in the following format:
///
/// ```txt
/// ((?:\.(?:xx)))|((?:\.(?:yy)))
///
/// Where `xx` and `yy` are extensions.
/// ```
pub fn to_regex_string(extensions: Result<Vec<String>, Box<dyn std::error::Error>>) -> String {
    let result = extensions
        .unwrap()
        .iter()
        .map(|ext| format!(r"((?:\.(?:{})))", regex_escape(ext)))
        .collect::<Vec<String>>()
        .join("|");

    result
}

/// A function that tries to extract the network location of a given URL.
/// This function may be used when you don't really know what kind of dataset
/// you injest. This function will check if the given `data` is a URL by parsing
/// it. If it is not the case, it will just return the given input.
///
/// # Arguments
///
/// * `data` - The presumed data to extract the netloc from.
///
/// # Returns
///
/// A string with the extracted network location.
///
pub fn extract_netloc(data: &String) -> String {
    let parsed_url = urlparse(data);
    let mut result;

    if parsed_url.netloc.is_empty() && !parsed_url.path.is_empty() {
        result = parsed_url.path.as_str()
    } else if !parsed_url.netloc.is_empty() {
        result = parsed_url.netloc.as_str()
    } else {
        result = &data.as_str()
    }

    if result.contains("//") {
        result = result.split("//").next().unwrap()
    }

    if result.contains("/") {
        result = result.split("/").next().unwrap()
    }

    result.to_string()
}

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

    #[test]
    fn test_to_regex_string() {
        let given = Ok(vec!["com".to_string(), "google".to_string()]);
        let expected = "((?:\\.(?:com)))|((?:\\.(?:google)))".to_string();

        assert_eq!(to_regex_string(given), expected)
    }

    #[test]
    fn test_to_regex_string_emtpy_vec() {
        let given = Ok(vec![]);
        let expected = "".to_string();

        assert_eq!(to_regex_string(given), expected)
    }

    #[test]
    fn test_to_regex_string_single_ext_vec() {
        let given = Ok(vec!["com".to_string()]);
        let expected = "((?:\\.(?:com)))".to_string();

        assert_eq!(to_regex_string(given), expected)
    }

    #[test]
    fn test_extract_netloc_empty_str() {
        let given = "".to_string();
        let expected = "".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_nothing_to_decode() {
        let given = "example.org".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_full_url() {
        let given = "https://example.org/hello/world/this/is/a/test".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_full_url_with_port() {
        let given = "https://example.org:8080/hello/world/this/is/a/test".to_string();
        let expected = "example.org:8080".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_full_url_with_params() {
        let given = "https://example.org/?is_admin=true".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_without_scheme() {
        let given = "example.org/hello/world/this/is/a/test".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_without_scheme_and_with_params() {
        let given = "example.org/?is_admin=true".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_without_protocol() {
        let given = "://example.org/hello/world/this/is/a/test".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_without_protocol_and_with_params() {
        let given = "://example.org/?is_admin=true".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_without_protocol_and_path() {
        let given = "://example.org/".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_startswith_2_slashes() {
        let given = "//example.org/hello/world/this/is/a/test".to_string();
        let expected = "example.org".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }

    #[test]
    fn test_extract_netloc_url_startswith_1_slash() {
        let given = "/example.org/hello/world/this/is/a/test".to_string();
        let expected = "".to_string();

        assert_eq!(extract_netloc(&given), expected)
    }
}