use std::sync::Arc;
use std::time::Duration;
use futures::StreamExt;
use interloper::parse::extract_otp;
use interloper::regex::Regex;
use interloper::{Address, Inbox, Interloper, MailFilter, Message, Request};
use crate::error::ApiError;
use crate::fleet::HealthSync;
use crate::store::Store;
pub struct Service {
pub il: Interloper,
pub store: Store,
pub fleet: Option<Arc<HealthSync>>,
}
impl Service {
pub fn new(il: Interloper, store: Store) -> Arc<Self> {
Self::with_fleet(il, store, None)
}
pub fn with_fleet(il: Interloper, store: Store, fleet: Option<Arc<HealthSync>>) -> Arc<Self> {
Arc::new(Service { il, store, fleet })
}
pub async fn create(&self, req: &Request) -> Result<Address, ApiError> {
let inbox = self.il.inbox(req).await?;
let address = inbox.address().clone();
self.store.put(&address).await?;
Ok(address)
}
pub async fn inbox(&self, value: &str) -> Result<Inbox, ApiError> {
let address = self
.store
.get(value)
.await?
.ok_or(ApiError::UnknownAddress)?;
Ok(self.il.resume(address)?)
}
pub async fn clear_quarantine(&self, provider: &str) -> Result<bool, ApiError> {
match &self.fleet {
Some(f) => Ok(f.clear_quarantine(provider).await?),
None => Ok(self.il.health().unquarantine(provider)),
}
}
pub async fn get_message(
&self,
value: &str,
id: &str,
) -> Result<(Message, Option<String>), ApiError> {
let m = self.inbox(value).await?.get(id).await?;
let code = extract_otp(&m.subject, &m.text, None);
Ok((m, code))
}
pub async fn wait(
&self,
value: &str,
timeout: Duration,
pattern: Option<&Regex>,
want_otp: bool,
filter: &MailFilter,
) -> Result<Option<(Message, Option<String>)>, ApiError> {
let inbox = self.inbox(value).await?;
let search = async {
let mut stream = inbox.watch(None);
while let Some(m) = stream.next().await {
let m = m?;
if !filter.accepts(&m) {
continue;
}
let code = extract_otp(&m.subject, &m.text, pattern);
if want_otp && code.is_none() {
continue;
}
return Ok(Some((m, code)));
}
Ok(None)
};
match tokio::time::timeout(timeout, search).await {
Ok(r) => r,
Err(_) => Ok(None),
}
}
}