| 1 | use common::model::{Community, Id, Rank}; |
| 2 | |
| 3 | use super::{Connection, community, maybe, member, run}; |
| 4 | use crate::error::ServerError; |
| 5 | |
| 6 | pub enum Opening { |
| 7 | Created(Community), |
| 8 | Existing(Community), |
| 9 | } |
| 10 | |
| 11 | pub async fn open(me: Id, other: Id, db: &Connection) -> Result<Opening, ServerError> { |
| 12 | let (user_a, user_b) = if me < other { (me, other) } else { (other, me) }; |
| 13 | |
| 14 | let existing: Option<Id> = maybe( |
| 15 | db, |
| 16 | "SELECT community_id FROM direct WHERE user_a = ?1 AND user_b = ?2", |
| 17 | (user_a, user_b), |
| 18 | |r| r.get(), |
| 19 | ) |
| 20 | .await?; |
| 21 | if let Some(community_id) = existing { |
| 22 | return Ok(Opening::Existing( |
| 23 | community::read(community_id, me, db).await?, |
| 24 | )); |
| 25 | } |
| 26 | |
| 27 | let community_id = if me == other { |
| 28 | let community_id = community::create(community::Kind::Notes, "", db).await?; |
| 29 | member::join(me, community_id, Rank::Owner, db).await?; |
| 30 | community_id |
| 31 | } else { |
| 32 | let community_id = community::create(community::Kind::Direct, "", db).await?; |
| 33 | member::join(me, community_id, Rank::Member, db).await?; |
| 34 | member::join(other, community_id, Rank::Member, db).await?; |
| 35 | community_id |
| 36 | }; |
| 37 | run( |
| 38 | db, |
| 39 | "INSERT INTO direct (user_a, user_b, community_id) VALUES (?1, ?2, ?3)", |
| 40 | (user_a, user_b, community_id), |
| 41 | ) |
| 42 | .await?; |
| 43 | |
| 44 | Ok(Opening::Created( |
| 45 | community::read(community_id, me, db).await?, |
| 46 | )) |
| 47 | } |