use ryuk::{
push::{Notification, Push},
queue::{Job, JobContext, JobError, Queue},
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use tokio::sync::OnceCell;
#[derive(Serialize, Deserialize)]
pub struct SendPush {
pub user_id: i64,
pub title: Option<String>,
pub body: Option<String>,
#[serde(default)]
pub data: BTreeMap<String, String>,
pub badge: Option<u32>,
pub collapse_key: Option<String>,
}
static PUSH: OnceCell<Push> = OnceCell::const_new();
impl Job for SendPush {
const NAME: &'static str = "send_push";
async fn handle(self, ctx: &JobContext) -> Result<(), JobError> {
let push = PUSH.get_or_try_init(|| Push::from_env(ctx.db.clone())).await.map_err(|e| JobError(e.to_string()))?;
let mut n = Notification::new();
if let Some(t) = self.title {
n = n.title(t);
}
if let Some(b) = self.body {
n = n.body(b);
}
for (k, v) in self.data {
n = n.data(k, v);
}
if let Some(b) = self.badge {
n = n.badge(b);
}
if let Some(c) = self.collapse_key {
n = n.collapse_key(c);
}
let r = push.send_to_user(self.user_id, &n).await.map_err(|e| JobError(e.to_string()))?;
tracing::info!(user_id = self.user_id, sent = r.sent, failed = r.failed, invalidated = r.invalidated, "push job");
Ok(())
}
}
pub async fn notify<'a>(
queue: &Queue,
user_id: i64,
title: &str,
body: &str,
data: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Result<(), sea_orm::DbErr> {
queue
.dispatch(SendPush {
user_id,
title: Some(title.into()),
body: Some(body.into()),
data: data.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
badge: None,
collapse_key: None,
})
.await
}