Debian Codegraph @

src/app.rs

raw ◀ ▶
Source reconstructed at patch state 2 of 3 — not the installed (fully patched) source.
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!(@weak self as this => async move {
94 let cm = FrgConnectionManager::default();
95
96 let local_connection = FrgConnection::default();
97 cm.connections().insert(0, &local_connection);
98
99 if let Err(err) = secret_store::open_keyring().await {
100 error!("Could not unlock keyring: {err}");
101 };
102
103 // Restore last used connection
104 let uuid = settings_manager::string(Key::ClientLastConnection);
105 this.set_connection(uuid).await;
106 });
107 glib::spawn_future_local(fut);
108
109 // No window available -> we have to create one
110 let window = FrgApplicationWindow::new(&self.obj());
111 let _ = self.window.set(window.downgrade());
112 window.present();
113 info!("Created application window.");
114
115 // Setup GActions
116 let string_ty = Some(glib::VariantTy::new("s").unwrap());
117
118 // app.add-torrent
119 let action = gio::SimpleAction::new("add-torrent", None);
120 action.connect_activate(clone!(@weak self as app => move |_, _| {
121 app.open_torrent_filechooser();
122 }));
123 utils::bind_connected_property(&action);
124 obj.add_action(&action);
125 obj.set_accels_for_action("app.add-torrent", &["<primary>o"]);
126
127 // app.add-link
128 let action = gio::SimpleAction::new("add-link", string_ty);
129 action.connect_activate(clone!(@weak self as this => move |_, target| {
130 if let Some(torrent_link) = target.and_then(|x| x.get::<String>()) {
131 // Both magnet and torrent links are supported
132 this.add_torrent_by_link(torrent_link);
133 }
134 }));
135 utils::bind_connected_property(&action);
136 obj.add_action(&action);
137
138 // app.search
139 let action = gio::SimpleAction::new("search", None);
140 action.connect_activate(clone!(@weak window => move |_, _| {
141 window.show_search(false);
142 }));
143 utils::bind_connected_property(&action);
144 obj.add_action(&action);
145 obj.set_accels_for_action("app.search", &["<primary>f"]);
146
147 // app.toggle-search
148 let action = gio::SimpleAction::new("toggle-search", None);
149 action.connect_activate(clone!(@weak window => move |_, _| {
150 window.show_search(true);
151 }));
152 utils::bind_connected_property(&action);
153 obj.add_action(&action);
154
155 // app.resume-torrents
156 let action = gio::SimpleAction::new("resume-torrents", None);
157 action.connect_activate(clone!(@weak self as app => move |_, _| {
158 let fut = async move {
159 let client = FrgConnectionManager::default().client();
160 if let Err(err) = client.start_torrents().await {
161 debug!("Could not resume torrents: {:?}", err);
162 };
163 };
164 glib::spawn_future_local(fut);
165 }));
166 obj.add_action(&action);
167
168 // app.pause-torrents
169 let action = gio::SimpleAction::new("pause-torrents", None);
170 action.connect_activate(clone!(@weak self as app => move |_, _| {
171 let fut = async move {
172 let client = FrgConnectionManager::default().client();
173 if let Err(err) = client.stop_torrents().await {
174 debug!("Could not pause torrents: {:?}", err);
175 };
176 };
177 glib::spawn_future_local(fut);
178
179 }));
180 obj.add_action(&action);
181
182 // app.remove-torrents
183 let action = gio::SimpleAction::new("remove-torrents", None);
184 action.connect_activate(clone!(@weak self as this => move |_, _| {
185 this.show_remove_torrents_dialog();
186 }));
187 obj.add_action(&action);
188
189 // app.show-stats
190 let action = gio::SimpleAction::new("show-stats", None);
191 action.connect_activate(clone!(@weak window => move |_, _| {
192 FrgStatsDialog::new().present(Some(&window));
193 }));
194 utils::bind_connected_property(&action);
195 obj.add_action(&action);
196
197 // app.set-connection
198 let action = gio::SimpleAction::new("set-connection", string_ty);
199 action.connect_activate(clone!(@weak self as this => move |_, target| {
200 if let Some(connection_uuid) = target.and_then(|x| x.get::<String>()) {
201 let fut = async move {
202 this.set_connection(connection_uuid).await;
203 };
204 glib::spawn_future_local(fut);
205 }
206 }));
207 obj.add_action(&action);
208
209 // app.reconnect
210 let action = gio::SimpleAction::new("reconnect", None);
211 action.connect_activate(clone!(@weak self as this => move |_, _| {
212 let cm = FrgConnectionManager::default();
213 this.obj().activate_action("set-connection", Some(&cm.current_connection().uuid().to_variant()));
214 }));
215 obj.add_action(&action);
216
217 // app.add-remote-connection
218 let action = gio::SimpleAction::new("add-remote-connection", None);
219 action.connect_activate(clone!(@weak window => move |_, _| {
220 let dialog = FrgAddConnectionDialog::new();
221 dialog.present(Some(&window));
222 }));
223 obj.add_action(&action);
224
225 // app.show-preferences
226 let action = gio::SimpleAction::new("show-preferences", None);
227 action.connect_activate(clone!(@weak window => move |_, _| {
228 FrgPreferencesDialog::default().present(Some(&window));
229 }));
230 obj.set_accels_for_action("app.show-preferences", &["<primary>comma"]);
231 obj.add_action(&action);
232
233 // app.about
234 let action = gio::SimpleAction::new("about", None);
235 action.connect_activate(clone!(@weak window => move |_, _| {
236 about_dialog::show(&window);
237 }));
238 obj.add_action(&action);
239
240 // app.quit
241 let action = gio::SimpleAction::new("quit", None);
242 action.connect_activate(clone!(@weak window => move |_, _| {
243 window.close();
244 }));
245 obj.set_accels_for_action("app.quit", &["<primary>q"]);
246 obj.add_action(&action);
247
248 obj.set_accels_for_action("window.close", &["<primary>w"]);
249
250 // Update state of `pause-torrents` and `remove-torrents` action
251 let stats = FrgConnectionManager::default().client().session_stats();
252 stats.connect_active_torrent_count_notify(clone!(@weak self as this => move |_|{
253 this.obj().update_inhibit_state();
254 }));
255 stats.connect_downloaded_torrent_count_notify(clone!(@weak self as this => move |_|{
256 this.update_session_gactions();
257 this.obj().update_inhibit_state();
258 }));
259 stats.connect_paused_torrent_count_notify(clone!(@weak self as this => move |_|{
260 this.update_session_gactions();
261 this.obj().update_inhibit_state();
262 }));
263 stats.connect_torrent_count_notify(clone!(@weak self as this => move |_|{
264 this.update_session_gactions();
265 }));
266
267 let client = FrgConnectionManager::default().client();
268 client.connect_is_connected_notify(clone!(@weak self as this => move |_|{
269 this.update_session_gactions();
270 }));
271
272 self.update_session_gactions();
273 }
274
275 fn open(&self, files: &[gio::File], _hint: &str) {
276 let application = self.obj();
277 application.activate();
278 debug!("Application {} handling files.", config::APP_ID);
279
280 let client = self.connection_manager.client();
281
282 if client.is_connected() {
283 application.add_torrents_from_files(&files.to_vec());
284 } else {
285 // Wait till we're connected with something to add the files
286 let signal_id: Rc<RefCell<Option<glib::SignalHandlerId>>> = Rc::default();
287 let files = files.to_vec().clone();
288 *signal_id.borrow_mut() = Some(client.connect_is_connected_notify(
289 clone!(@weak application, @strong signal_id, @strong files => move |client| {
290 if client.is_connected() {
291 application.add_torrents_from_files(&files);
292
293 // Disconnect from the signal, we only need it one time
294 let signal_id = signal_id.borrow_mut().take().unwrap();
295 glib::object::ObjectExt::disconnect(client, signal_id);
296 }
297 }),
298 ));
299 }
300 }
301 }
302
303 impl GtkApplicationImpl for FrgApplication {}
304
305 impl AdwApplicationImpl for FrgApplication {}
306
307 impl FrgApplication {
308 fn set_inhibit_suspend(&self, inhibit: bool) {
309 let mut inhibit_cookie = self.inhibit_cookie.borrow_mut();
310
311 if inhibit_cookie.is_some() && !inhibit {
312 debug!("Uninhibit suspend");
313 self.obj().uninhibit(inhibit_cookie.take().unwrap());
314 } else if inhibit && inhibit_cookie.is_none() {
315 debug!("Inhibit suspend");
316 let window = FrgApplicationWindow::default();
317
318 let cookie = self.obj().inhibit(
319 Some(&window),
320 gtk::ApplicationInhibitFlags::SUSPEND,
321 Some(&i18n("Downloading data…")),
322 );
323 *inhibit_cookie = Some(cookie);
324 }
325 }
326
327 /// Disable the `pause-torrents` or `remove-torrents` if there's no
328 /// connection or there are no torrents available to apply the
329 /// action eg. no 100% downloaded torrents available -> disable
330 /// `remove-torrents` action
331 fn update_session_gactions(&self) {
332 let client = FrgConnectionManager::default().client();
333 let stats = client.session_stats();
334 let obj = self.obj();
335
336 let resume_torrents_action: gio::SimpleAction = obj
337 .lookup_action("resume-torrents")
338 .unwrap()
339 .downcast()
340 .unwrap();
341
342 let pause_torrents_action: gio::SimpleAction = obj
343 .lookup_action("pause-torrents")
344 .unwrap()
345 .downcast()
346 .unwrap();
347
348 let remove_torrents_action: gio::SimpleAction = obj
349 .lookup_action("remove-torrents")
350 .unwrap()
351 .downcast()
352 .unwrap();
353
354 if !client.is_connected() {
355 resume_torrents_action.set_enabled(false);
356 pause_torrents_action.set_enabled(false);
357 remove_torrents_action.set_enabled(false);
358 } else {
359 let total_torrent_count = stats.torrent_count();
360 let paused_torrent_count = stats.paused_torrent_count();
361 let downloaded_torrent_count = stats.downloaded_torrent_count();
362
363 let resume_action = paused_torrent_count != 0;
364 resume_torrents_action.set_enabled(resume_action);
365
366 let pause_action = paused_torrent_count != total_torrent_count;
367 pause_torrents_action.set_enabled(pause_action);
368
369 let remove_action = downloaded_torrent_count != 0;
370 remove_torrents_action.set_enabled(remove_action);
371 }
372 }
373
374 async fn set_connection(&self, connection_uuid: String) {
375 let window = FrgApplicationWindow::default();
376 window.set_connection(connection_uuid).await;
377 }
378
379 pub fn add_torrent_by_file(&self, file: &PathBuf) {
380 debug!("Add torrent by file: {:?}", file);
381
382 if let Some(ext) = file.extension() {
383 if ext != "torrent" {
384 warn!("Unsupported file extension: {:?}", ext);
385 utils::inapp_notification(&i18n("Unsupported file format"), gtk::Widget::NONE);
386 return;
387 }
388 }
389
390 let fut = clone!(@strong file => async move {
391 match fs::read(&file).await {
392 Ok(content) => {
393 let encoded = STANDARD.encode(content);
394
395 let cm = FrgConnectionManager::default();
396 let res = cm.add_torrent_by_metainfo(encoded).await;
397 if let Err(err) = res {
398 debug!("Could not add file torrent: {:?}", err);
399 utils::inapp_notification("Unable to add file torrent", gtk::Widget::NONE);
400 }
401
402 if settings_manager::boolean(Key::TrashOriginalTorrentFiles){
403 let gfile = gio::File::for_path(file);
404 if let Err(err) = gfile.trash_future(glib::Priority::DEFAULT).await {
405 debug!("Unable to trash torrent file: {:?}", err);
406 utils::inapp_notification("Unable to trash torrent file", gtk::Widget::NONE);
407 }
408 }
409 }
410 Err(err) => {
411 debug!("Unable to read file content: {:?}", err);
412 utils::inapp_notification("Unable to read file content", gtk::Widget::NONE);
413 }
414 }
415 });
416
417 glib::spawn_future_local(fut);
418 }
419
420 pub fn add_torrent_by_link(&self, link: String) {
421 debug!("Add torrent by link: {}", link);
422 let fut = async move {
423 let cm = FrgConnectionManager::default();
424 cm.add_torrent_by_filename(link)
425 .map(move |result| match result {
426 Ok(_) => (),
427 Err(err) => {
428 debug!("Could not add torrent: {:?}", err);
429 utils::inapp_notification("Unable to add torrent", gtk::Widget::NONE);
430 }
431 })
432 .await;
433 };
434
435 glib::spawn_future_local(fut);
436 }
437
438 fn open_torrent_filechooser(&self) {
439 let window = FrgApplicationWindow::default();
440 let dialog = gtk::FileDialog::new();
441 dialog.set_title(&i18n("Open Torrents"));
442 dialog.set_accept_label(Some(&i18n("_Open")));
443
444 // Set a filter to only show torrent files
445 let filter = FileFilter::new();
446 FileFilter::set_name(&filter, Some(&i18n("Torrent files")));
447 filter.add_mime_type("application/x-bittorrent");
448
449 // Set a filter to show all files
450 let all_files_filter = FileFilter::new();
451 FileFilter::set_name(&all_files_filter, Some(&i18n("All files")));
452 all_files_filter.add_pattern("*");
453
454 let filters = gio::ListStore::new::<gtk::FileFilter>();
455 filters.append(&filter);
456 filters.append(&all_files_filter);
457
458 dialog.set_filters(Some(&filters));
459
460 dialog.open_multiple(
461 Some(&window),
462 gio::Cancellable::NONE,
463 clone!(@strong dialog, @weak self as this => move |result| {
464 if let Ok(files) = result {
465 let files = files
466 .snapshot()
467 .iter()
468 .map(|o| o.downcast_ref::<gio::File>().unwrap().clone())
469 .collect();
470 this.obj().add_torrents_from_files(&files);
471 }
472 }),
473 );
474 }
475
476 fn show_remove_torrents_dialog(&self) {
477 let window = self.obj().active_window().unwrap();
478
479 // NOTE: Title of the modal when the user removes all downloaded torrents
480 let heading = i18n("Remove all Downloaded Torrents?");
481 // NOTE: Text displayed in the modal when the user removes all downloaded
482 // torrents
483 let body = i18n(
484 "This will only remove torrents from Fragments, but will keep the downloaded content.",
485 );
486
487 let dialog = adw::MessageDialog::new(Some(&window), Some(&heading), Some(&body));
488
489 dialog.add_response("cancel", &i18n("_Cancel"));
490 dialog.set_default_response(Some("cancel"));
491 dialog.add_response("remove", &i18n("_Remove"));
492 dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
493
494 dialog.connect_response(None, move |dialog, response| {
495 dialog.destroy();
496 if response == "remove" {
497 let fut = async move {
498 let client = FrgConnectionManager::default().client();
499 if let Err(err) = client.remove_torrents(true, false).await {
500 debug!("Could not remove torrents: {:?}", err);
501 };
502 };
503 glib::spawn_future_local(fut);
504 }
505 });
506
507 dialog.present();
508 }
509 }
510 }
511
512 glib::wrapper! {
513 pub struct FrgApplication(ObjectSubclass<imp::FrgApplication>)
514 @extends gio::Application, gtk::Application, adw::Application,
515 @implements gio::ActionMap, gio::ActionGroup;
516 }
517
518 impl FrgApplication {
519 pub fn run() {
520 debug!(
521 "{} ({}) ({}) - Version {} ({})",
522 config::NAME,
523 config::APP_ID,
524 config::VCS_TAG,
525 config::VERSION,
526 config::PROFILE
527 );
528
529 // Create new GObject and downcast it into FrgApplication
530 let app = glib::Object::builder::<FrgApplication>()
531 .property("application-id", config::APP_ID)
532 .property("flags", gio::ApplicationFlags::HANDLES_OPEN)
533 .property("resource-base-path", config::PATH_ID)
534 .build();
535
536 // Start running gtk::Application
537 app.run();
538 }
539
540 /// Inhibit standby/suspend when there are active torrents
541 /// (and `InhibitSuspendActiveTorrents` setting is enabled)
542 pub fn update_inhibit_state(&self) {
543 debug!("Update inhibit state...");
544
545 let client = FrgConnectionManager::default().client();
546 let stats = client.session_stats();
547
548 let total_torrent_count = stats.torrent_count();
549 let paused_torrent_count = stats.paused_torrent_count();
550 let downloaded_torrent_count = stats.downloaded_torrent_count();
551
552 let inhibit = settings_manager::boolean(Key::InhibitSuspendActiveTorrents)
553 && (total_torrent_count - paused_torrent_count - downloaded_torrent_count) != 0;
554
555 self.set_inhibit_suspend(inhibit);
556 }
557
558 pub fn add_torrents_from_files(&self, files: &Vec<gio::File>) {
559 for file in files {
560 if let Some(path) = file.path() {
561 // Local file
562 self.imp().add_torrent_by_file(&path);
563 } else {
564 // URI, means magnet or torrent link
565 let uri = file.uri().to_string();
566 self.imp().add_torrent_by_link(normalize_magnet_uri(uri));
567 }
568 }
569 }
570 }
571
572 // `gio::File::for_uri("magnet:?xt=…").uri()` re-emits magnet URIs in
573 // hierarchical form (`magnet:///?xt=…`), which transmission's torrent-add
574 // rejects. Strip the spurious empty authority so we hand transmission the
575 // canonical `magnet:?xt=…` form.
576 fn normalize_magnet_uri(uri: String) -> String {
577 if let Some(rest) = uri.strip_prefix("magnet:") {
578 let rest = rest.trim_start_matches('/');
579 format!("magnet:{rest}")
580 } else {
581 uri
582 }
583 }
584
585 impl Default for FrgApplication {
586 fn default() -> Self {
587 gio::Application::default()
588 .expect("Could not get default GApplication")
589 .downcast()
590 .unwrap()
591 }
592 }