use crate::cache::get_hash;
use crate::common::{deserialize_from_json, get_hash_item, serialize_to_json};
use crate::constants::{REGIONS_KEY, REGION_IDENTS_KEY};
use crate::get_hash_all_values;
use cal_core::Region;
use redis::aio::MultiplexedConnection;
use redis::{AsyncCommands, RedisError, Value};
pub async fn get_regions(con: MultiplexedConnection) -> Result<Vec<Region>, RedisError> {
println!("Getting regions from key: {}", REGIONS_KEY);
let region_str: Vec<String> = get_hash_all_values(con.clone(), REGIONS_KEY).await?;
println!("Regions size: {}", region_str.len());
let mut regions: Vec<Region> = Vec::with_capacity(region_str.len());
for str in region_str {
regions.push(deserialize_from_json::<Region>(&str)?);
}
Ok(regions)
}
pub async fn get_region_by_ident(
con: MultiplexedConnection,
key: &str,
) -> Result<Option<Region>, RedisError> {
println!("Getting region by ident {} from key: {}", key, REGION_IDENTS_KEY);
match get_hash(con.clone(), REGION_IDENTS_KEY, key).await? {
Some(region_id) => {
get_region_by_id(con, ®ion_id).await
},
None => Ok(None),
}
}
pub async fn get_region_by_id(
con: MultiplexedConnection,
key: &str,
) -> Result<Option<Region>, RedisError> {
println!("Getting region by id {} from key: {}", key, REGIONS_KEY);
get_hash_item(con, REGIONS_KEY, key).await
}
pub async fn insert_region(
mut con: MultiplexedConnection,
region: Region,
) -> Result<(), RedisError> {
let value = serialize_to_json(®ion)?;
let _: String = con
.hset(REGIONS_KEY, region.id.to_string(), value)
.await?;
build_region_idents(&mut con, ®ion).await?;
Ok(())
}
pub async fn insert_region_idents(
mut con: MultiplexedConnection,
items: &[(String, String)],
) -> Result<Value, RedisError> {
let result: Value = con.hset_multiple(REGION_IDENTS_KEY, items).await?;
Ok(result)
}
async fn build_region_idents(
con: &mut MultiplexedConnection,
region: &Region,
) -> Result<(), RedisError> {
let mut ident_entries = vec![
(region.id.to_string(), region.id.to_string())
];
for vs in ®ion.voice_servers {
ident_entries.push((vs.id.clone(), region.id.to_string()));
ident_entries.push((vs.public_ip.clone(), region.id.to_string()));
ident_entries.push((vs.private_ip.clone(), region.id.to_string()));
}
let _: Value = con.hset_multiple(REGION_IDENTS_KEY, &ident_entries).await?;
Ok(())
}