Debian Codegraph @

src/backend/connection_manager.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // Fragments - connection_manager.rs
2 // Copyright (C) 2022-2024 Felix Häcker <[email protected]>
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17 use std::cell::{Cell, RefCell};
18 use std::fs;
19 use std::path::Path;
20 use std::time::Duration;
21
22 use gio::prelude::*;
23 use gio::ListStore;
24 use glib::subclass::Signal;
25 use glib::{clone, Enum, KeyFile, Properties};
26 use gtk::subclass::prelude::*;
27 use gtk::{gio, glib};
28 use once_cell::sync::Lazy;
29 use transmission_gobject::{ClientError, TrClient};
30
31 use crate::app::FrgApplication;
32 use crate::backend::{Daemon, FrgConnection};
33 use crate::i18n::i18n;
34 use crate::settings::{settings_manager, Key};
35 use crate::{path, utils};
36
37 #[derive(Default, Display, Copy, Debug, Clone, EnumString, PartialEq, Enum, Eq)]
38 #[repr(u32)]
39 #[enum_type(name = "FrgDirectoryType")]
40 pub enum FrgDirectoryType {
41 Incomplete,
42 Download,
43 #[default]
44 None,
45 }
46
47 #[derive(Display, Copy, Debug, Clone, EnumString, PartialEq, Enum, Eq)]
48 #[repr(u32)]
49 #[enum_type(name = "FrgDaemonStopReason")]
50 pub enum FrgDaemonStopReason {
51 Disconnected,
52 Restart,
53 Metered,
54 VpnDisconnect,
55 }
56
57 #[derive(Default, Display, Copy, Debug, Clone, EnumString, PartialEq, Enum, Eq)]
58 #[repr(u32)]
59 #[enum_type(name = "FrgPollingMode")]
60 pub enum FrgPollingMode {
61 #[default]
62 Regular,
63 InactiveWindow,
64 SuspendedWindow,
65 }
66
67 mod imp {
68 use super::*;
69
70 #[derive(Properties)]
71 #[properties(wrapper_type = super::FrgConnectionManager)]
72 pub struct FrgConnectionManager {
73 #[property(get)]
74 pub client: TrClient,
75 #[property(get, set=Self::set_polling_mode, builder(FrgPollingMode::default()))]
76 pub polling_mode: RefCell<FrgPollingMode>,
77 #[property(get)]
78 connections: ListStore,
79 #[property(get)]
80 pub current_connection: RefCell<FrgConnection>,
81 #[property(get, builder(FrgDirectoryType::default()))]
82 pub invalid_dir: RefCell<FrgDirectoryType>,
83 #[property(get, set)]
84 allow_metered: Cell<bool>,
85
86 daemon: Daemon,
87 }
88
89 #[glib::object_subclass]
90 impl ObjectSubclass for FrgConnectionManager {
91 const NAME: &'static str = "FrgConnectionManager";
92 type Type = super::FrgConnectionManager;
93
94 fn new() -> Self {
95 let connections = ListStore::new::<FrgConnection>();
96
97 Self {
98 client: TrClient::new(),
99 polling_mode: RefCell::default(),
100 connections,
101 current_connection: RefCell::default(),
102 invalid_dir: RefCell::default(),
103 allow_metered: Cell::default(),
104 daemon: Daemon::default(),
105 }
106 }
107 }
108
109 #[glib::derived_properties]
110 impl ObjectImpl for FrgConnectionManager {
111 fn constructed(&self) {
112 self.parent_constructed();
113
114 let nm = gio::NetworkMonitor::default();
115 nm.connect_network_metered_notify(clone!(@weak self as this => move |_| {
116 this.check_for_stop_reason();
117 }));
118
119 self.read_connections();
120 self.connections
121 .connect_items_changed(clone!(@weak self as this => move |_, _, _, _|{
122 this.write_connections();
123 }));
124 }
125
126 fn signals() -> &'static [Signal] {
127 static SIGNALS: Lazy<Vec<Signal>> = Lazy::new(|| {
128 vec![
129 Signal::builder("daemon-started").build(),
130 Signal::builder("daemon-stopped")
131 .param_types([FrgDaemonStopReason::static_type()])
132 .build(),
133 ]
134 });
135 SIGNALS.as_ref()
136 }
137 }
138
139 impl FrgConnectionManager {
140 /// Returns [FrgDaemonStopReason] if there is a reason why the daemon
141 /// cannot be started
142 pub async fn start_daemon(&self) -> anyhow::Result<Option<FrgDaemonStopReason>> {
143 let stop_reason = self.stop_reason();
144
145 if !self.daemon.is_running() {
146 if let Some(reason) = &stop_reason {
147 // If there's a stop reason then don't start daemon at all
148 self.obj().emit_by_name::<()>("daemon-stopped", &[reason]);
149 return Ok(Some(*reason));
150 } else {
151 // Start daemon
152 self.daemon.start().await?;
153
154 // Wait a bit to ensure that the daemon accepts rpc requests
155 glib::timeout_future(Duration::from_millis(500)).await;
156
157 // Connect client
158 let connection = self.obj().current_connection();
159 if !self.client.is_connected() && connection.is_fragments() {
160 self.update_polling_rate();
161 self.client.connect(connection.address()).await?;
162 }
163
164 self.obj().emit_by_name::<()>("daemon-started", &[]);
165 }
166 } else if self.daemon.is_running() {
167 debug!("Daemon is already started.");
168
169 if let Some(reason) = &stop_reason {
170 // Daemon is already running, but there's a stop reason -> stop it
171 self.stop_daemon(reason).await?;
172 return Ok(Some(*reason));
173 }
174 }
175
176 Ok(None)
177 }
178
179 pub async fn stop_daemon(&self, stop_reason: &FrgDaemonStopReason) -> anyhow::Result<()> {
180 if self.daemon.is_running() {
181 if self.client.is_connected() && self.obj().current_connection().is_fragments() {
182 self.client.disconnect(true).await;
183 }
184
185 self.daemon.stop().await?;
186
187 self.obj()
188 .emit_by_name::<()>("daemon-stopped", &[stop_reason]);
189 }
190
191 Ok(())
192 }
193
194 /// Returns `None` if there's no reason for stopping the daemon
195 pub fn stop_reason(&self) -> Option<FrgDaemonStopReason> {
196 // TODO: Also check for disconnecting from a VPN connection
197 let nm = gio::NetworkMonitor::default();
198
199 if nm.is_network_metered() && !self.obj().allow_metered() {
200 return Some(FrgDaemonStopReason::Metered);
201 }
202
203 None
204 }
205
206 /// Check if there's a stop reason, and stop the daemon if necessary
207 pub fn check_for_stop_reason(&self) {
208 let stop_reason = self.stop_reason();
209 let is_fragments = self.obj().current_connection().is_fragments();
210
211 if let Some(reason) = stop_reason {
212 if !self.daemon.is_running() {
213 return;
214 }
215
216 info!("Reason for stopping daemon: {:?}", reason);
217 let fut = clone!(@weak self as this, @strong reason => async move {
218 let res = this.stop_daemon(&reason).await;
219 if let Err(e) = res {
220 utils::inapp_notification(&i18n("Unable to stop transmission-daemon"), gtk::Widget::NONE);
221 error!("Unable to stop transmission-daemon: {}", e.to_string());
222 }
223 });
224 glib::spawn_future_local(fut);
225 } else if stop_reason.is_none() && is_fragments {
226 let fut = clone!(@weak self as this => async move {
227 let res = this.start_daemon().await;
228 if let Err(e) = res {
229 utils::inapp_notification(&i18n("Unable to start transmission-daemon"), gtk::Widget::NONE);
230 error!("Unable to start transmission-daemon: {}", e.to_string());
231 }
232 });
233 glib::spawn_future_local(fut);
234 }
235 }
236
237 pub fn set_polling_mode(&self, mode: FrgPollingMode) {
238 let before = *self.polling_mode.borrow();
239
240 if before == mode {
241 return;
242 }
243
244 *self.polling_mode.borrow_mut() = mode;
245 self.update_polling_rate();
246 }
247
248 pub fn update_polling_rate(&self) {
249 let is_fragments = self.current_connection.borrow().is_fragments();
250 let mode = self.obj().polling_mode();
251
252 let rate = match mode {
253 FrgPollingMode::Regular => {
254 if is_fragments {
255 1500
256 } else {
257 2500
258 }
259 }
260 FrgPollingMode::InactiveWindow => 5000,
261 FrgPollingMode::SuspendedWindow => 30000,
262 };
263
264 debug!("Setting client polling rate to {}ms ({:?})", rate, mode);
265 self.obj().client().set_polling_rate(rate);
266 }
267
268 fn read_connections(&self) {
269 debug!("Read connection data");
270 self.connections.remove_all();
271
272 let path = Path::new(&*path::CONFIG).join("connections.conf");
273
274 if !path.exists() {
275 debug!("No connections file found, skip reading.");
276 return;
277 }
278
279 let keyfile = KeyFile::new();
280 keyfile
281 .load_from_file(&path, glib::KeyFileFlags::NONE)
282 .expect("Unable to load connections data");
283
284 for group in keyfile.groups() {
285 let group = group.as_str();
286 let title = keyfile
287 .string(group, "title")
288 .expect("Unable to get connection title");
289 let address = keyfile
290 .string(group, "address")
291 .expect("Unable to get address title");
292
293 let connection = FrgConnection::new_with_uuid(&title, &address, group);
294 self.connections.append(&connection);
295 }
296 }
297
298 fn write_connections(&self) {
299 debug!("Write connection data");
300
301 let keyfile = KeyFile::new();
302
303 for pos in 0..self.connections.n_items() {
304 let connection = self
305 .connections
306 .item(pos)
307 .unwrap()
308 .downcast::<FrgConnection>()
309 .unwrap();
310
311 // Don't save local Fragments connection
312 if connection.is_fragments() {
313 continue;
314 }
315
316 let uuid = connection.uuid();
317
318 keyfile.set_string(&uuid, "title", &connection.title());
319 keyfile.set_string(&uuid, "address", &connection.address());
320 }
321
322 let path = Path::new(&*path::CONFIG).join("connections.conf");
323
324 fs::write(path, keyfile.to_data().as_bytes())
325 .expect("Unable to write connections data");
326 }
327 }
328 }
329
330 glib::wrapper! {
331 pub struct FrgConnectionManager(ObjectSubclass<imp::FrgConnectionManager>);
332 }
333
334 impl FrgConnectionManager {
335 pub fn new() -> Self {
336 glib::Object::new()
337 }
338
339 pub async fn connect(
340 &self,
341 connection: &FrgConnection,
342 ) -> Result<Option<FrgDaemonStopReason>, ClientError> {
343 let imp = self.imp();
344
345 if connection.uuid() == self.current_connection().uuid() && imp.client.is_connected() {
346 debug!("Already connected with {}", connection.address());
347 return Ok(None);
348 }
349
350 self.disconnect().await?;
351
352 debug!("Connect to {}", &connection.address());
353 *imp.current_connection.borrow_mut() = connection.clone();
354 self.notify_current_connection();
355
356 // If using Fragments local connenction ensure that daemon is started
357 if connection.is_fragments() {
358 let daemon_stop_reason = imp.start_daemon().await.map_err(|e| {
359 utils::inapp_notification(
360 &i18n("Unable to start transmission-daemon"),
361 gtk::Widget::NONE,
362 );
363 error!("Unable to start transmission-daemon: {}", e.to_string());
364
365 ClientError::TransmissionError("".into())
366 })?;
367
368 if let Some(reason) = daemon_stop_reason {
369 info!(
370 "Not going to start daemon because of stop reason: {:?}",
371 reason
372 );
373 return Ok(daemon_stop_reason);
374 }
375 } else {
376 imp.update_polling_rate();
377 imp.client.connect(connection.address()).await?;
378 }
379
380 debug!("Connected with {}", &connection.address());
381
382 // Save connection uuid to restore the connection on next Fragments startup
383 settings_manager::set_string(Key::ClientLastConnection, connection.uuid());
384
385 self.check_directories();
386 Ok(None)
387 }
388
389 pub async fn disconnect(&self) -> Result<(), ClientError> {
390 let imp = self.imp();
391
392 if imp.client.address().is_empty() || !imp.client.is_connected() {
393 // Nothing to disconnect
394 return Ok(());
395 }
396
397 debug!("Disconnect from {}", &imp.client.address());
398 if self.current_connection().is_fragments() {
399 imp.stop_daemon(&FrgDaemonStopReason::Disconnected)
400 .await
401 .map_err(|e| {
402 utils::inapp_notification(
403 &i18n("Unable to stop transmission-daemon"),
404 gtk::Widget::NONE,
405 );
406 error!("Unable to stop transmission-daemon: {}", e.to_string());
407
408 ClientError::TransmissionError("".into())
409 })?;
410 } else {
411 imp.client.disconnect(false).await;
412 }
413
414 Ok(())
415 }
416
417 /// Triggers a client reconnect. If the current connection is the local
418 /// Fragments session it also restarts the Transmission daemon.
419 pub async fn reconnect(&self) -> anyhow::Result<()> {
420 debug!("Reconnect...");
421 let imp = self.imp();
422
423 if self.current_connection().is_fragments() {
424 self.disconnect().await?;
425 self.connect(&self.current_connection()).await?;
426 } else {
427 imp.stop_daemon(&FrgDaemonStopReason::Restart).await?;
428 imp.start_daemon().await?;
429 }
430
431 Ok(())
432 }
433
434 /// `filename` can be a magnet url or a local file path
435 pub async fn add_torrent_by_filename(&self, filename: String) -> anyhow::Result<()> {
436 let imp = self.imp();
437 debug!("Add new torrent by filename: {}", filename);
438 imp.client.add_torrent_by_filename(filename).await?;
439 Ok(())
440 }
441
442 /// `metainfo` is the base64 encoded content of a .torrent file
443 pub async fn add_torrent_by_metainfo(&self, metainfo: String) -> anyhow::Result<()> {
444 let imp = self.imp();
445 debug!("Add new torrent by metainfo.");
446 imp.client.add_torrent_by_metainfo(metainfo).await?;
447 Ok(())
448 }
449
450 pub fn connection_by_uuid(&self, uuid: &str) -> Option<FrgConnection> {
451 let connections = self.connections();
452
453 for pos in 0..connections.n_items() {
454 let connection = connections
455 .item(pos)
456 .unwrap()
457 .downcast::<FrgConnection>()
458 .unwrap();
459
460 if connection.uuid() == uuid {
461 return Some(connection);
462 }
463 }
464
465 None
466 }
467
468 pub fn check_directories(&self) {
469 let imp = self.imp();
470 let mut dir_type = FrgDirectoryType::None;
471
472 // We can only check for locally Fragments session, since we can't access remote
473 // filesystems
474 if self.current_connection().is_fragments() {
475 let mut writable_download = false;
476 let mut writable_incomplete = false;
477
478 if let Some(download_dir) = self.client().session().download_dir() {
479 writable_download = utils::check_writable(download_dir.path().unwrap());
480 }
481
482 // Only check incomplete-dir if enabled
483 if self.client().session().incomplete_dir_enabled() {
484 if let Some(incomplete_dir) = self.client().session().incomplete_dir() {
485 writable_incomplete = utils::check_writable(incomplete_dir.path().unwrap())
486 }
487 } else {
488 writable_incomplete = true;
489 };
490
491 if !writable_incomplete {
492 dir_type = FrgDirectoryType::Incomplete;
493 } else if !writable_download {
494 dir_type = FrgDirectoryType::Download;
495 }
496 }
497
498 *imp.invalid_dir.borrow_mut() = dir_type;
499 self.notify_invalid_dir();
500 }
501 }
502
503 impl Default for FrgConnectionManager {
504 fn default() -> Self {
505 FrgApplication::default().connection_manager()
506 }
507 }