Skip to content

Commit

Permalink
fix(upgrade): upgrade only for one user (#82)
Browse files Browse the repository at this point in the history
* fix(upgrade): upgrade only for one user

* fix: remove println
  • Loading branch information
itsKhadeer authored Feb 22, 2024
1 parent 7a1a005 commit c4e098e
Show file tree
Hide file tree
Showing 12 changed files with 18 additions and 140 deletions.
37 changes: 7 additions & 30 deletions src/api/attack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,6 @@ async fn init_attack(
.await?
.map_err(|err| error::handle_error(err.into()))?;

println!("obatain {}", obtainable_artifacts);

let mut conn = pool.get().map_err(|err| error::handle_error(err.into()))?;

let user_details =
Expand All @@ -117,7 +115,6 @@ async fn init_attack(
})
.await?
.map_err(|err| error::handle_error(err.into()))?;
println!("Added game: {}", game_id);

//Generate attack token to validate the /attack/start
let attack_token = util::encode_attack_token(attacker_id, opponent_id, game_id)
Expand Down Expand Up @@ -150,7 +147,6 @@ async fn init_attack(
game_id,
};

println!("Sent game id {} to frontend", game_id);
Ok(Json(response))
}

Expand All @@ -160,7 +156,6 @@ async fn socket_handler(
req: HttpRequest,
body: web::Payload,
) -> Result<HttpResponse, Error> {
println!("error bug fs");
let query_params = req.query_string().split('&').collect::<Vec<&str>>();
let user_token = query_params[0].split('=').collect::<Vec<&str>>()[1];
let attack_token = query_params[1].split('=').collect::<Vec<&str>>()[1];
Expand All @@ -171,18 +166,14 @@ async fn socket_handler(
util::decode_attack_token(attack_token).map_err(|err| error::handle_error(err.into()))?;
let game_id = attack_token_data.game_id;

println!("Received game id {} from frontend", game_id);

let mut conn = pool.get().map_err(|err| error::handle_error(err.into()))?;

if attacker_id != attack_token_data.attacker_id {
println!("Attacker:{} is not authorised", attacker_id);
return Err(ErrorBadRequest("User not authorised"));
}

let defender_id = attack_token_data.defender_id;
if attacker_id == defender_id {
println!("Attacker:{} can't attack yourself", attacker_id);
return Err(ErrorBadRequest("Can't attack yourself"));
}

Expand All @@ -191,16 +182,13 @@ async fn socket_handler(
.map_err(|err| error::handle_error(err.into()))?;

if let Ok(Some(_)) = util::get_game_id_from_redis(attacker_id, &mut redis_conn, true) {
println!("Attacker:{} has an ongoing game", attacker_id);
return Err(ErrorBadRequest("Attacker has an ongoing game"));
}

if let Ok(Some(_)) = util::get_game_id_from_redis(defender_id, &mut redis_conn, false) {
println!("Defender:{} has an ongoing game", defender_id);
return Err(ErrorBadRequest("Defender has an ongoing game"));
}

println!("Checking if there are incomplte games");
if util::check_and_remove_incomplete_game(&attacker_id, &defender_id, &game_id, &mut conn)
.is_err()
{
Expand All @@ -223,7 +211,6 @@ async fn socket_handler(
let map_id = if let Some(map) = map {
map
} else {
println!("Defender:{}'s base is invalid", defender_id);
return Err(ErrorBadRequest("Invalid base"));
};

Expand Down Expand Up @@ -385,7 +372,6 @@ async fn socket_handler(
if let Ok(response_json) = serde_json::to_string(&response) {
// println!("Response Json ---- {}", response_json);
if response.result_type == ResultType::GameOver {
println!("Game over. Terminating the socket...");
if session_clone1.text(response_json).await.is_err() {
return;
}
Expand All @@ -402,23 +388,19 @@ async fn socket_handler(
println!("Error terminating the game 1");
}
} else if response.result_type == ResultType::MinesExploded {
println!("MinesExploded response sent");
if session_clone1.text(response_json).await.is_err() {
return;
}
} else if response.result_type == ResultType::DefendersDamaged {
println!("DefendersDamaged response sent");
if session_clone1.text(response_json).await.is_err() {
return;
}
} else if response.result_type == ResultType::DefendersTriggered
{
println!("DefendersTriggered response sent");
if session_clone1.text(response_json).await.is_err() {
return;
}
} else if response.result_type == ResultType::BuildingsDamaged {
println!("BuildingsDamaged response sent");
if util::deduct_artifacts_from_building(
response.damaged_buildings.unwrap(),
&mut conn,
Expand All @@ -431,15 +413,13 @@ async fn socket_handler(
return;
}
} else if response.result_type == ResultType::PlacedAttacker {
println!("PlacedAttacker response sent");
if session_clone1.text(response_json).await.is_err() {
return;
}
} else if response.result_type == ResultType::Nothing {
// println!("Nothing response sent");
if session_clone1.text(response_json).await.is_err() {
return;
}
} else if response.result_type == ResultType::Nothing
&& session_clone1.text(response_json).await.is_err()
{
return;
}
} else {
println!("Error serializing JSON");
Expand All @@ -459,14 +439,14 @@ async fn socket_handler(
}
}
} else {
println!("Error parsing JSON");
println!("Error serializing JSON");

if session_clone1.text("Error parsing JSON").await.is_err() {
return;
}
}
}
Message::Close(s) => {
println!("Received close: {:?}", s);
Message::Close(_s) => {
if util::terminate_game(game_logs, &mut conn, &mut redis_conn).is_err() {
println!("Error terminating the game 2");
}
Expand All @@ -481,7 +461,6 @@ async fn socket_handler(
let timeout_duration = time::Duration::from_secs((GAME_AGE_IN_MINUTES as u64) * 60);
let last_activity = time::Instant::now();

println!("Started timer");
loop {
actix_rt::time::sleep(time::Duration::from_secs(1)).await;

Expand All @@ -504,8 +483,6 @@ async fn socket_handler(
return;
}

println!("Connection timed out");

break;
}
}
Expand Down
37 changes: 1 addition & 36 deletions src/api/attack/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ pub fn add_game(
error: err,
})?;

println!("Successfully inserted game to table: {}", inserted_game.id);
Ok(inserted_game.id)
}

Expand Down Expand Up @@ -341,8 +340,6 @@ pub fn get_random_opponent_id(
return Err(anyhow::anyhow!("Failed to find an opponent"));
};

println!("Random opponent: {}", random_opponent);

loop {
if let Ok(Some(_)) = get_game_id_from_redis(random_opponent, &mut redis_conn, false) {
random_opponent =
Expand All @@ -360,14 +357,12 @@ pub fn get_random_opponent_id(
return Err(anyhow::anyhow!("Failed to find another opponent"))
}
};
println!("Random opponent (retry): {}", random_opponent);
} else {
return Ok(Some(random_opponent));
}
} else {
return Err(anyhow::anyhow!("Cannot check if attack can happen now"));
}
println!("Random opponent: {}", random_opponent);

attempts += 1;
if attempts > 10 {
Expand Down Expand Up @@ -434,15 +429,13 @@ pub fn add_game_id_to_redis(
)
.map_err(|err| anyhow::anyhow!("Failed to set attacker key: {}", err))?;

println!("Attacker:{} redis creation done", attacker_id);
redis_conn
.set_ex(
format!("Defender:{}", defender_id),
game_id,
GAME_AGE_IN_MINUTES * 60,
)
.map_err(|err| anyhow::anyhow!("Failed to set defender key: {}", err))?;
println!("Defender:{} redis creation done", defender_id);

Ok(())
}
Expand Down Expand Up @@ -470,15 +463,12 @@ pub fn delete_game_id_from_redis(
defender_id: i32,
redis_conn: &mut RedisConn,
) -> Result<()> {
println!("Deletion of game ids from redis in progress...");
redis_conn
.del(format!("Attacker:{}", attacker_id))
.map_err(|err| anyhow::anyhow!("Failed to delete attacker key: {}", err))?;
println!("Attacker redis deletion done");
redis_conn
.del(format!("Defender:{}", defender_id))
.map_err(|err| anyhow::anyhow!("Failed to delete defender key: {}", err))?;
println!("Defender redis deletion done");

Ok(())
}
Expand Down Expand Up @@ -694,10 +684,6 @@ pub fn update_buidling_artifacts(
// Update the buildings with the artifact count
for building in buildings.iter_mut() {
building.artifacts_obtained = *artifact_count.get(&building.id).unwrap_or(&0) as i32;
println!(
"during import : == Building id: {},hp: {}, Artifacts: {}",
building.id, building.total_hp, building.artifacts_obtained
);
}

Ok(buildings)
Expand All @@ -716,17 +702,12 @@ pub fn terminate_game(
let artifacts_collected = game_log.r.a;
let game_id = game_log.g;

println!("Damage done: {}", damage_done);
println!("Artifacts Collected: {}", artifacts_collected);

let (attack_score, defense_score) = if damage_done < WIN_THRESHOLD {
(damage_done - 100, 100 - damage_done)
} else {
(damage_done, -damage_done)
};

println!("Attack score: 1");

let attacker_details = user::table
.filter(user::id.eq(attacker_id))
.first::<User>(conn)
Expand All @@ -735,7 +716,6 @@ pub fn terminate_game(
function: function!(),
error: err,
})?;
println!("Attack score: 2");

let defender_details = user::table
.filter(user::id.eq(defender_id))
Expand All @@ -746,8 +726,6 @@ pub fn terminate_game(
error: err,
})?;

println!("Attack score: 3");

let attack_score = attack_score as f32 / 100_f32;
let defence_score = defense_score as f32 / 100_f32;

Expand All @@ -758,18 +736,13 @@ pub fn terminate_game(
defence_score,
);

println!("Attack score: 4");

//Add bonus trophies (just call the function)

game_log.r.oa = attacker_details.trophies;
game_log.r.od = defender_details.trophies;
game_log.r.na = new_trophies.0;
game_log.r.nd = new_trophies.1;

println!("Attack score: 5");

println!("Going to update game table {}", game_id);
diesel::update(game::table.find(game_id))
.set((
game::damage_done.eq(damage_done),
Expand All @@ -786,9 +759,6 @@ pub fn terminate_game(
error: err,
})?;

println!("Done update game table {}", game_id);
println!("Attack score: 6");

let (attacker_wins, defender_wins) = if damage_done < WIN_THRESHOLD {
(0, 1)
} else {
Expand Down Expand Up @@ -862,8 +832,6 @@ pub fn terminate_game(
// println!("Event: {:?}\n", event);
// }

println!("Result: {:?}", game_log.r);
println!("Game termination is done");
Ok(())
}

Expand All @@ -890,10 +858,9 @@ pub fn check_and_remove_incomplete_game(
error: err,
})?;

let len = pending_games.len();
let _len = pending_games.len();

for pending_game in pending_games {
println!("removing game id {}", pending_game.id);
diesel::delete(game.filter(id.eq(pending_game.id)))
.execute(conn)
.map_err(|err| DieselError {
Expand All @@ -903,8 +870,6 @@ pub fn check_and_remove_incomplete_game(
})?;
}

println!("Removed {} incomplete games", len);

Ok(())
}

Expand Down
1 change: 0 additions & 1 deletion src/api/defense/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ async fn set_base_details(
user: AuthUser,
) -> Result<impl Responder> {
let defender_id = user.0;
println!("Defender ID: {}", defender_id);
let map_spaces = map_spaces.into_inner();
let mut conn = pool.get().map_err(|err| error::handle_error(err.into()))?;
let (map, blocks, buildings) = web::block(move || {
Expand Down
5 changes: 0 additions & 5 deletions src/api/defense/shortest_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,5 @@ pub fn run_shortest_paths(
// })?;
// }

println!(
"shortest path ------------------------------------------------------------------- {:?}",
shortest_paths.len()
);

Ok(shortest_paths)
}
6 changes: 0 additions & 6 deletions src/api/defense/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,6 @@ pub fn is_valid_save_layout(
let building_type = block.building_type;

if artifacts > buildings[&building_type].capacity {
println!("Artifacts: {}", artifacts);
println!("Capacity: {}", buildings[&building_type].capacity);
println!("Building name: {}", buildings[&building_type].name);
println!("Block id: {}", block_type_id);
return Err(BaseInvalidError::InvalidArtifactCount);
}

Expand Down Expand Up @@ -175,8 +171,6 @@ pub fn is_valid_save_layout(
}
}

println!("Total Artifacts: {}", total_artifacts);
println!("User Artifacts: {}", user_artifacts);
if total_artifacts != *user_artifacts {
return Err(BaseInvalidError::InvalidArtifactCount);
}
Expand Down
3 changes: 0 additions & 3 deletions src/api/game/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,12 @@ async fn get_game_details(
let user_id = user.0;
let game_id = game_id.into_inner();

println!("Request for game_id stats: {}", game_id);

let response = web::block(move || {
let mut conn = pool.get()?;
util::fetch_game_details(game_id, user_id, &mut conn)
})
.await?
.map_err(|err| error::handle_error(err.into()))?;

println!("{:#?}", response);
Ok(web::Json(response))
}
2 changes: 0 additions & 2 deletions src/api/game/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,6 @@ pub fn fetch_replay(game_id: i32, conn: &mut PgConnection) -> Result<SimulationL
pub fn fetch_game_details(game_id: i32, user_id: i32, conn: &mut PgConnection) -> Result<Game> {
use crate::schema::game;

println!("Fetching game details for game_id: {}", game_id);

Ok(game::table
.filter(game::id.eq(game_id))
.filter(game::attack_id.eq(user_id).or(game::defend_id.eq(user_id)))
Expand Down
Loading

0 comments on commit c4e098e

Please sign in to comment.