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
// validate.rs
//
// Copyright © 2018
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use regex::Regex;
use EntityType;
use WikibaseError;

/// Returns true if the str is a valid integer.
fn number_is_integer(string: &str) -> bool {
    match string.parse::<u64>() {
        Ok(_) => true,
        Err(_) => false,
    }
}

pub fn parse_wikibase_entity_type(entity_id: &str) -> Result<EntityType, WikibaseError> {
    if entity_id.chars().count() < 2 {
        return Err(WikibaseError::Validation("ID is too short".to_string()));
    }

    let first_char = match entity_id.chars().nth(0) {
        Some(value) => value,
        None => {
            return Err(WikibaseError::Validation(
                "Error getting first character of string".to_string(),
            ))
        }
    };

    if number_is_integer(&entity_id[1..]) == false {
        return Err(WikibaseError::Serialization(
            "Wikibase ID is not a valid integer".to_string(),
        ));
    }

    match first_char {
        'P' => Ok(EntityType::Property),
        'Q' => Ok(EntityType::Item),
        _ => Err(WikibaseError::Serialization(
            "Wikibase ID does not have a P or Q prefix".to_string(),
        )),
    }
}

/// Checks the validity of a user-agent string and returns a Result
///
/// If the user-agent string is valid, the Result contains the string.
pub fn validate_user_agent(user_agent: &str) -> Result<String, WikibaseError> {
    let re = Regex::new(r"(?P<user_agent>[a-zA-Z0-9-_]+/[0-9\.]+)").unwrap();

    let valid = match re.captures(user_agent) {
        Some(value) => value,
        None => {
            return Err(WikibaseError::Configuration(
                "User agent is not valid".to_string(),
            ))
        }
    };

    Ok(valid["user_agent"].to_string())
}