Debian Codegraph @

src/app.rs

raw ◀ ▶
3 Debian patches touch this file
1 // Fragments - app.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::{OnceCell, RefCell};
18 use std::path::PathBuf;
19 use std::rc::Rc;
20
21 use adw::prelude::*;
22 use adw::subclass::prelude::*;
23 use base64::engine::general_purpose::STANDARD;
24 use base64::Engine;
25 use futures_util::FutureExt;
26 use glib::{clone, Properties, WeakRef};
27 use gtk::{gio, glib, FileFilter};
28 use smol::fs;
29
30 use crate::backend::{secret_store, FrgConnection, FrgConnectionManager};
31 use crate::i18n::i18n;
32 use crate::settings::{settings_manager, Key};
33 use crate::ui::{
34 about_dialog, FrgAddConnectionDialog, FrgApplicationWindow, FrgPreferencesDialog,
35 FrgStatsDialog,
36 };
37 use crate::{config, utils};
38
39 mod imp {
40 use super::*;
41
42 #[derive(Properties)]
43 #[properties(wrapper_type = super::FrgApplication)]
44 pub struct FrgApplication {
45 #[property(get)]
46 connection_manager: FrgConnectionManager,
47 #[property(get, set)]
48 search: RefCell<String>,
49 #[property(get, set=Self::set_inhibit_suspend)]
50 inhibit_suspend: RefCell<bool>,
51
52 inhibit_cookie: RefCell<Option<u32>>,
53 window: OnceCell<WeakRef<FrgApplicationWindow>>,
54 pub settings: gio::Settings,
55 }
56
57 #[glib::object_subclass]
58 impl ObjectSubclass for FrgApplication {
59 const NAME: &'static str = "FrgApplication";
60 type Type = super::FrgApplication;
61 type ParentType = adw::Application;
62
63 fn new() -> Self {
64 Self {
65 connection_manager: FrgConnectionManager::new(),
66 search: RefCell::default(),
67 inhibit_suspend: RefCell::default(),
68 inhibit_cookie: RefCell::default(),
69 window: OnceCell::default(),
70 settings: gio::Settings::new(config::APP_ID),
71 }
72 }
73 }
74
75 #[glib::derived_properties]
76 impl ObjectImpl for FrgApplication {}
77
78 impl ApplicationImpl for FrgApplication {
79 fn activate(&self) {
80 debug!("Activate GIO Application...");
81 let obj = self.obj();
82
83 // If the window already exists,
84 // present it instead creating a new one again.
85 if let Some(weak_win) = self.window.get() {
86 let window = weak_win.upgrade().unwrap();
87 window.present();
88 info!("Application window presented.");
89 return;
90 }
91
92 // Connect to last used connection
•93 let fut = clone!(
94 #[weak(rename_to = this)]
95 self,
96 async move {
97 let cm = FrgConnectionManager::default();
98
•99 let local_connection = FrgConnection::default();
100 cm.connections().insert(0, &local_connection);
101
•102 if let Err(err) = secret_store::open_keyring().await {
103 error!("Could not unlock keyring: {err}");
104 };
105
•106 // Restore last used connection
107 let uuid = settings_manager::string(Key::ClientLastConnection);
108 this.set_connection(uuid).await;
109 }
110 );
111 glib::spawn_future_local(fut);
112
113 // No window available -> we have to create one
114 let window = FrgApplicationWindow::new(&self.obj());
115 let _ = self.window.set(window.downgrade());
116 window.present();
117 info!("Created application window.");
118
119 // Setup GActions
120 let string_ty = Some(glib::VariantTy::new("s").unwrap());
121
122 // app.add-torrent
123 let action = gio::SimpleAction::new("add-torrent", None);
•124 action.connect_activate(clone!(
125 #[weak(rename_to = app)]
126 self,
127 move |_, _| {
128 app.open_torrent_filechooser();
129 }
130 ));
131 utils::bind_connected_property(&action);
132 obj.add_action(&action);
133 obj.set_accels_for_action("app.add-torrent", &["<primary>o"]);
134
135 // app.add-link
136 let action = gio::SimpleAction::new("add-link", string_ty);
•137 action.connect_activate(clone!(
138 #[weak(rename_to = this)]
139 self,
140 move |_, target| {
141 if let Some(torrent_link) = target.and_then(|x| x.get::<String>()) {
142 // Both magnet and torrent links are supported
143 this.add_torrent_by_link(torrent_link);
144 }
145 }
•146 ));
147 utils::bind_connected_property(&action);
148 obj.add_action(&action);
149
150 // app.search
151 let action = gio::SimpleAction::new("search", None);
•152 action.connect_activate(clone!(
153 #[weak]
154 window,
155 move |_, _| {
156 window.show_search(false);
157 }
158 ));
159 utils::bind_connected_property(&action);
160 obj.add_action(&action);
161 obj.set_accels_for_action("app.search", &["<primary>f"]);
162
163 // app.toggle-search
164 let action = gio::SimpleAction::new("toggle-search", None);
•165 action.connect_activate(clone!(
166 #[weak]
167 window,
168 move |_, _| {
169 window.show_search(true);
170 }
171 ));
172 utils::bind_connected_property(&action);
173 obj.add_action(&action);
174
175 // app.resume-torrents
176 let action = gio::SimpleAction::new("resume-torrents", None);
•177 action.connect_activate(move |_, _| {
178 let fut = async move {
179 let client = FrgConnectionManager::default().client();
180 if let Err(err) = client.start_torrents().await {
181 debug!("Could not resume torrents: {:?}", err);
182 };
183 };
184 glib::spawn_future_local(fut);
•185 });
186 obj.add_action(&action);
187
188 // app.pause-torrents
189 let action = gio::SimpleAction::new("pause-torrents", None);
•190 action.connect_activate(move |_, _| {
191 let fut = async move {
192 let client = FrgConnectionManager::default().client();
193 if let Err(err) = client.stop_torrents().await {
194 debug!("Could not pause torrents: {:?}", err);
195 };
196 };
197 glib::spawn_future_local(fut);
•198 });
199 obj.add_action(&action);
200
201 // app.remove-torrents
202 let action = gio::SimpleAction::new("remove-torrents", None);
•203 action.connect_activate(clone!(
204 #[weak(rename_to = this)]
205 self,
206 move |_, _| {
207 this.show_remove_torrents_dialog();
208 }
209 ));
210 obj.add_action(&action);
211
•212 // app.show-stats
213 let action = gio::SimpleAction::new("show-stats", None);
•214 action.connect_activate(clone!(
215 #[weak]
216 window,
217 move |_, _| {
218 FrgStatsDialog::new().present(Some(&window));
219 }
220 ));
221 utils::bind_connected_property(&action);
222 obj.add_action(&action);
223
224 // app.set-connection
225 let action = gio::SimpleAction::new("set-connection", string_ty);
•226 action.connect_activate(clone!(
227 #[weak(rename_to = this)]
228 self,
229 move |_, target| {
230 if let Some(connection_uuid) = target.and_then(|x| x.get::<String>()) {
231 let fut = async move {
232 this.set_connection(connection_uuid).await;
233 };
234 glib::spawn_future_local(fut);
235 }
236 }
•237 ));
238 obj.add_action(&action);
239
240 // app.reconnect
•241 let action = gio::SimpleAction::new("reconnect", None);
•242 action.connect_activate(clone!(
243 #[weak(rename_to = this)]
244 self,
245 move |_, _| {
246 let cm = FrgConnectionManager::default();
247 this.obj().activate_action(
•248 "set-connection",
249 Some(&cm.current_connection().uuid().to_variant()),
250 );
251 }
252 ));
253 obj.add_action(&action);
254
255 // app.add-remote-connection
256 let action = gio::SimpleAction::new("add-remote-connection", None);
•257 action.connect_activate(clone!(
258 #[weak]
259 window,
260 move |_, _| {
261 let dialog = FrgAddConnectionDialog::new();
262 dialog.present(Some(&window));
263 }
264 ));
265 obj.add_action(&action);
266
267 // app.show-preferences
268 let action = gio::SimpleAction::new("show-preferences", None);
•269 action.connect_activate(clone!(
270 #[weak]
271 window,
272 move |_, _| {
273 FrgPreferencesDialog::default().present(Some(&window));
274 }
275 ));
276 obj.set_accels_for_action("app.show-preferences", &["<primary>comma"]);
277 obj.add_action(&action);
278
279 // app.about
280 let action = gio::SimpleAction::new("about", None);
•281 action.connect_activate(clone!(
282 #[weak]
283 window,
284 move |_, _| {
285 about_dialog::show(&window);
286 }
287 ));
288 obj.add_action(&action);
289
290 // app.quit
291 let action = gio::SimpleAction::new("quit", None);
•292 action.connect_activate(clone!(
293 #[weak]
294 window,
295 move |_, _| {
296 window.close();
297 }
298 ));
299 obj.set_accels_for_action("app.quit", &["<primary>q"]);
300 obj.add_action(&action);
301
302 obj.set_accels_for_action("window.close", &["<primary>w"]);
303
304 // Update state of `pause-torrents` and `remove-torrents` action
305 let stats = FrgConnectionManager::default().client().session_stats();
•306 stats.connect_active_torrent_count_notify(clone!(
307 #[weak(rename_to = this)]
308 self,
309 move |_| {
310 this.obj().update_inhibit_state();
311 }
312 ));
313 stats.connect_downloaded_torrent_count_notify(clone!(
314 #[weak(rename_to = this)]
315 self,
316 move |_| {
317 this.update_session_gactions();
318 this.obj().update_inhibit_state();
319 }
320 ));
321 stats.connect_paused_torrent_count_notify(clone!(
322 #[weak(rename_to = this)]
323 self,
324 move |_| {
325 this.update_session_gactions();
326 this.obj().update_inhibit_state();
327 }
328 ));
329 stats.connect_torrent_count_notify(clone!(
330 #[weak(rename_to = this)]
331 self,
332 move |_| {
333 this.update_session_gactions();
334 }
335 ));
336
337 let client = FrgConnectionManager::default().client();
•338 client.connect_is_connected_notify(clone!(
339 #[weak(rename_to = this)]
340 self,
341 move |_| {
342 this.update_session_gactions();
343 }
344 ));
345
346 self.update_session_gactions();
347 }
348
349 fn open(&self, files: &[gio::File], _hint: &str) {
350 let application = self.obj();
351 application.activate();
352 debug!("Application {} handling files.", config::APP_ID);
353
354 let client = self.connection_manager.client();
355
356 if client.is_connected() {
357 application.add_torrents_from_files(&files.to_vec());
358 } else {
359 // Wait till we're connected with something to add the files
360 let signal_id: Rc<RefCell<Option<glib::SignalHandlerId>>> = Rc::default();
361 let files = files.to_vec().clone();
•362 *signal_id.borrow_mut() = Some(client.connect_is_connected_notify(clone!(
363 #[weak]
364 application,
365 #[strong]
366 signal_id,
367 #[strong]
368 files,
369 move |client| {
370 if client.is_connected() {
371 application.add_torrents_from_files(&files);
372
373 // Disconnect from the signal, we only need it one time
374 let signal_id = signal_id.borrow_mut().take().unwrap();
375 glib::object::ObjectExt::disconnect(client, signal_id);
376 }
•377 }
378 )));
379 }
380 }
381 }
382
383 impl GtkApplicationImpl for FrgApplication {}
384
385 impl AdwApplicationImpl for FrgApplication {}
386
387 impl FrgApplication {
388 fn set_inhibit_suspend(&self, inhibit: bool) {
389 let mut inhibit_cookie = self.inhibit_cookie.borrow_mut();
390
391 if inhibit_cookie.is_some() && !inhibit {
392 debug!("Uninhibit suspend");
393 self.obj().uninhibit(inhibit_cookie.take().unwrap());
394 } else if inhibit && inhibit_cookie.is_none() {
395 debug!("Inhibit suspend");
396 let window = FrgApplicationWindow::default();
397
398 let cookie = self.obj().inhibit(
399 Some(&window),
400 gtk::ApplicationInhibitFlags::SUSPEND,
401 Some(&i18n("Downloading data…")),
402 );
403 *inhibit_cookie = Some(cookie);
404 }
405 }
406
407 /// Disable the `pause-torrents` or `remove-torrents` if there's no
408 /// connection or there are no torrents available to apply the
409 /// action eg. no 100% downloaded torrents available -> disable
410 /// `remove-torrents` action
411 fn update_session_gactions(&self) {
412 let client = FrgConnectionManager::default().client();
413 let stats = client.session_stats();
414 let obj = self.obj();
415
416 let resume_torrents_action: gio::SimpleAction = obj
417 .lookup_action("resume-torrents")
418 .unwrap()
419 .downcast()
420 .unwrap();
421
422 let pause_torrents_action: gio::SimpleAction = obj
423 .lookup_action("pause-torrents")
424 .unwrap()
425 .downcast()
426 .unwrap();
427
428 let remove_torrents_action: gio::SimpleAction = obj
429 .lookup_action("remove-torrents")
430 .unwrap()
431 .downcast()
432 .unwrap();
433
434 if !client.is_connected() {
435 resume_torrents_action.set_enabled(false);
436 pause_torrents_action.set_enabled(false);
437 remove_torrents_action.set_enabled(false);
438 } else {
439 let total_torrent_count = stats.torrent_count();
440 let paused_torrent_count = stats.paused_torrent_count();
441 let downloaded_torrent_count = stats.downloaded_torrent_count();
442
443 let resume_action = paused_torrent_count != 0;
444 resume_torrents_action.set_enabled(resume_action);
445
446 let pause_action = paused_torrent_count != total_torrent_count;
447 pause_torrents_action.set_enabled(pause_action);
448
449 let remove_action = downloaded_torrent_count != 0;
450 remove_torrents_action.set_enabled(remove_action);
451 }
452 }
453
454 async fn set_connection(&self, connection_uuid: String) {
455 let window = FrgApplicationWindow::default();
456 window.set_connection(connection_uuid).await;
457 }
458
459 pub fn add_torrent_by_file(&self, file: &PathBuf) {
460 debug!("Add torrent by file: {:?}", file);
461
462 if let Some(ext) = file.extension() {
463 if ext != "torrent" {
464 warn!("Unsupported file extension: {:?}", ext);
465 utils::inapp_notification(&i18n("Unsupported file format"), gtk::Widget::NONE);
466 return;
467 }
468 }
469
•470 let fut = clone!(
471 #[strong]
472 file,
473 async move {
474 match fs::read(&file).await {
475 Ok(content) => {
476 let encoded = STANDARD.encode(content);
477
478 let cm = FrgConnectionManager::default();
479 let res = cm.add_torrent_by_metainfo(encoded).await;
480 if let Err(err) = res {
481 debug!("Could not add file torrent: {:?}", err);
482 utils::inapp_notification(
483 "Unable to add file torrent",
484 gtk::Widget::NONE,
485 );
486 }
487
•488 if settings_manager::boolean(Key::TrashOriginalTorrentFiles) {
489 let gfile = gio::File::for_path(file);
490 if let Err(err) = gfile.trash_future(glib::Priority::DEFAULT).await
491 {
492 debug!("Unable to trash torrent file: {:?}", err);
493 utils::inapp_notification(
494 "Unable to trash torrent file",
495 gtk::Widget::NONE,
496 );
497 }
498 }
499 }
•500 Err(err) => {
501 debug!("Unable to read file content: {:?}", err);
502 utils::inapp_notification(
503 "Unable to read file content",
504 gtk::Widget::NONE,
505 );
506 }
507 }
508 }
•509 );
510
511 glib::spawn_future_local(fut);
512 }
513
514 pub fn add_torrent_by_link(&self, link: String) {
515 debug!("Add torrent by link: {}", link);
516 let fut = async move {
517 let cm = FrgConnectionManager::default();
518 cm.add_torrent_by_filename(link)
519 .map(move |result| match result {
520 Ok(_) => (),
521 Err(err) => {
522 debug!("Could not add torrent: {:?}", err);
523 utils::inapp_notification("Unable to add torrent", gtk::Widget::NONE);
524 }
525 })
526 .await;
527 };
528
529 glib::spawn_future_local(fut);
530 }
531
532 fn open_torrent_filechooser(&self) {
533 let window = FrgApplicationWindow::default();
534 let dialog = gtk::FileDialog::new();
535 dialog.set_title(&i18n("Open Torrents"));
536 dialog.set_accept_label(Some(&i18n("_Open")));
537
538 // Set a filter to only show torrent files
539 let filter = FileFilter::new();
540 FileFilter::set_name(&filter, Some(&i18n("Torrent files")));
541 filter.add_mime_type("application/x-bittorrent");
542
543 // Set a filter to show all files
544 let all_files_filter = FileFilter::new();
545 FileFilter::set_name(&all_files_filter, Some(&i18n("All files")));
546 all_files_filter.add_pattern("*");
547
548 let filters = gio::ListStore::new::<gtk::FileFilter>();
549 filters.append(&filter);
550 filters.append(&all_files_filter);
551
552 dialog.set_filters(Some(&filters));
553
554 dialog.open_multiple(
555 Some(&window),
556 gio::Cancellable::NONE,
•557 clone!(
558 #[strong(rename_to = _dialog)]
559 dialog,
560 #[weak(rename_to = this)]
561 self,
562 move |result| {
563 if let Ok(files) = result {
564 let files = files
565 .snapshot()
566 .iter()
567 .map(|o| o.downcast_ref::<gio::File>().unwrap().clone())
568 .collect();
569 this.obj().add_torrents_from_files(&files);
570 }
571 }
•572 ),
573 );
574 }
575
576 fn show_remove_torrents_dialog(&self) {
577 let window = self.obj().active_window().unwrap();
578
579 // NOTE: Title of the modal when the user removes all downloaded torrents
580 let heading = i18n("Remove all Downloaded Torrents?");
581 // NOTE: Text displayed in the modal when the user removes all downloaded
582 // torrents
583 let body = i18n(
584 "This will only remove torrents from Fragments, but will keep the downloaded content.",
585 );
586
587 let dialog = adw::MessageDialog::new(Some(&window), Some(&heading), Some(&body));
588
589 dialog.add_response("cancel", &i18n("_Cancel"));
590 dialog.set_default_response(Some("cancel"));
591 dialog.add_response("remove", &i18n("_Remove"));
592 dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
593
594 dialog.connect_response(None, move |dialog, response| {
595 dialog.destroy();
596 if response == "remove" {
597 let fut = async move {
598 let client = FrgConnectionManager::default().client();
599 if let Err(err) = client.remove_torrents(true, false).await {
600 debug!("Could not remove torrents: {:?}", err);
601 };
602 };
603 glib::spawn_future_local(fut);
604 }
605 });
606
607 dialog.present();
608 }
609 }
610 }
611
612 glib::wrapper! {
613 pub struct FrgApplication(ObjectSubclass<imp::FrgApplication>)
614 @extends gio::Application, gtk::Application, adw::Application,
615 @implements gio::ActionMap, gio::ActionGroup;
616 }
617
618 impl FrgApplication {
619 pub fn run() {
620 debug!(
621 "{} ({}) ({}) - Version {} ({})",
622 config::NAME,
623 config::APP_ID,
624 config::VCS_TAG,
625 config::VERSION,
626 config::PROFILE
627 );
628
629 // Create new GObject and downcast it into FrgApplication
630 let app = glib::Object::builder::<FrgApplication>()
631 .property("application-id", config::APP_ID)
632 .property("flags", gio::ApplicationFlags::HANDLES_OPEN)
633 .property("resource-base-path", config::PATH_ID)
634 .build();
635
636 // Start running gtk::Application
637 app.run();
638 }
639
640 /// Inhibit standby/suspend when there are active torrents
641 /// (and `InhibitSuspendActiveTorrents` setting is enabled)
642 pub fn update_inhibit_state(&self) {
643 debug!("Update inhibit state...");
644
645 let client = FrgConnectionManager::default().client();
646 let stats = client.session_stats();
647
648 let total_torrent_count = stats.torrent_count();
649 let paused_torrent_count = stats.paused_torrent_count();
650 let downloaded_torrent_count = stats.downloaded_torrent_count();
651
652 let inhibit = settings_manager::boolean(Key::InhibitSuspendActiveTorrents)
653 && (total_torrent_count - paused_torrent_count - downloaded_torrent_count) != 0;
654
655 self.set_inhibit_suspend(inhibit);
656 }
657
658 pub fn add_torrents_from_files(&self, files: &Vec<gio::File>) {
659 for file in files {
660 if let Some(path) = file.path() {
661 // Local file
662 self.imp().add_torrent_by_file(&path);
663 } else {
664 // URI, means magnet or torrent link
665 let uri = file.uri().to_string();
•666 self.imp().add_torrent_by_link(normalize_magnet_uri(uri));
667 }
668 }
669 }
670 }
671
•672 // `gio::File::for_uri("magnet:?xt=…").uri()` re-emits magnet URIs in
673 // hierarchical form (`magnet:///?xt=…`), which transmission's torrent-add
674 // rejects. Strip the spurious empty authority so we hand transmission the
675 // canonical `magnet:?xt=…` form.
676 fn normalize_magnet_uri(uri: String) -> String {
677 if let Some(rest) = uri.strip_prefix("magnet:") {
678 let rest = rest.trim_start_matches('/');
679 format!("magnet:{rest}")
680 } else {
681 uri
682 }
683 }
684
685 impl Default for FrgApplication {
686 fn default() -> Self {
687 gio::Application::default()
688 .expect("Could not get default GApplication")
689 .downcast()
690 .unwrap()
691 }
692 }