plugin_framework, plugin manager

Signed-off-by: fufesou <shuanglongchen@yeah.net>
This commit is contained in:
fufesou
2023-04-22 22:21:02 +08:00
parent b1b867dd9d
commit ae789ff5f1
7 changed files with 421 additions and 70 deletions

View File

@@ -1,3 +1,5 @@
use crate::plugins::Plugin;
use super::desc::ConfigItem;
use hbb_common::{bail, config::Config as HbbConfig, lazy_static, ResultType};
use serde_derive::{Deserialize, Serialize};
@@ -12,6 +14,10 @@ lazy_static::lazy_static! {
static ref CONFIG_LOCAL_ITEMS: Arc<Mutex<HashMap<String, Vec<ConfigItem>>>> = Default::default();
static ref CONFIG_PEERS: Arc<Mutex<HashMap<String, PeersConfig>>> = Default::default();
static ref CONFIG_PEER_ITEMS: Arc<Mutex<HashMap<String, Vec<ConfigItem>>>> = Default::default();
static ref CONFIG_MANAGER: Arc<Mutex<ManagerConfig>> = {
let conf = hbb_common::config::load_path::<ManagerConfig>(ManagerConfig::path());
Arc::new(Mutex::new(conf))
};
}
pub(super) const CONFIG_TYPE_LOCAL: &str = "local";
@@ -178,3 +184,78 @@ pub(super) fn set_peer_items(id: &str, items: &Vec<ConfigItem>) {
.unwrap()
.insert(id.to_owned(), items.clone());
}
#[derive(Debug, Serialize, Deserialize)]
pub struct PluginStatus {
pub enabled: bool,
}
const MANAGER_VERSION: &str = "0.1.0";
#[derive(Debug, Serialize, Deserialize)]
pub struct ManagerConfig {
pub version: String,
pub enabled: bool,
pub plugins: HashMap<String, PluginStatus>,
}
impl Default for ManagerConfig {
fn default() -> Self {
Self {
version: "0.1.0".to_owned(),
enabled: true,
plugins: HashMap::new(),
}
}
}
// Do not care about the `store_path` error, no need to store the old value and restore if failed.
impl ManagerConfig {
#[inline]
fn path() -> PathBuf {
HbbConfig::path("plugins").join("manager.toml")
}
#[inline]
pub fn is_enabled() -> bool {
CONFIG_MANAGER.lock().unwrap().enabled
}
#[inline]
pub fn set_enabled(enabled: bool) -> ResultType<()> {
let mut lock = CONFIG_MANAGER.lock().unwrap();
lock.enabled = enabled;
hbb_common::config::store_path(Self::path(), &*lock)
}
#[inline]
pub fn get_plugin_status<T>(id: &str, f: fn(&PluginStatus) -> T) -> Option<T> {
let lock = CONFIG_MANAGER.lock().unwrap();
lock.plugins.get(id).map(f)
}
pub fn set_plugin_enabled(id: &str, enabled: bool) -> ResultType<()> {
let mut lock = CONFIG_MANAGER.lock().unwrap();
if let Some(status) = lock.plugins.get_mut(id) {
status.enabled = enabled;
hbb_common::config::store_path(Self::path(), &*lock)
} else {
bail!("No such plugin {}", id)
}
}
#[inline]
pub fn add_plugin(id: &str) -> ResultType<()> {
let mut lock = CONFIG_MANAGER.lock().unwrap();
lock.plugins
.insert(id.to_owned(), PluginStatus { enabled: true });
hbb_common::config::store_path(Self::path(), &*lock)
}
#[inline]
pub fn remove_plugin(id: &str) -> ResultType<()> {
let mut lock = CONFIG_MANAGER.lock().unwrap();
lock.plugins.remove(id);
hbb_common::config::store_path(Self::path(), &*lock)
}
}