generalize get config

This commit is contained in:
jb-alvarado 2022-06-17 19:01:53 +02:00
parent f9a82b4f93
commit 8e3194813d

View File

@ -1,13 +1,14 @@
use log::error;
use reqwest::{
header::{HeaderMap, AUTHORIZATION, CONTENT_TYPE},
Client, Response,
};
use serde::{Deserialize, Serialize};
use simplelog::*;
use crate::api::{
errors::ServiceError, handles::db_get_settings, models::TextPreset, utils::read_playout_config,
};
use crate::utils::PlayoutConfig;
#[derive(Debug, Deserialize, Serialize, Clone)]
struct RpcObj<T> {
@ -34,47 +35,53 @@ impl<T> RpcObj<T> {
}
}
fn create_header(content: &str, auth: &str) -> HeaderMap {
fn create_header(auth: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, content.parse().unwrap());
headers.insert(
CONTENT_TYPE,
"Content-Type: application/json".parse().unwrap(),
);
headers.insert(AUTHORIZATION, auth.parse().unwrap());
headers
}
pub async fn send_message(id: i64, msg: TextPreset) -> Result<Response, ServiceError> {
let client = Client::new();
if let Ok(settings) = db_get_settings(&id).await {
async fn playout_config(channel_id: &i64) -> Result<PlayoutConfig, ServiceError> {
if let Ok(settings) = db_get_settings(channel_id).await {
if let Ok(config) = read_playout_config(&settings.config_path) {
let url = format!("http://{}", config.rpc_server.address);
let json_obj = RpcObj::new(
id,
"player".into(),
TextParams {
control: "text".into(),
message: msg,
},
);
match client
.post(&url)
.headers(create_header(
"Content-Type: application/json",
&config.rpc_server.authorization,
))
.json(&json_obj)
.send()
.await
{
Ok(result) => return Ok(result),
Err(e) => {
error!("{e:?}");
return Err(ServiceError::BadRequest(e.to_string()));
}
};
return Ok(config);
}
};
}
Err(ServiceError::InternalServerError)
Err(ServiceError::BadRequest(
"Error in getting config!".to_string(),
))
}
pub async fn send_message(id: i64, message: TextPreset) -> Result<Response, ServiceError> {
let config = playout_config(&id).await?;
let url = format!("http://{}", config.rpc_server.address);
let client = Client::new();
let json_obj = RpcObj::new(
id,
"player".into(),
TextParams {
control: "text".into(),
message,
},
);
match client
.post(&url)
.headers(create_header(&config.rpc_server.authorization))
.json(&json_obj)
.send()
.await
{
Ok(result) => Ok(result),
Err(e) => {
error!("{e:?}");
Err(ServiceError::BadRequest(e.to_string()))
}
}
}