Debian Codegraph @

src/ui/connection_box.rs

raw ◀ ▶
1 Debian patch touch this file
1 // Fragments - connection_box.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 async_recursion::async_recursion;
18 use glib::{clone, subclass};
19 use gtk::prelude::*;
20 use gtk::subclass::prelude::*;
21 use gtk::{gdk, glib, CompositeTemplate};
22 use transmission_gobject::{ClientError, TrAuthentication, TrClient};
23
24 use crate::app::FrgApplication;
25 use crate::backend::{
26 secret_store, FrgConnection, FrgConnectionManager, FrgDaemonStopReason, FrgDirectoryType,
27 };
28 use crate::i18n::{i18n, i18n_f};
29 use crate::ui::{FrgDragOverlay, FrgTorrentPage};
30 use crate::{config, utils};
31
32 pub enum View {
33 Authentication,
34 Loading,
35 Ready,
36 Torrents,
37 Metered,
38 Failure(String),
39 }
40
41 mod imp {
42 use super::*;
43
44 #[derive(Default, Debug, CompositeTemplate)]
45 #[template(resource = "/de/haeckerfelix/Fragments/gtk/connection_box.ui")]
46 pub struct FrgConnectionBox {
47 #[template_child]
48 stack: TemplateChild<gtk::Stack>,
49 #[template_child]
50 pub torrent_page: TemplateChild<FrgTorrentPage>,
51 #[template_child]
52 welcome_status_page: TemplateChild<adw::StatusPage>,
53 #[template_child]
54 failure_status_page: TemplateChild<adw::StatusPage>,
55 #[template_child]
56 username_row: TemplateChild<adw::EntryRow>,
57 #[template_child]
58 password_row: TemplateChild<adw::PasswordEntryRow>,
59 #[template_child]
60 authenticate_button: TemplateChild<gtk::Button>,
61 #[template_child]
62 invalid_dir_banner: TemplateChild<adw::Banner>,
63 #[template_child]
64 drag_overlay: TemplateChild<FrgDragOverlay>,
65 }
66
67 #[glib::object_subclass]
68 impl ObjectSubclass for FrgConnectionBox {
69 const NAME: &'static str = "FrgConnectionBox";
70 type ParentType = gtk::Box;
71 type Type = super::FrgConnectionBox;
72
73 fn class_init(klass: &mut Self::Class) {
74 klass.bind_template();
75 klass.bind_template_callbacks();
76 }
77
78 fn instance_init(obj: &subclass::InitializingObject<Self>) {
79 obj.init_template();
80 }
81 }
82
83 impl ObjectImpl for FrgConnectionBox {
84 fn constructed(&self) {
85 self.parent_constructed();
86
87 let cm = FrgConnectionManager::default();
88 let client = cm.client();
89
90 // Set welcome icon
91 if config::PROFILE == "development" {
92 let icon = Some("de.haeckerfelix.Fragments.Devel");
93 self.welcome_status_page.set_icon_name(icon);
94 }
95
96 // Initial view -> Loading
97 self.set_view(View::Loading);
98
99 // Show a message when the currently configured directory is not accessible
•100 cm.connect_invalid_dir_notify(clone!(
101 #[weak(rename_to = this)]
102 self,
103 move |cm| {
104 let res: Option<String> = match cm.invalid_dir() {
105 FrgDirectoryType::Download => Some(i18n(
106 "The configured download directory cannot be accessed.",
107 )),
108 FrgDirectoryType::Incomplete => Some(i18n(
109 "The configured incomplete directory cannot be accessed.",
110 )),
111 _ => None,
112 };
113
•114 if let Some(res) = res {
115 this.invalid_dir_banner.set_revealed(true);
116 this.invalid_dir_banner.set_title(&res);
117 } else {
118 this.invalid_dir_banner.set_revealed(false);
119 }
120 }
•121 ));
122
123 cm.connect_local(
124 "daemon-started",
125 false,
•126 clone!(
127 #[weak(rename_to = this)]
128 self,
129 #[upgrade_or_panic]
130 move |_| {
131 this.update_torrents_view();
132 None
133 }
134 ),
135 );
136
137 cm.connect_local(
138 "daemon-stopped",
139 false,
•140 clone!(
141 #[weak(rename_to = this)]
142 self,
143 #[upgrade_or_panic]
144 move |val| {
145 let reason = val[1].get::<FrgDaemonStopReason>().unwrap();
146 this.show_stop_reason(reason);
147 None
148 }
149 ),
150 );
151
152 client.torrents().connect_local(
153 "items-changed",
154 false,
•155 clone!(
156 #[weak(rename_to = this)]
157 self,
158 #[upgrade_or_panic]
159 move |_| {
160 this.update_torrents_view();
161 None
162 }
163 ),
164 );
165
166 client.connect_local("connection-failure", false, move |_| {
167 let app = FrgApplication::default();
168 let cm = FrgConnectionManager::default();
169 let connection = cm.current_connection();
170
171 utils::inapp_notification(
172 &i18n_f("Connection with {} was lost.", &[&connection.title()]),
173 gtk::Widget::NONE,
174 );
175
176 // Try to reconnect
177 app.activate_action("set-connection", Some(&connection.uuid().to_variant()));
178 None
179 });
180
181 // Drag and drop support
182 let drop_target = self.drag_overlay.drop_target();
183 drop_target.set_types(&[gdk::FileList::static_type()]);
184
•185 drop_target.connect_accept(clone!(
186 #[weak]
187 client,
188 #[upgrade_or]
189 false,
190 move |_, _| {
191 // Only accept drops when we're connected to a Transmission session
192 client.is_connected()
193 }
194 ));
195
•196 drop_target.connect_drop(move |_, value, _, _| {
197 let files = match value.get::<gdk::FileList>() {
198 Ok(list) => list.files(),
199 Err(err) => {
200 error!("Issue with drop value: {err}");
201 return false;
202 }
•203 };
204
205 if !files.is_empty() {
206 let app = FrgApplication::default();
207 app.add_torrents_from_files(&files);
208 return true;
209 } else {
210 error!("Dropped FileList was empty");
211 return false;
212 }
213 });
214
215 self.stack.add_controller(drop_target.clone());
216 }
217 }
218 impl WidgetImpl for FrgConnectionBox {}
219
220 impl BoxImpl for FrgConnectionBox {}
221
222 #[gtk::template_callbacks]
223 impl FrgConnectionBox {
224 pub fn update_torrents_view(&self) {
225 let client = FrgConnectionManager::default().client();
226 let model = client.torrents();
227
228 if !client.is_connected() {
229 return;
230 }
231
232 if model.n_items() == 0 {
233 self.set_view(View::Ready);
234 } else {
235 self.set_view(View::Torrents);
236 }
237 }
238
239 pub fn show_authentication(&self, failure: bool) {
240 if failure {
241 self.username_row.add_css_class("error");
242 self.password_row.add_css_class("error");
243 } else {
244 self.username_row.remove_css_class("error");
245 self.password_row.remove_css_class("error");
246 }
247
248 self.set_view(View::Authentication);
249 }
250
251 pub fn show_stop_reason(&self, reason: FrgDaemonStopReason) {
252 match reason {
253 FrgDaemonStopReason::Metered => self.set_view(View::Metered),
254 FrgDaemonStopReason::VpnDisconnect => unimplemented!(),
255 _ => (),
256 }
257 }
258
259 pub fn set_view(&self, view: View) {
260 let name = match view {
261 View::Authentication => {
262 // Unset previous entry text
263 self.username_row.set_text("");
264 self.password_row.set_text("");
265 "authentication"
266 }
•267 View::Loading => "loading",
268 View::Ready => "ready",
269 View::Torrents => "torrents",
270 View::Metered => "metered",
271 View::Failure(err) => {
272 self.failure_status_page.set_description(Some(&err));
273 "failure"
274 }
275 };
276
277 self.stack.set_visible_child_name(name);
278 }
279
280 #[template_callback]
281 async fn authenticate_button_clicked(&self) {
282 let cm = FrgConnectionManager::default();
283
284 let auth = TrAuthentication::new(&self.username_row.text(), &self.password_row.text());
285 cm.client().set_authentication(auth.clone());
286
287 let res = secret_store::store(&cm.current_connection(), &auth).await;
288 if let Err(err) = res {
289 warn!("Credentials could not be saved: {}", err.to_string());
290 utils::inapp_notification(
291 &i18n("Credentials could not be saved"),
292 gtk::Widget::NONE,
293 );
294 }
295
296 FrgApplication::default().activate_action("reconnect", None);
297 }
298
299 #[template_callback]
300 fn reconnect_button_clicked(&self) {
301 FrgApplication::default().activate_action("reconnect", None);
302 }
303
304 #[template_callback]
305 fn allow_metered_clicked(&self) {
306 debug!("Allow metered connections...");
307
308 let cm = FrgConnectionManager::default();
309 cm.set_allow_metered(true);
310
311 FrgApplication::default().activate_action("reconnect", None);
312 }
313 }
314 }
315
316 glib::wrapper! {
317 pub struct FrgConnectionBox(
318 ObjectSubclass<imp::FrgConnectionBox>)
•319 @extends gtk::Widget, gtk::Box,
320 @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
321 }
322
323 impl FrgConnectionBox {
324 #[async_recursion(?Send)]
325 pub async fn set_connection(&self, connection_uuid: String) {
326 let cm = FrgConnectionManager::default();
327
328 // Try to retrieve a `FrgConnection` by using the connection uuid
329 let connection = if let Some(connection) = cm.connection_by_uuid(&connection_uuid) {
330 connection
331 } else {
332 let msg = i18n_f("No connection found with UUID \"{}\"", &[&connection_uuid]);
333 utils::inapp_notification(&msg, gtk::Widget::NONE);
334
335 // Fallback to local Fragments connection
336 let default_uuid = FrgConnection::default().uuid();
337 if connection_uuid != default_uuid {
338 self.set_connection(default_uuid).await;
339 }
340
341 return;
342 };
343
344 self.imp().set_view(View::Loading);
345
346 // Establish connection
347 match cm.connect(&connection).await {
348 Ok(stop_reason) => {
349 if let Some(reason) = stop_reason {
350 self.imp().show_stop_reason(reason);
351 } else {
352 self.imp().update_torrents_view();
353 }
354 }
355 Err(err) => {
356 if matches!(err, ClientError::TransmissionUnauthorized) {
357 if let Ok(Some(auth)) = secret_store::get(&connection).await {
358 let addr = connection.address();
359
360 // Test if the saved credentials are valid
361 if let Err(err) =
362 TrClient::test_connectivity(addr, Some(auth.clone())).await
363 {
364 if matches!(err, ClientError::TransmissionUnauthorized) {
365 // Nope -> Show authentication page again
366 self.imp().show_authentication(true);
367 }
368 } else {
369 cm.client().set_authentication(auth);
370 FrgApplication::default().activate_action("reconnect", None);
371 }
372 } else {
373 self.imp().show_authentication(false);
374 }
375 } else {
376 let msg = i18n_f(
377 "Failed to establish a connection with the Transmission service (“{}”).",
378 &[&err.to_string()],
379 );
380
381 warn!("{msg}");
382 self.imp().set_view(View::Failure(msg));
383 }
384 }
385 }
386 }
387 }