termscp 1.0.0

termscp is a feature rich terminal file transfer and explorer with support for SCP/SFTP/FTP/Kube/S3/WebDAV
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
//! ## AuthActivity
//!
//! `auth_activity` is the module which implements the authentication activity

// Sub modules
mod bookmarks;
mod components;
mod misc;
mod update;
mod view;

// locals
// Includes
use std::time::Duration;

use tuirealm::application::{Application, PollStrategy};
use tuirealm::event::NoUserEvent;
use tuirealm::listener::EventListenerCfg;
use tuirealm::terminal::TerminalAdapter;

use super::{Activity, CROSSTERM_MAX_POLL, Context, ExitReason};
use crate::config::themes::Theme;
use crate::filetransfer::{FileTransferParams, FileTransferProtocol};
use crate::system::bookmarks_client::BookmarksClient;
use crate::system::config_client::ConfigClient;

// host bridge protocol radio
const HOST_BRIDGE_RADIO_PROTOCOL_LOCALHOST: usize = 0;
const HOST_BRIDGE_RADIO_PROTOCOL_SFTP: usize = 1;
const HOST_BRIDGE_RADIO_PROTOCOL_SCP: usize = 2;
const HOST_BRIDGE_RADIO_PROTOCOL_FTP: usize = 3;
const HOST_BRIDGE_RADIO_PROTOCOL_FTPS: usize = 4;
const HOST_BRIDGE_RADIO_PROTOCOL_S3: usize = 5;
const HOST_BRIDGE_RADIO_PROTOCOL_KUBE: usize = 6;
const HOST_BRIDGE_RADIO_PROTOCOL_WEBDAV: usize = 7;
const HOST_BRIDGE_RADIO_PROTOCOL_SMB: usize = 8; // Keep as last

// remote protocol radio
const REMOTE_RADIO_PROTOCOL_SFTP: usize = 0;
const REMOTE_RADIO_PROTOCOL_SCP: usize = 1;
const REMOTE_RADIO_PROTOCOL_FTP: usize = 2;
const REMOTE_RADIO_PROTOCOL_FTPS: usize = 3;
const REMOTE_RADIO_PROTOCOL_S3: usize = 4;
const REMOTE_RADIO_PROTOCOL_KUBE: usize = 5;
const REMOTE_RADIO_PROTOCOL_WEBDAV: usize = 6;
const REMOTE_RADIO_PROTOCOL_SMB: usize = 7; // Keep as last

// -- components
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum Id {
    BookmarkName,
    BookmarkSavePassword,
    BookmarksList,
    DeleteBookmarkPopup,
    DeleteRecentPopup,
    ErrorPopup,
    GlobalListener,
    HelpFooter,
    HostBridge(AuthFormId),
    InfoPopup,
    InstallUpdatePopup,
    Keybindings,
    NewVersionChangelog,
    NewVersionDisclaimer,
    QuitPopup,
    RecentsList,
    Remote(AuthFormId),
    Subtitle,
    Title,
    WaitPopup,
    WindowSizeError,
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
pub enum AuthFormId {
    Address,
    KubeNamespace,
    KubeClusterUrl,
    KubeUsername,
    KubeClientCert,
    KubeClientKey,
    LocalDirectory,
    Password,
    Port,
    Protocol,
    RemoteDirectory,
    S3AccessKey,
    S3Bucket,
    S3Endpoint,
    S3NewPathStyle,
    S3Profile,
    S3Region,
    S3SecretAccessKey,
    S3SecurityToken,
    S3SessionToken,
    SmbShare,
    #[cfg(posix)]
    SmbWorkgroup,
    Username,
    WebDAVUri,
}

#[derive(Debug, Eq, PartialEq)]
enum Msg {
    Form(FormMsg),
    Ui(UiMsg),
    None,
}

#[derive(Debug, PartialEq, Eq)]
enum FormMsg {
    Connect,
    DeleteBookmark,
    DeleteRecent,
    EnterSetup,
    InstallUpdate,
    LoadBookmark(usize),
    LoadRecent(usize),
    HostBridgeProtocolChanged(HostBridgeProtocol),
    RemoteProtocolChanged(FileTransferProtocol),
    Quit,
    SaveBookmark(FormTab),
}

#[derive(Debug, PartialEq, Eq)]
pub enum UiMsg {
    BookmarksListBlur,
    BookmarksTabBlur,
    CloseDeleteBookmark,
    CloseDeleteRecent,
    CloseErrorPopup,
    CloseInfoPopup,
    CloseInstallUpdatePopup,
    CloseKeybindingsPopup,
    CloseQuitPopup,
    CloseSaveBookmark,
    HostBridge(UiAuthFormMsg),
    RececentsListBlur,
    Remote(UiAuthFormMsg),
    BookmarkNameBlur,
    SaveBookmarkPasswordBlur,
    ShowDeleteBookmarkPopup,
    ShowDeleteRecentPopup,
    ShowKeybindingsPopup,
    ShowQuitPopup,
    ShowReleaseNotes,
    ShowSaveBookmarkPopup,
    WindowResized,
}

#[derive(Debug, PartialEq, Eq)]
pub enum UiAuthFormMsg {
    AddressBlurDown,
    AddressBlurUp,
    ChangeFormTab,
    KubeNamespaceBlurDown,
    KubeNamespaceBlurUp,
    KubeClusterUrlBlurDown,
    KubeClusterUrlBlurUp,
    KubeUsernameBlurDown,
    KubeUsernameBlurUp,
    KubeClientCertBlurDown,
    KubeClientCertBlurUp,
    KubeClientKeyBlurDown,
    KubeClientKeyBlurUp,
    LocalDirectoryBlurDown,
    LocalDirectoryBlurUp,
    ParamsFormBlur,
    PasswordBlurDown,
    PasswordBlurUp,
    PortBlurDown,
    PortBlurUp,
    ProtocolBlurDown,
    ProtocolBlurUp,
    RemoteDirectoryBlurDown,
    RemoteDirectoryBlurUp,
    S3AccessKeyBlurDown,
    S3AccessKeyBlurUp,
    S3BucketBlurDown,
    S3BucketBlurUp,
    S3EndpointBlurDown,
    S3EndpointBlurUp,
    S3NewPathStyleBlurDown,
    S3NewPathStyleBlurUp,
    S3ProfileBlurDown,
    S3ProfileBlurUp,
    S3RegionBlurDown,
    S3RegionBlurUp,
    S3SecretAccessKeyBlurDown,
    S3SecretAccessKeyBlurUp,
    S3SecurityTokenBlurDown,
    S3SecurityTokenBlurUp,
    S3SessionTokenBlurDown,
    S3SessionTokenBlurUp,
    SmbShareBlurDown,
    SmbShareBlurUp,
    #[cfg(posix)]
    SmbWorkgroupDown,
    #[cfg(posix)]
    SmbWorkgroupUp,
    UsernameBlurDown,
    UsernameBlurUp,
    WebDAVUriBlurDown,
    WebDAVUriBlurUp,
}

/// Auth form input mask
#[derive(Eq, PartialEq)]
enum InputMask {
    Generic,
    AwsS3,
    Kube,
    Localhost,
    Smb,
    WebDAV,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum HostBridgeProtocol {
    Localhost,
    Remote(FileTransferProtocol),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FormTab {
    HostBridge,
    Remote,
}

// Store keys
const STORE_KEY_LATEST_VERSION: &str = "AUTH_LATEST_VERSION";
const STORE_KEY_RELEASE_NOTES: &str = "AUTH_RELEASE_NOTES";

/// AuthActivity is the data holder for the authentication activity
pub struct AuthActivity {
    app: Application<Id, Msg, NoUserEvent>,
    /// List of bookmarks
    bookmarks_list: Vec<String>,
    /// List of recent hosts
    recents_list: Vec<String>,
    /// Exit reason
    exit_reason: Option<ExitReason>,
    /// Should redraw ui
    redraw: bool,
    /// Host bridge protocol
    host_bridge_protocol: HostBridgeProtocol,
    last_form_tab: FormTab,
    /// Remote file transfer protocol
    remote_protocol: FileTransferProtocol,
    context: Option<Context>,
}

impl AuthActivity {
    /// Instantiates a new AuthActivity
    pub fn new(ticks: Duration) -> AuthActivity {
        AuthActivity {
            app: Application::init(
                EventListenerCfg::default().crossterm_input_listener(ticks, CROSSTERM_MAX_POLL),
            ),
            context: None,
            bookmarks_list: Vec::new(),
            exit_reason: None,
            last_form_tab: FormTab::Remote,
            recents_list: Vec::new(),
            redraw: true,
            host_bridge_protocol: HostBridgeProtocol::Localhost,
            remote_protocol: FileTransferProtocol::Sftp,
        }
    }

    /// Returns a reference to context
    fn context(&self) -> &Context {
        self.context.as_ref().unwrap()
    }

    /// Returns a mutable reference to context
    fn context_mut(&mut self) -> &mut Context {
        self.context.as_mut().unwrap()
    }

    /// Returns config client reference
    fn config(&self) -> &ConfigClient {
        self.context().config()
    }

    fn bookmarks_client(&self) -> Option<&BookmarksClient> {
        self.context().bookmarks_client()
    }

    fn bookmarks_client_mut(&mut self) -> Option<&mut BookmarksClient> {
        self.context_mut().bookmarks_client_mut()
    }

    /// Returns a reference to theme
    fn theme(&self) -> &Theme {
        self.context().theme_provider().theme()
    }

    /// Get current input mask to show
    fn remote_input_mask(&self) -> InputMask {
        Self::file_transfer_protocol_input_mask(self.remote_protocol)
    }

    /// Get current input mask to show
    fn host_bridge_input_mask(&self) -> InputMask {
        match self.host_bridge_protocol {
            HostBridgeProtocol::Localhost => InputMask::Localhost,
            HostBridgeProtocol::Remote(protocol) => {
                Self::file_transfer_protocol_input_mask(protocol)
            }
        }
    }

    /// Get input mask for protocol
    fn file_transfer_protocol_input_mask(protocol: FileTransferProtocol) -> InputMask {
        match protocol {
            FileTransferProtocol::AwsS3 => InputMask::AwsS3,
            FileTransferProtocol::Ftp(_)
            | FileTransferProtocol::Scp
            | FileTransferProtocol::Sftp => InputMask::Generic,
            FileTransferProtocol::Kube => InputMask::Kube,
            FileTransferProtocol::Smb => InputMask::Smb,
            FileTransferProtocol::WebDAV => InputMask::WebDAV,
        }
    }
}

impl Activity for AuthActivity {
    /// `on_create` is the function which must be called to initialize the activity.
    /// `on_create` must initialize all the data structures used by the activity
    /// Context is taken from activity manager and will be released only when activity is destroyed
    fn on_create(&mut self, mut context: Context) {
        debug!("Initializing activity");
        // Initialize file transfer params
        context.set_remote_params(FileTransferParams::default());
        // Set context
        self.context = Some(context);
        // Clear terminal
        if let Err(err) = self.context_mut().terminal().clear_screen() {
            error!("Failed to clear screen: {}", err);
        }
        // Put raw mode on enabled
        if let Err(err) = self.context_mut().terminal().enable_raw_mode() {
            error!("Failed to enter raw mode: {}", err);
        }
        // If check for updates is enabled, check for updates
        self.check_for_updates();
        // Initialize view
        self.init();
        // Init bookmarks client
        if self.bookmarks_client().is_some() {
            self.init_bookmarks_client();
            self.view_bookmarks();
            self.view_recent_connections();
        }
        // Verify error state from context
        if let Some(err) = self.context_mut().error() {
            self.mount_error(err.as_str());
        }
        info!("Activity initialized");
    }

    /// `on_draw` is the function which draws the graphical interface.
    /// This function must be called at each tick to refresh the interface
    fn on_draw(&mut self) {
        // Context must be something
        if self.context.is_none() {
            return;
        }
        // Tick
        match self
            .app
            .tick(PollStrategy::UpTo(3, std::time::Duration::from_millis(10)))
        {
            Ok(messages) => {
                for msg in messages.into_iter() {
                    let mut msg = Some(msg);
                    while msg.is_some() {
                        msg = self.update(msg);
                    }
                }
            }
            Err(err) => {
                self.mount_error(format!("Application error: {err}"));
            }
        }
        // View
        if self.redraw {
            self.view();
        }
    }

    /// `will_umount` is the method which must be able to report to the activity manager, whether
    /// the activity should be terminated or not.
    /// If not, the call will return `None`, otherwise return`Some(ExitReason)`
    fn will_umount(&self) -> Option<&ExitReason> {
        self.exit_reason.as_ref()
    }

    /// `on_destroy` is the function which cleans up runtime variables and data before terminating the activity.
    /// This function must be called once before terminating the activity.
    /// This function finally releases the context
    fn on_destroy(&mut self) -> Option<Context> {
        // Disable raw mode
        if let Err(err) = self.context_mut().terminal().disable_raw_mode() {
            error!("Failed to disable raw mode: {}", err);
        }
        if let Err(err) = self.context_mut().terminal().clear_screen() {
            error!("Failed to clear screen: {}", err);
        }
        self.context.take()
    }
}