phoebe/src/bridgers.rs

88 lines
2.9 KiB
Rust
Raw Normal View History

2021-09-12 02:59:13 +00:00
use std::{cell::RefCell, str::FromStr, sync::Mutex};
use sled::Db;
2021-09-12 02:59:13 +00:00
use crate::{
discord::{self, forward_to_discord},
matrix::{self, forward_to_matrix},
messages::{MessageReference, SentMessage},
2021-09-12 02:59:13 +00:00
};
pub struct Bridgers {
pub db: Db,
2021-09-12 02:59:13 +00:00
pub discord: Mutex<RefCell<Option<discord::Context>>>,
pub matrix: Mutex<RefCell<Option<matrix::Client>>>,
}
impl Bridgers {
pub fn new() -> Self {
let db = sled::open("data/phoebe.sled").expect("Failed to open database");
2021-09-12 02:59:13 +00:00
Self {
db,
2021-09-12 02:59:13 +00:00
discord: Mutex::new(RefCell::new(None)),
matrix: Mutex::new(RefCell::new(None)),
}
}
fn get_linked_discord_channel(&self, source: &MessageReference) -> Option<discord::ChannelId> {
match source {
MessageReference::Matrix(_room_id, _event_id) => {
// TODO: Look up the linked channel
Some(discord::ChannelId(885690775193661463))
}
_ => None,
}
}
fn get_linked_matrix_room(&self, source: &MessageReference) -> Option<matrix::RoomId> {
match source {
MessageReference::Discord(_, _) => {
// TODO: Look up the linked channel
Some(matrix::RoomId::from_str("!SjQatGOikRshcWNcln:matrix.org").unwrap())
}
_ => None,
}
}
pub async fn send_message(&self, message: SentMessage) -> Vec<MessageReference> {
let mut related_messages = vec![message.source.clone()];
2021-09-12 02:59:13 +00:00
if let Some(discord) = self.discord.lock().unwrap().borrow().as_ref() {
if let Some(channel) = self.get_linked_discord_channel(&message.source) {
if let Some(m) = forward_to_discord(discord, channel, &message).await {
related_messages.push(m);
2021-09-12 02:59:13 +00:00
}
}
2021-09-12 02:59:13 +00:00
}
if let Some(matrix) = self.matrix.lock().unwrap().borrow().as_ref() {
if let Some(room_id) = self.get_linked_matrix_room(&message.source) {
if let Some(m) = forward_to_matrix(matrix, room_id, &message).await {
related_messages.push(m);
2021-09-12 02:59:13 +00:00
}
}
}
for source in related_messages.iter() {
let relations = related_messages
.iter()
.filter(|r| r != &source)
.collect::<Vec<_>>();
let tree = self
.db
.open_tree("message_relations")
.expect("Failed to open relations tree");
tree.insert(
bincode::serialize(source).expect("Failed to serialize message reference"),
bincode::serialize(&relations).expect("Failed to serialize message relations"),
)
.expect("Failed to store message relations");
}
related_messages
2021-09-12 02:59:13 +00:00
}
}