webcomment/src/notify.rs

65 lines
1.4 KiB
Rust

use crate::config::Config;
use crossbeam_channel::Receiver;
use matrix_sdk::ruma;
use std::sync::Arc;
struct Notifier {
matrix: Option<(matrix_sdk::Client, matrix_sdk::room::Joined)>,
}
impl Notifier {
async fn new(config: &Config) -> Self {
Self {
matrix: if config.matrix_notify {
let user = ruma::UserId::parse(&config.matrix_user).unwrap();
let client = matrix_sdk::Client::builder()
.homeserver_url(&config.matrix_server)
.user_agent("Webcomment")
.build()
.await
.unwrap();
client
.login_username(&user, &config.matrix_password)
.send()
.await
.unwrap();
client
.sync_once(matrix_sdk::config::SyncSettings::default())
.await
.unwrap();
let room_id = <&ruma::RoomId>::try_from(config.matrix_room.as_str()).unwrap();
let room = client.get_room(room_id).unwrap();
if let matrix_sdk::room::Room::Joined(room) = room {
Some((client, room))
} else {
None
}
} else {
None
},
}
}
async fn notify(&self) {
if let Some((_client, room)) = &self.matrix {
room.send(
ruma::events::room::message::RoomMessageEventContent::text_plain("New comment."),
None,
)
.await
.unwrap();
}
}
}
pub async fn run_notifier(config: Arc<Config>, recv: Receiver<()>) {
let notifier = Notifier::new(&config).await;
for () in recv {
notifier.notify().await;
}
}