Skip to content

Commit

Permalink
added like counter to posts
Browse files Browse the repository at this point in the history
  • Loading branch information
Dromader2137 committed Apr 3, 2024
1 parent 2faffc3 commit fde2b6e
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 79 deletions.
3 changes: 1 addition & 2 deletions react-curl.sh
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@ curl --location --request POST "$path" \
--header 'Content-Type: text/plain' \
--data-raw '{
"post_id": '$2',
"reaction_type": '$3',
"token": "'"$4"'"
"token": "'"$3"'"
}'
7 changes: 4 additions & 3 deletions setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ CREATE TABLE posts(
post_id INTEGER PRIMARY KEY NOT NULL,
user_id INTEGER NOT NULL,
date BIGINT NOT NULL,
body VARCHAR(2048) NOT NULL
body VARCHAR(2048) NOT NULL,
likes INTEGER NOT NULL
);

CREATE TABLE posts_tags(
Expand Down Expand Up @@ -55,8 +56,8 @@ CREATE TABLE images(
-- | user_name | |-------------------------+- many | user_id | | | tag_id | many -| | tag_name |
-- | display_name | | | | date | | -------------- ------------
-- | description | | | | body | |
-- | passwd | | | ----------- | ---------------- --------------
-- | is_admin | | | | | posts_images | | images |
-- | passwd | | | | likes | | ---------------- --------------
-- | is_admin | | | ----------- | | posts_images | | images |
-- | is_banned | | | | ---------------- --------------
-- ---------------- | | |- many | post_id | |- 1 | image_id |
-- | ----------- | | image_id | many -| | image_uuid |
Expand Down
73 changes: 24 additions & 49 deletions src/api_calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ pub async fn get_posts_by_user(user_id: i64) -> Result<impl warp::Reply, warp::R
post_id: row.get(0).unwrap(),
user_id: row.get(1).unwrap(),
date: row.get(2).unwrap(),
body: row.get(3).unwrap()
body: row.get(3).unwrap(),
likes: row.get(4).unwrap()
}
);
}
Expand Down Expand Up @@ -81,8 +82,10 @@ pub async fn get_posts_by_tag(tag: String) -> Result<impl warp::Reply, warp::Rej
post_id: row.get(0).unwrap(),
user_id: row.get(1).unwrap(),
date: row.get(2).unwrap(),
body: row.get(3).unwrap()
body: row.get(3).unwrap(),
likes: row.get(4).unwrap()
}

);
}
Ok(post_vec)
Expand All @@ -109,7 +112,8 @@ pub async fn get_posts() -> Result<impl warp::Reply, warp::Rejection> {
post_id: row.get(0).unwrap(),
user_id: row.get(1).unwrap(),
date: row.get(2).unwrap(),
body: row.get(3).unwrap()
body: row.get(3).unwrap(),
likes: row.get(4).unwrap()
}
);
}
Expand Down Expand Up @@ -169,18 +173,20 @@ pub async fn get_post_by_id(post_id: i64) -> Result<impl warp::Reply, warp::Reje
let mut rows = statement.query(params![post_id]).unwrap();
let post: Post;
if let Ok(Some(row)) = rows.next() {
post = Post {
post_id: row.get(0).unwrap(),
user_id: row.get(1).unwrap(),
date: row.get(2).unwrap(),
body: row.get(3).unwrap()
};
post = Post {
post_id: row.get(0).unwrap(),
user_id: row.get(1).unwrap(),
date: row.get(2).unwrap(),
body: row.get(3).unwrap(),
likes: row.get(4).unwrap()
};
} else {
post = Post {
post_id: -1,
user_id: -1,
date: -1,
body: "".to_string()
post_id: -1,
user_id: 0,
date: 0,
body: "".to_string(),
likes: 0
};
}
Ok(post)
Expand Down Expand Up @@ -297,38 +303,6 @@ pub async fn get_user_id(user_name: String) -> Result<impl warp::Reply, warp::Re
))
}

pub async fn get_likes_from_post(post_id: i64) -> Result<impl warp::Reply, warp::Rejection> {
let query = "SELECT type, COUNT(user_id) FROM likes WHERE post_id = ? GROUP BY type";
let connection = tokio_rusqlite::Connection::open("projekt-db").await.unwrap();

if !check_post(&connection, post_id).await {
let r = "Post not found";
return Ok(warp::reply::with_status(
warp::reply::json(&r),
warp::http::StatusCode::NOT_FOUND
));
}

let like_count_map = connection.call(move |conn| {
let mut statement = conn.prepare(query).unwrap();
let mut rows = statement.query(params![post_id]).unwrap();
let mut likes_map: HashMap<i64, i64> = HashMap::new();
while let Ok(Some(row)) = rows.next() {
likes_map.insert(row.get(0).unwrap(), row.get(1).unwrap());
}
Ok(likes_map)
}).await.unwrap();

let likes = LikeCountMap {
like_count_map
};

Ok(warp::reply::with_status(
warp::reply::json(&likes),
warp::http::StatusCode::OK
))
}

pub async fn post(request: PostCreateRequest) -> Result<impl warp::Reply, warp::Rejection> {
let token: TokenData<Claims>;
match verify_token::verify_token(request.token) {
Expand Down Expand Up @@ -370,7 +344,8 @@ pub async fn post(request: PostCreateRequest) -> Result<impl warp::Reply, warp::
post_id: post_count,
user_id: id,
date: -1,
body: request.body
body: request.body,
likes: 0
},
request.tags
).await;
Expand All @@ -382,7 +357,7 @@ pub async fn post(request: PostCreateRequest) -> Result<impl warp::Reply, warp::
))
}

pub async fn react(request: ReactRequest) -> Result<impl warp::Reply, warp::Rejection> {
pub async fn react(request: LikeRequest) -> Result<impl warp::Reply, warp::Rejection> {
let token: TokenData<Claims>;
match verify_token::verify_token(request.token) {
Ok(val) => {token = val}
Expand Down Expand Up @@ -415,7 +390,7 @@ pub async fn react(request: ReactRequest) -> Result<impl warp::Reply, warp::Reje
));
}

let existed = add_like_db(&connection, token.claims.uid, request.post_id, request.like_type).await;
let existed = add_like_db(&connection, token.claims.uid, request.post_id).await;

if existed {
let r = "Like already exists";
Expand Down Expand Up @@ -725,7 +700,7 @@ pub fn ban_json() -> impl Filter<Extract = (UserBanRequest,), Error = warp::Reje
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}

pub fn react_json() -> impl Filter<Extract = (ReactRequest,), Error = warp::Rejection> + Clone {
pub fn react_json() -> impl Filter<Extract = (LikeRequest,), Error = warp::Rejection> + Clone {
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}

Expand Down
49 changes: 38 additions & 11 deletions src/database_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,27 @@ pub async fn purge_data(connection: &Connection, user_id: i64) {
}).await.unwrap();
}

let find_posts_query = "SELECT post_id FROM likes WHERE user_id = ?";
let like_post_ids = connection.call(move |conn| {
let mut statement = conn.prepare(find_posts_query).unwrap();
let mut rows = statement.query(params![user_id]).unwrap();
let mut post_id_vec: Vec<i64> = Vec::new();
while let Ok(Some(row)) = rows.next() {
post_id_vec.push(row.get(0).unwrap());
}
Ok(post_id_vec)
}).await.unwrap();

let post_like_delete_query = "UPDATE posts SET likes=likes-1 WHERE post_id = ?";
for post_id in like_post_ids.iter() {
let post_id = *post_id;
connection.call(move |conn| {
let mut statement = conn.prepare(post_like_delete_query).unwrap();
statement.execute(params![post_id]).unwrap();
Ok(0)
}).await.unwrap();
};

let likes_delete_query = "DELETE FROM likes WHERE user_id = ?";
connection.call(move |conn| {
let mut statement = conn.prepare(likes_delete_query).unwrap();
Expand Down Expand Up @@ -203,10 +224,10 @@ pub async fn add_tag_db(connection: &Connection, name: String) -> i64 {
pub async fn add_post_db(connection: &Connection, post: Post, tags: Vec<String>) {
let time_since_epoch: i64 = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as i64;

let query = "INSERT INTO posts VALUES (?, ?, ?, ?)";
let query = "INSERT INTO posts VALUES (?, ?, ?, ?, ?)";
connection.call(move |conn| {
let mut statement = conn.prepare(query).unwrap();
statement.execute(params![post.post_id, post.user_id, time_since_epoch, post.body]).unwrap();
statement.execute(params![post.post_id, post.user_id, time_since_epoch, post.body, 0]).unwrap();
Ok(0)
}).await.unwrap();

Expand Down Expand Up @@ -269,12 +290,12 @@ pub async fn get_id_passwd_adm(connection: &Connection, user: String) -> Result<

}

pub async fn check_like(connection: &Connection, user_id: i64, post_id: i64, like_type: i64) -> bool {
let query = "SELECT post_id FROM likes WHERE post_id = ?";
pub async fn check_like(connection: &Connection, user_id: i64, post_id: i64) -> bool {
let query = "SELECT post_id FROM likes WHERE post_id = ? AND user_id = ?";

connection.call(move |conn| {
let mut statement = conn.prepare(query).unwrap();
let mut rows = statement.query(params![like_type, user_id, post_id]).unwrap();
let mut rows = statement.query(params![post_id, user_id]).unwrap();
if let Ok(Some(_)) = rows.next() {
Ok(true)
} else {
Expand All @@ -283,21 +304,27 @@ pub async fn check_like(connection: &Connection, user_id: i64, post_id: i64, lik
}).await.unwrap()
}

pub async fn add_like_db(connection: &Connection, user_id: i64, post_id: i64, like_type: i64) -> bool {
let query = "INSERT INTO likes VALUES (?, ?, ?)";
pub async fn add_like_db(connection: &Connection, user_id: i64, post_id: i64) -> bool {
let query = "INSERT INTO likes VALUES (?, ?)";
let update_query = "UPDATE posts SET likes=likes+1 WHERE post_id = ?";

if check_like(connection, user_id, post_id, like_type).await {
if check_like(connection, user_id, post_id).await {
info!("Like already exists");
return true;
}

connection.call(move |conn| {
let mut statement = conn.prepare(query).unwrap();
statement.execute(params![like_type, user_id, post_id]).unwrap();
statement.execute(params![user_id, post_id]).unwrap();
Ok(0)
}).await.unwrap();

connection.call(move |conn| {
let mut statement = conn.prepare(update_query).unwrap();
statement.execute(params![post_id]).unwrap();
Ok(0)
}).await.unwrap();

info!("Like {} added for post {} by user {}", like_type, post_id, user_id);
info!("Like added for post {} by user {}", post_id, user_id);
false
}

10 changes: 0 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,6 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.and(warp::path::end())
.and_then(get_profile_by_id);

let get_likes_from_post = warp::get()
.and(warp::path("api"))
.and(warp::path("get"))
.and(warp::path("likes"))
.and(warp::path("from-post"))
.and(warp::path::param())
.and(warp::path::end())
.and_then(get_likes_from_post);

let get_profile_picture = warp::get()
.and(warp::path("api"))
.and(warp::path("get"))
Expand Down Expand Up @@ -202,7 +193,6 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.or(get_posts_by_tag)
.or(get_tags_from_post)
.or(react)
.or(get_likes_from_post)
.or(get_profile_by_id)
.or(get_profile_picture)
.or(change_display_name)
Expand Down
8 changes: 4 additions & 4 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub struct Post {
pub user_id: i64,
pub date: i64,
pub body: String,
pub likes: i64
}

#[derive(Debug, Deserialize, Serialize, Clone)]
Expand All @@ -34,8 +35,8 @@ pub struct TagList {
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LikeCountMap {
pub like_count_map: HashMap<i64, i64>
pub struct LikeCount {
pub like_count: i64
}

#[derive(Debug, Deserialize, Serialize, Clone)]
Expand All @@ -58,9 +59,8 @@ pub struct PostCreateRequest {
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ReactRequest {
pub struct LikeRequest {
pub post_id: i64,
pub like_type: i64,
pub token: String
}

Expand Down
1 change: 1 addition & 0 deletions test-posts.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SELECT * FROM posts;
27 changes: 27 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#!/bin/bash

ip="localhost:8000"
token_0=$(./login-curl.sh $ip root toor)
tok_0=${token_0:1:-1}
./create-post.sh $ip hello welcome yo $tok_0
echo
./create-post.sh $ip hello welcome yo $tok_0
echo
./create-post.sh $ip hello welcome yo $tok_0
echo
sqlite3 projekt-db < test-posts.sql
./react-curl.sh $ip 0 $tok_0
echo
sqlite3 projekt-db < test-posts.sql
token_1=$(./signup-curl.sh $ip dr 1234)
tok_1=${token_1:1:-1}
./react-curl.sh $ip 0 $tok_1
echo
./react-curl.sh $ip 1 $tok_1
echo
./react-curl.sh $ip 2 $tok_1
echo
sqlite3 projekt-db < test-posts.sql
./ban-curl.sh $ip 1 $tok_0
echo
sqlite3 projekt-db < test-posts.sql

0 comments on commit fde2b6e

Please sign in to comment.