use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use getrandom::SysRng;
use nibkeep_crypto::rand_core::{CryptoRng, UnwrapErr};
use nibkeep_node::at_login::{self, LoginEntry};
use nibkeep_node::{NodeError, PassphraseParams};
use nibkeep_passwords::{Board, ClipboardError};
use zeroize::Zeroizing;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Account {
pub name: Option<String>,
pub full_name: Option<String>,
}
pub trait Environment {
type Rng: CryptoRng;
fn rng(&mut self) -> &mut Self::Rng;
fn now(&self) -> u64;
fn offset_minutes(&self) -> i32;
fn time_zone(&self) -> jiff::tz::TimeZone {
jiff::tz::Offset::from_seconds(self.offset_minutes() * 60)
.map_or(jiff::tz::TimeZone::UTC, jiff::tz::TimeZone::fixed)
}
fn passphrase(&mut self, prompt: &str) -> io::Result<Zeroizing<String>>;
fn passphrase_params(&self) -> PassphraseParams;
fn computer_name(&self) -> String;
fn account(&self) -> Account;
fn current_dir(&self) -> io::Result<PathBuf>;
fn default_library(&self) -> Option<PathBuf>;
fn ceiling(&self) -> Option<PathBuf> {
None
}
fn keystore(&mut self) -> bool;
fn languages(&self) -> Vec<String>;
fn downloads(&self) -> Option<PathBuf> {
None
}
fn note(&mut self, line: &str) {
eprintln!("nib: {}", crate::printable(line));
}
fn ask(&mut self, question: &str) -> io::Result<Option<String>> {
let _ = question;
Ok(None)
}
fn can_ask(&self) -> bool {
false
}
fn clipboard(&mut self) -> Result<Box<dyn Board>, ClipboardError> {
Err(ClipboardError::new("there is none here"))
}
fn interruptible(&mut self) {}
fn wait(&mut self, duration: Duration) -> bool {
std::thread::sleep(duration);
false
}
fn stop_on_interrupt(&mut self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
let _ = stop;
}
fn state_folder(&self) -> Option<PathBuf> {
None
}
fn sync_program(&self) -> Option<PathBuf> {
None
}
fn nib_program(&self) -> Option<PathBuf> {
None
}
fn ai_client(&self, program: &str) -> Option<std::process::Command> {
let _ = program;
None
}
fn git(&self) -> std::process::Command {
let mut git = std::process::Command::new("git");
clear_git_variables(&mut git);
git
}
fn login_entry(&self) -> Option<LoginEntry> {
None
}
fn open_firewall(&mut self) -> Firewall {
Firewall::NotHere
}
fn sync_version(&self, program: &Path) -> Option<String> {
at_login::service_version(program)
}
fn start_sync(&mut self, program: &Path) -> Result<(), NodeError> {
at_login::start_service(program)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Firewall {
NotHere,
Open,
Opened,
Refused,
}
pub struct System {
rng: UnwrapErr<SysRng>,
keystore: Option<bool>,
interruptions: Option<mpsc::Receiver<()>>,
}
impl System {
#[must_use]
pub fn new() -> Self {
Self {
rng: UnwrapErr(SysRng),
keystore: None,
interruptions: None,
}
}
}
impl Default for System {
fn default() -> Self {
Self::new()
}
}
impl Environment for System {
type Rng = UnwrapErr<SysRng>;
fn rng(&mut self) -> &mut Self::Rng {
&mut self.rng
}
fn now(&self) -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| {
u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
})
}
fn offset_minutes(&self) -> i32 {
jiff::tz::TimeZone::system()
.to_offset(jiff::Timestamp::now())
.seconds()
/ 60
}
fn time_zone(&self) -> jiff::tz::TimeZone {
jiff::tz::TimeZone::system()
}
fn passphrase(&mut self, prompt: &str) -> io::Result<Zeroizing<String>> {
rpassword::prompt_password(prompt).map(Zeroizing::new)
}
fn passphrase_params(&self) -> PassphraseParams {
PassphraseParams::LOW_MEMORY
}
fn computer_name(&self) -> String {
gethostname::gethostname().to_string_lossy().into_owned()
}
fn account(&self) -> Account {
let lossy = |name: std::ffi::OsString| name.to_string_lossy().into_owned();
Account {
name: whoami::username_os().ok().map(lossy),
full_name: whoami::realname_os().ok().map(lossy),
}
}
fn current_dir(&self) -> io::Result<PathBuf> {
std::env::current_dir()
}
fn default_library(&self) -> Option<PathBuf> {
std::env::var_os("NIBKEEP_LIBRARY")
.filter(|folder| !folder.is_empty())
.map(PathBuf::from)
}
fn ceiling(&self) -> Option<PathBuf> {
std::env::var_os("NIBKEEP_CEILING")
.map(PathBuf::from)
.filter(|folder| folder.is_absolute())
.map(|folder| nibkeep_node::resolved_path(&folder).unwrap_or(folder))
}
fn keystore(&mut self) -> bool {
*self
.keystore
.get_or_insert_with(|| !at_login::app::kept_away() && platform_keystore())
}
fn downloads(&self) -> Option<PathBuf> {
directories::UserDirs::new()
.and_then(|directories| directories.download_dir().map(PathBuf::from))
}
fn state_folder(&self) -> Option<PathBuf> {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
return at_login::settings_folder();
#[cfg(any(target_os = "android", target_os = "ios"))]
None
}
fn login_entry(&self) -> Option<LoginEntry> {
LoginEntry::platform()
}
fn open_firewall(&mut self) -> Firewall {
#[cfg(windows)]
{
use nibkeep_node::at_login::firewall;
if firewall::has_rule() {
Firewall::Open
} else if firewall::add_rule() {
Firewall::Opened
} else {
Firewall::Refused
}
}
#[cfg(not(windows))]
Firewall::NotHere
}
fn sync_program(&self) -> Option<PathBuf> {
let name = format!(
"{}{}",
at_login::SERVICE_PROGRAM,
std::env::consts::EXE_SUFFIX
);
let program = std::env::current_exe().ok()?.with_file_name(name);
program.is_file().then_some(program)
}
fn nib_program(&self) -> Option<PathBuf> {
std::env::current_exe().ok()
}
fn ai_client(&self, program: &str) -> Option<std::process::Command> {
let name = format!("{program}{}", std::env::consts::EXE_SUFFIX);
let found = std::env::split_paths(&std::env::var_os("PATH")?)
.map(|folder| folder.join(&name))
.find(|path| path.is_file())?;
Some(std::process::Command::new(found))
}
fn can_ask(&self) -> bool {
io::stdin().is_terminal() && io::stderr().is_terminal()
}
fn ask(&mut self, question: &str) -> io::Result<Option<String>> {
if !self.can_ask() {
return Ok(None);
}
let mut stderr = io::stderr();
write!(stderr, "{}", crate::printable(question))?;
stderr.flush()?;
let mut answer = String::new();
if io::stdin().read_line(&mut answer)? == 0 {
return Ok(None);
}
Ok(Some(answer.trim().to_owned()))
}
fn clipboard(&mut self) -> Result<Box<dyn Board>, ClipboardError> {
#[cfg(not(any(target_os = "android", target_os = "ios")))]
return Ok(Box::new(nibkeep_passwords::SystemBoard::new()?));
#[cfg(any(target_os = "android", target_os = "ios"))]
Err(ClipboardError::new("nib has no clipboard on phones"))
}
fn interruptible(&mut self) {
if self.interruptions.is_none() {
let (interrupted, interruptions) = mpsc::channel();
if ctrlc::set_handler(move || {
let _ = interrupted.send(());
})
.is_ok()
{
self.interruptions = Some(interruptions);
}
}
}
fn stop_on_interrupt(&mut self, stop: std::sync::Arc<std::sync::atomic::AtomicBool>) {
if self.interruptions.is_none() {
let _ = ctrlc::set_handler(move || {
stop.store(true, std::sync::atomic::Ordering::SeqCst);
});
}
}
fn wait(&mut self, duration: Duration) -> bool {
self.interruptible();
if let Some(interruptions) = &self.interruptions {
interruptions.recv_timeout(duration).is_ok()
} else {
std::thread::sleep(duration);
false
}
}
fn languages(&self) -> Vec<String> {
#[cfg(unix)]
if let Ok(ranked) = std::env::var("LANGUAGE")
&& !ranked.is_empty()
{
return ranked.split(':').map(str::to_owned).collect();
}
sys_locale::get_locales().collect()
}
}
#[must_use]
pub fn platform_keystore() -> bool {
#[cfg(target_os = "macos")]
let store = apple_native_keyring_store::keychain::Store::new();
#[cfg(target_os = "windows")]
let store = windows_native_keyring_store::Store::new();
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
))]
let store = zbus_secret_service_keyring_store::Store::new();
#[cfg(any(
target_os = "macos",
target_os = "windows",
all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
)
))]
{
match store {
Ok(store) => {
keyring_core::set_default_store(store);
true
}
Err(_) => false,
}
}
#[cfg(not(any(
target_os = "macos",
target_os = "windows",
all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
)
)))]
false
}
pub use nibkeep_git::clear_variables as clear_git_variables;