tina-core 0.0.2

Tina platform
Documentation
//! 客户端工具 mod

use once_cell::sync::Lazy;
use std::borrow::Cow;
use user_agent_parser::UserAgentParser;

/// 用户Agent解析器
static USER_AGENT_PARSER: Lazy<UserAgentParser> = Lazy::new(|| {
    UserAgentParser::from_str(include_str!("../../../resources/user_agent_parser.yml")).expect("build USER_AGENT_PARSER failed")
});

/// 客户端工具
pub struct ClientUtil;

impl ClientUtil {
    /// 获取客户端操作系统
    pub fn get_user_agent_os(user_agent: &str) -> Cow<str> {
        let os = USER_AGENT_PARSER.parse_os(user_agent);
        match os.name {
            None => Cow::Borrowed("Unkown"),
            Some(s1) => match os.major {
                None => s1,
                Some(s2) => Cow::Owned(format!("{} {}", s1, s2)),
            },
        }
    }
    /// 获取客户端浏览器
    pub fn get_user_agent_browser(user_agent: &str) -> Cow<str> {
        let browser = USER_AGENT_PARSER.parse_product(user_agent);
        match browser.name {
            None => Cow::Borrowed("Unkown"),
            Some(s1) => match browser.major {
                None => s1,
                Some(s2) => Cow::Owned(format!("{} {}", s1, s2)),
            },
        }
    }
}

#[allow(unused)]
#[cfg(test)]
mod test {
    use crate::tina::util::client::USER_AGENT_PARSER;
    use std::error::Error;

    #[test]
    #[ignore]
    fn test_user_agent() -> Result<(), Box<dyn Error>> {
        let user_agents = vec![
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.124 Safari/537.36 Edg/102.0.1245.44",
        ];
        println!("==================================");
        for user_agent in user_agents {
            let os = format!("{:?}", USER_AGENT_PARSER.parse_os(user_agent));
            let device = format!("{:?}", USER_AGENT_PARSER.parse_device(user_agent));
            let engine = format!("{:?}", USER_AGENT_PARSER.parse_engine(user_agent));
            let product = format!("{:?}", USER_AGENT_PARSER.parse_product(user_agent));
            println!("os: {}", os);
            println!("device: {}", device);
            println!("engine: {}", engine);
            println!("product: {}", product);
            println!("==================================");
        }
        Ok(())
    }
}