64 lines
1.9 KiB
Rust
64 lines
1.9 KiB
Rust
use std::{collections::HashMap, sync::Arc};
|
|
|
|
use ormlite::{Model, sqlite::SqliteConnection};
|
|
|
|
use crate::{
|
|
db::Db,
|
|
log_err,
|
|
models::Connection,
|
|
settings::{AsyncMutex, AsyncMutexGuard, Result},
|
|
};
|
|
|
|
#[async_trait::async_trait]
|
|
pub trait Event: Send + Sync {
|
|
async fn invoke(&self, context: &Context) -> Result<()>;
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Context {
|
|
db: Arc<AsyncMutex<SqliteConnection>>,
|
|
certificates: Arc<AsyncMutex<HashMap<String, (String, String)>>>,
|
|
on_update_ssl: Arc<AsyncMutex<Option<Arc<dyn Event>>>>,
|
|
}
|
|
impl Context {
|
|
pub async fn new() -> Self {
|
|
Context {
|
|
db: Db::connect().await,
|
|
certificates: AsyncMutex::new(HashMap::new()).into(),
|
|
on_update_ssl: AsyncMutex::new(None).into(),
|
|
}
|
|
}
|
|
|
|
pub async fn db(&'_ self) -> AsyncMutexGuard<'_, SqliteConnection> {
|
|
self.db.lock().await
|
|
}
|
|
|
|
pub async fn get_connection(&'_ self, domain: &str) -> Option<Connection> {
|
|
let mut conn = self.db().await;
|
|
Connection::fetch_one(domain, &mut *conn).await.ok()
|
|
}
|
|
|
|
pub async fn on_update_ssl(&self, event: Arc<dyn Event>) {
|
|
let mut on_update_ssl = self.on_update_ssl.lock().await;
|
|
*on_update_ssl = Some(event.clone());
|
|
}
|
|
|
|
pub async fn update_ssl(&self) {
|
|
let on_update_ssl = self.on_update_ssl.lock().await;
|
|
if let Some(event) = on_update_ssl.clone() {
|
|
if let Err(err) = event.invoke(self).await {
|
|
log_err!("Failed to update SSL: {}", err);
|
|
}
|
|
}
|
|
}
|
|
pub async fn add_cert(&self, domain: String, cert: (String, String)) {
|
|
let mut certificates = self.certificates.lock().await;
|
|
certificates.insert(domain, cert);
|
|
}
|
|
|
|
pub fn get_cert(&self, domain: &str) -> Option<(String, String)> {
|
|
let certificates = self.certificates.try_lock().ok()?;
|
|
certificates.get(domain).cloned()
|
|
}
|
|
}
|