use buttplug_core::errors::ButtplugDeviceError;
use dashmap::DashMap;
use getset::Getters;
use std::{
collections::HashMap,
fmt::{self, Debug},
};
use uuid::Uuid;
use crate::{
BaseDeviceIdentifier,
ButtplugDeviceConfigError,
ProtocolCommunicationSpecifier,
ServerDeviceDefinition,
ServerDeviceDefinitionBuilder,
UserDeviceIdentifier,
};
#[derive(Default, Clone)]
pub struct DeviceConfigurationManagerBuilder {
base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
user_communication_specifiers: DashMap<String, Vec<ProtocolCommunicationSpecifier>>,
base_device_definitions: HashMap<BaseDeviceIdentifier, ServerDeviceDefinition>,
user_device_definitions: DashMap<UserDeviceIdentifier, ServerDeviceDefinition>,
}
impl DeviceConfigurationManagerBuilder {
pub fn communication_specifier(
&mut self,
protocol_name: &str,
specifier: &[ProtocolCommunicationSpecifier],
) -> &mut Self {
self
.base_communication_specifiers
.entry(protocol_name.to_owned())
.or_default()
.extend(specifier.iter().cloned());
self
}
pub fn base_device_definition(
&mut self,
identifier: &BaseDeviceIdentifier,
features: &ServerDeviceDefinition,
) -> &mut Self {
self
.base_device_definitions
.insert(identifier.clone(), features.clone());
self
}
pub fn user_communication_specifier(
&mut self,
protocol_name: &str,
specifier: &[ProtocolCommunicationSpecifier],
) -> &mut Self {
self
.user_communication_specifiers
.entry(protocol_name.to_owned())
.or_default()
.extend(specifier.iter().cloned());
self
}
pub fn user_device_definition(
&mut self,
identifier: &UserDeviceIdentifier,
device_definition: &ServerDeviceDefinition,
) -> Result<&mut Self, ButtplugDeviceConfigError> {
if self
.base_device_definitions
.iter()
.any(|(_, x)| x.id() == device_definition.base_id().unwrap_or_default())
{
self
.user_device_definitions
.insert(identifier.clone(), device_definition.clone());
Ok(self)
} else {
error!(
"Cannot find protocol with base id {:?} for user id {}",
device_definition.base_id(),
device_definition.id()
);
Err(ButtplugDeviceConfigError::BaseIdNotFound(
device_definition.id(),
))
}
}
pub fn finish(&mut self) -> Result<DeviceConfigurationManager, ButtplugDeviceError> {
let mut attribute_tree_map = HashMap::new();
for (ident, attr) in &self.base_device_definitions {
attribute_tree_map.insert(ident.clone(), attr.clone());
}
let user_attribute_tree_map = DashMap::new();
for kv in &self.user_device_definitions {
user_attribute_tree_map.insert(kv.key().clone(), kv.value().clone());
}
Ok(DeviceConfigurationManager {
base_communication_specifiers: self.base_communication_specifiers.clone(),
user_communication_specifiers: self.user_communication_specifiers.clone(),
base_device_definitions: attribute_tree_map,
user_device_definitions: user_attribute_tree_map,
})
}
}
#[derive(Getters)]
#[getset(get = "pub(crate)")]
pub struct DeviceConfigurationManager {
#[getset(get = "pub")]
base_communication_specifiers: HashMap<String, Vec<ProtocolCommunicationSpecifier>>,
base_device_definitions: HashMap<BaseDeviceIdentifier, ServerDeviceDefinition>,
#[getset(get = "pub")]
user_communication_specifiers: DashMap<String, Vec<ProtocolCommunicationSpecifier>>,
#[getset(get = "pub")]
user_device_definitions: DashMap<UserDeviceIdentifier, ServerDeviceDefinition>,
}
impl Debug for DeviceConfigurationManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeviceConfigurationManager").finish()
}
}
impl Default for DeviceConfigurationManager {
fn default() -> Self {
DeviceConfigurationManagerBuilder::default()
.finish()
.expect("Default creation of a DCM should always work.")
}
}
impl DeviceConfigurationManager {
pub fn add_user_communication_specifier(
&self,
protocol: &str,
specifier: &ProtocolCommunicationSpecifier,
) -> Result<(), ButtplugDeviceError> {
self
.user_communication_specifiers
.entry(protocol.to_owned())
.or_default()
.push(specifier.clone());
Ok(())
}
pub fn remove_user_communication_specifier(
&self,
protocol: &str,
specifier: &ProtocolCommunicationSpecifier,
) {
if let Some(mut specifiers) = self.user_communication_specifiers.get_mut(protocol) {
let specifier_vec = specifiers.value_mut();
*specifier_vec = specifier_vec
.iter()
.filter(|s| *specifier != **s)
.cloned()
.collect();
}
}
pub fn add_user_device_definition(
&self,
identifier: &UserDeviceIdentifier,
definition: &ServerDeviceDefinition,
) {
self
.user_device_definitions
.insert(identifier.clone(), definition.clone());
}
pub fn remove_user_device_definition(&self, identifier: &UserDeviceIdentifier) {
self.user_device_definitions.remove(identifier);
}
pub fn address_allowed(&self, address: &str) -> bool {
if self
.user_device_definitions
.iter()
.any(|kv| kv.key().address() == address && kv.value().deny())
{
info!(
"Device {} denied by configuration, not connecting.",
address
);
false
} else if self
.user_device_definitions
.iter()
.any(|kv| kv.value().allow())
&& !self
.user_device_definitions
.iter()
.any(|kv| kv.key().address() == address && kv.value().allow())
{
info!(
"Device {} not on allow list and allow list not empty, not connecting.",
address
);
false
} else {
true
}
}
fn device_index(&self, identifier: &UserDeviceIdentifier) -> u32 {
if let Some(config) = self.user_device_definitions.get(identifier) {
let index = config.index();
debug!("Found index {index} for device {identifier:?}");
return index;
}
let current_indexes: Vec<u32> = self
.user_device_definitions
.iter()
.map(|x| x.index())
.collect();
let mut index = 0;
while current_indexes.contains(&index) {
index += 1;
}
debug!("Generating and assigning index {index:?} for device {identifier:?}");
index
}
pub fn device_definition(
&self,
identifier: &UserDeviceIdentifier,
) -> Option<ServerDeviceDefinition> {
let features = if let Some(definition) = self.user_device_definitions.get(identifier) {
debug!("User device config found for {:?}", identifier);
definition.clone()
} else if let Some(definition) = self.base_device_definitions.get(&BaseDeviceIdentifier::new(
identifier.protocol(),
identifier.identifier(),
)) {
debug!(
"Protocol + Identifier device config found for {:?}, creating new user device from configuration",
identifier
);
let mut builder = ServerDeviceDefinitionBuilder::from_base(definition, Uuid::new_v4(), true);
builder.index(self.device_index(identifier)).finish()
} else if let Some(definition) = self
.base_device_definitions
.get(&BaseDeviceIdentifier::new(identifier.protocol(), &None))
{
debug!(
"Protocol device config found for {:?}, creating new user device from protocol defaults",
identifier
);
let mut builder = ServerDeviceDefinitionBuilder::from_base(definition, Uuid::new_v4(), true);
builder.index(self.device_index(identifier)).finish()
} else {
return None;
};
if self.user_device_definitions.get(identifier).is_none() {
self
.user_device_definitions
.insert(identifier.clone(), features.clone());
}
Some(features)
}
}