muchrooms/src/room.rs

197 lines
6.2 KiB
Rust
Raw Normal View History

// Copyright (C) 2022-2099 The crate authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
// for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::component::ComponentTrait;
use crate::error::Error;
use std::collections::HashMap;
use std::iter::IntoIterator;
use chrono;
use log::debug;
use xmpp_parsers::{
date::DateTime,
delay::Delay,
message::{Message, MessageType, Subject},
muc::{
user::{Affiliation, Item as MucItem, Role, Status as MucStatus},
MucUser,
},
presence::{Presence, Type as PresenceType},
BareJid, FullJid, Jid,
};
pub type Nick = String;
#[derive(Debug)]
pub struct Room {
pub jid: BareJid,
pub occupants: HashMap<BareJid, Occupant>,
// TODO: Subject struct.
// TODO: Store subject lang
pub subject: Option<(String, Occupant, DateTime)>,
}
impl Room {
pub fn new(jid: BareJid) -> Self {
Room {
jid,
occupants: HashMap::new(),
subject: None,
}
}
pub async fn add_session<C: ComponentTrait>(
&mut self,
component: &mut C,
realjid: FullJid,
nick: Nick,
) -> Result<(), Error> {
let bare = BareJid::from(realjid.clone());
if let Some(occupant) = self.occupants.get_mut(&bare) {
occupant.add_session(realjid)?;
} else {
debug!("{} is joining {}", realjid, self.jid);
let new_occupant = Occupant::new(&self, realjid.clone(), nick.clone());
// Ensure nick isn't already assigned
let _ = self.occupants.iter().try_for_each(|(_, occupant)| {
let nick = nick.clone();
if occupant.nick == nick {
return Err(Error::NickAlreadyAssigned(nick));
}
Ok(())
})?;
// Send occupants
debug!("Sending occupants for {}", realjid);
let presence = Presence::new(PresenceType::None)
// New occupant with a single session
.with_to(new_occupant.sessions[0].clone())
.with_payloads(vec![MucUser {
status: Vec::new(),
items: vec![MucItem::new(Affiliation::Owner, Role::Moderator)],
}.into()]);
for (_, occupant) in self.occupants.iter() {
let presence = presence.clone()
.with_from(occupant.participant.clone());
component.send_stanza(presence).await?;
}
// Add into occupants
let _ = self.occupants.insert(bare.clone(), new_occupant.clone());
// Self-presence
debug!("Sending self-presence for {}", realjid);
let participant: FullJid = self.jid.clone().with_resource(nick);
let status = vec![MucStatus::SelfPresence, MucStatus::AssignedNick];
let items = vec![MucItem::new(Affiliation::Owner, Role::Moderator)];
let self_presence = Presence::new(PresenceType::None)
.with_from(participant.clone())
.with_to(realjid.clone())
.with_payloads(vec![MucUser { status, items }.into()]);
component.send_stanza(self_presence).await?;
// Send subject
debug!("Sending subject!");
if self.subject.is_none() {
let subject = String::from("");
let setter = new_occupant;
let stamp = DateTime::from_utc(chrono::Utc::now());
self.subject = Some((subject, setter, stamp));
}
let mut subject = Message::new(Some(Jid::Full(realjid)));
subject.from = Some(Jid::Full(
self.subject.as_ref().unwrap().1.participant.clone(),
));
subject.subjects.insert(
String::from("en"),
Subject(self.subject.as_ref().unwrap().0.clone()),
);
subject.type_ = MessageType::Groupchat;
subject.payloads = vec![Delay {
from: Some(Jid::Bare(self.jid.clone())),
stamp: self.subject.as_ref().unwrap().2.clone(),
data: None,
}
.into()];
component.send_stanza(subject).await?;
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct Occupant {
/// Public Jid for the Occupant
real: BareJid,
participant: FullJid,
nick: Nick,
sessions: Vec<FullJid>,
}
impl Occupant {
fn new(room: &Room, real: FullJid, nick: Nick) -> Occupant {
Occupant {
real: BareJid::from(real.clone()),
participant: room.jid.clone().with_resource(nick.clone()),
nick,
sessions: vec![real],
}
}
pub fn add_session(&mut self, real: FullJid) -> Result<(), Error> {
if BareJid::from(real.clone()) != self.real {
return Err(Error::MismatchJids(Jid::from(real.clone())));
}
Ok(())
}
}
impl IntoIterator for Occupant {
type Item = FullJid;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.sessions.into_iter()
}
}
impl Occupant {
fn iter(&self) -> std::slice::Iter<'_, FullJid> {
self.sessions.iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
use xmpp_parsers::{BareJid, FullJid};
#[test]
fn occupant_ignore_dup_session() {
let room = Room::new(BareJid::from_str("room@muc").unwrap());
let real = FullJid::from_str("foo@bar/meh").unwrap();
let mut occupant = Occupant::new(&room, real.clone(), String::from("nick"));
occupant.add_session(real.clone()).unwrap();
assert_eq!(occupant.iter().count(), 1);
}
}