1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// from webkit-gir-files
// DO NOT EDIT

use crate::{
    ffi, CookieManager, Download, ITPThirdParty, MemoryPressureSettings, NetworkProxyMode,
    NetworkProxySettings, TLSErrorsPolicy, WebsiteDataManager,
};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, pin::Pin};

glib::wrapper! {
    /// Manages network configuration.
    ///
    /// ## Properties
    ///
    ///
    /// #### `cache-directory`
    ///  The base caches directory used to create the #WebKitWebsiteDataManager. If [`None`], a default location will be used.
    ///
    /// Writeable | Construct Only
    ///
    ///
    /// #### `data-directory`
    ///  The base data directory used to create the #WebKitWebsiteDataManager. If [`None`], a default location will be used.
    ///
    /// Writeable | Construct Only
    ///
    ///
    /// #### `is-ephemeral`
    ///  Whether to create an ephermeral #WebKitWebsiteDataManager for the session.
    ///
    /// Readable | Writeable | Construct Only
    ///
    /// ## Signals
    ///
    ///
    /// #### `download-started`
    ///  This signal is emitted when a new download request is made.
    ///
    ///
    #[doc(alias = "WebKitNetworkSession")]
    pub struct NetworkSession(Object<ffi::WebKitNetworkSession, ffi::WebKitNetworkSessionClass>);

    match fn {
        type_ => || ffi::webkit_network_session_get_type(),
    }
}

impl NetworkSession {
    /// Creates a new #WebKitNetworkSession with a persistent #WebKitWebsiteDataManager.
    /// The parameters @data_directory and @cache_directory will be used as construct
    /// properties of the #WebKitWebsiteDataManager of the network session. Note that if
    /// [`None`] is passed, the default directory will be passed to #WebKitWebsiteDataManager
    /// so that webkit_website_data_manager_get_base_data_directory() and
    /// webkit_website_data_manager_get_base_cache_directory() always return a value for
    /// non ephemeral sessions.
    ///
    /// It must be passed as construct parameter of a #WebKitWebView.
    /// ## `data_directory`
    /// a base directory for data, or [`None`]
    /// ## `cache_directory`
    /// a base directory for caches, or [`None`]
    ///
    /// # Returns
    ///
    /// the newly created #WebKitNetworkSession
    #[doc(alias = "webkit_network_session_new")]
    pub fn new(data_directory: Option<&str>, cache_directory: Option<&str>) -> NetworkSession {
        assert_initialized_main_thread!();
        unsafe {
            from_glib_full(ffi::webkit_network_session_new(
                data_directory.to_glib_none().0,
                cache_directory.to_glib_none().0,
            ))
        }
    }

    /// Creates a new #WebKitNetworkSession with an ephemeral #WebKitWebsiteDataManager.
    ///
    /// # Returns
    ///
    /// a new ephemeral #WebKitNetworkSession.
    #[doc(alias = "webkit_network_session_new_ephemeral")]
    pub fn new_ephemeral() -> NetworkSession {
        assert_initialized_main_thread!();
        unsafe { from_glib_full(ffi::webkit_network_session_new_ephemeral()) }
    }

    // rustdoc-stripper-ignore-next
    /// Creates a new builder-pattern struct instance to construct [`NetworkSession`] objects.
    ///
    /// This method returns an instance of [`NetworkSessionBuilder`](crate::builders::NetworkSessionBuilder) which can be used to create [`NetworkSession`] objects.
    pub fn builder() -> NetworkSessionBuilder {
        NetworkSessionBuilder::new()
    }

    /// Ignore further TLS errors on the @host for the certificate present in @info.
    ///
    /// If @host is an IPv6 address, it should not be surrounded by brackets. This
    /// expectation matches g_uri_get_host().
    /// ## `certificate`
    /// a #GTlsCertificate
    /// ## `host`
    /// the host for which a certificate is to be allowed
    #[doc(alias = "webkit_network_session_allow_tls_certificate_for_host")]
    pub fn allow_tls_certificate_for_host(
        &self,
        certificate: &impl IsA<gio::TlsCertificate>,
        host: &str,
    ) {
        unsafe {
            ffi::webkit_network_session_allow_tls_certificate_for_host(
                self.to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
                host.to_glib_none().0,
            );
        }
    }

    /// Requests downloading of the specified URI string.
    ///
    /// The download operation will not be associated to any #WebKitWebView,
    /// if you are interested in starting a download from a particular #WebKitWebView use
    /// webkit_web_view_download_uri() instead.
    /// ## `uri`
    /// the URI to download
    ///
    /// # Returns
    ///
    /// a new #WebKitDownload representing
    ///    the download operation.
    #[doc(alias = "webkit_network_session_download_uri")]
    pub fn download_uri(&self, uri: &str) -> Option<Download> {
        unsafe {
            from_glib_full(ffi::webkit_network_session_download_uri(
                self.to_glib_none().0,
                uri.to_glib_none().0,
            ))
        }
    }

    /// Get the #WebKitCookieManager of @self.
    ///
    /// # Returns
    ///
    /// a #WebKitCookieManager
    #[doc(alias = "webkit_network_session_get_cookie_manager")]
    #[doc(alias = "get_cookie_manager")]
    pub fn cookie_manager(&self) -> Option<CookieManager> {
        unsafe {
            from_glib_none(ffi::webkit_network_session_get_cookie_manager(
                self.to_glib_none().0,
            ))
        }
    }

    /// Get whether Intelligent Tracking Prevention (ITP) is enabled or not.
    ///
    /// # Returns
    ///
    /// [`true`] if ITP is enabled, or [`false`] otherwise.
    #[doc(alias = "webkit_network_session_get_itp_enabled")]
    #[doc(alias = "get_itp_enabled")]
    pub fn is_itp_enabled(&self) -> bool {
        unsafe {
            from_glib(ffi::webkit_network_session_get_itp_enabled(
                self.to_glib_none().0,
            ))
        }
    }

    /// Asynchronously get the list of #WebKitITPThirdParty seen for @self.
    ///
    /// Every #WebKitITPThirdParty
    /// contains the list of #WebKitITPFirstParty under which it has been seen.
    ///
    /// When the operation is finished, @callback will be called. You can then call
    /// webkit_network_session_get_itp_summary_finish() to get the result of the operation.
    /// ## `cancellable`
    /// a #GCancellable or [`None`] to ignore
    /// ## `callback`
    /// a #GAsyncReadyCallback to call when the request is satisfied
    #[doc(alias = "webkit_network_session_get_itp_summary")]
    #[doc(alias = "get_itp_summary")]
    pub fn itp_summary<P: FnOnce(Result<Vec<ITPThirdParty>, glib::Error>) + 'static>(
        &self,
        cancellable: Option<&impl IsA<gio::Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn itp_summary_trampoline<
            P: FnOnce(Result<Vec<ITPThirdParty>, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut gio::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret = ffi::webkit_network_session_get_itp_summary_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(FromGlibPtrContainer::from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = itp_summary_trampoline::<P>;
        unsafe {
            ffi::webkit_network_session_get_itp_summary(
                self.to_glib_none().0,
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    pub fn itp_summary_future(
        &self,
    ) -> Pin<
        Box_<dyn std::future::Future<Output = Result<Vec<ITPThirdParty>, glib::Error>> + 'static>,
    > {
        Box_::pin(gio::GioFuture::new(self, move |obj, cancellable, send| {
            obj.itp_summary(Some(cancellable), move |res| {
                send.resolve(res);
            });
        }))
    }

    /// Get whether persistent credential storage is enabled or not.
    ///
    /// See also webkit_network_session_set_persistent_credential_storage_enabled().
    ///
    /// # Returns
    ///
    /// [`true`] if persistent credential storage is enabled, or [`false`] otherwise.
    #[doc(alias = "webkit_network_session_get_persistent_credential_storage_enabled")]
    #[doc(alias = "get_persistent_credential_storage_enabled")]
    pub fn is_persistent_credential_storage_enabled(&self) -> bool {
        unsafe {
            from_glib(
                ffi::webkit_network_session_get_persistent_credential_storage_enabled(
                    self.to_glib_none().0,
                ),
            )
        }
    }

    /// Get the TLS errors policy of @self.
    ///
    /// # Returns
    ///
    /// a #WebKitTLSErrorsPolicy
    #[doc(alias = "webkit_network_session_get_tls_errors_policy")]
    #[doc(alias = "get_tls_errors_policy")]
    pub fn tls_errors_policy(&self) -> TLSErrorsPolicy {
        unsafe {
            from_glib(ffi::webkit_network_session_get_tls_errors_policy(
                self.to_glib_none().0,
            ))
        }
    }

    /// Get the #WebKitWebsiteDataManager of @self.
    ///
    /// # Returns
    ///
    /// a #WebKitWebsiteDataManager
    #[doc(alias = "webkit_network_session_get_website_data_manager")]
    #[doc(alias = "get_website_data_manager")]
    pub fn website_data_manager(&self) -> Option<WebsiteDataManager> {
        unsafe {
            from_glib_none(ffi::webkit_network_session_get_website_data_manager(
                self.to_glib_none().0,
            ))
        }
    }

    /// Get whether @self is ephemeral.
    /// A #WebKitNetworkSession is ephemeral when its #WebKitWebsiteDataManager is ephemeral.
    /// See #WebKitWebsiteDataManager:is-ephemeral for more details.
    ///
    /// # Returns
    ///
    /// [`true`] if @self is pehmeral, or [`false`] otherwise
    #[doc(alias = "webkit_network_session_is_ephemeral")]
    pub fn is_ephemeral(&self) -> bool {
        unsafe {
            from_glib(ffi::webkit_network_session_is_ephemeral(
                self.to_glib_none().0,
            ))
        }
    }

    /// Resolve the domain name of the given @hostname in advance, so that if a URI
    /// of @hostname is requested the load will be performed more quickly.
    /// ## `hostname`
    /// a hostname to be resolved
    #[doc(alias = "webkit_network_session_prefetch_dns")]
    pub fn prefetch_dns(&self, hostname: &str) {
        unsafe {
            ffi::webkit_network_session_prefetch_dns(
                self.to_glib_none().0,
                hostname.to_glib_none().0,
            );
        }
    }

    /// Enable or disable Intelligent Tracking Prevention (ITP).
    ///
    /// When ITP is enabled resource load statistics
    /// are collected and used to decide whether to allow or block third-party cookies and prevent user tracking.
    /// Note that while ITP is enabled the accept policy [`CookieAcceptPolicy::NoThirdParty`][crate::CookieAcceptPolicy::NoThirdParty] is ignored and
    /// [`CookieAcceptPolicy::Always`][crate::CookieAcceptPolicy::Always] is used instead. See also webkit_cookie_session_set_accept_policy().
    /// ## `enabled`
    /// value to set
    #[doc(alias = "webkit_network_session_set_itp_enabled")]
    pub fn set_itp_enabled(&self, enabled: bool) {
        unsafe {
            ffi::webkit_network_session_set_itp_enabled(self.to_glib_none().0, enabled.into_glib());
        }
    }

    /// Enable or disable persistent credential storage.
    ///
    /// When enabled, which is the default for
    /// non-ephemeral sessions, the network process will try to read and write HTTP authentiacation
    /// credentials from persistent storage.
    /// ## `enabled`
    /// value to set
    #[doc(alias = "webkit_network_session_set_persistent_credential_storage_enabled")]
    pub fn set_persistent_credential_storage_enabled(&self, enabled: bool) {
        unsafe {
            ffi::webkit_network_session_set_persistent_credential_storage_enabled(
                self.to_glib_none().0,
                enabled.into_glib(),
            );
        }
    }

    /// Set the network proxy settings to be used by connections started in @self session.
    ///
    /// By default [`NetworkProxyMode::Default`][crate::NetworkProxyMode::Default] is used, which means that the
    /// system settings will be used (g_proxy_resolver_get_default()).
    /// If you want to override the system default settings, you can either use
    /// [`NetworkProxyMode::NoProxy`][crate::NetworkProxyMode::NoProxy] to make sure no proxies are used at all,
    /// or [`NetworkProxyMode::Custom`][crate::NetworkProxyMode::Custom] to provide your own proxy settings.
    /// When @proxy_mode is [`NetworkProxyMode::Custom`][crate::NetworkProxyMode::Custom] @proxy_settings must be
    /// a valid #WebKitNetworkProxySettings; otherwise, @proxy_settings must be [`None`].
    /// ## `proxy_mode`
    /// a #WebKitNetworkProxyMode
    /// ## `proxy_settings`
    /// a #WebKitNetworkProxySettings, or [`None`]
    #[doc(alias = "webkit_network_session_set_proxy_settings")]
    pub fn set_proxy_settings(
        &self,
        proxy_mode: NetworkProxyMode,
        proxy_settings: Option<&NetworkProxySettings>,
    ) {
        unsafe {
            ffi::webkit_network_session_set_proxy_settings(
                self.to_glib_none().0,
                proxy_mode.into_glib(),
                mut_override(proxy_settings.to_glib_none().0),
            );
        }
    }

    /// Set the TLS errors policy of @self as @policy.
    /// ## `policy`
    /// a #WebKitTLSErrorsPolicy
    #[doc(alias = "webkit_network_session_set_tls_errors_policy")]
    pub fn set_tls_errors_policy(&self, policy: TLSErrorsPolicy) {
        unsafe {
            ffi::webkit_network_session_set_tls_errors_policy(
                self.to_glib_none().0,
                policy.into_glib(),
            );
        }
    }

    /// Get the default network session.
    /// The default network session is created using webkit_network_session_new() and passing
    /// [`None`] as data and cache directories.
    ///
    /// # Returns
    ///
    /// a #WebKitNetworkSession
    #[doc(alias = "webkit_network_session_get_default")]
    #[doc(alias = "get_default")]
    #[allow(clippy::should_implement_trait)]
    pub fn default() -> Option<NetworkSession> {
        assert_initialized_main_thread!();
        unsafe { from_glib_none(ffi::webkit_network_session_get_default()) }
    }

    /// Sets @settings as the #WebKitMemoryPressureSettings.
    ///
    /// Sets @settings as the #WebKitMemoryPressureSettings to be used by the network
    /// process created by any instance of #WebKitNetworkSession after this function
    /// is called.
    ///
    /// Be sure to call this function before creating any #WebKitNetworkSession.
    ///
    /// The periodic check for used memory is disabled by default on network processes. This will
    /// be enabled only if custom settings have been set using this function. After that, in order
    /// to remove the custom settings and disable the periodic check, this function must be called
    /// passing [`None`] as the value of @settings.
    /// ## `settings`
    /// a WebKitMemoryPressureSettings.
    #[doc(alias = "webkit_network_session_set_memory_pressure_settings")]
    pub fn set_memory_pressure_settings(settings: &mut MemoryPressureSettings) {
        assert_initialized_main_thread!();
        unsafe {
            ffi::webkit_network_session_set_memory_pressure_settings(settings.to_glib_none_mut().0);
        }
    }

    /// This signal is emitted when a new download request is made.
    /// ## `download`
    /// the #WebKitDownload associated with this event
    #[doc(alias = "download-started")]
    pub fn connect_download_started<F: Fn(&Self, &Download) + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn download_started_trampoline<
            F: Fn(&NetworkSession, &Download) + 'static,
        >(
            this: *mut ffi::WebKitNetworkSession,
            download: *mut ffi::WebKitDownload,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(&from_glib_borrow(this), &from_glib_borrow(download))
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"download-started\0".as_ptr() as *const _,
                Some(std::mem::transmute::<*const (), unsafe extern "C" fn()>(
                    download_started_trampoline::<F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl Default for NetworkSession {
    fn default() -> Self {
        glib::object::Object::new::<Self>()
    }
}

// rustdoc-stripper-ignore-next
/// A [builder-pattern] type to construct [`NetworkSession`] objects.
///
/// [builder-pattern]: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
#[must_use = "The builder must be built to be used"]
pub struct NetworkSessionBuilder {
    builder: glib::object::ObjectBuilder<'static, NetworkSession>,
}

impl NetworkSessionBuilder {
    fn new() -> Self {
        Self {
            builder: glib::object::Object::builder(),
        }
    }

    /// The base caches directory used to create the #WebKitWebsiteDataManager. If [`None`], a default location will be used.
    pub fn cache_directory(self, cache_directory: impl Into<glib::GString>) -> Self {
        Self {
            builder: self
                .builder
                .property("cache-directory", cache_directory.into()),
        }
    }

    /// The base data directory used to create the #WebKitWebsiteDataManager. If [`None`], a default location will be used.
    pub fn data_directory(self, data_directory: impl Into<glib::GString>) -> Self {
        Self {
            builder: self
                .builder
                .property("data-directory", data_directory.into()),
        }
    }

    /// Whether to create an ephermeral #WebKitWebsiteDataManager for the session.
    pub fn is_ephemeral(self, is_ephemeral: bool) -> Self {
        Self {
            builder: self.builder.property("is-ephemeral", is_ephemeral),
        }
    }

    // rustdoc-stripper-ignore-next
    /// Build the [`NetworkSession`].
    #[must_use = "Building the object from the builder is usually expensive and is not expected to have side effects"]
    pub fn build(self) -> NetworkSession {
        self.builder.build()
    }
}