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

feat: artifact transfer route #72

Closed
wants to merge 5 commits into from
Closed
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
155 changes: 154 additions & 1 deletion src/api/defense/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ use super::user::util::fetch_user;
use super::PgPool;
use crate::api::error;
use crate::api::util::HistoryboardQuery;
use crate::constants::*;
use crate::models::*;
use actix_web::error::{ErrorBadRequest, ErrorNotFound};
use actix_web::web::{self, Data, Json};
use actix_web::{Responder, Result};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
// use super::RedisPool; //Uncomment to check for user under attack//

mod shortest_path;
mod util;
Expand All @@ -21,6 +23,7 @@ pub fn routes(cfg: &mut web::ServiceConfig) {
.route(web::get().to(get_user_base_details)),
)
.service(web::resource("/top").route(web::get().to(get_top_defenses)))
.service(web::resource("/transfer").route(web::post().to(post_transfer_artifacts)))
.service(web::resource("/save").route(web::put().to(confirm_base_details)))
.service(web::resource("/game/{id}").route(web::get().to(get_game_base_details)))
.service(web::resource("/history").route(web::get().to(defense_history)))
Expand All @@ -35,6 +38,156 @@ pub struct MapSpacesEntry {
pub block_type_id: i32,
}

#[derive(Deserialize)]
pub struct TransferArtifactEntry {
pub artifacts_differ: i32,
pub map_space_id: i32,
}

#[derive(Serialize)]
pub struct TransferArtifactResponse {
pub building_map_space_id: i32,
pub artifacts_in_building: i32,
pub bank_map_space_id: i32,
pub artifacts_in_bank: i32,
}

async fn post_transfer_artifacts(
transfer: Json<TransferArtifactEntry>,
pg_pool: Data<PgPool>,
// redis_pool: Data<RedisPool>, //Uncomment to check for user under attack//
user: AuthUser,
) -> Result<impl Responder> {
let user_id = user.0;
let bank_block_type_id = BLOCK_TYPE_ID_OF_BANK;
let transfer = transfer.into_inner();

// let is_defender = match util::check_user_under_attack(&redis_pool, &user_id) { //Uncomment to check for user under attack//
// Ok(result) => result,
// Err(e) => {
// eprintln!("Error checking if user is under attack: {}", e);
// false // or handle the error in another way
// }
// };

// if !is_defender { //Uncomment to check for user under attack//

let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
let current_layout_id =
web::block(move || util::check_valid_map_id(&mut conn, &user_id, &transfer.map_space_id))
.await?
.map_err(|err| error::handle_error(err.into()))?;

let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
let is_valid_map_space_building =
web::block(move || util::check_valid_map_space_building(&mut conn, &transfer.map_space_id))
.await?
.map_err(|err| error::handle_error(err.into()))?;

if !is_valid_map_space_building {
return Err(ErrorBadRequest(
"Map Space ID does not correspond to a valid building",
));
}

let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
let bank_map_space_id = web::block(move || {
util::get_bank_map_space_id(&mut conn, &current_layout_id, &bank_block_type_id)
})
.await?
.map_err(|err| error::handle_error(err.into()))?;

if bank_map_space_id == transfer.map_space_id {
return Err(ErrorBadRequest("Cannot transfer to the same building"));
}

let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
let bank_artifact_count = web::block(move || {
util::get_building_artifact_count(&mut conn, &current_layout_id, &bank_map_space_id)
})
.await?
.map_err(|err| error::handle_error(err.into()))?;

if transfer.artifacts_differ > bank_artifact_count {
return Err(ErrorBadRequest("Not enough artifacts in the bank"));
}

let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
let mut building_artifact_count = web::block(move || {
util::get_building_artifact_count(&mut conn, &current_layout_id, &transfer.map_space_id)
})
.await?
.map_err(|err| error::handle_error(err.into()))?;

if building_artifact_count == -1 {
let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
web::block(move || util::create_artifact_record(&mut conn, &transfer.map_space_id, &0))
.await?
.map_err(|err| error::handle_error(err.into()))?;
building_artifact_count = 0;
}

if transfer.artifacts_differ + building_artifact_count < 0 {
return Err(ErrorBadRequest("Not enough artifacts in the building"));
}

let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
let building_capacity =
web::block(move || util::get_building_capacity(&mut conn, &transfer.map_space_id))
.await?
.map_err(|err| error::handle_error(err.into()))?;

if building_capacity < transfer.artifacts_differ + building_artifact_count {
return Err(ErrorBadRequest("Building capacity not sufficient"));
}

let new_building_artifact_count = building_artifact_count + transfer.artifacts_differ;
let new_bank_artifact_count = bank_artifact_count - transfer.artifacts_differ;

//Transfer Artifacts
let mut conn = pg_pool
.get()
.map_err(|err| error::handle_error(err.into()))?;
web::block(move || {
util::transfer_artifacts_building(
&mut conn,
&transfer.map_space_id,
&bank_map_space_id,
&new_building_artifact_count,
&new_bank_artifact_count,
)
})
.await?
.map_err(|err| error::handle_error(err.into()))?;

Ok(web::Json(TransferArtifactResponse {
building_map_space_id: transfer.map_space_id,
artifacts_in_building: new_building_artifact_count,
bank_map_space_id,
artifacts_in_bank: new_bank_artifact_count,
}))
// } //Uncomment to check for user under attack//
// else{
// return Err(ErrorBadRequest(
// "Cannot transfer while under attack",
// ));
// }
}

async fn get_user_base_details(pool: Data<PgPool>, user: AuthUser) -> Result<impl Responder> {
let defender_id = user.0;
let response = web::block(move || {
Expand Down
197 changes: 197 additions & 0 deletions src/api/defense/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use diesel::dsl::exists;
use diesel::{prelude::*, select};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
// use redis::Commands; //Uncomment to check for user under attack//
// use crate::api::RedisPool;

#[derive(Serialize)]
pub struct MineTypeResponse {
Expand Down Expand Up @@ -67,6 +69,43 @@ pub struct DefenceHistoryResponse {
pub games: Vec<Game>,
}

//Uncomment to check for user under attack//

// pub fn check_user_under_attack(redis_pool: &RedisPool, user_id: &i32) -> Result<bool> {
// // Get a connection from the pool
// let mut conn = redis_pool.get()?;

// // Use the GET command to check if the user_id exists and is 'defender'
// let result: Option<String> = conn.get(format!("Game:{}", user_id))?;

// match result {
// Some(_value) => Ok(true),
// //Some(value) if value == "defender_id" => Ok(true),
// _ => Ok(false),
// }
// }

pub fn check_valid_map_id(
conn: &mut PgConnection,
player: &i32,
map_space_id: &i32,
) -> Result<i32> {
use crate::schema::{map_layout, map_spaces};

let map_layout_id = map_layout::table
.filter(map_layout::player.eq(player))
.inner_join(map_spaces::table.on(map_layout::id.eq(map_spaces::map_id))) //.on(map_layout::id.eq(map_spaces::map_id)))
.filter(map_spaces::id.eq(map_space_id))
.select(map_layout::id)
.first::<i32>(conn)
.map_err(|err| DieselError {
table: "map_layout",
function: function!(),
error: err,
})?;
Ok(map_layout_id)
}

pub fn defender_exists(defender: i32, conn: &mut PgConnection) -> Result<bool> {
use crate::schema::user;

Expand All @@ -79,6 +118,164 @@ pub fn defender_exists(defender: i32, conn: &mut PgConnection) -> Result<bool> {
})?)
}

pub fn transfer_artifacts_building(
conn: &mut PgConnection,
building_map_space_id: &i32,
bank_map_space_id: &i32,
new_building_artifact_count: &i32,
new_bank_artifact_count: &i32,
) -> Result<()> {
use crate::schema::artifact;

diesel::update(artifact::table.filter(artifact::map_space_id.eq(building_map_space_id)))
.set(artifact::count.eq(new_building_artifact_count))
.execute(conn)
.map_err(|err| DieselError {
table: "map_spaces",
function: function!(),
error: err,
})
.unwrap();

if *new_building_artifact_count == 0 {
diesel::delete(
artifact::dsl::artifact.filter(artifact::dsl::map_space_id.eq(building_map_space_id)),
)
.execute(conn)
.map_err(|err| DieselError {
table: "shortest_path",
function: function!(),
error: err,
})?;
Ok(())
} else {
diesel::update(artifact::table.filter(artifact::map_space_id.eq(bank_map_space_id)))
.set(artifact::count.eq(new_bank_artifact_count))
.execute(conn)
.map_err(|err| DieselError {
table: "map_spaces",
function: function!(),
error: err,
})
.unwrap();
Ok(())
}
}

pub fn create_artifact_record(
conn: &mut PgConnection,
map_space_id: &i32,
artifact_count: &i32,
) -> Result<()> {
use crate::schema::artifact;

let new_artifact = NewArtifact {
map_space_id: *map_space_id,
count: *artifact_count,
};

diesel::insert_into(artifact::table)
.values(&new_artifact)
.execute(conn)
.map_err(|err| DieselError {
table: "artifact",
function: function!(),
error: err,
})?;

Ok(())
}

pub fn get_bank_map_space_id(
conn: &mut PgConnection,
filtered_layout_id: &i32,
bank_block_type_id: &i32,
) -> Result<i32> {
use crate::schema::map_spaces;
let fetched_bank_map_space_id = map_spaces::table
.filter(map_spaces::map_id.eq(filtered_layout_id))
.filter(map_spaces::block_type_id.eq(bank_block_type_id))
.select(map_spaces::id)
.first::<i32>(conn)
.map_err(|err| DieselError {
table: "map_spaces",
function: function!(),
error: err,
})?;
Ok(fetched_bank_map_space_id)
}

pub fn check_valid_map_space_building(
conn: &mut PgConnection,
given_map_space_id: &i32,
) -> Result<bool> {
use crate::schema::{block_type, building_type, map_spaces};

let category_type = map_spaces::table
.filter(map_spaces::id.eq(given_map_space_id))
.inner_join(block_type::table.on(map_spaces::block_type_id.eq(block_type::id)))
.select(block_type::category)
.first::<BlockCategory>(conn)
.map_err(|err| DieselError {
table: "map_spaces",
function: function!(),
error: err,
})?;

if category_type != BlockCategory::Building {
return Ok(false);
}

let builiding_type_id = map_spaces::table
.filter(map_spaces::id.eq(given_map_space_id))
.inner_join(block_type::table.on(map_spaces::block_type_id.eq(block_type::id)))
.inner_join(building_type::table.on(block_type::building_type.eq(building_type::id)))
.select(building_type::id)
.first::<i32>(conn)
.map_err(|err| DieselError {
table: "map_spaces",
function: function!(),
error: err,
})?;

if builiding_type_id == ROAD_ID {
return Ok(false);
}
Ok(true)
}

pub fn get_building_artifact_count(
conn: &mut PgConnection,
filtered_layout_id: &i32,
given_map_space_id: &i32,
) -> Result<i32> {
use crate::schema::{artifact, map_spaces};
let building_artifact_count = map_spaces::table
.inner_join(artifact::table)
.filter(map_spaces::map_id.eq(filtered_layout_id)) //Eg:1
.filter(map_spaces::id.eq(given_map_space_id))
.select(artifact::count)
.first::<i32>(conn)
.unwrap_or(-1);
Ok(building_artifact_count)
}

pub fn get_building_capacity(conn: &mut PgConnection, given_map_space_id: &i32) -> Result<i32> {
use crate::schema::{block_type, building_type, map_spaces};
let building_capacity = map_spaces::table
.filter(map_spaces::id.eq(given_map_space_id))
.inner_join(block_type::table.on(map_spaces::block_type_id.eq(block_type::id)))
.inner_join(building_type::table.on(block_type::building_type.eq(building_type::id)))
.select(building_type::capacity)
.first::<i32>(conn)
.map_err(|err| DieselError {
table: "map_spaces",
function: function!(),
error: err,
})?;
Ok(building_capacity)
}

pub fn fetch_map_layout(conn: &mut PgConnection, player: &i32) -> Result<MapLayout> {
use crate::schema::map_layout;

Expand Down
Loading
Loading