Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search #82

Merged
merged 3 commits into from
May 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions scripts/delete-post.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash

path="$1/api/post/delete-post"

curl --location --request POST "$path" \
--cookie "token=$3" \
--header 'Content-Type: application/json' \
--header 'Content-Type: text/plain' \
--data-raw '{
"post_id": '$2'
}'
148 changes: 145 additions & 3 deletions src/api_calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub async fn get_posts_by_tag(tag: String, limit: i64, offset: i64) -> Result<im
.as_secs() as i64;
let query = format!(
"
SELECT posts.post_id, posts.user_id, posts.date, posts.body, users.user_id
SELECT posts.*, users.user_name
FROM posts
JOIN posts_tags
ON posts.post_id = posts_tags.post_id
Expand Down Expand Up @@ -127,6 +127,108 @@ pub async fn get_posts_by_tag(tag: String, limit: i64, offset: i64) -> Result<im
))
}

pub async fn get_posts_from_search(phrase: String, limit: i64, offset: i64) -> Result<impl warp::Reply, warp::Rejection> {
let connection = tokio_rusqlite::Connection::open("projekt-db")
.await
.unwrap();

let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let phrase_cpy = "%".to_string() + &phrase + "%";
let query = format!(
"
SELECT posts.*, users.user_name
FROM posts
JOIN users
ON posts.user_id = users.user_id
WHERE posts.body LIKE ?
AND posts.user_id NOT IN
(SELECT user_id FROM bans WHERE is_active = 1 AND expires_on > {})
LIMIT ? OFFSET ?
",
timestamp
);
let post_list = connection
.call(move |conn| {
let mut statement = conn.prepare(&query).unwrap();
let mut rows = statement.query(params![phrase_cpy, limit, offset]).unwrap();
let mut post_vec: Vec<Post> = Vec::new();
while let Ok(Some(row)) = rows.next() {
post_vec.push(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(),
user_name: row.get(5).unwrap(),
});
}
Ok(post_vec)
})
.await
.unwrap();

let post = PostList { post_list };
Ok(warp::reply::with_status(
warp::reply::json(&post),
warp::http::StatusCode::OK,
))
}

pub async fn get_users_from_search(phrase: String, limit: i64, offset: i64) -> Result<impl warp::Reply, warp::Rejection> {
let connection = tokio_rusqlite::Connection::open("projekt-db")
.await
.unwrap();

let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let phrase_cpy = "%".to_string() + &phrase + "%";
let query = format!(
"
SELECT users.user_id, users.user_name, users.display_name, users.description, images.image_file
FROM users
LEFT JOIN images ON images.image_id=users.pfp_id
WHERE users.user_name LIKE ?
AND users.user_id NOT IN
(SELECT user_id FROM bans WHERE is_active = 1 AND expires_on > {})
LIMIT ? OFFSET ?
", // tutaj tez ten left join do wywalenia
timestamp
);
let profile_list = connection
.call(move |conn| {
let mut statement = conn.prepare(&query).unwrap();
let mut rows = statement.query(params![phrase_cpy, limit, offset]).unwrap();
let mut profile_vec: Vec<Profile> = Vec::new();
while let Ok(Some(row)) = rows.next() {
let pfp = match row.get::<_, String>(4) {
Ok(val) => format!("pfp_{}", val),
Err(_) => "".to_string()
};
profile_vec.push(Profile {
user_id: row.get(0).unwrap(),
user_name: row.get(1).unwrap(),
display_name: row.get(2).unwrap(),
description: row.get(3).unwrap(),
pfp_image: pfp,
});
}
Ok(profile_vec)
})
.await
.unwrap();

let post = ProfileList { profile_list };
Ok(warp::reply::with_status(
warp::reply::json(&post),
warp::http::StatusCode::OK,
))
}

pub async fn get_posts(limit: i64, offset: i64) -> Result<impl warp::Reply, warp::Rejection> {
let connection = tokio_rusqlite::Connection::open("projekt-db")
.await
Expand Down Expand Up @@ -386,9 +488,9 @@ pub async fn get_profile_by_id(user_id: i64) -> Result<impl warp::Reply, warp::R
users.display_name, users.description,
images.image_file
FROM users
JOIN images ON images.image_id=users.pfp_id
LEFT JOIN images ON images.image_id=users.pfp_id
WHERE users.user_id = ?
";
"; // na razie jest left join zeby zwracalo cokolwiek, do naprawienia

if !check_user_id(&connection, user_id).await {
let r = "User not found";
Expand Down Expand Up @@ -970,6 +1072,42 @@ pub async fn delete_user(
}
}

pub async fn delete_post(token: String, request: PostDeleteRequest,) -> Result<impl warp::Reply, warp::Rejection> {
info!("{}", token);
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
return Err(warp::reject::custom(WrongToken));
}
};
let connection = tokio_rusqlite::Connection::open("projekt-db")
.await
.unwrap();
let id = token.claims.uid;
if check_user_id(&connection, id).await || token.claims.is_admin == 1 {
let delete_query = "
DELETE FROM posts WHERE post_id = ?;
DELETE FROM posts_tags WHERE post_id = ?;
DELETE FROM posts_images WHERE post_id = ?"; // nie wszystko jest usuwane, naprawic
connection
.call(move |conn| {
let mut statement = conn.prepare(delete_query).unwrap();
statement.execute(params![request.post_id]).unwrap();
Ok(0)
})
.await
.unwrap();

info!("Post {} deleted", id);
let r = "Post deleted";
let res = warp::reply::with_status(r, warp::http::StatusCode::OK);
let res = warp::reply::with_header(res, "Access-Control-Allow-Origin", "*");
Ok(res)
} else {
Err(warp::reject::custom(UserNotFound))
}
}

pub async fn upgrade_user(
token: String,
request: UserUpgradeRequest,
Expand Down Expand Up @@ -1554,6 +1692,10 @@ pub fn delete_json() -> impl Filter<Extract = (UserDeleteRequest,), Error = warp
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
}

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

pub fn upgrade_json(
) -> impl Filter<Extract = (UserUpgradeRequest,), Error = warp::Rejection> + Clone {
warp::body::content_length_limit(1024 * 16).and(warp::body::json())
Expand Down
32 changes: 20 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![recursion_limit = "256"]
use warp::Filter;
pub mod auth;
pub mod api_calls;
Expand Down Expand Up @@ -60,13 +61,13 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.and(warp::cookie::optional::<String>("token"))
.and_then(validate_token);

// let get_posts_from_search = warp::get()
// .and(warp::path!("api" / "get" / "posts" / "from-search" / String))
// .and_then(get_posts_from_search);
let get_posts_from_search = warp::get()
.and(warp::path!("api" / "get" / "posts" / "from-search" / String / i64 / i64))
.and_then(get_posts_from_search);

// let get_users_from_search = warp::get()
// .and(warp::path("api" / "get" / "users" / "from-search" / String))
// .and_then(get_posts_from_search);
let get_users_from_search = warp::get()
.and(warp::path!("api" / "get" / "users" / "from-search" / String / i64 / i64))
.and_then(get_users_from_search);

let post = warp::post()
.and(warp::path!("api" / "post" / "add-post"))
Expand Down Expand Up @@ -107,12 +108,18 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.and(signup_json())
.and_then(signup);

let delete = warp::post()
let delete_user = warp::post()
.and(warp::path!("api" / "post" / "delete-user"))
.and(warp::cookie::<String>("token"))
.and(delete_json())
.and_then(delete_user);

let delete_post = warp::post()
.and(warp::path!("api" / "post" / "delete-post"))
.and(warp::cookie::<String>("token"))
.and(delete_post_json())
.and_then(delete_post);

let upgrade = warp::post()
.and(warp::path!("api" / "admin" / "post" / "upgrade-user"))
.and(warp::cookie::<String>("token"))
Expand Down Expand Up @@ -144,7 +151,7 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.and_then(change_description);

let upload_image = warp::post()
.and(warp::path!("api" / "post" / "upload" / "image")) // test
.and(warp::path!("api" / "post" / "upload" / "image"))
.and(warp::cookie::<String>("token"))
.and(warp::multipart::form().max_length(25000000))
.and_then(upload_image);
Expand All @@ -167,7 +174,8 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.or(login)
.or(signup)
.or(get_user_name)
.or(delete)
.or(delete_user)
.or(delete_post)
.or(get_user_id)
.or(upgrade)
.or(get_post_by_id)
Expand All @@ -190,8 +198,8 @@ pub fn routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejecti
.or(set_pfp)
.or(comment)
.or(get_comments_from_post)
// .or(get_posts_from_search)
// .or(get_users_from_search)
.or(get_posts_from_search)
.or(get_users_from_search)
}

#[tokio::main]
Expand All @@ -202,6 +210,6 @@ async fn main() {
.allow_headers(vec!["content-type", "Access-Control-Allow-Origin"])
.allow_credentials(true);

let routes = routes().recover(handle_rejection).with(cors); // change back to do error handling
let routes = routes().with(cors).recover(handle_rejection); // change back to do error handling .recover(handle_rejection)
warp::serve(routes).run(([0, 0, 0, 0], 8000)).await;
}
7 changes: 6 additions & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub struct PostList {

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ProfileList {
pub post_list: Vec<Profile>
pub profile_list: Vec<Profile>
}

#[derive(Debug, Deserialize, Serialize, Clone)]
Expand Down Expand Up @@ -107,6 +107,11 @@ pub struct UserDeleteRequest {
pub user_id: i64, // NOT NEEDED
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct PostDeleteRequest {
pub post_id: i64,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct UserUpgradeRequest {
pub user_id: i64,
Expand Down
Loading