Skip to main content

utopia_user_agent/
agent.rs

1//! The entry point: a user-agent string and what detection finds in it.
2//!
3//! PHP: `Utopia\UserAgent\UserAgent`.
4
5use std::cell::OnceCell;
6
7use crate::detection;
8use crate::values::{Bot, Client, Device, OperatingSystem};
9
10/// A lazily evaluated analysis of one user-agent string.
11///
12/// Each category is detected at most once, on first access. Bot detection
13/// is independent from client and device detection: a bot never suppresses
14/// the other results.
15#[derive(Debug, Clone)]
16pub struct UserAgent<'a> {
17    value: &'a [u8],
18    operating_system: OnceCell<OperatingSystem<'a>>,
19    client: OnceCell<Client<'a>>,
20    device: OnceCell<Device<'a>>,
21    bot: OnceCell<Option<Bot<'a>>>,
22}
23
24impl<'a> UserAgent<'a> {
25    /// Wraps a user-agent string without detecting anything yet.
26    ///
27    /// Accepts any bytes, as a header can carry them.
28    ///
29    /// PHP: `UserAgent::parse()`.
30    pub fn parse(value: &'a (impl AsRef<[u8]> + ?Sized)) -> Self {
31        Self {
32            value: value.as_ref(),
33            operating_system: OnceCell::new(),
34            client: OnceCell::new(),
35            device: OnceCell::new(),
36            bot: OnceCell::new(),
37        }
38    }
39
40    /// The user-agent string as given.
41    ///
42    /// PHP: `raw()`.
43    pub fn raw(&self) -> &'a [u8] {
44        self.value
45    }
46
47    /// The operating system, detected on first call.
48    ///
49    /// PHP: `operatingSystem()`.
50    pub fn operating_system(&self) -> &OperatingSystem<'a> {
51        self.operating_system.get_or_init(|| detection::operating_system(self.value))
52    }
53
54    /// The client (browser, HTTP library or native app), detected on first
55    /// call.
56    ///
57    /// PHP: `client()`.
58    pub fn client(&self) -> &Client<'a> {
59        self.client.get_or_init(|| detection::client(self.value))
60    }
61
62    /// The device, detected on first call.
63    ///
64    /// PHP: `device()`.
65    pub fn device(&self) -> &Device<'a> {
66        self.device.get_or_init(|| detection::device(self.value))
67    }
68
69    /// The bot behind the string, or `None` for a human client. Detected on
70    /// first call.
71    ///
72    /// PHP: `bot()`.
73    pub fn bot(&self) -> Option<&Bot<'a>> {
74        self.bot.get_or_init(|| detection::bot(self.value)).as_ref()
75    }
76
77    /// Whether the string belongs to a bot ([`UserAgent::bot`] is `Some`).
78    ///
79    /// PHP: `isBot()`.
80    pub fn is_bot(&self) -> bool {
81        self.bot().is_some()
82    }
83}