feat: PipeRUN API running

This commit is contained in:
Jelson Stoelben Rodrigues
2025-06-07 08:16:04 -03:00
commit 33101951bc
7 changed files with 2147 additions and 0 deletions

7
src/.env.example Normal file
View File

@@ -0,0 +1,7 @@
OLLAMA_URL=localhost
OLLAMA_PORT=11432
PIPERUN_API_URL=novanet.cxm.pipe.run
PIPERUN_CLIENT_ID=0
PIPERUN_CLIENT_SECRET=
PIPERUN_BOT_USERNAME=
PIPERUN_BOT_PASSWORD=

7
src/config.rs Normal file
View File

@@ -0,0 +1,7 @@
const OLLAMA_URL: str = "localhost";
const OLLAMA_PORT: str = 11434;
const PIPERUN_API_URL: str = "novanet.cxm.pipe.run";
const PIPERUN_CLIENT_ID: i32 = 0;
const PIPERUN_CLIENT_SECRET: str = "";
const PIPERUN_BOT_USERNAME: str = "";
const PIPERUN_BOT_PASSWORD: str = "";

239
src/main.rs Normal file
View File

@@ -0,0 +1,239 @@
use std::{any::Any, env, iter};
// use http::{self, response};
use chrono::{self, Timelike};
use dotenv;
use reqwest;
use serde_json;
fn main() {
match dotenv::dotenv().ok() {
Some(_) => println!("Environment variables loaded from .env file"),
None => eprintln!("Failed to load .env file"),
}
// Read environment variables
let OLLAMA_URL = env::var("OLLAMA_URL").unwrap_or("localhost".to_string());
let OLLAMA_PORT = env::var("OLLAMA_PORT")
.unwrap_or("11432".to_string())
.parse::<u16>()
.unwrap_or(11432);
let PIPERUN_API_URL = env::var("PIPERUN_API_URL").expect("PIPERUN_API_URL has not been set!");
let PIPERUN_CLIENT_ID = env::var("PIPERUN_CLIENT_ID")
.expect("PIPERUN_CLIENT_ID has not been set!")
.parse::<i32>()
.unwrap_or(0);
let PIPERUN_CLIENT_SECRET =
env::var("PIPERUN_CLIENT_SECRET").expect("PIPERUN_CLIENT_SECRET has not been set!");
let PIPERUN_BOT_USERNAME =
env::var("PIPERUN_BOT_USERNAME").expect("PIPERUN_BOT_USERNAME has not been set!");
let PIPERUN_BOT_PASSWORD =
env::var("PIPERUN_BOT_PASSWORD").expect("PIPERUN_BOT_PASSWORD has not been set!");
// Print the configuration
println!("OLLAMA_URL: {}", OLLAMA_URL);
println!("OLLAMA_PORT: {}", OLLAMA_PORT);
println!("PIPERUN_API_URL: {}", PIPERUN_API_URL);
println!("PIPERUN_CLIENT_ID: {}", PIPERUN_CLIENT_ID);
println!("PIPERUN_CLIENT_SECRET: {}", PIPERUN_CLIENT_SECRET);
println!("PIPERUN_BOT_USERNAME: {}", PIPERUN_BOT_USERNAME);
println!("PIPERUN_BOT_PASSWORD: {}", PIPERUN_BOT_PASSWORD);
// Authenticate with Piperun API
// Send the authentication request
let client = reqwest::blocking::Client::new();
let auth_request = client
.post(format!("https://{}/oauth/token", PIPERUN_API_URL))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.body(
serde_json::json!({
"grant_type": "password",
"client_id": PIPERUN_CLIENT_ID,
"client_secret": PIPERUN_CLIENT_SECRET,
"username": PIPERUN_BOT_USERNAME,
"password": PIPERUN_BOT_PASSWORD,
})
.to_string(),
);
println!("Sending authentication request to Piperun API...");
println!("{:?}", auth_request);
let response = auth_request.send();
let access_token = match response {
Ok(resp) => {
if resp.status().is_success() {
let json: serde_json::Value = resp.json().unwrap();
// println!("Authentication successful: {:?}", json);
// Extract the access token
if let Some(access_token) = json.get("access_token") {
println!("Access Token: {}", access_token);
access_token
.as_str()
.expect("Failed to get token")
.to_string()
} else {
eprintln!("Access token not found in response");
panic!("Failed to retrieve access token from Piperun API");
}
} else {
eprintln!("Authentication failed: {}", resp.status());
let json: serde_json::Value = resp.json().unwrap();
eprintln!("Response body: {:?}", json);
panic!("Failed to authenticate with Piperun API");
}
}
Err(e) => {
eprintln!("Error sending authentication request: {}", e);
panic!("Failed to send authentication request to Piperun API");
}
};
// Get the current day in the format YYYY-MM-DD
let current_date = chrono::Local::now();
let formatted_date = current_date.format("%Y-%m-%d").to_string();
println!("Current date: {}", formatted_date);
// Get the day before the current date
let day_before = current_date
.checked_sub_signed(chrono::Duration::days(1))
.expect("Failed to get the day before");
let formatted_day_before = day_before.format("%Y-%m-%d").to_string();
println!("Day before: {}", formatted_day_before);
let day_before_at_midnight = day_before
.with_hour(0)
.unwrap()
.with_minute(0)
.unwrap()
.with_second(0)
.unwrap();
let formatted_day_before_at_midnight =
day_before_at_midnight.format("%Y-%m-%d %H:%M").to_string();
let day_before_at_23_59_59 = day_before
.with_hour(23)
.unwrap()
.with_minute(59)
.unwrap()
.with_second(59)
.unwrap();
let formatted_day_before_at_23_59_59 =
day_before_at_23_59_59.format("%Y-%m-%d %H:%M").to_string();
println!(
"Day before at midnight: {}, Day before at 23:59:59: {}",
formatted_day_before_at_midnight, formatted_day_before_at_23_59_59
);
let start_of_talk_code: String = "1".to_string();
let support_queue_id: String = "13".to_string();
// Get the list of consolidated talks from the day before
let talks_request = client
.get(format!(
"https://{}/api/reports/talks/consolidated",
PIPERUN_API_URL
))
.bearer_auth(&access_token)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.query(&[
("start_date", formatted_day_before_at_midnight),
("end_date", formatted_day_before_at_23_59_59),
("date_range_type", start_of_talk_code),
("queue_id[]", support_queue_id),
]);
println!("Sending request for consolidated talks... {talks_request:?}");
let talks_response = talks_request.send();
let talks = match talks_response {
Ok(resp) => {
if resp.status().is_success() {
let json: serde_json::Value = resp.json().unwrap();
// println!("Consolidated talks response: {:?}", json);
json
} else {
eprintln!("Failed to get consolidated talks: {}", resp.status());
let json: serde_json::Value = resp.json().unwrap();
eprintln!("Response body: {:?}", json);
panic!("Failed to retrieve consolidated talks from Piperun API");
}
}
Err(e) => {
eprintln!("Error sending request for consolidated talks: {}", e);
panic!("Failed to send request for consolidated talks to Piperun API");
}
};
let talks_array = talks
.as_array()
.expect("Failed to parse talks response as array");
// talks_array.iter().for_each(|talk| println!("{talk}"));
println!("Number of consolidated talks: {}", talks_array.len());
let talk_ids = talks_array
.iter()
.cloned()
.map(|value| {
serde_json::from_value::<serde_json::Value>(value).expect("Failed to parse the JSON")
["id"]
.clone()
.to_string()
})
.collect::<Vec<String>>();
println!("IDS {:?}", talk_ids);
talk_ids
.iter()
.cloned()
.map(|talk_id| {
let talk_id_get_request = client
.get(format!("https://{}/api/talk_histories", PIPERUN_API_URL))
.bearer_auth(&access_token)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.query(&[
("talk_id", talk_id),
("type", "a".to_string()),
("only_view", "1".to_string()),
]);
let talk_id_get_result = talk_id_get_request.send();
return talk_id_get_result;
})
.take(1)
.for_each(|result| {
let json = result.unwrap().json::<serde_json::Value>().expect("Failed to deserialize response to JSON");
let talk_histories = &json["talk_histories"];
let data = &talk_histories["data"];
talk_histories.as_array().expect("Wrong message type received from talk histories").iter().rev().for_each(|message_object|
{
println!("Message obj: {:?}", message_object)
});
// println!("Whole talk Histories \n\n{:?}", talk_histories);
// println!("\n\nData Only\n\n{:?}", data);
// println!(
// "{:?}",
// result
// .unwrap()
// .json::<serde_json::Value>()
// .expect("Failed to deserialize response to JSON")["talk_histories"]
// )
});
}