Skip to content

Commit

Permalink
Merge pull request #50 from kochamaltki/chlopczyk
Browse files Browse the repository at this point in the history
like counter added to posts
  • Loading branch information
Dromader2137 authored Apr 3, 2024
2 parents 277d68b + 8e25221 commit 24748c5
Show file tree
Hide file tree
Showing 9 changed files with 150 additions and 103 deletions.
42 changes: 34 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@
- Note: All tags of post {id}
#### /api/get/user/name/{id}
- Get: 200 (string) / 404 ("User not found")
- Note: Get username of user {id} ("" if there is no such user)
- Note: Get username of user {id}
#### /api/get/user/id/{name}
- Get: 200 (i64) / 404 ("User not found")
- Note: Get id of user {name} (-1 if there is no such user)
#### /api/get/likes/from-post/{id}
- Note: Get id of user {name}
#### /api/get/profile/by-id/{id}
- Get: 200 (Profile) / 404 ("User not found")
- Note: Get user profile
#### /api/get/likes/from-post/{id}
- Get: 200 (LikeCountMap) / 404 ("Post not found")
- Note: Get (like, count) map from post {id}
#### /api/post/add-post
Expand All @@ -38,7 +41,7 @@
- Return: 201 ("Post created") / 401 ("Wrong token" / "User is banned") / 404 ("User not found")
- Headers: 'Content-Type: application/json' 'Content-Type: text/plain'
#### /api/post/react
- Post: ReactRequest
- Post: LikeRequest
- Effects: Adds like to a post
- Return: 200 ("Like added") / 406 ("Like already exists")
- Headers: 'Content-Type: application/json' 'Content-Type: text/plain'
Expand Down Expand Up @@ -69,13 +72,30 @@
- Note: Token must belong to an admin
- Return: 200 ("Ban succesful") / 401 ("User is not admin" / "Wrong token") / 404 ("User not found")
- Headers: 'Content-Type: application/json' 'Content-Type: text/plain'
#### /api/post/change/display-name
- Post: DisplayNameChangeRequest
- Effect: User's display name changes
- Return: 200 ("Ban succesful") / 401 ("Wrong token") / 404 ("User not found")
- Headers: 'Content-Type: application/json' 'Content-Type: text/plain'
#### /api/post/change/upload/image
- Post: Image (max 25MB)
- ALPHA FEATURE DO NOT USE
### Types
```
Post {
post_id: i64
user_id: i64
date: i64
body: string (max 2048 chars)
likes: i64
}
```
```
Profile {
user_id: i64
user_name: string (max 64 chars)
display_name: string (max 64 chars)
description: string (max 2048 chars)
}
```
```
Expand All @@ -89,8 +109,8 @@ TagList {
}
```
```
LikeCountMap {
like_count_map: map(i64, i64)
LikeCount {
like_count: i64
}
```
```
Expand All @@ -108,13 +128,13 @@ SignupRequest {
```
PostCreateRequest {
body: string (max 2048 chars)
tags: Vec<string (max 64 chars)>
token: string
}
```
```
ReactRequest {
LikeRequest {
post_id: i64
like_type: i64
token: string
}
```
Expand All @@ -135,3 +155,9 @@ UserBanRequest {
token: string
}
```
```
DisplayNameChangeRequest {
new_display_name: string (max 64 chars)
token: string
}
```
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"'"
}'
40 changes: 21 additions & 19 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 @@ -40,29 +41,30 @@ CREATE TABLE likes(

CREATE TABLE posts_images(
post_id INTEGER NOT NULL,
image_uuid VARCHAR(34) NOT NULL
image_id INTEGER NOT NULL
);

CREATE TABLE images(
image_id INTEGER NOT NULL,
image_uuid VARCHAR(34) NOT NULL
);

-- ---------------- ----------- ---------------- ____________
-- | users | | posts | | posts_tags | | tags |
-- ---------------- ----------- ---------------- ------------
-- | user_id | 1 -| |------- 1 | post_id | 1 - many | post_id | |- 1 | tag_id |
-- | user_name | |--------------------------- ---- many | user_id | | tag_id | many -| | tag_name |
-- | display_name | | | | date | ---------------- ------------
-- | description | | | | body |
-- | passwd | | | -----------
-- | is_admin | | |
-- | is_banned | | |
-- ---------------- | |
-- | ------------- |
-- | | likes | |
-- | ------------- |
-- |- many | user_id | |
-- | post_id | many -|
-- -------------
-- ---------------- ----------- -------------- ____________
-- | users | | posts | | posts_tags | | tags |
-- ---------------- ----------- -------------- ------------
-- | user_id | 1 -| |---- 1 | post_id | 1 -- many | post_id | |- 1 | tag_id |
-- | user_name | |-------------------------+- many | user_id | | | tag_id | many -| | tag_name |
-- | display_name | | | | date | | -------------- ------------
-- | description | | | | body | |
-- | passwd | | | | likes | | ---------------- --------------
-- | is_admin | | | ----------- | | posts_images | | images |
-- | is_banned | | | | ---------------- --------------
-- ---------------- | | |- many | post_id | |- 1 | image_id |
-- | ----------- | | image_id | many -| | image_uuid |
-- | | likes | | ---------------- --------------
-- | ----------- |
-- |- many | user_id | |
-- | post_id | many -|
-- -----------

INSERT INTO users VALUES (0, 'root', 'gigachadadmin', 'hala madrid', 'toor', 1, 0);
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
}

Loading

0 comments on commit 24748c5

Please sign in to comment.