use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::any::Any;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum PluginError {
#[error("插件初始化失败: {0}")]
InitFailed(String),
#[error("插件未找到: {0}")]
NotFound(String),
#[error("插件已禁用: {0}")]
Disabled(String),
#[error("方法未找到: {0}")]
MethodNotFound(String),
#[error("参数错误: {0}")]
InvalidParams(String),
#[error("执行错误: {0}")]
ExecutionError(String),
#[error("其他错误: {0}")]
Other(#[from] anyhow::Error),
}
pub type PluginResult<T> = Result<T, PluginError>;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PluginInfo {
pub name: String,
pub key: String,
pub hook: String,
pub version: String,
pub description: String,
pub author: String,
pub logo: String,
pub readme: String,
pub config: serde_json::Value,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginStatus {
Installed,
Enabled,
Disabled,
Error,
}
#[async_trait]
pub trait Plugin: Send + Sync {
fn info(&self) -> PluginInfo;
fn status(&self) -> PluginStatus {
PluginStatus::Enabled
}
async fn init(&mut self, _config: serde_json::Value) -> PluginResult<()> {
Ok(())
}
async fn ready(&mut self) -> PluginResult<()> {
Ok(())
}
async fn destroy(&mut self) -> PluginResult<()> {
Ok(())
}
async fn invoke(
&self,
method: &str,
_params: serde_json::Value,
) -> PluginResult<serde_json::Value> {
Err(PluginError::MethodNotFound(method.to_string()))
}
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}