Compare commits
8 Commits
6a79fb2c54
...
v1.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4ca9e7542 | ||
|
|
17bf4d546a | ||
|
|
fdc9219742 | ||
|
|
a9aa0ad736 | ||
|
|
a83987af19 | ||
|
|
3d6fd77d85 | ||
|
|
b438cbd6b4 | ||
|
|
25ccff3a37 |
131
Cargo.lock
generated
131
Cargo.lock
generated
@@ -50,6 +50,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.5.3"
|
||||
@@ -149,6 +155,12 @@ dependencies = [
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.10.0"
|
||||
@@ -214,6 +226,33 @@ dependencies = [
|
||||
"phf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.23.0"
|
||||
@@ -254,6 +293,16 @@ version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5729f5117e208430e437df2f4843f5e5952997175992d1414f94c57d61e270b4"
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
@@ -336,6 +385,31 @@ dependencies = [
|
||||
"litrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"rand_core 0.6.4",
|
||||
"serde",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
@@ -377,6 +451,12 @@ dependencies = [
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "filedescriptor"
|
||||
version = "0.8.3"
|
||||
@@ -1123,13 +1203,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ostiary"
|
||||
version = "1.0.10"
|
||||
version = "1.1.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
"crossterm",
|
||||
"dirs",
|
||||
"ed25519-dalek",
|
||||
"futures",
|
||||
"libc",
|
||||
"rand 0.8.5",
|
||||
"ratatui",
|
||||
"reqwest",
|
||||
"serde",
|
||||
@@ -1277,6 +1360,16 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "portable-atomic"
|
||||
version = "1.13.1"
|
||||
@@ -1408,6 +1501,8 @@ version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha 0.3.1",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
@@ -1417,10 +1512,20 @@ version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_chacha 0.9.0",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
@@ -1436,6 +1541,9 @@ name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
@@ -1845,6 +1953,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "siphasher"
|
||||
version = "1.0.2"
|
||||
@@ -1873,6 +1990,16 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ostiary"
|
||||
version = "1.0.10"
|
||||
version = "1.1.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -18,3 +18,6 @@ tokio-util = "0.7"
|
||||
toml = "0.8"
|
||||
serde_path_to_error = "0.1"
|
||||
libc = "0.2"
|
||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||
rand = "0.8"
|
||||
base64 = "0.22"
|
||||
|
||||
18
install.sh
18
install.sh
@@ -84,34 +84,28 @@ ok "Installed → $INSTALL_DIR/$BINARY"
|
||||
|
||||
# ── Add ~/.local/bin to PATH if missing ──────────────────────────────────────
|
||||
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
|
||||
warn "$INSTALL_DIR is not in PATH — adding it now..."
|
||||
export PATH="$INSTALL_DIR:$PATH"
|
||||
|
||||
EXPORT_LINE="export PATH=\"\$HOME/.local/bin:\$PATH\""
|
||||
|
||||
# Determine which profile file to update
|
||||
if [ -f "$HOME/.bashrc" ]; then
|
||||
if [ -f "$HOME/.zshrc" ]; then
|
||||
PROFILE="$HOME/.zshrc"
|
||||
elif [ -f "$HOME/.bashrc" ]; then
|
||||
PROFILE="$HOME/.bashrc"
|
||||
elif [ -f "$HOME/.bash_profile" ]; then
|
||||
PROFILE="$HOME/.bash_profile"
|
||||
elif [ -f "$HOME/.profile" ]; then
|
||||
PROFILE="$HOME/.profile"
|
||||
else
|
||||
# Create .bashrc if nothing exists
|
||||
PROFILE="$HOME/.bashrc"
|
||||
fi
|
||||
|
||||
# Avoid duplicate entries
|
||||
if ! grep -qF "$INSTALL_DIR" "$PROFILE" 2>/dev/null; then
|
||||
printf '\n# Added by ostiary installer\n%s\n' "$EXPORT_LINE" >> "$PROFILE"
|
||||
ok "Added PATH entry to $PROFILE"
|
||||
fi
|
||||
|
||||
warn "Run the following to use ostiary in this session:"
|
||||
warn " export PATH=\"\$HOME/.local/bin:\$PATH\""
|
||||
warn "New shells will pick it up automatically."
|
||||
else
|
||||
ok "$INSTALL_DIR is already in PATH"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
ok "Done! Run: $BINARY"
|
||||
ok "Launching ${BINARY}..."
|
||||
exec "$INSTALL_DIR/$BINARY"
|
||||
|
||||
653
src/app.rs
653
src/app.rs
@@ -1,11 +1,11 @@
|
||||
// src/app.rs
|
||||
use crate::config::Config;
|
||||
use crate::error::Result;
|
||||
use crate::executor;
|
||||
use crate::menu::{Action, InteractionMode, MenuItem, MenuItemKind, MenuRoot};
|
||||
use crate::network;
|
||||
use crate::text_input::TextInput;
|
||||
use crate::updater;
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEventKind};
|
||||
use crossterm::event::{Event as CrosstermEvent, KeyCode, KeyEventKind, KeyModifiers};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -22,10 +22,10 @@ pub enum Event {
|
||||
/// Carries the exe path captured before the binary was replaced.
|
||||
UpdateDone(std::path::PathBuf),
|
||||
UpdateError(String),
|
||||
AccessRequested(crate::error::Result<String>),
|
||||
}
|
||||
|
||||
/// A pending request to hand the terminal to an external interactive process.
|
||||
/// Set by the structured-protocol handler; consumed by the main event loop.
|
||||
pub struct PendingExec {
|
||||
pub shell: String,
|
||||
pub reply_tx: tokio::sync::mpsc::UnboundedSender<String>,
|
||||
@@ -37,11 +37,10 @@ pub struct App {
|
||||
pub error: Option<String>,
|
||||
pub breadcrumbs: Vec<usize>,
|
||||
pub selected_index: usize,
|
||||
pub menu_scroll_offset: usize,
|
||||
pub popup: Option<Popup>,
|
||||
pub event_tx: UnboundedSender<Event>,
|
||||
/// When set, main loop suspends ratatui, runs the command, then restores.
|
||||
pub pending_exec: Option<PendingExec>,
|
||||
/// Exe path to exec after update; captured before the binary was replaced.
|
||||
pub pending_restart: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
@@ -54,26 +53,38 @@ pub enum Popup {
|
||||
ExecutingBashTerminal { child: tokio::process::Child },
|
||||
ExecutingStructured {
|
||||
reply_tx: tokio::sync::mpsc::UnboundedSender<String>,
|
||||
/// Fires SIGTERM to the script's process group on Esc.
|
||||
kill_tx: Option<tokio::sync::oneshot::Sender<()>>,
|
||||
log_buffer: Vec<String>,
|
||||
current_command: Option<executor::StructuredCommand>,
|
||||
input_buffer: String,
|
||||
/// Cursor position for Menu-type commands.
|
||||
input: TextInput,
|
||||
menu_selected_index: usize,
|
||||
/// Cursor position for Form-type commands.
|
||||
form_cursor: usize,
|
||||
/// Checked/selected state for each Form field (parallel to fields vec).
|
||||
form_values: Vec<bool>,
|
||||
/// Index of the first visible line in log_buffer (0 = top of output).
|
||||
log_scroll_pos: usize,
|
||||
/// When true, keep position pinned to the bottom as new output arrives.
|
||||
log_scroll_x: usize,
|
||||
log_follow_bottom: bool,
|
||||
/// Set when the process has exited; popup stays open until Esc.
|
||||
finished: Option<i32>,
|
||||
},
|
||||
EndpointSelector {
|
||||
selected: usize,
|
||||
scroll_offset: usize,
|
||||
},
|
||||
/// Unified add/edit popup. `edit_index = None` → adding new endpoint.
|
||||
UpsertEndpoint {
|
||||
edit_index: Option<usize>,
|
||||
/// [0] = name, [1] = url
|
||||
fields: [TextInput; 2],
|
||||
active_field: usize,
|
||||
error: Option<String>,
|
||||
return_selected: usize,
|
||||
},
|
||||
ConfirmDeleteEndpoint {
|
||||
index: usize,
|
||||
return_selected: usize,
|
||||
},
|
||||
AccessDenied { endpoint_url: String },
|
||||
Downloading { progress: f32, message: String },
|
||||
Message { text: String, level: MessageLevel },
|
||||
Message { text: String, level: MessageLevel, on_dismiss: MessageAction },
|
||||
UpdateConfirm {
|
||||
info: updater::UpdateInfo,
|
||||
},
|
||||
@@ -99,6 +110,12 @@ pub enum MessageLevel {
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum MessageAction {
|
||||
Stay,
|
||||
Exit,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(config: Config, event_tx: UnboundedSender<Event>) -> Self {
|
||||
Self {
|
||||
@@ -107,6 +124,7 @@ impl App {
|
||||
error: None,
|
||||
breadcrumbs: Vec::new(),
|
||||
selected_index: 0,
|
||||
menu_scroll_offset: 0,
|
||||
popup: None,
|
||||
event_tx,
|
||||
pending_exec: None,
|
||||
@@ -130,12 +148,15 @@ impl App {
|
||||
}
|
||||
|
||||
pub async fn load_menu(&mut self) {
|
||||
let server_url = self.config.server_url.clone();
|
||||
let server_url = self.config.active_url().to_string();
|
||||
let timeout = self.config.timeout_sec;
|
||||
let tx = self.event_tx.clone();
|
||||
let identity_b64 = self.config.active_identity().map(|id| id.to_b64());
|
||||
|
||||
tokio::spawn(async move {
|
||||
let result = network::fetch_menu(&server_url, timeout).await;
|
||||
let identity = identity_b64.as_deref()
|
||||
.and_then(|k| crate::identity::Identity::from_b64(k).ok());
|
||||
let result = network::fetch_menu(&server_url, timeout, identity.as_ref()).await;
|
||||
let _ = tx.send(Event::MenuLoaded(result));
|
||||
});
|
||||
}
|
||||
@@ -172,6 +193,12 @@ impl App {
|
||||
self.error = None;
|
||||
Ok(false)
|
||||
}
|
||||
Event::MenuLoaded(Err(crate::error::AppError::AccessDenied)) => {
|
||||
self.popup = Some(Popup::AccessDenied {
|
||||
endpoint_url: self.config.active_endpoint.clone(),
|
||||
});
|
||||
Ok(false)
|
||||
}
|
||||
Event::MenuLoaded(Err(e)) => {
|
||||
self.error = Some(format!("Ошибка загрузки меню: {}", e));
|
||||
Ok(false)
|
||||
@@ -185,9 +212,6 @@ impl App {
|
||||
Ok(false)
|
||||
}
|
||||
Event::StructuredCommand(cmd) => {
|
||||
// Exec hands the terminal to an external process — clone reply_tx,
|
||||
// store as pending_exec, and skip setting current_command so the
|
||||
// main loop can suspend ratatui immediately.
|
||||
if let executor::StructuredCommand::Exec { shell } = &cmd {
|
||||
if let Some(Popup::ExecutingStructured { reply_tx, .. }) = &self.popup {
|
||||
self.pending_exec = Some(PendingExec {
|
||||
@@ -221,30 +245,30 @@ impl App {
|
||||
Ok(false)
|
||||
}
|
||||
Event::StructuredOutput(line) => {
|
||||
if let Some(Popup::ExecutingStructured {
|
||||
log_buffer,
|
||||
log_follow_bottom,
|
||||
log_scroll_pos,
|
||||
..
|
||||
}) = &mut self.popup
|
||||
{
|
||||
if let Some(Popup::ExecutingStructured { log_buffer, .. }) = &mut self.popup {
|
||||
log_buffer.push(line);
|
||||
// log_follow_bottom: render will pin pos to bottom.
|
||||
// Otherwise pos stays fixed → new line appears off-screen.
|
||||
let _ = (log_follow_bottom, log_scroll_pos); // used by render
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
Event::StructuredFinished(exit_code) => {
|
||||
if let Some(Popup::ExecutingStructured { finished, .. }) = &mut self.popup {
|
||||
if let Some(Popup::ExecutingStructured {
|
||||
finished,
|
||||
current_command,
|
||||
..
|
||||
}) = &mut self.popup
|
||||
{
|
||||
*finished = Some(exit_code);
|
||||
if matches!(
|
||||
current_command,
|
||||
Some(executor::StructuredCommand::Progress { .. })
|
||||
| Some(executor::StructuredCommand::Message { .. })
|
||||
) {
|
||||
*current_command = None;
|
||||
}
|
||||
}
|
||||
// If popup was already closed (user pressed Esc to kill the
|
||||
// script), we silently discard the exit event.
|
||||
Ok(false)
|
||||
}
|
||||
Event::UpdateAvailable(info) => {
|
||||
// Only show if no popup is currently open (don't interrupt running scripts)
|
||||
if self.popup.is_none() {
|
||||
self.popup = Some(Popup::UpdateConfirm { info });
|
||||
}
|
||||
@@ -269,6 +293,27 @@ impl App {
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
Event::AccessRequested(Ok(msg)) => {
|
||||
let on_dismiss = if self.config.endpoints.len() == 1 && self.menu.is_none() {
|
||||
MessageAction::Exit
|
||||
} else {
|
||||
MessageAction::Stay
|
||||
};
|
||||
self.popup = Some(Popup::Message {
|
||||
text: msg,
|
||||
level: MessageLevel::Info,
|
||||
on_dismiss,
|
||||
});
|
||||
Ok(false)
|
||||
}
|
||||
Event::AccessRequested(Err(e)) => {
|
||||
self.popup = Some(Popup::Message {
|
||||
text: format!("Не удалось отправить запрос: {}", e),
|
||||
level: MessageLevel::Error,
|
||||
on_dismiss: MessageAction::Stay,
|
||||
});
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,15 +340,16 @@ impl App {
|
||||
Popup::ExecutingStructured {
|
||||
reply_tx,
|
||||
kill_tx,
|
||||
input_buffer,
|
||||
input,
|
||||
current_command,
|
||||
menu_selected_index,
|
||||
form_cursor,
|
||||
form_values,
|
||||
log_scroll_pos,
|
||||
log_scroll_x,
|
||||
log_follow_bottom,
|
||||
log_buffer,
|
||||
finished,
|
||||
finished: _,
|
||||
} => {
|
||||
let is_menu = matches!(
|
||||
current_command,
|
||||
@@ -317,50 +363,47 @@ impl App {
|
||||
current_command,
|
||||
Some(executor::StructuredCommand::Form { .. })
|
||||
);
|
||||
let has_command = current_command.is_some();
|
||||
// Vim motions are disabled only when free text input is active.
|
||||
let blocks_scroll = matches!(
|
||||
current_command,
|
||||
Some(executor::StructuredCommand::Input { .. })
|
||||
| Some(executor::StructuredCommand::Menu { .. })
|
||||
| Some(executor::StructuredCommand::Confirm { .. })
|
||||
| Some(executor::StructuredCommand::Form { .. })
|
||||
);
|
||||
let is_text_input = matches!(
|
||||
current_command,
|
||||
Some(executor::StructuredCommand::Input { .. })
|
||||
);
|
||||
let alt = key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SUPER);
|
||||
|
||||
match key.code {
|
||||
// ── Log scrolling (PageUp / PageDown always work) ─
|
||||
// ── Log scrolling ────────────────────────────────
|
||||
KeyCode::PageUp => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_sub(10);
|
||||
*log_follow_bottom = false;
|
||||
}
|
||||
KeyCode::PageDown => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(10);
|
||||
// Render will clamp to max; if we're at the
|
||||
// bottom, mark as following.
|
||||
*log_follow_bottom =
|
||||
*log_scroll_pos + 1 >= log_buffer.len();
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
|
||||
// ── Form: navigation and toggle ──────────────────
|
||||
// ── Form navigation ──────────────────────────────
|
||||
KeyCode::Up if is_form => {
|
||||
if *form_cursor > 0 { *form_cursor -= 1; }
|
||||
}
|
||||
KeyCode::Down if is_form => {
|
||||
let len = if let Some(
|
||||
executor::StructuredCommand::Form { fields, .. }
|
||||
) = current_command { fields.len() } else { 0 };
|
||||
let len = if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command {
|
||||
fields.len()
|
||||
} else { 0 };
|
||||
if *form_cursor + 1 < len { *form_cursor += 1; }
|
||||
}
|
||||
KeyCode::Char(' ') if is_form => {
|
||||
let cursor = *form_cursor;
|
||||
// Collect toggle info before mutating form_values
|
||||
let toggle = if let Some(
|
||||
executor::StructuredCommand::Form { fields, .. }
|
||||
) = current_command {
|
||||
let toggle = if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command {
|
||||
fields.get(cursor).map(|f| {
|
||||
let group_indices: Vec<usize> = fields.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, ff)| {
|
||||
ff.group.is_some()
|
||||
&& ff.group == f.group
|
||||
})
|
||||
.filter(|(_, ff)| ff.group.is_some() && ff.group == f.group)
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
(f.field_type.clone(), group_indices)
|
||||
@@ -385,73 +428,67 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Arrow keys ────────────────────────────────────
|
||||
// ── Arrow / cursor keys ──────────────────────────
|
||||
KeyCode::Up if is_menu => {
|
||||
if *menu_selected_index > 0 {
|
||||
*menu_selected_index -= 1;
|
||||
}
|
||||
if *menu_selected_index > 0 { *menu_selected_index -= 1; }
|
||||
}
|
||||
KeyCode::Down if is_menu => {
|
||||
if let Some(executor::StructuredCommand::Menu {
|
||||
options, ..
|
||||
}) = current_command
|
||||
{
|
||||
if let Some(executor::StructuredCommand::Menu { options, .. }) = current_command {
|
||||
if *menu_selected_index + 1 < options.len() {
|
||||
*menu_selected_index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Scroll log one line when no interactive command pending
|
||||
KeyCode::Up if !has_command => {
|
||||
KeyCode::Up if !blocks_scroll => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
|
||||
*log_follow_bottom = false;
|
||||
}
|
||||
KeyCode::Down if !has_command => {
|
||||
KeyCode::Down if !blocks_scroll => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(1);
|
||||
*log_follow_bottom =
|
||||
*log_scroll_pos + 1 >= log_buffer.len();
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
KeyCode::Left if is_text_input && alt => { input.word_back(); }
|
||||
KeyCode::Right if is_text_input && alt => { input.word_fwd(); }
|
||||
KeyCode::Left if is_text_input => { input.move_left(); }
|
||||
KeyCode::Right if is_text_input => { input.move_right(); }
|
||||
KeyCode::Left if !is_text_input && !is_menu && !is_form => {
|
||||
*log_scroll_x = log_scroll_x.saturating_sub(4);
|
||||
}
|
||||
KeyCode::Right if !is_text_input && !is_menu && !is_form => {
|
||||
*log_scroll_x = log_scroll_x.saturating_add(4);
|
||||
}
|
||||
|
||||
// ── Confirm shortcuts (immediate, no Enter needed) ─
|
||||
// ── Confirm shortcuts ────────────────────────────
|
||||
KeyCode::Char('y') | KeyCode::Char('Y') if is_confirm => {
|
||||
let _ = current_command.take();
|
||||
let _ = reply_tx.send("y".to_string());
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') if is_confirm => {
|
||||
let _ = current_command.take();
|
||||
let _ = reply_tx.send("n".to_string());
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
}
|
||||
|
||||
// ── Text input ────────────────────────────────────
|
||||
// Excluded: vim motions (j/k/l/h) and form mode.
|
||||
// ── Text input ───────────────────────────────────
|
||||
KeyCode::Char('b') if is_text_input && alt => { input.word_back(); }
|
||||
KeyCode::Char('f') if is_text_input && alt => { input.word_fwd(); }
|
||||
KeyCode::Char(c)
|
||||
if !is_menu
|
||||
&& !is_confirm
|
||||
&& !is_form
|
||||
&& (is_text_input
|
||||
|| !matches!(c, 'j' | 'k' | 'l' | 'h')) =>
|
||||
if !is_menu && !is_confirm && !is_form
|
||||
&& (is_text_input || !matches!(c, 'j' | 'k' | 'l' | 'h' | 'd' | 'u')) =>
|
||||
{
|
||||
input_buffer.push(c);
|
||||
}
|
||||
KeyCode::Backspace if !is_menu && !is_form => {
|
||||
input_buffer.pop();
|
||||
input.insert(c);
|
||||
}
|
||||
KeyCode::Backspace if is_text_input && alt => { input.word_delete_back(); }
|
||||
KeyCode::Backspace if !is_menu && !is_form => { input.backspace(); }
|
||||
|
||||
// ── Enter: commit response ────────────────────────
|
||||
// ── Enter ────────────────────────────────────────
|
||||
KeyCode::Enter => {
|
||||
// Form submit: collect checked IDs
|
||||
if is_form {
|
||||
if let Some(executor::StructuredCommand::Form {
|
||||
fields, ..
|
||||
}) = current_command.take() {
|
||||
if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command.take() {
|
||||
let response = fields.iter().enumerate()
|
||||
.filter_map(|(i, f)| {
|
||||
form_values.get(i)
|
||||
.copied()
|
||||
.filter(|&v| v)
|
||||
.map(|_| f.id.as_str())
|
||||
form_values.get(i).copied().filter(|&v| v).map(|_| f.id.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
@@ -461,26 +498,17 @@ impl App {
|
||||
}
|
||||
} else if let Some(cmd) = current_command.take() {
|
||||
let response = match &cmd {
|
||||
executor::StructuredCommand::Input { .. } => {
|
||||
input_buffer.clone()
|
||||
}
|
||||
executor::StructuredCommand::Input { .. } => input.buf.clone(),
|
||||
executor::StructuredCommand::Confirm { .. } => {
|
||||
if input_buffer.to_lowercase().starts_with('y') {
|
||||
"y".to_string()
|
||||
} else {
|
||||
"n".to_string()
|
||||
}
|
||||
if input.buf.to_lowercase().starts_with('y') { "y".to_string() } else { "n".to_string() }
|
||||
}
|
||||
executor::StructuredCommand::Menu { options, .. } => {
|
||||
options.get(*menu_selected_index).map(|o| o.id.clone()).unwrap_or_default()
|
||||
}
|
||||
executor::StructuredCommand::Menu {
|
||||
options, ..
|
||||
} => options
|
||||
.get(*menu_selected_index)
|
||||
.map(|opt| opt.id.clone())
|
||||
.unwrap_or_default(),
|
||||
_ => String::new(),
|
||||
};
|
||||
let _ = reply_tx.send(response);
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
*menu_selected_index = 0;
|
||||
}
|
||||
}
|
||||
@@ -498,47 +526,40 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Vim motions (off during text input) ───────────
|
||||
// ── Vim motions ──────────────────────────────────
|
||||
KeyCode::Char('k') if !is_text_input => {
|
||||
if is_menu {
|
||||
if *menu_selected_index > 0 { *menu_selected_index -= 1; }
|
||||
} else if is_form {
|
||||
if *form_cursor > 0 { *form_cursor -= 1; }
|
||||
} else if !has_command {
|
||||
} else if !blocks_scroll {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_sub(1);
|
||||
*log_follow_bottom = false;
|
||||
}
|
||||
}
|
||||
KeyCode::Char('j') if !is_text_input => {
|
||||
if is_menu {
|
||||
if let Some(executor::StructuredCommand::Menu {
|
||||
options, ..
|
||||
}) = current_command {
|
||||
if let Some(executor::StructuredCommand::Menu { options, .. }) = current_command {
|
||||
if *menu_selected_index + 1 < options.len() {
|
||||
*menu_selected_index += 1;
|
||||
}
|
||||
}
|
||||
} else if is_form {
|
||||
let len = if let Some(
|
||||
executor::StructuredCommand::Form { fields, .. }
|
||||
) = current_command { fields.len() } else { 0 };
|
||||
let len = if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command {
|
||||
fields.len()
|
||||
} else { 0 };
|
||||
if *form_cursor + 1 < len { *form_cursor += 1; }
|
||||
} else if !has_command {
|
||||
} else if !blocks_scroll {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(1);
|
||||
*log_follow_bottom =
|
||||
*log_scroll_pos + 1 >= log_buffer.len();
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
}
|
||||
KeyCode::Char('l') if !is_text_input => {
|
||||
// Form submit
|
||||
if is_form {
|
||||
if let Some(executor::StructuredCommand::Form {
|
||||
fields, ..
|
||||
}) = current_command.take() {
|
||||
if let Some(executor::StructuredCommand::Form { fields, .. }) = current_command.take() {
|
||||
let response = fields.iter().enumerate()
|
||||
.filter_map(|(i, f)| {
|
||||
form_values.get(i).copied()
|
||||
.filter(|&v| v).map(|_| f.id.as_str())
|
||||
form_values.get(i).copied().filter(|&v| v).map(|_| f.id.as_str())
|
||||
})
|
||||
.collect::<Vec<_>>().join(" ");
|
||||
let _ = reply_tx.send(response);
|
||||
@@ -547,41 +568,291 @@ impl App {
|
||||
}
|
||||
} else if let Some(cmd) = current_command.take() {
|
||||
let response = match &cmd {
|
||||
executor::StructuredCommand::Confirm { .. } => {
|
||||
"y".to_string()
|
||||
}
|
||||
executor::StructuredCommand::Confirm { .. } => "y".to_string(),
|
||||
executor::StructuredCommand::Menu { options, .. } => {
|
||||
options.get(*menu_selected_index)
|
||||
.map(|o| o.id.clone())
|
||||
.unwrap_or_default()
|
||||
options.get(*menu_selected_index).map(|o| o.id.clone()).unwrap_or_default()
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
let _ = reply_tx.send(response);
|
||||
input_buffer.clear();
|
||||
input.clear();
|
||||
*menu_selected_index = 0;
|
||||
} else {
|
||||
*log_scroll_x = log_scroll_x.saturating_add(4);
|
||||
}
|
||||
}
|
||||
KeyCode::Char('h') if !is_text_input => {
|
||||
// Back / cancel — same logic as Esc.
|
||||
if is_confirm {
|
||||
let _ = current_command.take();
|
||||
let _ = reply_tx.send("n".to_string());
|
||||
} else {
|
||||
if let Some(kx) = kill_tx.take() {
|
||||
let _ = kx.send(());
|
||||
}
|
||||
self.popup = None;
|
||||
} else if !is_menu && !is_form {
|
||||
*log_scroll_x = log_scroll_x.saturating_sub(4);
|
||||
}
|
||||
}
|
||||
KeyCode::Char('H') if !is_text_input && !is_menu && !is_form => {
|
||||
*log_scroll_x = 0;
|
||||
}
|
||||
KeyCode::Char('L') if !is_text_input && !is_menu && !is_form => {
|
||||
*log_scroll_x = usize::MAX;
|
||||
}
|
||||
KeyCode::Char('d') if !is_text_input && !is_form => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(10);
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
}
|
||||
KeyCode::Char('u') if !is_text_input && !is_form => {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_sub(10);
|
||||
*log_follow_bottom = false;
|
||||
}
|
||||
|
||||
_ => {}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::Message { .. } => {
|
||||
Popup::EndpointSelector { selected, scroll_offset: _ } => {
|
||||
match key.code {
|
||||
KeyCode::Up | KeyCode::Char('k') => {
|
||||
if *selected > 0 { *selected -= 1; }
|
||||
}
|
||||
KeyCode::Down | KeyCode::Char('j') => {
|
||||
let len = self.config.endpoints.len();
|
||||
if *selected + 1 < len { *selected += 1; }
|
||||
}
|
||||
KeyCode::Enter | KeyCode::Char('l') => {
|
||||
let sel = *selected;
|
||||
self.popup = None;
|
||||
let url = self.config.endpoints.get(sel).map(|ep| ep.url.clone());
|
||||
if let Some(url) = url {
|
||||
if url != self.config.active_endpoint {
|
||||
self.config.active_endpoint = url;
|
||||
let _ = self.config.save();
|
||||
self.menu = None;
|
||||
self.breadcrumbs.clear();
|
||||
self.selected_index = 0;
|
||||
self.menu_scroll_offset = 0;
|
||||
self.load_menu().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Char('d') | KeyCode::Char('D') => {
|
||||
let sel = *selected;
|
||||
if sel < self.config.endpoints.len() {
|
||||
self.popup = Some(Popup::ConfirmDeleteEndpoint {
|
||||
index: sel,
|
||||
return_selected: sel,
|
||||
});
|
||||
}
|
||||
}
|
||||
KeyCode::Char('e') | KeyCode::Char('E') => {
|
||||
let sel = *selected;
|
||||
if let Some(ep) = self.config.endpoints.get(sel) {
|
||||
let name = ep.name.clone();
|
||||
let url = ep.url.clone();
|
||||
self.popup = Some(Popup::UpsertEndpoint {
|
||||
edit_index: Some(sel),
|
||||
fields: [TextInput::with_text(name), TextInput::with_text(url)],
|
||||
active_field: 0,
|
||||
error: None,
|
||||
return_selected: sel,
|
||||
});
|
||||
}
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') => {
|
||||
let sel = *selected;
|
||||
self.popup = Some(Popup::UpsertEndpoint {
|
||||
edit_index: None,
|
||||
fields: [TextInput::new(), TextInput::new()],
|
||||
active_field: 0,
|
||||
error: None,
|
||||
return_selected: sel,
|
||||
});
|
||||
}
|
||||
KeyCode::Esc | KeyCode::Tab => {
|
||||
self.popup = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::UpsertEndpoint {
|
||||
edit_index,
|
||||
fields,
|
||||
active_field,
|
||||
error,
|
||||
return_selected,
|
||||
} => {
|
||||
match key.code {
|
||||
KeyCode::Enter => {
|
||||
if *active_field == 0 {
|
||||
let name = fields[0].buf.trim().to_string();
|
||||
let edit_idx = *edit_index;
|
||||
if name.is_empty() {
|
||||
*error = Some("Название не может быть пустым".to_string());
|
||||
} else if let Some(conflict_url) = self.config.endpoints.iter()
|
||||
.enumerate()
|
||||
.find(|(i, ep)| Some(*i) != edit_idx && ep.name == name)
|
||||
.map(|(_, ep)| ep.url.clone())
|
||||
{
|
||||
*error = Some(format!(
|
||||
"Название \"{}\" уже используется для {}",
|
||||
name, conflict_url
|
||||
));
|
||||
} else {
|
||||
fields[0].buf = name;
|
||||
*active_field = 1;
|
||||
*error = None;
|
||||
}
|
||||
} else {
|
||||
let url = fields[1].buf.trim().to_string();
|
||||
let name = fields[0].buf.trim().to_string();
|
||||
let edit_idx = *edit_index;
|
||||
let ret = *return_selected;
|
||||
if url.is_empty() {
|
||||
*error = Some("URL не может быть пустым".to_string());
|
||||
} else if let Some(conflict_name) = self.config.endpoints.iter()
|
||||
.enumerate()
|
||||
.find(|(i, ep)| Some(*i) != edit_idx && ep.url == url)
|
||||
.map(|(_, ep)| ep.name.clone())
|
||||
{
|
||||
*error = Some(format!(
|
||||
"URL уже используется для эндпоинта \"{}\"",
|
||||
conflict_name
|
||||
));
|
||||
} else {
|
||||
match edit_idx {
|
||||
None => {
|
||||
self.config.endpoints.push(crate::config::Endpoint::new(name, url));
|
||||
let _ = self.config.save();
|
||||
let new_sel = self.config.endpoints.len() - 1;
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: new_sel,
|
||||
scroll_offset: ret,
|
||||
});
|
||||
}
|
||||
Some(idx) => {
|
||||
let was_active = self.config.endpoints
|
||||
.get(idx)
|
||||
.map(|ep| ep.url == self.config.active_endpoint)
|
||||
.unwrap_or(false);
|
||||
if let Some(ep) = self.config.endpoints.get_mut(idx) {
|
||||
ep.name = name;
|
||||
ep.url = url.clone();
|
||||
}
|
||||
if was_active {
|
||||
self.config.active_endpoint = url;
|
||||
}
|
||||
let _ = self.config.save();
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: ret,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
let ret = *return_selected;
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: ret,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
let af = *active_field;
|
||||
if fields[af].handle_key(&key) {
|
||||
*error = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::ConfirmDeleteEndpoint { index, return_selected } => {
|
||||
match key.code {
|
||||
KeyCode::Char('y') | KeyCode::Char('Y') => {
|
||||
let idx = *index;
|
||||
let ret = *return_selected;
|
||||
self.popup = None;
|
||||
if idx < self.config.endpoints.len() {
|
||||
let was_active = self.config.endpoints[idx].url == self.config.active_endpoint;
|
||||
self.config.endpoints.remove(idx);
|
||||
let _ = self.config.save();
|
||||
if self.config.endpoints.is_empty() {
|
||||
self.config.active_endpoint = String::new();
|
||||
self.menu = None;
|
||||
} else {
|
||||
if was_active {
|
||||
self.config.active_endpoint = self.config.endpoints[0].url.clone();
|
||||
self.menu = None;
|
||||
self.breadcrumbs.clear();
|
||||
self.selected_index = 0;
|
||||
self.menu_scroll_offset = 0;
|
||||
self.load_menu().await;
|
||||
}
|
||||
let new_sel = ret.min(self.config.endpoints.len() - 1);
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: new_sel,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
|
||||
let ret = *return_selected;
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: ret,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::AccessDenied { endpoint_url } => {
|
||||
match key.code {
|
||||
KeyCode::Char('y') | KeyCode::Char('Y') => {
|
||||
let url = endpoint_url.clone();
|
||||
let timeout = self.config.timeout_sec;
|
||||
// Generate a key for this endpoint if it doesn't have one yet
|
||||
// (happens when an endpoint was added before auth was implemented).
|
||||
if let Some(ep) = self.config.endpoints.iter_mut().find(|ep| ep.url == url) {
|
||||
if ep.private_key.is_none() {
|
||||
ep.private_key = Some(crate::identity::Identity::generate().to_b64());
|
||||
let _ = self.config.save();
|
||||
}
|
||||
}
|
||||
let identity_b64 = self.config.endpoints.iter()
|
||||
.find(|ep| ep.url == url)
|
||||
.and_then(|ep| ep.private_key.clone());
|
||||
let tx = self.event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = match identity_b64
|
||||
.as_deref()
|
||||
.and_then(|k| crate::identity::Identity::from_b64(k).ok())
|
||||
{
|
||||
Some(id) => network::request_access(&url, timeout, &id).await,
|
||||
None => Err(crate::error::AppError::Config(
|
||||
"Ключ для эндпоинта не найден".to_string(),
|
||||
)),
|
||||
};
|
||||
let _ = tx.send(Event::AccessRequested(result));
|
||||
});
|
||||
}
|
||||
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
|
||||
self.popup = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
Popup::Message { on_dismiss, .. } => {
|
||||
let exit = matches!(on_dismiss, MessageAction::Exit);
|
||||
self.popup = None;
|
||||
if exit { return Ok(true); }
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@@ -600,34 +871,21 @@ impl App {
|
||||
let tx = self.event_tx.clone();
|
||||
let info_clone = info.clone();
|
||||
|
||||
// Forward progress events
|
||||
tokio::spawn(async move {
|
||||
while let Some(bytes) = progress_rx.recv().await {
|
||||
let _ = tx.send(Event::UpdateProgress(bytes));
|
||||
}
|
||||
});
|
||||
|
||||
// Download and apply
|
||||
let tx2 = self.event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
match updater::download_and_apply(
|
||||
&info_clone,
|
||||
progress_tx,
|
||||
)
|
||||
.await
|
||||
{
|
||||
match updater::download_and_apply(&info_clone, progress_tx).await {
|
||||
Ok(exe_path) => {
|
||||
// Write expected version before exec so
|
||||
// the next startup can detect a failed
|
||||
// replacement (wrong asset, etc.).
|
||||
updater::write_update_target(
|
||||
&info_clone.new_version,
|
||||
);
|
||||
updater::write_update_target(&info_clone.new_version);
|
||||
let _ = tx2.send(Event::UpdateDone(exe_path));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ =
|
||||
tx2.send(Event::UpdateError(e.to_string()));
|
||||
let _ = tx2.send(Event::UpdateError(e.to_string()));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -646,7 +904,6 @@ impl App {
|
||||
if matches!(status, UpdatingStatus::Failed(_)) {
|
||||
self.popup = None;
|
||||
}
|
||||
// Ignore Esc while downloading/applying
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -655,35 +912,80 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Main menu navigation ─────────────────────────────────────────
|
||||
// ── Main menu navigation ──────────────────────────────────────────
|
||||
match key.code {
|
||||
KeyCode::Char('q') => return Ok(true),
|
||||
KeyCode::Up | KeyCode::Char('k') => {
|
||||
let len = self.current_items().len();
|
||||
if len > 0 {
|
||||
self.selected_index = (self.selected_index + len - 1) % len;
|
||||
self.selected_index = self.selected_index.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
KeyCode::Down | KeyCode::Char('j') => {
|
||||
let len = self.current_items().len();
|
||||
if len > 0 {
|
||||
self.selected_index = (self.selected_index + 1) % len;
|
||||
if len > 0 && self.selected_index + 1 < len {
|
||||
self.selected_index += 1;
|
||||
}
|
||||
}
|
||||
KeyCode::Enter | KeyCode::Char('l') => {
|
||||
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
|
||||
if let Some(item) = self.selected_item().cloned() {
|
||||
self.activate_item(item).await?;
|
||||
}
|
||||
}
|
||||
KeyCode::Esc | KeyCode::Char('h') => {
|
||||
KeyCode::Esc | KeyCode::Char('h') | KeyCode::Left => {
|
||||
if !self.breadcrumbs.is_empty() {
|
||||
self.breadcrumbs.pop();
|
||||
self.selected_index = 0;
|
||||
self.menu_scroll_offset = 0;
|
||||
}
|
||||
}
|
||||
KeyCode::Char('r') | KeyCode::Char('R') => {
|
||||
self.load_menu().await;
|
||||
}
|
||||
KeyCode::Tab => {
|
||||
let sel = self.config.endpoints.iter()
|
||||
.position(|ep| ep.url == self.config.active_endpoint)
|
||||
.unwrap_or(0);
|
||||
self.popup = Some(Popup::EndpointSelector {
|
||||
selected: sel,
|
||||
scroll_offset: 0,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
CrosstermEvent::Mouse(mouse) => {
|
||||
use crossterm::event::MouseEventKind;
|
||||
match mouse.kind {
|
||||
MouseEventKind::ScrollUp => {
|
||||
if let Some(Popup::ExecutingStructured { log_scroll_pos, log_follow_bottom, .. }) = &mut self.popup {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_sub(3);
|
||||
*log_follow_bottom = false;
|
||||
} else if let Some(Popup::EndpointSelector { selected, .. }) = &mut self.popup {
|
||||
if *selected > 0 { *selected -= 1; }
|
||||
} else if self.popup.is_none() {
|
||||
let len = self.current_items().len();
|
||||
if len > 0 {
|
||||
self.selected_index = (self.selected_index + len - 1) % len;
|
||||
}
|
||||
}
|
||||
}
|
||||
MouseEventKind::ScrollDown => {
|
||||
if let Some(Popup::ExecutingStructured {
|
||||
log_scroll_pos, log_follow_bottom, log_buffer, ..
|
||||
}) = &mut self.popup {
|
||||
*log_scroll_pos = log_scroll_pos.saturating_add(3);
|
||||
*log_follow_bottom = *log_scroll_pos + 1 >= log_buffer.len();
|
||||
} else if let Some(Popup::EndpointSelector { selected, .. }) = &mut self.popup {
|
||||
let len = self.config.endpoints.len();
|
||||
if *selected + 1 < len { *selected += 1; }
|
||||
} else if self.popup.is_none() {
|
||||
let len = self.current_items().len();
|
||||
if len > 0 {
|
||||
self.selected_index = (self.selected_index + 1) % len;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -718,27 +1020,15 @@ impl App {
|
||||
|
||||
async fn run_action(&mut self, action: Action) -> Result<()> {
|
||||
match action {
|
||||
Action::Bash {
|
||||
script,
|
||||
interaction,
|
||||
confirm: _,
|
||||
confirm_message: _,
|
||||
} => match interaction {
|
||||
InteractionMode::Terminal => {
|
||||
self.run_bash_terminal(&script).await?;
|
||||
}
|
||||
InteractionMode::Structured => {
|
||||
self.run_bash_structured(&script).await?;
|
||||
}
|
||||
Action::Bash { script, interaction, confirm: _, confirm_message: _ } => match interaction {
|
||||
InteractionMode::Terminal => self.run_bash_terminal(&script).await?,
|
||||
InteractionMode::Structured => self.run_bash_structured(&script).await?,
|
||||
},
|
||||
Action::Download {
|
||||
url,
|
||||
confirm: _,
|
||||
..
|
||||
} => {
|
||||
Action::Download { url, confirm: _, .. } => {
|
||||
self.popup = Some(Popup::Message {
|
||||
text: format!("Скачивание {} пока не реализовано", url),
|
||||
level: MessageLevel::Info,
|
||||
on_dismiss: MessageAction::Stay,
|
||||
});
|
||||
}
|
||||
Action::DownloadAndRun { .. } => {}
|
||||
@@ -762,9 +1052,7 @@ impl App {
|
||||
tokio::spawn(async move {
|
||||
let mut rx = output_rx;
|
||||
while let Some(line) = rx.recv().await {
|
||||
if tx_output.send(Event::StructuredOutput(line)).is_err() {
|
||||
break;
|
||||
}
|
||||
if tx_output.send(Event::StructuredOutput(line)).is_err() { break; }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -772,9 +1060,7 @@ impl App {
|
||||
tokio::spawn(async move {
|
||||
let mut rx = command_rx;
|
||||
while let Some(cmd) = rx.recv().await {
|
||||
if tx_cmd.send(Event::StructuredCommand(cmd)).is_err() {
|
||||
break;
|
||||
}
|
||||
if tx_cmd.send(Event::StructuredCommand(cmd)).is_err() { break; }
|
||||
}
|
||||
});
|
||||
|
||||
@@ -789,11 +1075,12 @@ impl App {
|
||||
kill_tx: Some(kill_tx),
|
||||
log_buffer: Vec::new(),
|
||||
current_command: None,
|
||||
input_buffer: String::new(),
|
||||
input: TextInput::new(),
|
||||
menu_selected_index: 0,
|
||||
form_cursor: 0,
|
||||
form_values: Vec::new(),
|
||||
log_scroll_pos: 0,
|
||||
log_scroll_x: 0,
|
||||
log_follow_bottom: false,
|
||||
finished: None,
|
||||
});
|
||||
|
||||
123
src/config.rs
123
src/config.rs
@@ -3,9 +3,39 @@ use anyhow::Result;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Endpoint {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub private_key: Option<String>,
|
||||
}
|
||||
|
||||
impl Endpoint {
|
||||
/// Creates a new endpoint with a freshly generated Ed25519 key pair.
|
||||
pub fn new(name: String, url: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
url,
|
||||
private_key: Some(crate::identity::Identity::generate().to_b64()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn identity(&self) -> Option<crate::identity::Identity> {
|
||||
self.private_key.as_deref()
|
||||
.and_then(|k| crate::identity::Identity::from_b64(k).ok())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Config {
|
||||
pub server_url: String,
|
||||
// Legacy field — present only in old configs; migrated to endpoints on load.
|
||||
#[serde(default, skip_serializing)]
|
||||
server_url: Option<String>,
|
||||
#[serde(default)]
|
||||
pub endpoints: Vec<Endpoint>,
|
||||
#[serde(default)]
|
||||
pub active_endpoint: String,
|
||||
pub timeout_sec: u64,
|
||||
#[serde(default = "default_theme")]
|
||||
pub theme: Theme,
|
||||
@@ -24,13 +54,10 @@ fn default_selected_bg() -> String {
|
||||
}
|
||||
|
||||
fn default_theme() -> Theme {
|
||||
Theme {
|
||||
selected_bg: default_selected_bg(),
|
||||
}
|
||||
Theme { selected_bg: default_selected_bg() }
|
||||
}
|
||||
|
||||
pub fn config_path() -> PathBuf {
|
||||
// Respect XDG_CONFIG_HOME; fall back to ~/.config on all platforms.
|
||||
let base = std::env::var("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| {
|
||||
@@ -42,41 +69,89 @@ pub fn config_path() -> PathBuf {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Returns true when a config file already exists.
|
||||
pub fn exists() -> bool {
|
||||
config_path().exists()
|
||||
}
|
||||
|
||||
/// Load config from disk. Panics-safe: returns error if file is missing or malformed.
|
||||
pub fn active_url(&self) -> &str {
|
||||
&self.active_endpoint
|
||||
}
|
||||
|
||||
/// Returns the identity for the currently active endpoint, if any.
|
||||
pub fn active_identity(&self) -> Option<crate::identity::Identity> {
|
||||
self.endpoints.iter()
|
||||
.find(|ep| ep.url == self.active_endpoint)
|
||||
.and_then(|ep| ep.identity())
|
||||
}
|
||||
|
||||
pub fn load() -> Result<Self> {
|
||||
let path = config_path();
|
||||
let content = fs::read_to_string(&path)?;
|
||||
Ok(toml::from_str(&content)?)
|
||||
let mut cfg: Config = toml::from_str(&content)?;
|
||||
// Migrate old single server_url format to endpoints list.
|
||||
if cfg.endpoints.is_empty() {
|
||||
if let Some(url) = cfg.server_url.take() {
|
||||
cfg.active_endpoint = url.clone();
|
||||
cfg.endpoints.push(Endpoint { name: "Default".to_string(), url, private_key: None });
|
||||
}
|
||||
}
|
||||
if cfg.active_endpoint.is_empty() {
|
||||
if let Some(ep) = cfg.endpoints.first() {
|
||||
cfg.active_endpoint = ep.url.clone();
|
||||
}
|
||||
}
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// Create and persist a new config with the given server URL.
|
||||
pub fn create_with_url(server_url: &str) -> Result<Self> {
|
||||
pub fn create_with_endpoint(url: &str, name: &str) -> Result<Self> {
|
||||
let path = config_path();
|
||||
let config = Config {
|
||||
server_url: server_url.to_string(),
|
||||
server_url: None,
|
||||
endpoints: vec![Endpoint::new(name.to_string(), url.to_string())],
|
||||
active_endpoint: url.to_string(),
|
||||
timeout_sec: 10,
|
||||
theme: default_theme(),
|
||||
update_api: Some("https://git.vainend.com/api/v1/repos/admin/ostiary".to_string()),
|
||||
};
|
||||
let contents = format!(
|
||||
r#"server_url = "{}"
|
||||
timeout_sec = {}
|
||||
update_api = "https://git.vainend.com/api/v1/repos/admin/ostiary"
|
||||
|
||||
[theme]
|
||||
selected_bg = "{}"
|
||||
"#,
|
||||
config.server_url,
|
||||
config.timeout_sec,
|
||||
config.theme.selected_bg,
|
||||
);
|
||||
fs::create_dir_all(path.parent().unwrap())?;
|
||||
fs::write(&path, contents)?;
|
||||
fs::write(&path, config.to_toml())?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let path = config_path();
|
||||
fs::create_dir_all(path.parent().unwrap())?;
|
||||
fs::write(&path, self.to_toml())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn to_toml(&self) -> String {
|
||||
let mut s = format!(
|
||||
"active_endpoint = \"{}\"\ntimeout_sec = {}\n",
|
||||
escape_toml(&self.active_endpoint),
|
||||
self.timeout_sec,
|
||||
);
|
||||
if let Some(api) = &self.update_api {
|
||||
s.push_str(&format!("update_api = \"{}\"\n", escape_toml(api)));
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"\n[theme]\nselected_bg = \"{}\"\n",
|
||||
escape_toml(&self.theme.selected_bg),
|
||||
));
|
||||
for ep in &self.endpoints {
|
||||
s.push_str(&format!(
|
||||
"\n[[endpoints]]\nname = \"{}\"\nurl = \"{}\"\n",
|
||||
escape_toml(&ep.name),
|
||||
escape_toml(&ep.url),
|
||||
));
|
||||
if let Some(key) = &ep.private_key {
|
||||
s.push_str(&format!("private_key = \"{}\"\n", escape_toml(key)));
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_toml(s: &str) -> String {
|
||||
s.replace('\\', "\\\\").replace('"', "\\\"")
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ pub enum AppError {
|
||||
Child(String),
|
||||
#[error("Protocol error: {0}")]
|
||||
Protocol(String),
|
||||
#[error("Access denied by server")]
|
||||
AccessDenied,
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, AppError>;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
pub mod structured;
|
||||
pub use structured::{StructuredCommand, MessageLevel, FormField, FormFieldType};
|
||||
pub use structured::{StructuredCommand, MessageLevel, FormFieldType};
|
||||
|
||||
// Здесь могут быть функции для download, http и т.д.
|
||||
|
||||
@@ -28,7 +28,9 @@ pub enum StructuredCommand {
|
||||
text: String,
|
||||
},
|
||||
Progress {
|
||||
percent: u8,
|
||||
/// Some(n) = deterministic bar (0-100).
|
||||
/// None = indeterminate spinner (percent omitted from JSON).
|
||||
percent: Option<u8>,
|
||||
message: Option<String>,
|
||||
},
|
||||
/// A list of checkboxes and radio buttons.
|
||||
@@ -218,7 +220,8 @@ fn parse_command(json_str: &str, cmd_tx: UnboundedSender<StructuredCommand>) ->
|
||||
StructuredCommand::Message { level, text }
|
||||
}
|
||||
"progress" => {
|
||||
let percent = v["percent"].as_u64().unwrap_or(0) as u8;
|
||||
// percent absent or null → None (indeterminate spinner)
|
||||
let percent = v["percent"].as_u64().map(|n| n.min(100) as u8);
|
||||
let message = v["message"].as_str().map(String::from);
|
||||
StructuredCommand::Progress { percent, message }
|
||||
}
|
||||
|
||||
46
src/identity.rs
Normal file
46
src/identity.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD as B64, Engine};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use rand::rngs::OsRng;
|
||||
|
||||
pub struct Identity {
|
||||
key: SigningKey,
|
||||
}
|
||||
|
||||
impl Identity {
|
||||
pub fn generate() -> Self {
|
||||
Self { key: SigningKey::generate(&mut OsRng) }
|
||||
}
|
||||
|
||||
pub fn from_b64(s: &str) -> Result<Self> {
|
||||
let bytes = B64.decode(s)?;
|
||||
let arr: [u8; 32] = bytes.try_into().map_err(|_| anyhow!("invalid key length"))?;
|
||||
Ok(Self { key: SigningKey::from_bytes(&arr) })
|
||||
}
|
||||
|
||||
pub fn to_b64(&self) -> String {
|
||||
B64.encode(self.key.to_bytes())
|
||||
}
|
||||
|
||||
pub fn public_key_b64(&self) -> String {
|
||||
B64.encode(self.key.verifying_key().to_bytes())
|
||||
}
|
||||
|
||||
/// Signs `"METHOD\nPATH\nTIMESTAMP"` and returns base64url signature.
|
||||
pub fn sign(&self, method: &str, path: &str, timestamp: u64) -> String {
|
||||
let msg = format!("{}\n{}\n{}", method, path, timestamp);
|
||||
B64.encode(self.key.sign(msg.as_bytes()).to_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current_hostname() -> String {
|
||||
let mut buf = vec![0u8; 256];
|
||||
unsafe {
|
||||
if libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) == 0 {
|
||||
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
|
||||
String::from_utf8_lossy(&buf[..len]).into_owned()
|
||||
} else {
|
||||
"unknown".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
82
src/main.rs
82
src/main.rs
@@ -3,8 +3,10 @@ mod app;
|
||||
mod config;
|
||||
mod error;
|
||||
mod executor;
|
||||
mod identity;
|
||||
mod menu;
|
||||
mod network;
|
||||
mod text_input;
|
||||
mod ui;
|
||||
mod updater;
|
||||
|
||||
@@ -23,8 +25,8 @@ async fn main() -> Result<()> {
|
||||
let config = if config::Config::exists() {
|
||||
config::Config::load()?
|
||||
} else {
|
||||
let url = prompt_server_url()?;
|
||||
config::Config::create_with_url(&url)?
|
||||
let (url, name) = prompt_first_endpoint()?;
|
||||
config::Config::create_with_endpoint(&url, &name)?
|
||||
};
|
||||
|
||||
enable_raw_mode()?;
|
||||
@@ -107,7 +109,7 @@ async fn run_app(
|
||||
terminal.show_cursor()?;
|
||||
#[cfg(unix)]
|
||||
updater::exec_updated(&exe_path);
|
||||
// fallback for non-unix or if exec failed
|
||||
#[cfg(not(unix))]
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -166,35 +168,63 @@ async fn run_exec(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs before ratatui starts. Prompts for the server URL on first launch.
|
||||
fn prompt_server_url() -> Result<String> {
|
||||
use std::io::Write;
|
||||
/// Runs before ratatui starts. Prompts for endpoint URL and name on first launch.
|
||||
fn prompt_first_endpoint() -> Result<(String, String)> {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
|
||||
println!();
|
||||
println!(" ╔══════════════════════════════════╗");
|
||||
println!(" ║ Ostiary — первый запуск ║");
|
||||
println!(" ╚══════════════════════════════════╝");
|
||||
println!();
|
||||
println!(" Конфиг будет сохранён в:");
|
||||
println!(" {}", config::config_path().display());
|
||||
println!();
|
||||
// Open /dev/tty directly so input works even when launched via `curl | bash`
|
||||
// (where stdin is the pipe carrying the script, not the keyboard).
|
||||
let tty = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open("/dev/tty")
|
||||
.map_err(|e| anyhow::anyhow!(
|
||||
"Не удалось открыть терминал ({e}). Запустите ostiary напрямую."
|
||||
))?;
|
||||
let mut out = tty.try_clone()?;
|
||||
let mut reader = BufReader::new(tty);
|
||||
|
||||
loop {
|
||||
print!(" URL сервера меню: ");
|
||||
std::io::stdout().flush()?;
|
||||
writeln!(out)?;
|
||||
writeln!(out, " ╔══════════════════════════════════╗")?;
|
||||
writeln!(out, " ║ Ostiary — первый запуск ║")?;
|
||||
writeln!(out, " ╚══════════════════════════════════╝")?;
|
||||
writeln!(out)?;
|
||||
writeln!(out, " Конфиг будет сохранён в:")?;
|
||||
writeln!(out, " {}", config::config_path().display())?;
|
||||
writeln!(out)?;
|
||||
|
||||
let mut url = String::new();
|
||||
std::io::stdin().read_line(&mut url)?;
|
||||
let url = url.trim().to_string();
|
||||
|
||||
if url.is_empty() {
|
||||
println!(" URL не может быть пустым. Попробуйте ещё раз.\n");
|
||||
let name = loop {
|
||||
write!(out, " Название эндпоинта: ")?;
|
||||
out.flush()?;
|
||||
let mut buf = String::new();
|
||||
if reader.read_line(&mut buf)? == 0 {
|
||||
anyhow::bail!("Неожиданный конец ввода.");
|
||||
}
|
||||
let val = buf.trim().to_string();
|
||||
if val.is_empty() {
|
||||
writeln!(out, " Название не может быть пустым. Попробуйте ещё раз.\n")?;
|
||||
continue;
|
||||
}
|
||||
break val;
|
||||
};
|
||||
|
||||
println!();
|
||||
return Ok(url);
|
||||
}
|
||||
let url = loop {
|
||||
write!(out, " URL эндпоинта: ")?;
|
||||
out.flush()?;
|
||||
let mut buf = String::new();
|
||||
if reader.read_line(&mut buf)? == 0 {
|
||||
anyhow::bail!("Неожиданный конец ввода.");
|
||||
}
|
||||
let val = buf.trim().to_string();
|
||||
if val.is_empty() {
|
||||
writeln!(out, " URL не может быть пустым. Попробуйте ещё раз.\n")?;
|
||||
continue;
|
||||
}
|
||||
break val;
|
||||
};
|
||||
|
||||
writeln!(out)?;
|
||||
Ok((url, name))
|
||||
}
|
||||
|
||||
async fn read_crossterm_event() -> Result<Option<crossterm::event::Event>> {
|
||||
|
||||
143
src/network.rs
143
src/network.rs
@@ -1,29 +1,138 @@
|
||||
use crate::error::Result;
|
||||
use crate::error::{AppError, Result};
|
||||
use crate::identity::Identity;
|
||||
use crate::menu::{MenuItem, MenuRoot};
|
||||
use reqwest::Client;
|
||||
use serde_path_to_error as path_to_error;
|
||||
|
||||
pub async fn fetch_menu(server_url: &str, timeout_sec: u64) -> Result<MenuRoot> {
|
||||
pub async fn fetch_menu(server_url: &str, timeout_sec: u64, identity: Option<&Identity>) -> Result<MenuRoot> {
|
||||
let client = Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(timeout_sec))
|
||||
.build()?;
|
||||
|
||||
let resp = client.get(server_url).send().await?;
|
||||
let text = resp.text().await?;
|
||||
let mut req = client.get(server_url);
|
||||
|
||||
let mut deserializer = serde_json::Deserializer::from_str(&text);
|
||||
match path_to_error::deserialize(&mut deserializer) {
|
||||
Ok(root) => Ok(root),
|
||||
Err(e) => {
|
||||
// Если не удалось распарсить как объект с полем "menu",
|
||||
// пробуем интерпретировать ответ как прямой массив пунктов меню.
|
||||
match serde_json::from_str::<Vec<MenuItem>>(&text) {
|
||||
Ok(items) => Ok(MenuRoot {
|
||||
version: "1.0".to_string(),
|
||||
menu: items,
|
||||
}),
|
||||
Err(_) => Err(crate::error::AppError::Json(e.into_inner())),
|
||||
}
|
||||
if let Some(id) = identity {
|
||||
let timestamp = unix_now();
|
||||
let path = url_path(server_url);
|
||||
req = req
|
||||
.header("X-Public-Key", id.public_key_b64())
|
||||
.header("X-Timestamp", timestamp.to_string())
|
||||
.header("X-Signature", id.sign("GET", &path, timestamp));
|
||||
}
|
||||
|
||||
let resp = req.send().await?;
|
||||
|
||||
if resp.status() == reqwest::StatusCode::FORBIDDEN {
|
||||
return Err(parse_access_denied(resp).await);
|
||||
}
|
||||
|
||||
let text = resp.text().await?;
|
||||
parse_menu_body(&text)
|
||||
}
|
||||
|
||||
/// Sends an enrollment request to `{server_url}/access-request`.
|
||||
/// The server stores the public key + source IP for admin approval.
|
||||
/// Returns a human-readable status string on success.
|
||||
pub async fn request_access(server_url: &str, timeout_sec: u64, identity: &Identity) -> Result<String> {
|
||||
let access_url = enrollment_url(server_url);
|
||||
|
||||
let client = Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(timeout_sec))
|
||||
.build()?;
|
||||
|
||||
let resp = client
|
||||
.post(&access_url)
|
||||
.json(&serde_json::json!({
|
||||
"public_key": identity.public_key_b64(),
|
||||
"hostname": crate::identity::current_hostname(),
|
||||
}))
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let status = resp.status();
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
|
||||
let json_status = serde_json::from_str::<serde_json::Value>(&body)
|
||||
.ok()
|
||||
.and_then(|v| v["status"].as_str().map(|s| s.to_string()));
|
||||
|
||||
if status == reqwest::StatusCode::FORBIDDEN {
|
||||
let msg = match json_status.as_deref() {
|
||||
Some("banned") => "Ваш IP заблокирован администратором.".to_string(),
|
||||
_ => format!("Сервер вернул {}: {}", status, body),
|
||||
};
|
||||
return Ok(msg);
|
||||
}
|
||||
|
||||
if !status.is_success() {
|
||||
return Err(AppError::Config(format!("Сервер вернул {}: {}", status, body)));
|
||||
}
|
||||
|
||||
let msg = match json_status.as_deref() {
|
||||
Some("pending") => "Запрос отправлен. Ожидайте одобрения администратора.".to_string(),
|
||||
Some("already_pending") => "Запрос уже был отправлен ранее. Ожидайте одобрения.".to_string(),
|
||||
Some("already_authorized") => "Ключ уже авторизован. Нажмите R для обновления меню.".to_string(),
|
||||
_ => format!("Ответ сервера: {}", body),
|
||||
};
|
||||
Ok(msg)
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
fn unix_now() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
}
|
||||
|
||||
/// Builds the enrollment URL: `access-request.php` in the same directory as the menu URL.
|
||||
/// `https://host/api/menu/index.php` → `https://host/api/menu/access-request.php`
|
||||
/// `https://host/api/menu/` → `https://host/api/menu/access-request.php`
|
||||
fn enrollment_url(server_url: &str) -> String {
|
||||
reqwest::Url::parse(server_url)
|
||||
.map(|mut u| {
|
||||
let path = u.path().to_string();
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
// If the last path segment looks like a file (contains '.'), use its parent dir.
|
||||
let dir = match trimmed.rfind('/') {
|
||||
Some(pos) if trimmed[pos + 1..].contains('.') => &trimmed[..pos],
|
||||
_ => trimmed,
|
||||
};
|
||||
u.set_path(&format!("{}/access-request.php", dir));
|
||||
u.set_query(None);
|
||||
u.to_string()
|
||||
})
|
||||
.unwrap_or_else(|_| format!("{}/access-request.php", server_url.trim_end_matches('/')))
|
||||
}
|
||||
|
||||
/// Extracts just the path component from a URL string.
|
||||
fn url_path(url: &str) -> String {
|
||||
reqwest::Url::parse(url)
|
||||
.map(|u| u.path().to_string())
|
||||
.unwrap_or_else(|_| "/".to_string())
|
||||
}
|
||||
|
||||
/// Returns `AppError::AccessDenied` when the 403 body contains `{"error":"access_denied"}`,
|
||||
/// otherwise a generic config error.
|
||||
async fn parse_access_denied(resp: reqwest::Response) -> AppError {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ErrBody { error: String }
|
||||
if let Ok(body) = resp.json::<ErrBody>().await {
|
||||
if body.error == "access_denied" {
|
||||
return AppError::AccessDenied;
|
||||
}
|
||||
}
|
||||
AppError::Config("Сервер вернул 403 Forbidden".to_string())
|
||||
}
|
||||
|
||||
fn parse_menu_body(text: &str) -> Result<MenuRoot> {
|
||||
let mut de = serde_json::Deserializer::from_str(text);
|
||||
match path_to_error::deserialize(&mut de) {
|
||||
Ok(root) => Ok(root),
|
||||
Err(e) => match serde_json::from_str::<Vec<MenuItem>>(text) {
|
||||
Ok(items) => Ok(MenuRoot { version: "1.0".to_string(), menu: items }),
|
||||
Err(_) => Err(AppError::Json(e.into_inner())),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
98
src/text_input.rs
Normal file
98
src/text_input.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
pub struct TextInput {
|
||||
pub buf: String,
|
||||
pub cursor: usize,
|
||||
}
|
||||
|
||||
impl TextInput {
|
||||
pub fn new() -> Self {
|
||||
Self { buf: String::new(), cursor: 0 }
|
||||
}
|
||||
|
||||
pub fn with_text(text: impl Into<String>) -> Self {
|
||||
let buf = text.into();
|
||||
let cursor = buf.chars().count();
|
||||
Self { buf, cursor }
|
||||
}
|
||||
|
||||
pub fn value(&self) -> &str {
|
||||
&self.buf
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.buf.clear();
|
||||
self.cursor = 0;
|
||||
}
|
||||
|
||||
pub fn move_left(&mut self) {
|
||||
self.cursor = self.cursor.saturating_sub(1);
|
||||
}
|
||||
|
||||
pub fn move_right(&mut self) {
|
||||
self.cursor = (self.cursor + 1).min(self.buf.chars().count());
|
||||
}
|
||||
|
||||
pub fn word_back(&mut self) {
|
||||
let chars: Vec<char> = self.buf.chars().collect();
|
||||
let mut pos = self.cursor;
|
||||
while pos > 0 && !is_word(chars[pos - 1]) { pos -= 1; }
|
||||
while pos > 0 && is_word(chars[pos - 1]) { pos -= 1; }
|
||||
self.cursor = pos;
|
||||
}
|
||||
|
||||
pub fn word_fwd(&mut self) {
|
||||
let chars: Vec<char> = self.buf.chars().collect();
|
||||
let len = chars.len();
|
||||
let mut pos = self.cursor;
|
||||
while pos < len && !is_word(chars[pos]) { pos += 1; }
|
||||
while pos < len && is_word(chars[pos]) { pos += 1; }
|
||||
self.cursor = pos;
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, c: char) {
|
||||
let byte_idx = self.buf.char_indices().nth(self.cursor).map(|(b, _)| b).unwrap_or(self.buf.len());
|
||||
self.buf.insert(byte_idx, c);
|
||||
self.cursor += 1;
|
||||
}
|
||||
|
||||
pub fn backspace(&mut self) {
|
||||
if self.cursor == 0 { return; }
|
||||
let byte_idx = self.buf.char_indices().nth(self.cursor - 1).map(|(b, _)| b).unwrap_or(0);
|
||||
self.buf.remove(byte_idx);
|
||||
self.cursor -= 1;
|
||||
}
|
||||
|
||||
pub fn word_delete_back(&mut self) {
|
||||
let chars: Vec<char> = self.buf.chars().collect();
|
||||
let mut new_cursor = self.cursor;
|
||||
while new_cursor > 0 && !is_word(chars[new_cursor - 1]) { new_cursor -= 1; }
|
||||
while new_cursor > 0 && is_word(chars[new_cursor - 1]) { new_cursor -= 1; }
|
||||
if new_cursor == self.cursor { return; }
|
||||
let start_byte = self.buf.char_indices().nth(new_cursor).map(|(b, _)| b).unwrap_or(0);
|
||||
let end_byte = self.buf.char_indices().nth(self.cursor).map(|(b, _)| b).unwrap_or(self.buf.len());
|
||||
self.buf.drain(start_byte..end_byte);
|
||||
self.cursor = new_cursor;
|
||||
}
|
||||
|
||||
/// Returns true if the key was consumed.
|
||||
pub fn handle_key(&mut self, key: &KeyEvent) -> bool {
|
||||
let alt = key.modifiers.intersects(KeyModifiers::ALT | KeyModifiers::SUPER);
|
||||
match key.code {
|
||||
KeyCode::Left if alt => { self.word_back(); true }
|
||||
KeyCode::Right if alt => { self.word_fwd(); true }
|
||||
KeyCode::Char('b') if alt => { self.word_back(); true }
|
||||
KeyCode::Char('f') if alt => { self.word_fwd(); true }
|
||||
KeyCode::Left => { self.move_left(); true }
|
||||
KeyCode::Right => { self.move_right(); true }
|
||||
KeyCode::Backspace if alt => { self.word_delete_back(); true }
|
||||
KeyCode::Backspace => { self.backspace(); true }
|
||||
KeyCode::Char(c) => { self.insert(c); true }
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_word(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
@@ -61,8 +61,8 @@ pub async fn check(api_base: &str, timeout_sec: u64) -> Result<Option<UpdateInfo
|
||||
let tag = tag.split('@').next().unwrap_or(tag).trim();
|
||||
let new_version = tag.to_string();
|
||||
|
||||
// Already up to date
|
||||
if new_version == current_version {
|
||||
// Only offer update if the remote version is strictly newer
|
||||
if !is_newer(&new_version, ¤t_version) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -185,6 +185,16 @@ pub fn take_update_target() -> Option<String> {
|
||||
Some(version.trim().to_string())
|
||||
}
|
||||
|
||||
/// Returns true if `candidate` is strictly greater than `current` by semver rules.
|
||||
/// Parses `MAJOR.MINOR.PATCH`; any unparseable component is treated as 0.
|
||||
fn is_newer(candidate: &str, current: &str) -> bool {
|
||||
fn parse(v: &str) -> (u64, u64, u64) {
|
||||
let mut parts = v.splitn(3, '.').map(|s| s.parse::<u64>().unwrap_or(0));
|
||||
(parts.next().unwrap_or(0), parts.next().unwrap_or(0), parts.next().unwrap_or(0))
|
||||
}
|
||||
parse(candidate) > parse(current)
|
||||
}
|
||||
|
||||
/// Replaces current process via execv (Unix). Never returns on success.
|
||||
/// `exe_path` must be the path captured *before* the binary was replaced —
|
||||
/// do NOT call std::env::current_exe() here, it returns "(deleted)" on Linux.
|
||||
|
||||
Reference in New Issue
Block a user