use super::{twirp_client::TwirpClient, ServiceBase, ServiceResult, LIVEKIT_PACKAGE};
use crate::{
access_token::{AccessTokenError, VideoGrants},
get_env_keys,
};
use http::header::HeaderMap;
use livekit_protocol as proto;
const SVC: &str = "AgentDispatchService";
#[derive(Debug)]
pub struct AgentDispatchClient {
base: ServiceBase,
client: TwirpClient,
}
impl AgentDispatchClient {
pub fn with_api_key(host: &str, api_key: &str, api_secret: &str) -> Self {
Self {
base: ServiceBase::with_api_key(api_key, api_secret),
client: TwirpClient::new(host, LIVEKIT_PACKAGE, None),
}
}
pub fn new(host: &str) -> ServiceResult<Self> {
let (api_key, api_secret) = get_env_keys()?;
Ok(Self::with_api_key(host, &api_key, &api_secret))
}
pub async fn create_dispatch(
&self,
req: proto::CreateAgentDispatchRequest,
) -> ServiceResult<proto::AgentDispatch> {
const METHOD: &str = "CreateDispatch";
let headers = self.auth_headers(req.room.to_string())?;
Ok(self.client.request(SVC, METHOD, req, headers).await?)
}
pub async fn delete_dispatch(
&self,
dispatch_id: impl Into<String>,
room_name: impl Into<String>,
) -> ServiceResult<proto::AgentDispatch> {
const METHOD: &str = "DeleteDispatch";
let req = proto::DeleteAgentDispatchRequest {
dispatch_id: dispatch_id.into(),
room: room_name.into(),
};
let headers = self.auth_headers(req.room.to_string())?;
Ok(self.client.request(SVC, METHOD, req, headers).await?)
}
pub async fn list_dispatch(
&self,
room_name: impl Into<String>,
) -> ServiceResult<Vec<proto::AgentDispatch>> {
const METHOD: &str = "ListDispatch";
let req = proto::ListAgentDispatchRequest { room: room_name.into(), ..Default::default() };
let headers = self.auth_headers(req.room.to_string())?;
let res: proto::ListAgentDispatchResponse =
self.client.request(SVC, METHOD, req, headers).await?;
Ok(res.agent_dispatches)
}
pub async fn get_dispatch(
&self,
dispatch_id: impl Into<String>,
room_name: impl Into<String>,
) -> ServiceResult<Option<proto::AgentDispatch>> {
const METHOD: &str = "ListDispatch";
let req = proto::ListAgentDispatchRequest {
room: room_name.into(),
dispatch_id: dispatch_id.into(),
};
let headers = self.auth_headers(req.room.to_string())?;
let mut res: proto::ListAgentDispatchResponse =
self.client.request(SVC, METHOD, req, headers).await?;
Ok(res.agent_dispatches.pop())
}
}
impl AgentDispatchClient {
fn auth_headers(&self, room: String) -> Result<HeaderMap, AccessTokenError> {
self.base.auth_header(VideoGrants { room, room_admin: true, ..Default::default() }, None)
}
}