freechat/server/src/messages.rs
2020-07-30 23:31:20 -07:00

67 lines
2.1 KiB
Rust

use std::borrow::Cow;
use mysql_async::{Pool, params};
use mysql_async::prelude::{Queryable};
use mysql_async::error::Error;
use hyper::{Response, Body, StatusCode};
use serde_json::Value;
use chrono::Utc;
use crate::db_types::{UBigInt, VarChar};
struct Message {
id: UBigInt,
content: Option<VarChar>, // some messages later might only have file attachments and not text content
author_id: UBigInt,
channel_id: UBigInt,
permissions: UBigInt,
}
pub async fn insert_message_table(pool: &Pool, content: &Value, channel_id: &Value, author_id: UBigInt)
-> Result<(), Error>{
match (content.as_str(), channel_id.as_u64()) {
(Some(content), Some(channel)) => {
let conn = pool.get_conn().await?;
let time = Utc::now().timestamp();
conn.prep_exec(r"", params!{
"time" => time,
"content" => content,
"author" => author_id,
"channel" => channel
}).await?;
Ok(())
}
_ => {
let e = Cow::from("Required parameter missing");
Err(Error::Other(e))
}
}
}
pub async fn send_message(pool: &Pool, response: &mut Response<Body>, params: Value) {
/*
* @content: expecting string type
* @id: expecting the channel id that we're posting data to
*/
let content_r = params.get("content");
let channel_id_r = params.get("channel");
// auth module guarantees this will be there in the correct form
let author = params.get("userid")
.unwrap().as_u64().unwrap();
match (content_r, channel_id_r) {
(Some(content), Some(channel_id)) => {
// insert the new message into our db
if let Ok(_db_result) = insert_message_table(pool, content, channel_id, author).await {
*response.status_mut() = StatusCode::OK;
}
},
_ => {
*response.status_mut() = StatusCode::BAD_REQUEST;
*response.body_mut() = Body::from("content/channel missing from json parameters");
}
}
}