Debian Codegraph @

src/ui/connection_box.rs

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