ctb_formats_useragent/
useragent.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! User-Agent string parsing and device/browser extraction utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use include_dir::{Dir, include_dir};
30use std::sync::OnceLock;
31use ua_parser::{Extractor, Regexes};
32
33static USERAGENT_DATA_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/data");
34
35/// The detected operating system.
36#[derive(
37    Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize,
38)]
39pub enum OperatingSystem {
40    /// Linux operating system.
41    Linux,
42    /// Windows operating system.
43    Windows,
44    /// macOS operating system.
45    MacOS,
46    /// Unknown operating system.
47    Unknown,
48}
49
50impl OperatingSystem {
51    /// Returns a string representation of the operating system.
52    pub fn as_str(self) -> &'static str {
53        match self {
54            Self::Linux => "Linux",
55            Self::Windows => "Windows",
56            Self::MacOS => "macOS",
57            Self::Unknown => "Unknown",
58        }
59    }
60}
61
62fn get_extractor() -> Option<&'static Extractor<'static>> {
63    static EXTRACTOR: OnceLock<Option<Extractor<'static>>> = OnceLock::new();
64    EXTRACTOR
65        .get_or_init(|| {
66            let file = USERAGENT_DATA_DIR.get_file("regexes.yaml")?;
67            let regexes: Regexes<'static> =
68                serde_yaml::from_slice(file.contents()).ok()?;
69            Extractor::try_from(regexes).ok()
70        })
71        .as_ref()
72}
73
74/// Detects the operating system from a user agent string.
75pub fn detect_os(user_agent: &str) -> OperatingSystem {
76    let Some(extractor) = get_extractor() else {
77        return OperatingSystem::Unknown;
78    };
79
80    let (_, os_ref, _) = extractor.extract(user_agent);
81    let Some(os) = os_ref else {
82        return OperatingSystem::Unknown;
83    };
84
85    let family = os.os.to_lowercase();
86    if family.contains("linux") {
87        OperatingSystem::Linux
88    } else if family.contains("windows") {
89        OperatingSystem::Windows
90    } else if family.contains("mac") || family.contains("os x") {
91        OperatingSystem::MacOS
92    } else {
93        OperatingSystem::Unknown
94    }
95}
96
97#[cfg(test)]
98#[allow(
99    clippy::panic,
100    clippy::expect_used,
101    clippy::unwrap_used,
102    clippy::unwrap_in_result,
103    clippy::panic_in_result_fn,
104    clippy::indexing_slicing,
105    clippy::arithmetic_side_effects,
106    reason = "Standard repository test boilerplate"
107)]
108mod tests {
109    use super::*;
110
111    #[crate::ctb_test]
112    fn test_detect_os_linux() {
113        let ua = "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/119.0";
114        assert_eq!(detect_os(ua), OperatingSystem::Linux);
115    }
116
117    #[crate::ctb_test]
118    fn test_detect_os_windows() {
119        let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
120        assert_eq!(detect_os(ua), OperatingSystem::Windows);
121    }
122
123    #[crate::ctb_test]
124    fn test_detect_os_macos() {
125        let ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15";
126        assert_eq!(detect_os(ua), OperatingSystem::MacOS);
127    }
128
129    #[crate::ctb_test]
130    fn test_detect_os_unknown() {
131        let ua = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
132        assert_eq!(detect_os(ua), OperatingSystem::Unknown);
133    }
134}