Debian Codegraph @

src/backend/connection_manager.rs

raw ◀ ▶
2 Debian patches touch this file
1 // Fragments - connection_manager.rs
•2 // Copyright (C) 2022-2025 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::sync::LazyLock;
21 use std::time::Duration;
22
23 use gio::prelude::*;
24 use gio::ListStore;
25 use glib::subclass::Signal;
26 use glib::{clone, Enum, KeyFile, Properties};
27 use gtk::subclass::prelude::*;
28 use gtk::{gio, glib};
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!(
116 #[weak(rename_to = this)]
117 self,
118 move |_| {
119 this.check_for_stop_reason();
120 }
121 ));
122
123 self.read_connections();
•124 self.connections.connect_items_changed(clone!(
125 #[weak(rename_to = this)]
126 self,
127 move |_, _, _, _| {
128 this.write_connections();
•129 }
130 ));
131 }
132
133 fn signals() -> &'static [Signal] {
•134 static SIGNALS: LazyLock<Vec<Signal>> = LazyLock::new(|| {
135 vec![
136 Signal::builder("daemon-started").build(),
137 Signal::builder("daemon-stopped")
138 .param_types([FrgDaemonStopReason::static_type()])
139 .build(),
140 ]
141 });
142 SIGNALS.as_ref()
143 }
144 }
145
146 impl FrgConnectionManager {
147 /// Returns [FrgDaemonStopReason] if there is a reason why the daemon
148 /// cannot be started
149 pub async fn start_daemon(&self) -> anyhow::Result<Option<FrgDaemonStopReason>> {
150 let stop_reason = self.stop_reason();
151
152 if !self.daemon.is_running() {
153 if let Some(reason) = &stop_reason {
154 // If there's a stop reason then don't start daemon at all
155 self.obj().emit_by_name::<()>("daemon-stopped", &[reason]);
156 return Ok(Some(*reason));
157 } else {
158 // Start daemon
159 self.daemon.start().await?;
160
161 // Wait a bit to ensure that the daemon accepts rpc requests
162 glib::timeout_future(Duration::from_millis(500)).await;
163
164 // Connect client
165 let connection = self.obj().current_connection();
166 if !self.client.is_connected() && connection.is_fragments() {
167 self.update_polling_rate();
168 self.client.connect(connection.address()).await?;
169 }
170
171 self.obj().emit_by_name::<()>("daemon-started", &[]);
172 }
173 } else if self.daemon.is_running() {
174 debug!("Daemon is already started.");
175
176 if let Some(reason) = &stop_reason {
177 // Daemon is already running, but there's a stop reason -> stop it
178 self.stop_daemon(reason).await?;
179 return Ok(Some(*reason));
180 }
181 }
182
183 Ok(None)
184 }
185
186 pub async fn stop_daemon(&self, stop_reason: &FrgDaemonStopReason) -> anyhow::Result<()> {
187 if self.daemon.is_running() {
188 if self.client.is_connected() && self.obj().current_connection().is_fragments() {
189 self.client.disconnect(true).await;
190 }
191
192 self.daemon.stop().await?;
193
194 self.obj()
195 .emit_by_name::<()>("daemon-stopped", &[stop_reason]);
196 }
197
198 Ok(())
199 }
200
201 /// Returns `None` if there's no reason for stopping the daemon
202 pub fn stop_reason(&self) -> Option<FrgDaemonStopReason> {
203 // TODO: Also check for disconnecting from a VPN connection
204 let nm = gio::NetworkMonitor::default();
205
206 if nm.is_network_metered() && !self.obj().allow_metered() {
207 return Some(FrgDaemonStopReason::Metered);
208 }
209
210 None
211 }
212
213 /// Check if there's a stop reason, and stop the daemon if necessary
214 pub fn check_for_stop_reason(&self) {
215 let stop_reason = self.stop_reason();
216 let is_fragments = self.obj().current_connection().is_fragments();
217
218 if let Some(reason) = stop_reason {
219 if !self.daemon.is_running() {
220 return;
221 }
222
223 info!("Reason for stopping daemon: {:?}", reason);
•224 let fut = clone!(
225 #[weak(rename_to = this)]
226 self,
227 #[strong]
228 reason,
229 async move {
230 let res = this.stop_daemon(&reason).await;
231 if let Err(e) = res {
232 utils::inapp_notification(
233 &i18n("Unable to stop transmission-daemon"),
234 gtk::Widget::NONE,
235 );
236 error!("Unable to stop transmission-daemon: {}", e.to_string());
237 }
238 }
•239 );
240 glib::spawn_future_local(fut);
241 } else if stop_reason.is_none() && is_fragments {
•242 let fut = clone!(
243 #[weak(rename_to = this)]
244 self,
245 async move {
246 let res = this.start_daemon().await;
247 if let Err(e) = res {
248 utils::inapp_notification(
249 &i18n("Unable to start transmission-daemon"),
250 gtk::Widget::NONE,
251 );
252 error!("Unable to start transmission-daemon: {}", e.to_string());
253 }
254 }
•255 );
256 glib::spawn_future_local(fut);
257 }
258 }
259
260 pub fn set_polling_mode(&self, mode: FrgPollingMode) {
261 let before = *self.polling_mode.borrow();
262
263 if before == mode {
264 return;
265 }
266
267 *self.polling_mode.borrow_mut() = mode;
268 self.update_polling_rate();
269 }
270
271 pub fn update_polling_rate(&self) {
272 let is_fragments = self.current_connection.borrow().is_fragments();
273 let mode = self.obj().polling_mode();
274
275 let rate = match mode {
276 FrgPollingMode::Regular => {
277 if is_fragments {
278 1500
279 } else {
280 2500
281 }
282 }
283 FrgPollingMode::InactiveWindow => 5000,
284 FrgPollingMode::SuspendedWindow => 30000,
285 };
286
287 debug!("Setting client polling rate to {}ms ({:?})", rate, mode);
288 self.obj().client().set_polling_rate(rate);
289 }
290
291 fn read_connections(&self) {
292 debug!("Read connection data");
293 self.connections.remove_all();
294
295 let path = Path::new(&*path::CONFIG).join("connections.conf");
296
297 if !path.exists() {
298 debug!("No connections file found, skip reading.");
299 return;
300 }
301
302 let keyfile = KeyFile::new();
303 keyfile
304 .load_from_file(&path, glib::KeyFileFlags::NONE)
305 .expect("Unable to load connections data");
306
307 for group in keyfile.groups() {
308 let group = group.as_str();
309 let title = keyfile
310 .string(group, "title")
311 .expect("Unable to get connection title");
312 let address = keyfile
313 .string(group, "address")
314 .expect("Unable to get address title");
315
316 let connection = FrgConnection::new_with_uuid(&title, &address, group);
317 self.connections.append(&connection);
318 }
319 }
320
321 fn write_connections(&self) {
322 debug!("Write connection data");
323
324 let keyfile = KeyFile::new();
325
326 for pos in 0..self.connections.n_items() {
327 let connection = self
328 .connections
329 .item(pos)
330 .unwrap()
331 .downcast::<FrgConnection>()
332 .unwrap();
333
334 // Don't save local Fragments connection
335 if connection.is_fragments() {
336 continue;
337 }
338
339 let uuid = connection.uuid();
340
341 keyfile.set_string(&uuid, "title", &connection.title());
342 keyfile.set_string(&uuid, "address", &connection.address());
343 }
344
345 let path = Path::new(&*path::CONFIG).join("connections.conf");
346
347 fs::write(path, keyfile.to_data().as_bytes())
348 .expect("Unable to write connections data");
349 }
350 }
351 }
352
353 glib::wrapper! {
354 pub struct FrgConnectionManager(ObjectSubclass<imp::FrgConnectionManager>);
355 }
356
357 impl FrgConnectionManager {
358 pub fn new() -> Self {
359 glib::Object::new()
360 }
361
362 pub async fn connect(
363 &self,
364 connection: &FrgConnection,
365 ) -> Result<Option<FrgDaemonStopReason>, ClientError> {
366 let imp = self.imp();
367
368 if connection.uuid() == self.current_connection().uuid() && imp.client.is_connected() {
369 debug!("Already connected with {}", connection.address());
370 return Ok(None);
371 }
372
373 self.disconnect().await?;
374
375 debug!("Connect to {}", &connection.address());
376 *imp.current_connection.borrow_mut() = connection.clone();
377 self.notify_current_connection();
378
379 // If using Fragments local connenction ensure that daemon is started
380 if connection.is_fragments() {
381 let daemon_stop_reason = imp.start_daemon().await.map_err(|e| {
382 utils::inapp_notification(
383 &i18n("Unable to start transmission-daemon"),
384 gtk::Widget::NONE,
385 );
386 error!("Unable to start transmission-daemon: {}", e.to_string());
387
388 ClientError::TransmissionError("".into())
389 })?;
390
391 if let Some(reason) = daemon_stop_reason {
392 info!(
393 "Not going to start daemon because of stop reason: {:?}",
394 reason
395 );
396 return Ok(daemon_stop_reason);
397 }
398 } else {
399 imp.update_polling_rate();
400 imp.client.connect(connection.address()).await?;
401 }
402
403 debug!("Connected with {}", &connection.address());
404
405 // Save connection uuid to restore the connection on next Fragments startup
406 settings_manager::set_string(Key::ClientLastConnection, connection.uuid());
407
408 self.check_directories();
409 Ok(None)
410 }
411
412 pub async fn disconnect(&self) -> Result<(), ClientError> {
413 let imp = self.imp();
414
415 if imp.client.address().is_empty() || !imp.client.is_connected() {
416 // Nothing to disconnect
417 return Ok(());
418 }
419
420 debug!("Disconnect from {}", &imp.client.address());
421 if self.current_connection().is_fragments() {
422 imp.stop_daemon(&FrgDaemonStopReason::Disconnected)
423 .await
424 .map_err(|e| {
425 utils::inapp_notification(
426 &i18n("Unable to stop transmission-daemon"),
427 gtk::Widget::NONE,
428 );
429 error!("Unable to stop transmission-daemon: {}", e.to_string());
430
431 ClientError::TransmissionError("".into())
432 })?;
433 } else {
434 imp.client.disconnect(false).await;
435 }
436
437 Ok(())
438 }
439
440 /// Triggers a client reconnect. If the current connection is the local
441 /// Fragments session it also restarts the Transmission daemon.
442 pub async fn reconnect(&self) -> anyhow::Result<()> {
443 debug!("Reconnect...");
444 let imp = self.imp();
445
446 if self.current_connection().is_fragments() {
447 self.disconnect().await?;
448 self.connect(&self.current_connection()).await?;
449 } else {
450 imp.stop_daemon(&FrgDaemonStopReason::Restart).await?;
451 imp.start_daemon().await?;
452 }
453
454 Ok(())
455 }
456
457 /// `filename` can be a magnet url or a local file path
458 pub async fn add_torrent_by_filename(&self, filename: String) -> anyhow::Result<()> {
459 let imp = self.imp();
460 debug!("Add new torrent by filename: {}", filename);
461 imp.client.add_torrent_by_filename(filename).await?;
462 Ok(())
463 }
464
465 /// `metainfo` is the base64 encoded content of a .torrent file
466 pub async fn add_torrent_by_metainfo(&self, metainfo: String) -> anyhow::Result<()> {
467 let imp = self.imp();
468 debug!("Add new torrent by metainfo.");
469 imp.client.add_torrent_by_metainfo(metainfo).await?;
470 Ok(())
471 }
472
473 pub fn connection_by_uuid(&self, uuid: &str) -> Option<FrgConnection> {
474 let connections = self.connections();
475
476 for pos in 0..connections.n_items() {
477 let connection = connections
478 .item(pos)
479 .unwrap()
480 .downcast::<FrgConnection>()
481 .unwrap();
482
483 if connection.uuid() == uuid {
484 return Some(connection);
485 }
486 }
487
488 None
489 }
490
491 pub fn check_directories(&self) {
492 let imp = self.imp();
493 let mut dir_type = FrgDirectoryType::None;
494
495 // We can only check for locally Fragments session, since we can't access remote
496 // filesystems
497 if self.current_connection().is_fragments() {
498 let mut writable_download = false;
499 let mut writable_incomplete = false;
500
501 if let Some(download_dir) = self.client().session().download_dir() {
502 writable_download = utils::check_writable(download_dir.path().unwrap());
503 }
504
505 // Only check incomplete-dir if enabled
506 if self.client().session().incomplete_dir_enabled() {
507 if let Some(incomplete_dir) = self.client().session().incomplete_dir() {
508 writable_incomplete = utils::check_writable(incomplete_dir.path().unwrap())
509 }
510 } else {
511 writable_incomplete = true;
512 };
513
514 if !writable_incomplete {
515 dir_type = FrgDirectoryType::Incomplete;
516 } else if !writable_download {
517 dir_type = FrgDirectoryType::Download;
518 }
519 }
520
521 *imp.invalid_dir.borrow_mut() = dir_type;
522 self.notify_invalid_dir();
523 }
524 }
525
526 impl Default for FrgConnectionManager {
527 fn default() -> Self {
528 FrgApplication::default().connection_manager()
529 }
530 }