smirrors 0.1.0

Automatic mirror list updater for Linux distributions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! TUI application state and logic
//!
//! This module manages the state for the interactive terminal UI,
//! including view management, user actions, and async operations.

use crate::config::Config;
use crate::core::{Mirror, MirrorTester, TestResult};
use crate::storage::Database;
use anyhow::Result;
use ratatui::widgets::ListState;
use std::sync::Arc;
use tracing::{debug, info};

/// Available views in the TUI
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
    Dashboard,
    Testing,
    History,
    Config,
    StaticMirrors,
    Help,
}

/// Current testing state
#[derive(Debug, Clone, PartialEq)]
pub enum TestingState {
    Idle,
    InProgress {
        completed: usize,
        total: usize,
        current_mirror: String,
    },
    Completed,
}

/// Application state for the TUI
pub struct App {
    /// Current view being displayed
    pub current_view: View,

    /// Whether the app should quit
    pub should_quit: bool,

    /// Available mirrors (all mirrors from database)
    pub mirrors: Vec<Mirror>,

    /// Most recent test results
    pub test_results: Vec<TestResult>,

    /// Selected mirror index in the current list
    pub selected_mirror: Option<usize>,

    /// List widget state for mirror selection
    pub list_state: ListState,

    /// Current testing state
    pub testing_state: TestingState,

    /// Application configuration
    pub config: Config,

    /// Database connection
    pub database: Database,

    /// Service status (running/stopped)
    pub service_running: bool,

    /// Last update timestamp
    pub last_update: Option<chrono::DateTime<chrono::Utc>>,

    /// Update history records
    pub history: Vec<crate::storage::UpdateRecord>,

    /// Static mirrors list
    pub static_mirrors: Vec<Mirror>,

    /// Selected history index
    pub selected_history: Option<usize>,

    /// History list state
    pub history_list_state: ListState,

    /// Configuration edit mode flag
    pub config_edit_mode: bool,

    /// Selected config item index
    pub selected_config_item: usize,

    /// Status message to display
    pub status_message: Option<String>,

    /// Error message to display
    pub error_message: Option<String>,

    /// Input buffer for adding static mirrors
    pub input_buffer: String,

    /// Input mode (for adding mirrors, editing config, etc.)
    pub input_mode: bool,

    /// Scroll offset for long lists
    pub scroll_offset: u16,
}

impl App {
    /// Create a new application instance
    ///
    /// # Arguments
    /// * `config` - Application configuration
    /// * `database` - Database connection
    ///
    /// # Returns
    /// A new App instance with initialized state
    pub async fn new(config: Config, database: Database) -> Result<Self> {
        debug!("Initializing TUI application");

        // Load initial data
        let mirrors = database.get_mirrors(&Default::default()).unwrap_or_default();
        let test_results = database.get_test_results(&Default::default()).unwrap_or_default();
        let history = database.get_history(50).unwrap_or_default();
        let last_update = database.get_latest_update()
            .ok()
            .flatten()
            .map(|r| r.updated_at);

        let static_mirrors = database.get_mirrors(&crate::storage::MirrorFilter {
            static_only: true,
            ..Default::default()
        }).unwrap_or_default();

        let service_running = Self::check_service_status();

        let mut list_state = ListState::default();
        if !mirrors.is_empty() {
            list_state.select(Some(0));
        }

        info!("TUI application initialized with {} mirrors", mirrors.len());

        Ok(Self {
            current_view: View::Dashboard,
            should_quit: false,
            mirrors,
            test_results,
            selected_mirror: Some(0),
            list_state,
            testing_state: TestingState::Idle,
            config,
            database,
            service_running,
            last_update,
            history,
            static_mirrors,
            selected_history: None,
            history_list_state: ListState::default(),
            config_edit_mode: false,
            selected_config_item: 0,
            status_message: None,
            error_message: None,
            input_buffer: String::new(),
            input_mode: false,
            scroll_offset: 0,
        })
    }

    /// Check if the systemd service is running
    fn check_service_status() -> bool {
        std::process::Command::new("systemctl")
            .args(&["is-active", "--quiet", "smirrors.service"])
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    /// Switch to a different view
    pub fn switch_view(&mut self, view: View) {
        debug!("Switching to view: {:?}", self.current_view);
        self.current_view = view;
        self.clear_messages();
    }

    /// Move selection to next mirror in list
    pub fn next_mirror(&mut self) {
        let list_len = match self.current_view {
            View::Dashboard | View::Testing => self.mirrors.len(),
            View::History => self.history.len(),
            View::StaticMirrors => self.static_mirrors.len(),
            _ => return,
        };

        if list_len == 0 {
            return;
        }

        let state = match self.current_view {
            View::History => &mut self.history_list_state,
            _ => &mut self.list_state,
        };

        let i = match state.selected() {
            Some(i) => {
                if i >= list_len - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };

        state.select(Some(i));

        match self.current_view {
            View::History => self.selected_history = Some(i),
            _ => self.selected_mirror = Some(i),
        }
    }

    /// Move selection to previous mirror in list
    pub fn previous_mirror(&mut self) {
        let list_len = match self.current_view {
            View::Dashboard | View::Testing => self.mirrors.len(),
            View::History => self.history.len(),
            View::StaticMirrors => self.static_mirrors.len(),
            _ => return,
        };

        if list_len == 0 {
            return;
        }

        let state = match self.current_view {
            View::History => &mut self.history_list_state,
            _ => &mut self.list_state,
        };

        let i = match state.selected() {
            Some(i) => {
                if i == 0 {
                    list_len - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };

        state.select(Some(i));

        match self.current_view {
            View::History => self.selected_history = Some(i),
            _ => self.selected_mirror = Some(i),
        }
    }

    /// Select a specific mirror by index
    pub fn select_mirror(&mut self, index: usize) {
        if index < self.mirrors.len() {
            self.list_state.select(Some(index));
            self.selected_mirror = Some(index);
        }
    }

    /// Get currently selected mirror
    pub fn get_selected_mirror(&self) -> Option<&Mirror> {
        self.selected_mirror.and_then(|i| self.mirrors.get(i))
    }

    /// Run mirror tests asynchronously
    pub async fn run_test(&mut self) -> Result<()> {
        info!("Starting mirror tests");
        self.testing_state = TestingState::InProgress {
            completed: 0,
            total: self.mirrors.len(),
            current_mirror: String::new(),
        };

        let tester = MirrorTester::from_config(&self.config)?;
        let mirrors = self.mirrors.clone();

        // Create progress callback
        let progress_callback = {
            let total = mirrors.len();
            Arc::new(move |completed: usize, _: usize, mirror: &str| {
                debug!("Test progress: {}/{} - {}", completed, total, mirror);
            })
        };

        let results = tester.test_all(mirrors, Some(progress_callback)).await;

        // Save results to database
        for result in &results {
            if let Err(e) = self.database.save_test_result(result) {
                debug!("Failed to save test result: {}", e);
            }
        }

        self.test_results = results;
        self.testing_state = TestingState::Completed;

        // Refresh mirrors from database to get updated stats
        self.refresh_mirrors()?;

        self.status_message = Some(format!(
            "Testing completed: {} mirrors tested",
            self.test_results.len()
        ));

        info!("Mirror tests completed");
        Ok(())
    }

    /// Run mirror update operation
    pub async fn run_update(&mut self, dry_run: bool) -> Result<()> {
        info!("Starting mirror update (dry_run: {})", dry_run);

        if dry_run {
            self.status_message = Some("Dry run: Would update mirrors".to_string());
            return Ok(());
        }

        // This would trigger actual mirror updates via the updater
        self.status_message = Some("Update triggered".to_string());

        Ok(())
    }

    /// Add a static mirror
    pub async fn add_static_mirror(&mut self, url: String) -> Result<()> {
        info!("Adding static mirror: {}", url);

        let parsed_url = url::Url::parse(&url)
            .map_err(|e| anyhow::anyhow!("Invalid URL: {}", e))?;

        let mirror = Mirror::new_static(parsed_url);

        self.database.save_mirror(&mirror)?;

        // Refresh static mirrors list
        self.static_mirrors = self.database.get_mirrors(&crate::storage::MirrorFilter {
            static_only: true,
            ..Default::default()
        })?;

        self.status_message = Some(format!("Added static mirror: {}", url));

        info!("Static mirror added successfully");
        Ok(())
    }

    /// Remove selected static mirror
    pub async fn remove_static_mirror(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_mirror {
            if let Some(mirror) = self.static_mirrors.get(idx) {
                info!("Removing static mirror: {}", mirror.url);
                // In a real implementation, we'd delete from database
                // For now, just refresh the list
                self.status_message = Some(format!("Removed static mirror: {}", mirror.url));
            }
        }
        Ok(())
    }

    /// Refresh mirrors from database
    pub fn refresh_mirrors(&mut self) -> Result<()> {
        debug!("Refreshing mirrors from database");
        self.mirrors = self.database.get_mirrors(&Default::default())?;
        self.test_results = self.database.get_test_results(&Default::default())?;
        self.history = self.database.get_history(50)?;
        Ok(())
    }

    /// Reload configuration
    pub fn reload_config(&mut self) -> Result<()> {
        debug!("Reloading configuration");
        self.config = Config::load()?;
        self.status_message = Some("Configuration reloaded".to_string());
        Ok(())
    }

    /// Save current configuration
    pub fn save_config(&mut self) -> Result<()> {
        debug!("Saving configuration");
        self.config.save()?;
        self.status_message = Some("Configuration saved".to_string());
        Ok(())
    }

    /// Handle input character (for text input modes)
    pub fn handle_input_char(&mut self, c: char) {
        if self.input_mode {
            self.input_buffer.push(c);
        }
    }

    /// Handle backspace in input mode
    pub fn handle_input_backspace(&mut self) {
        if self.input_mode {
            self.input_buffer.pop();
        }
    }

    /// Submit input buffer
    pub fn submit_input(&mut self) {
        if !self.input_buffer.is_empty() {
            match self.current_view {
                View::StaticMirrors => {
                    // Will be handled by async runtime
                    self.input_mode = false;
                }
                _ => {}
            }
        }
    }

    /// Cancel input mode
    pub fn cancel_input(&mut self) {
        self.input_mode = false;
        self.input_buffer.clear();
    }

    /// Enter input mode
    pub fn enter_input_mode(&mut self) {
        self.input_mode = true;
        self.input_buffer.clear();
    }

    /// Clear status and error messages
    pub fn clear_messages(&mut self) {
        self.status_message = None;
        self.error_message = None;
    }

    /// Set error message
    pub fn set_error(&mut self, msg: String) {
        self.error_message = Some(msg);
    }

    /// Set status message
    pub fn set_status(&mut self, msg: String) {
        self.status_message = Some(msg);
    }

    /// Increment selected config item
    pub fn next_config_item(&mut self) {
        self.selected_config_item = (self.selected_config_item + 1) % 15;
    }

    /// Decrement selected config item
    pub fn previous_config_item(&mut self) {
        if self.selected_config_item == 0 {
            self.selected_config_item = 14;
        } else {
            self.selected_config_item -= 1;
        }
    }

    /// Quit the application
    pub fn quit(&mut self) {
        info!("Quitting TUI application");
        self.should_quit = true;
    }
}