system_proxy/unix/gio.rs
1// Copyright (c) 2022 Sebastian Wiesner <sebastian@swsnr.de>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7//! Provide a Gio proxy resolver.
8//!
9//! This module prpvides a thin wrapper around [`Gio.ProxyResolver`](https://docs.gtk.org/gio/iface.ProxyResolver.html)
10//! from Glib/Gio, and adds a more convenient [`Url`]-based API around the underlying API.
11//!
12//! This module requires the `gio` feature.
13
14use gio::glib;
15use gio::traits::ProxyResolverExt;
16use url::Url;
17
18/// A convenience wrapper around [`gio::ProxyResolver`].
19///
20/// See [`Gio.ProxyResolver`](https://docs.gtk.org/gio/iface.ProxyResolver.html) for the underlying
21/// Gio type.
22///
23/// This type can be cloned cheaply.
24#[derive(Debug, Clone)]
25pub struct GioProxyResolver {
26 resolver: gio::ProxyResolver,
27}
28
29impl GioProxyResolver {
30 /// Wrap the given GIO proxy `resolver`.
31 pub fn new(resolver: gio::ProxyResolver) -> Self {
32 Self { resolver }
33 }
34
35 /// Lookup the Gio proxy for the given `url`.
36 ///
37 /// Return the proxy to use, or `None` for a direct connection. If accessing the proxy
38 /// configuration fails or the proxy configuration returns an invalid URL return the
39 /// corresponding error.
40 pub async fn lookup(&self, url: &Url) -> Result<Option<Url>, glib::Error> {
41 let proxies = self.resolver.lookup_future(url.as_str()).await?;
42 match proxies.get(0) {
43 None => Ok(None),
44 Some(url) if url == "direct://" => Ok(None),
45 Some(url) => Url::parse(url).map(Some).map_err(|parse_error| {
46 glib::Error::new(
47 glib::UriError::Failed,
48 &format!("Failed to parse proxy URL {}: {}", url, parse_error),
49 )
50 }),
51 }
52 }
53}
54
55impl Default for GioProxyResolver {
56 /// Get the default proxy resolver.
57 ///
58 /// See [`gio::ProxyResolver::default`], and [`g_proxy_resolver_get_default`](https://docs.gtk.org/gio/type_func.ProxyResolver.get_default.htmll)
59 /// for the underlying Gio function.
60 fn default() -> Self {
61 Self {
62 resolver: gio::ProxyResolver::default(),
63 }
64 }
65}