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 db::UBigInt; pub async fn send_message(pool: &Pool, response: &mut Response, params: Value) { /* * @content: expecting string type * @channel: channel id that we're going to send a message to */ // NOTE: auth module guarantees this will be there in the correct form let author = params.get("id") .unwrap().as_u64().unwrap(); match (params.get("conetnt") , params.get("channel")) { (Some(content_v), Some(channel_id_v)) => { let (content, channel) = (content_v.as_str(), channel_id_v.as_u64()); if let (Some(message), Some(cid)) = (content, channel) { // call returns empty on sucess so we don't need to do anything if let Err(issue) = db::messages::Message::send(pool, message, cid, author).await { *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR; // log(send) } // if there's no issue then we don't need to do anything at all } else { *response.status_mut() = StatusCode::BAD_REQUEST; } }, _ => *response.status_mut() = StatusCode::BAD_REQUEST } } #[cfg(test)] mod messaging_tests { use crate::testing::{get_pool, hyper_resp}; use serde_json::Value; use hyper::StatusCode; #[tokio::test] async fn send_message_test_missing_channel() { /* * Attempt to send a message i na channel that does not exist */ let p = get_pool(); let mut resp = hyper_resp(); let params: Value = serde_json::from_str(r#" { "channel": "this does not exist", "content": "bs message", "id": 420 } "#).unwrap(); super::send_message(&p, &mut resp, params).await; assert_ne!(StatusCode::OK, resp.status()); } #[tokio::test]#[ignore] async fn send_message_good() { use crate::members::insert_new_member; use crate::perms::GENERAL_NEW; use mysql_async::params; use mysql_async::prelude::Queryable; use crate::testing::tmp_channel_params; let p = get_pool(); let mut resp = hyper_resp(); let tmp_chan = tmp_channel_params(&p, "sample").await; const TMP_NAME: &'static str = "bs user"; let temp_member = insert_new_member(&p, TMP_NAME.into(), GENERAL_NEW).await.unwrap(); let params: Value = serde_json::from_str(&format!(r#" {{ "id": {}, "channel": "{}", "content": "bs message" }} "#, temp_member.id, tmp_chan.name)).unwrap(); super::send_message(&p, &mut resp, params).await; if resp.status() == StatusCode::BAD_REQUEST { panic!("{:?}", resp.body()); } // Destroy the the message and the user that we created let conn = match p.get_conn().await { Ok(c) => c, Err(e) => panic!("Could not get connection to db during send_message_good:\nIssue:\t{}", e) }; let conn = conn.drop_exec("DELETE FROM messages WHERE author_id = :id", params!{"id" => temp_member.id}).await.unwrap(); let conn = conn.drop_exec("DELETE FROM members WHERE id = :id", params!{"id" => temp_member.id}).await.unwrap(); let _ = conn.drop_exec("DELETE FROM channels WHERE name = :name", params!{"name" => tmp_chan.name}).await; } }