Skip to content

Commit

Permalink
Merge pull request #15 from driftluo/add-comment-notify
Browse files Browse the repository at this point in the history
Add comment notify
  • Loading branch information
driftluo authored Apr 4, 2018
2 parents cf70135 + 148004d commit 2e6f45c
Show file tree
Hide file tree
Showing 31 changed files with 500 additions and 152 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "blog"
version = "0.1.0"
version = "0.2.0"
authors = ["piaoliu <[email protected]>"]

[dependencies]
Expand Down
5 changes: 3 additions & 2 deletions src/api/admin_article_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde_json;
use uuid::Uuid;

use super::super::{ArticleList, ArticlesWithTag, EditArticle, ModifyPublish, NewArticle,
Permissions, Postgresql};
Permissions, Postgresql, Redis};

pub struct AdminArticle;

Expand All @@ -25,8 +25,9 @@ impl AdminArticle {
let params = get_path_params!(req);
let article_id: Uuid = t_param!(params, "id").clone().parse().unwrap();
let pg_pool = req.ext().get::<Postgresql>().unwrap().get().unwrap();
let redis_pool = req.ext().get::<Redis>().unwrap();

let res = match ArticlesWithTag::delete_with_id(&pg_pool, article_id) {
let res = match ArticlesWithTag::delete_with_id(&pg_pool, redis_pool, article_id) {
Ok(num_deleted) => json!({
"status": true,
"num_deleted": num_deleted
Expand Down
5 changes: 3 additions & 2 deletions src/api/admin_user_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde_json;
use sapper_std::{JsonParams, PathParams, QueryParams};
use uuid::Uuid;

use super::super::{ChangePermission, DisabledUser, Permissions, Postgresql, UserInfo, Users};
use super::super::{ChangePermission, DisabledUser, Permissions, Postgresql, Redis, UserInfo, Users};

pub struct AdminUser;

Expand All @@ -13,8 +13,9 @@ impl AdminUser {
let params = get_path_params!(req);
let user_id: Uuid = t_param!(params, "id").clone().parse().unwrap();
let pg_pool = req.ext().get::<Postgresql>().unwrap().get().unwrap();
let redis_pool = req.ext().get::<Redis>().unwrap();

let res = match Users::delete(&pg_pool, user_id) {
let res = match Users::delete(&pg_pool, redis_pool, user_id) {
Ok(num_deleted) => json!({
"status": true,
"num_deleted": num_deleted
Expand Down
53 changes: 50 additions & 3 deletions src/api/user_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use sapper::{Error as SapperError, Request, Response, Result as SapperResult, Sa
use sapper_std::{JsonParams, SessionVal};
use serde_json;

use super::super::{ChangePassword, DeleteComment, EditUser, LoginUser, NewComments, Permissions,
Postgresql, Redis, UserInfo};
use super::super::{ArticlesWithTag, ChangePassword, DeleteComment, EditUser, LoginUser,
NewComments, Permissions, Postgresql, Redis, UserInfo, UserNotify};

pub struct User;

Expand Down Expand Up @@ -64,10 +64,57 @@ impl User {
}

fn new_comment(req: &mut Request) -> SapperResult<Response> {
let body: NewComments = get_json_params!(req);
let mut body: NewComments = get_json_params!(req);
let cookie = req.ext().get::<SessionVal>().unwrap();
let redis_pool = req.ext().get::<Redis>().unwrap();
let pg_pool = req.ext().get::<Postgresql>().unwrap().get().unwrap();
let user =
serde_json::from_str::<UserInfo>(&UserInfo::view_user_with_cookie(redis_pool, cookie))
.unwrap();
let admin = UserInfo::view_admin(&pg_pool, redis_pool);
let article =
ArticlesWithTag::query_without_article(&pg_pool, body.article_id(), false).unwrap();

match body.reply_user_id() {
// Reply comment
Some(reply_user_id) => {
// Notification replyee
let user_reply_notify = UserNotify {
user_id: reply_user_id,
send_user_name: user.nickname.clone(),
article_id: article.id,
article_title: article.title.clone(),
notify_type: "reply".into(),
};
user_reply_notify.cache(&redis_pool);

// If the sender is not an admin and also the responder is also not admin, notify admin
if reply_user_id != admin.id && user.groups != 0 {
let comment_notify = UserNotify {
user_id: admin.id,
send_user_name: user.nickname.clone(),
article_id: article.id,
article_title: article.title.clone(),
notify_type: "comment".into(),
};
comment_notify.cache(&redis_pool);
}
}
// Normal comment
None => {
if user.groups != 0 {
let comment_notify = UserNotify {
user_id: admin.id,
send_user_name: user.nickname.clone(),
article_id: article.id,
article_title: article.title.clone(),
notify_type: "comment".into(),
};
comment_notify.cache(&redis_pool);
}
}
}

let res = json!({
"status": body.insert(&pg_pool, redis_pool, cookie)
});
Expand Down
14 changes: 11 additions & 3 deletions src/api/visitor_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use sapper::header::{ContentType, Location};
use sapper::status;
use serde_json;

use super::super::{ArticleList, ArticlesWithTag, Comments, LoginUser, Permissions, Postgresql,
Redis, RegisteredUser, UserInfo, get_github_token, get_github_account_nickname_address};
use super::super::{get_github_account_nickname_address, get_github_token, ArticleList,
ArticlesWithTag, Comments, LoginUser, Permissions, Postgresql, Redis,
RegisteredUser, UserInfo};
use uuid::Uuid;

pub struct Visitor;
Expand Down Expand Up @@ -167,7 +168,14 @@ impl Visitor {
response.headers_mut().set(ContentType::json());

let (account, nickname, github_address) = get_github_account_nickname_address(&token)?;
match LoginUser::login_with_github(&pg_pool, redis_pool, github_address, nickname, account, &token) {
match LoginUser::login_with_github(
&pg_pool,
redis_pool,
github_address,
nickname,
account,
&token,
) {
Ok(cookie) => {
let res = json!({
"status": true,
Expand Down
10 changes: 6 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ extern crate diesel;
#[macro_use]
extern crate diesel_infer_schema;
extern crate dotenv;
extern crate hyper;
extern crate hyper_native_tls;
extern crate r2d2;
extern crate r2d2_redis;
extern crate rand;
Expand All @@ -22,11 +24,9 @@ extern crate serde;
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate serde_urlencoded;
extern crate tiny_keccak;
extern crate uuid;
extern crate hyper;
extern crate hyper_native_tls;
extern crate serde_urlencoded;

pub mod schema;
pub mod models;
Expand All @@ -41,8 +41,10 @@ pub(crate) use models::{ChangePassword, ChangePermission, DisabledUser, EditUser
RegisteredUser, UserInfo, Users};
pub(crate) use models::{NewTag, TagCount, Tags};
pub(crate) use models::{Comments, DeleteComment, NewComments};
pub(crate) use models::UserNotify;
pub(crate) use util::{get_password, markdown_render, random_string, sha3_256_encode};
pub(crate) use util::{get_github_account_nickname_address, get_github_token, get_github_primary_email};
pub(crate) use util::{get_github_account_nickname_address, get_github_primary_email,
get_github_token};
#[cfg(not(feature = "monitor"))]
pub(crate) use util::visitor_log;
pub use util::{create_redis_pool, get_identity_and_web_context, Permissions, Redis, RedisPool,
Expand Down
3 changes: 2 additions & 1 deletion src/models/article_tag_relation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ impl RelationTag {
}

pub fn insert_all(&self, conn: &PgConnection) -> bool {
// If `tag` exist, insert all the new tags into the table all at once, and return the ID of the newly added tag
// If `tag` exist, insert all the new tags into the table all at once,
// and return the ID of the newly added tag
let mut tags_id = if self.tag.is_some() {
NewTag::insert_all(
self.tag
Expand Down
26 changes: 19 additions & 7 deletions src/models/articles.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use super::super::articles::dsl::articles as all_articles;
use super::super::{article_with_tag, articles};
use super::super::article_with_tag::dsl::article_with_tag as all_article_with_tag;
use super::super::markdown_render;
use super::{RelationTag, Relations};
use super::super::{markdown_render, RedisPool};
use super::{RelationTag, Relations, UserNotify};

use chrono::NaiveDateTime;
use diesel;
use diesel::prelude::*;
use diesel::sql_types::{BigInt, Text};
use uuid::Uuid;
use std::sync::Arc;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ArticlesWithTag {
Expand All @@ -23,11 +24,18 @@ pub struct ArticlesWithTag {
}

impl ArticlesWithTag {
pub fn delete_with_id(conn: &PgConnection, id: Uuid) -> Result<usize, String> {
pub fn delete_with_id(
conn: &PgConnection,
redis_pool: &Arc<RedisPool>,
id: Uuid,
) -> Result<usize, String> {
Relations::delete_all(conn, id, "article");
let res = diesel::delete(all_articles.filter(articles::id.eq(id))).execute(conn);
let res = diesel::delete(all_articles.filter(articles::id.eq(&id))).execute(conn);
match res {
Ok(data) => Ok(data),
Ok(data) => {
UserNotify::remove_with_article(id, redis_pool);
Ok(data)
}
Err(err) => Err(format!("{}", err)),
}
}
Expand Down Expand Up @@ -290,6 +298,7 @@ impl RawArticlesWithTag {
fn into_without_content(self) -> ArticlesWithoutContent {
ArticlesWithoutContent {
id: self.id,
title: self.title,
published: self.published,
tags_id: self.tags_id,
tags: self.tags,
Expand All @@ -313,8 +322,10 @@ struct Articles {
#[derive(Queryable, Debug, Clone, Deserialize, Serialize, QueryableByName)]
#[table_name = "articles"]
pub struct PublishedStatistics {
#[sql_type = "Text"] pub dimension: String,
#[sql_type = "BigInt"] pub quantity: i64,
#[sql_type = "Text"]
pub dimension: String,
#[sql_type = "BigInt"]
pub quantity: i64,
}

impl PublishedStatistics {
Expand All @@ -333,6 +344,7 @@ impl PublishedStatistics {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ArticlesWithoutContent {
pub id: Uuid,
pub title: String,
pub published: bool,
pub tags_id: Vec<Option<Uuid>>,
pub tags: Vec<Option<String>>,
Expand Down
15 changes: 12 additions & 3 deletions src/models/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ pub struct Comments {
comment: String,
article_id: Uuid,
user_id: Uuid,
#[sql_type = "Text"] nickname: String,
#[sql_type = "Text"]
nickname: String,
create_time: NaiveDateTime,
}

Expand Down Expand Up @@ -70,6 +71,7 @@ impl InsertComments {
pub struct NewComments {
comment: String,
article_id: Uuid,
reply_user_id: Option<Uuid>,
}

impl NewComments {
Expand All @@ -86,6 +88,14 @@ impl NewComments {
serde_json::from_str::<UserInfo>(&redis_pool.hget::<String>(cookie, "info")).unwrap();
self.into_insert_comments(info.id).insert(conn)
}

pub fn reply_user_id(&mut self) -> Option<Uuid> {
self.reply_user_id.take()
}

pub fn article_id(&self) -> Uuid {
self.article_id
}
}

#[derive(Debug, Clone, Deserialize, Serialize)]
Expand All @@ -105,8 +115,7 @@ impl DeleteComment {
match *permission {
Some(0) => Comments::delete_with_comment_id(conn, self.comment_id),
_ => {
let info = serde_json::from_str::<UserInfo>(&redis_pool
.hget::<String>(cookie, "info"))
let info = serde_json::from_str::<UserInfo>(&redis_pool.hget::<String>(cookie, "info"))
.unwrap();
if self.user_id == info.id {
Comments::delete_with_comment_id(conn, self.comment_id)
Expand Down
2 changes: 2 additions & 0 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod user;
pub mod tag;
pub mod article_tag_relation;
pub mod comment;
pub mod notifys;

pub(crate) use self::articles::{ArticleList, ArticlesWithTag, EditArticle, ModifyPublish,
NewArticle};
Expand All @@ -12,3 +13,4 @@ pub(crate) use self::user::{ChangePassword, ChangePermission, DisabledUser, Edit
pub(crate) use self::tag::{NewTag, TagCount, Tags};
pub(crate) use self::article_tag_relation::{RelationTag, Relations};
pub(crate) use self::comment::{Comments, DeleteComment, NewComments};
pub(crate) use self::notifys::UserNotify;
Loading

0 comments on commit 2e6f45c

Please sign in to comment.