#[cfg(target_os = "android")]
#[manganis::ffi("src/android/storage")]
unsafe extern "Kotlin" {
pub type StoragePlugin;
}
#[cfg(target_os = "android")]
const STORAGE_CLASS: &str = "dev.dioxus.g3_native_plugins.storage.StoragePlugin";
#[cfg(target_os = "android")]
type StorageHandle = crate::android_bridge::AndroidPlugin;
#[cfg(target_os = "ios")]
type StorageHandle = StoragePlugin;
#[cfg(target_os = "ios")]
#[manganis::ffi("src/ios")]
unsafe extern "Swift" {
pub type StoragePlugin;
pub fn getFromRust(this: &StoragePlugin, key: String) -> Option<String>;
pub fn setFromRust(this: &StoragePlugin, entryJson: String) -> Option<String>;
pub fn removeFromRust(this: &StoragePlugin, key: String) -> Option<String>;
pub fn clearFromRust(this: &StoragePlugin) -> Option<String>;
pub fn keysFromRust(this: &StoragePlugin) -> Option<String>;
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub struct KeyValueStore {
plugin: Option<StorageHandle>,
}
#[cfg(target_arch = "wasm32")]
pub struct KeyValueStore;
#[cfg(target_os = "macos")]
pub struct KeyValueStore;
#[cfg(any(target_os = "android", target_os = "ios"))]
impl KeyValueStore {
pub fn new() -> Self {
Self { plugin: None }
}
fn get_plugin(&mut self) -> Result<&StorageHandle, String> {
if self.plugin.is_none() {
#[cfg(target_os = "android")]
let created = StorageHandle::new(STORAGE_CLASS)?;
#[cfg(target_os = "ios")]
let created = StoragePlugin::new()
.map_err(|error| format!("Failed to create StoragePlugin: {error:?}"))?;
self.plugin = Some(created);
}
Ok(self.plugin.as_ref().unwrap())
}
pub fn prepare(&mut self) -> Result<(), String> {
self.get_plugin()?;
Ok(())
}
pub fn get(&mut self, key: &str) -> Result<Option<String>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let raw = plugin.call_string_str("getFromRust", key)?;
#[cfg(target_os = "ios")]
let raw = getFromRust(plugin, key.to_string())?;
let Some(raw) = raw else {
return Ok(None);
};
Self::unwrap_result(&raw).map(Some)
}
pub fn set(&mut self, key: &str, value: &str) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return Self::check(plugin.call_string_str_str("setFromRust", key, value)?);
#[cfg(target_os = "ios")]
{
let entry = serde_json::to_string(&serde_json::json!({
"key": key,
"value": value,
}))
.map_err(|error| format!("Failed to encode storage entry: {error}"))?;
Self::check(setFromRust(plugin, entry)?)
}
}
pub fn remove(&mut self, key: &str) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return Self::check(plugin.call_string_str("removeFromRust", key)?);
#[cfg(target_os = "ios")]
return Self::check(removeFromRust(plugin, key.to_string())?);
}
pub fn clear(&mut self) -> Result<(), String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
return Self::check(plugin.call_string("clearFromRust")?);
#[cfg(target_os = "ios")]
return Self::check(clearFromRust(plugin)?);
}
pub fn keys(&mut self) -> Result<Vec<String>, String> {
let plugin = self.get_plugin()?;
#[cfg(target_os = "android")]
let reported = plugin.call_string("keysFromRust")?;
#[cfg(target_os = "ios")]
let reported = keysFromRust(plugin)?;
let raw = reported.ok_or_else(|| "The store did not report its keys".to_string())?;
let value: serde_json::Value = serde_json::from_str(&raw)
.map_err(|error| format!("Failed to read stored keys: {error}"))?;
if let Some(error) = value.get("error").and_then(|error| error.as_str()) {
return Err(error.to_string());
}
serde_json::from_value(value)
.map_err(|error| format!("Failed to read stored keys: {error}"))
}
pub fn contains(&mut self, key: &str) -> Result<bool, String> {
Ok(self.get(key)?.is_some())
}
fn unwrap_result(raw: &str) -> Result<String, String> {
if let Some(error) = Self::error_in(raw) {
return Err(error);
}
Ok(raw.to_string())
}
fn check(raw: Option<String>) -> Result<(), String> {
match raw.as_deref().and_then(Self::error_in) {
Some(error) => Err(error),
None => Ok(()),
}
}
fn error_in(raw: &str) -> Option<String> {
if !raw.starts_with('{') {
return None;
}
serde_json::from_str::<serde_json::Value>(raw)
.ok()?
.get("error")?
.as_str()
.map(str::to_string)
}
}
#[cfg(target_arch = "wasm32")]
impl KeyValueStore {
pub fn new() -> Self {
Self
}
pub fn prepare(&mut self) -> Result<(), String> {
Ok(())
}
fn store() -> Result<web_sys::Storage, String> {
web_sys::window()
.ok_or_else(|| "Window is not available".to_string())?
.local_storage()
.map_err(|_| "Local storage is not available".to_string())?
.ok_or_else(|| "Local storage is disabled".to_string())
}
pub fn get(&mut self, key: &str) -> Result<Option<String>, String> {
Self::store()?
.get_item(key)
.map_err(|_| "Unable to read from local storage".to_string())
}
pub fn set(&mut self, key: &str, value: &str) -> Result<(), String> {
Self::store()?
.set_item(key, value)
.map_err(|_| "Unable to write to local storage".to_string())
}
pub fn remove(&mut self, key: &str) -> Result<(), String> {
Self::store()?
.remove_item(key)
.map_err(|_| "Unable to remove from local storage".to_string())
}
pub fn clear(&mut self) -> Result<(), String> {
Self::store()?
.clear()
.map_err(|_| "Unable to clear local storage".to_string())
}
pub fn keys(&mut self) -> Result<Vec<String>, String> {
let store = Self::store()?;
let length = store
.length()
.map_err(|_| "Unable to read local storage".to_string())?;
let mut keys = Vec::new();
for index in 0..length {
if let Ok(Some(key)) = store.key(index) {
keys.push(key);
}
}
Ok(keys)
}
pub fn contains(&mut self, key: &str) -> Result<bool, String> {
Ok(self.get(key)?.is_some())
}
}
#[cfg(target_os = "macos")]
impl KeyValueStore {
pub fn new() -> Self {
Self
}
fn unimplemented<T>() -> Result<T, String> {
Err("Secure storage is not implemented on macOS".to_string())
}
pub fn prepare(&mut self) -> Result<(), String> {
Self::unimplemented()
}
pub fn get(&mut self, _key: &str) -> Result<Option<String>, String> {
Self::unimplemented()
}
pub fn set(&mut self, _key: &str, _value: &str) -> Result<(), String> {
Self::unimplemented()
}
pub fn remove(&mut self, _key: &str) -> Result<(), String> {
Self::unimplemented()
}
pub fn clear(&mut self) -> Result<(), String> {
Self::unimplemented()
}
pub fn keys(&mut self) -> Result<Vec<String>, String> {
Self::unimplemented()
}
pub fn contains(&mut self, _key: &str) -> Result<bool, String> {
Self::unimplemented()
}
}