use common::model::{Community, Id, Rank}; use super::{Connection, all, community, maybe, member, run}; use crate::error::ServerError; pub enum Opening { Created(Community), Existing(Community), } pub async fn open(me: Id, other: Id, db: &Connection) -> Result { let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; let existing: Option = maybe( db, "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", (user_a, user_b), |r| r.get(), ) .await?; if let Some(community_id) = existing { return Ok(Opening::Existing( community::read(community_id, me, db).await?, )); } let community_id = if me == other { let community_id = community::create(community::Kind::Notes, "", db).await?; member::join(me, community_id, Rank::Owner, db).await?; community_id } else { let community_id = community::create(community::Kind::Direct, "", db).await?; member::join(me, community_id, Rank::Member, db).await?; member::join(other, community_id, Rank::Member, db).await?; community_id }; run( db, "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)", (user_a, user_b, community_id), ) .await?; Ok(Opening::Created( community::read(community_id, me, db).await?, )) } pub async fn communities_of(user_id: Id, db: &Connection) -> Result, ServerError> { all( db, "SELECT community_id FROM direct WHERE user_a = ?1 OR user_b = ?1", (user_id,), |r| r.get(), ) .await }