nullnet_libipinfo/ip_info_provider.rs
1use crate::IpInfo;
2use crate::api::api_config::ApiConfig;
3use crate::api::api_fields::ApiFields;
4use crate::mmdb::mmdb_config::MmdbConfig;
5use nullnet_liberror::Error;
6use reqwest::Client;
7
8/// An IP information provider.
9pub struct IpInfoProvider {
10 inner: IpInfoProviderInner,
11}
12
13impl IpInfoProvider {
14 /// Returns a new API-based `IpInfoProvider`.
15 ///
16 /// # Arguments
17 /// * `url` - The URL of the API endpoint.
18 /// The string "`{ip}`" will be replaced with the IP address, and "`{api_key}`" with the API key, if any.
19 /// * `api_key` - The API key to use.
20 /// * `fields` - The fields to request from the API.
21 #[must_use]
22 pub fn new_api_provider(url: &str, api_key: &str, fields: ApiFields) -> Self {
23 Self {
24 inner: IpInfoProviderInner::Api(ApiConfig::new(url, api_key, fields)),
25 }
26 }
27
28 /// Returns a new MMDB-based `IpInfoProvider`.
29 ///
30 /// # Arguments
31 ///
32 /// * `location_url` - The URL of the location MMDB file.
33 /// The string "`{api_key}`" will be replaced with the API key, if any.
34 /// * `asn_url` - The URL of the ASN MMDB file.
35 /// The string "`{api_key}`" will be replaced with the API key, if any.
36 /// * `api_key` - The API key to use.
37 /// * `refresh_days` - The number of days to wait before refreshing the MMDB files.
38 #[must_use]
39 pub fn new_mmdb_provider(
40 location_url: &str,
41 asn_url: &str,
42 api_key: &str,
43 refresh_days: u64,
44 ) -> Self {
45 Self {
46 inner: IpInfoProviderInner::Mmdb(MmdbConfig::new(
47 location_url,
48 asn_url,
49 api_key,
50 refresh_days,
51 )),
52 }
53 }
54
55 pub(crate) async fn lookup_ip(&self, client: &Client, ip: &str) -> Result<IpInfo, Error> {
56 match &self.inner {
57 IpInfoProviderInner::Api(config) => config.lookup_ip(client, ip).await,
58 IpInfoProviderInner::Mmdb(config) => config.lookup_ip(ip),
59 }
60 }
61}
62
63enum IpInfoProviderInner {
64 Api(ApiConfig),
65 Mmdb(MmdbConfig),
66}