lt_rs/
session.rs

1use std::mem;
2
3use cxx::UniquePtr;
4
5use crate::{
6    add_torrent_params::{AddTorrentParamsIntoPtr, AddTorrentParamsRef},
7    alerts::Alert,
8    ffi::ffi,
9    settings_pack::SettingsPack,
10    torrent_handle::{StatusFlags, TorrentHandle},
11};
12
13pub struct LtSession {
14    inner: UniquePtr<ffi::session>,
15    alerts: Vec<Alert>,
16}
17
18impl LtSession {
19    pub fn new() -> LtSession {
20        LtSession {
21            inner: ffi::lt_create_session(),
22            alerts: Vec::new(),
23        }
24    }
25
26    pub fn new_with_settings(settings: &SettingsPack) -> LtSession {
27        LtSession {
28            inner: ffi::lt_create_session_with_settings(settings.inner()),
29            alerts: Vec::new(),
30        }
31    }
32
33    pub fn add_torrent<'a>(&'a mut self, _params: &AddTorrentParamsRef) -> TorrentHandle {
34        unimplemented!()
35        // ffi::lt_session_add_torrent(self.inner.pin_mut(), params.inner()).into()
36    }
37
38    pub fn async_add_torrent<T: AddTorrentParamsIntoPtr>(&mut self, params: &T) {
39        unsafe { ffi::lt_session_async_add_torrent(self.inner.pin_mut(), params.as_ptr()) };
40    }
41
42    pub fn pop_alerts(&mut self) {
43        let alerts = ffi::lt_session_pop_alerts(self.inner.pin_mut());
44        self.alerts.clear();
45
46        for alert in alerts {
47            self.alerts.push(alert.into());
48        }
49    }
50
51    pub fn alerts(&self) -> &Vec<Alert> {
52        &self.alerts
53    }
54
55    /// This functions instructs the session to post the state_update_alert, containing the status of
56    /// all torrents whose state changed since the last time this function was called.
57    ///
58    /// Only torrents who has the state subscription flag set will be included. This flag is on by default.
59    pub fn post_torrent_updates(&mut self, flags: StatusFlags) {
60        ffi::lt_session_post_torrent_updates(self.inner.pin_mut(), flags.bits());
61    }
62
63    /// Marked as unsafe because it takes ownership of the alerts. If the session pops alerts again
64    /// the alerts will become invalid.
65    ///
66    /// As long [`LtSession::pop_alerts()`] is not called again the alerts are valid
67    pub unsafe fn take_alerts(&mut self) -> Vec<Alert> {
68        let alerts = mem::replace(&mut self.alerts, Vec::new());
69        alerts
70    }
71}
72
73// TODO: Check if this is safe
74unsafe impl Send for LtSession {}
75
76// impl Drop for LtSession {
77//     fn drop(&mut self) {
78//         ffi::lt_destroy_session(self.inner.pin_mut());
79//     }
80// }