key_storage.rs (2749B)
1 use enostr::Keypair; 2 3 #[cfg(target_os = "linux")] 4 use crate::linux_key_storage::LinuxKeyStorage; 5 #[cfg(target_os = "macos")] 6 use crate::macos_key_storage::MacOSKeyStorage; 7 8 #[cfg(target_os = "macos")] 9 pub const SERVICE_NAME: &str = "Notedeck"; 10 11 #[derive(Debug, PartialEq)] 12 pub enum KeyStorageType { 13 None, 14 #[cfg(target_os = "macos")] 15 MacOS, 16 #[cfg(target_os = "linux")] 17 Linux, 18 // TODO: 19 // Windows, 20 // Android, 21 } 22 23 #[allow(dead_code)] 24 #[derive(Debug, PartialEq)] 25 pub enum KeyStorageResponse<R> { 26 Waiting, 27 ReceivedResult(Result<R, KeyStorageError>), 28 } 29 30 pub trait KeyStorage { 31 fn get_keys(&self) -> KeyStorageResponse<Vec<Keypair>>; 32 fn add_key(&self, key: &Keypair) -> KeyStorageResponse<()>; 33 fn remove_key(&self, key: &Keypair) -> KeyStorageResponse<()>; 34 } 35 36 impl KeyStorage for KeyStorageType { 37 fn get_keys(&self) -> KeyStorageResponse<Vec<Keypair>> { 38 match self { 39 Self::None => KeyStorageResponse::ReceivedResult(Ok(Vec::new())), 40 #[cfg(target_os = "macos")] 41 Self::MacOS => MacOSKeyStorage::new(SERVICE_NAME).get_keys(), 42 #[cfg(target_os = "linux")] 43 Self::Linux => LinuxKeyStorage::new().get_keys(), 44 } 45 } 46 47 fn add_key(&self, key: &Keypair) -> KeyStorageResponse<()> { 48 let _ = key; 49 match self { 50 Self::None => KeyStorageResponse::ReceivedResult(Ok(())), 51 #[cfg(target_os = "macos")] 52 Self::MacOS => MacOSKeyStorage::new(SERVICE_NAME).add_key(key), 53 #[cfg(target_os = "linux")] 54 Self::Linux => LinuxKeyStorage::new().add_key(key), 55 } 56 } 57 58 fn remove_key(&self, key: &Keypair) -> KeyStorageResponse<()> { 59 let _ = key; 60 match self { 61 Self::None => KeyStorageResponse::ReceivedResult(Ok(())), 62 #[cfg(target_os = "macos")] 63 Self::MacOS => MacOSKeyStorage::new(SERVICE_NAME).remove_key(key), 64 #[cfg(target_os = "linux")] 65 Self::Linux => LinuxKeyStorage::new().remove_key(key), 66 } 67 } 68 } 69 70 #[allow(dead_code)] 71 #[derive(Debug, PartialEq)] 72 pub enum KeyStorageError { 73 Retrieval(String), 74 Addition(String), 75 Removal(String), 76 OSError(String), 77 } 78 79 impl std::fmt::Display for KeyStorageError { 80 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 81 match self { 82 Self::Retrieval(e) => write!(f, "Failed to retrieve keys: {:?}", e), 83 Self::Addition(key) => write!(f, "Failed to add key: {:?}", key), 84 Self::Removal(key) => write!(f, "Failed to remove key: {:?}", key), 85 Self::OSError(e) => write!(f, "OS had an error: {:?}", e), 86 } 87 } 88 } 89 90 impl std::error::Error for KeyStorageError {}