use std::collections::HashMap;
use async_trait::async_trait;
use crate::plugin::{Plugin, PluginCommand, PluginMetadata};
use crate::http;
type PluginResult<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub struct HttpPlugin {
metadata: PluginMetadata,
}
impl HttpPlugin {
pub fn new() -> Self {
Self {
metadata: PluginMetadata {
name: "http".to_string(),
version: "1.0.0".to_string(),
description: "HTTP plugin for OpenScript".to_string(),
author: "OpenScript Team".to_string(),
license: "MIT".to_string(),
dependencies: vec!["reqwest".to_string()],
api_version: "1.0".to_string(),
},
}
}
}
#[async_trait]
impl Plugin for HttpPlugin {
fn metadata(&self) -> &PluginMetadata {
&self.metadata
}
async fn initialize(&mut self) -> PluginResult<()> {
Ok(())
}
fn register_commands(&self) -> HashMap<String, Box<dyn PluginCommand>> {
let mut commands = HashMap::new();
commands.insert("http_get".to_string(), Box::new(HttpGetCommand) as Box<dyn PluginCommand>);
commands.insert("http_post".to_string(), Box::new(HttpPostCommand) as Box<dyn PluginCommand>);
commands
}
async fn cleanup(&mut self) -> PluginResult<()> {
Ok(())
}
}
struct HttpGetCommand;
#[async_trait]
impl PluginCommand for HttpGetCommand {
async fn execute(&self, args: &[String]) -> PluginResult<String> {
if args.is_empty() {
return Err("http_get() requires a URL".into());
}
let url = &args[0];
let headers = HashMap::new();
let result = http::http_get(url, headers).await.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
Ok(result.to_string())
}
fn help(&self) -> &str {
"Sends an HTTP GET request."
}
fn usage(&self) -> &str {
"http_get <url> [headers]"
}
}
struct HttpPostCommand;
#[async_trait]
impl PluginCommand for HttpPostCommand {
async fn execute(&self, args: &[String]) -> PluginResult<String> {
if args.len() < 2 {
return Err("http_post() requires a URL and a body".into());
}
let url = &args[0];
let body = &args[1];
let headers = HashMap::new();
let result = http::http_post(url, body, headers).await.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
Ok(result.to_string())
}
fn help(&self) -> &str {
"Sends an HTTP POST request."
}
fn usage(&self) -> &str {
"http_post <url> <body> [headers]"
}
}