Add creating new personal chats
This commit is contained in:
@@ -3,6 +3,7 @@ use std::{
|
||||
TryFrom,
|
||||
TryInto,
|
||||
},
|
||||
collections::BTreeSet,
|
||||
fmt::Display,
|
||||
str::FromStr,
|
||||
};
|
||||
@@ -520,6 +521,56 @@ impl Mutation {
|
||||
|
||||
Ok(ID::new(id_to_uuid(&user.id)?.to_simple().to_string()))
|
||||
}
|
||||
|
||||
async fn newChat(context: &Context, user: ID, password_hash: String, with: ID) -> FieldResult<ID> {
|
||||
let user = id_to_uuid(&user)?.to_simple();
|
||||
let chat_partner = id_to_uuid(&with)?.to_simple();
|
||||
// Sort users
|
||||
let users = BTreeSet::from_iter([user, chat_partner]);
|
||||
|
||||
// User authentication
|
||||
let authentication_successful = sqlx::query(format!(
|
||||
r#"SELECT users.id FROM users, security_preferences WHERE users.id = "{}" AND password_hash = "{}""#,
|
||||
user,
|
||||
password_hash,
|
||||
).as_str()).fetch_optional(&context.db).await?.is_some();
|
||||
if !authentication_successful {
|
||||
return Err("authentication failed".into());
|
||||
}
|
||||
|
||||
// Chat partner needs to be another user (for now)
|
||||
if user == chat_partner {
|
||||
return Err("chat partner is the same user".into());
|
||||
}
|
||||
|
||||
// Chat partner must exist
|
||||
let chat_partner_exists = sqlx::query(
|
||||
format!(r#"SELECT id FROM users WHERE id = "{}""#, chat_partner).as_str()
|
||||
).fetch_optional(&context.db).await?.is_some();
|
||||
if !chat_partner_exists {
|
||||
return Err(format!(r#"chat partner "{}" does not exist on this server"#, chat_partner).into());
|
||||
}
|
||||
|
||||
// non-group chats must be unique
|
||||
let chat_already_exists = sqlx::query(format!(
|
||||
r#"SELECT id FROM chat_index WHERE is_group_chat = 0 AND users = "{}""#,
|
||||
format_array_for_sql(&users),
|
||||
).as_str()).fetch_optional(&context.db).await?.is_some();
|
||||
if chat_already_exists {
|
||||
return Err("a personal chat with this chat partner already exists".into());
|
||||
}
|
||||
|
||||
// create new personal chat
|
||||
let chat_uuid = Uuid::new_v4();
|
||||
sqlx::query(format!(
|
||||
r#"INSERT INTO chat_index VALUES ("{}", 0, "{}", NULL, "{1}")"#,
|
||||
chat_uuid.to_simple(),
|
||||
format_array_for_sql(users),
|
||||
).as_str()).execute(&context.db).await?;
|
||||
crate::sqlite::create_chat(&context.db, &chat_uuid).await?;
|
||||
|
||||
Ok(chat_uuid.to_simple().to_string().into())
|
||||
}
|
||||
}
|
||||
|
||||
pub type Schema<'root_node> = RootNode<'root_node, Query, Mutation, EmptySubscription<Context>>;
|
||||
|
Reference in New Issue
Block a user