Skip to content

Commit

Permalink
/game post: any discord user may sign for the associated player
Browse files Browse the repository at this point in the history
  • Loading branch information
laggycomputer committed Sep 19, 2024
1 parent 8f396b3 commit c701b3f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 15 deletions.
38 changes: 24 additions & 14 deletions src/commands/ewar/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use serenity::all::{CreateActionRow, CreateButton, CreateInteractionResponse, Cr
use std::collections::HashSet;
use std::convert::identity;
use std::num::NonZeroUsize;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use timeago::TimeUnit::Seconds;

Expand Down Expand Up @@ -114,7 +115,7 @@ pub(crate) async fn post(
].into_iter().filter_map(identity).collect_vec();

// part 1: validate proposed game
let poster_info = try_lookup_player(&ctx.data().mongo, DiscordID(ctx.author().id.get())).await?
let poster_player = try_lookup_player(&ctx.data().mongo, DiscordID(ctx.author().id.get())).await?
.expect("user disappeared after check");

let poster_not_moderator = !_is_league_moderator(ctx).await?;
Expand Down Expand Up @@ -162,8 +163,8 @@ pub(crate) async fn post(
return Ok(());
}

let mut not_signed_off = placement_discord.clone().into_iter().collect::<HashSet<_>>();
not_signed_off.remove(&ctx.author());
let mut not_signed_off = placement_players.clone().into_iter().collect::<HashSet<_>>();
not_signed_off.remove(&poster_player);

// remove "please react below..." and button
waited.unwrap().create_response(ctx.http(), CreateInteractionResponse::UpdateMessage(
Expand All @@ -182,7 +183,7 @@ pub(crate) async fn post(
// part 3: parties to game must sign
// moderators can skip this
if poster_not_moderator {
let make_signoff_msg = |not_signed_off: &HashSet<User>, disable_button: bool| (
let make_signoff_msg = |not_signed_off: &HashSet<Player>, disable_button: bool| (
format!(
"please sign off on this game with :white_check_mark:\n\
currently have {}/{} required to submit game\n\
Expand All @@ -193,7 +194,11 @@ pub(crate) async fn post(
placement_discord.len() - not_signed_off.len(),
pluralize("signature", num_need_to_sign as isize, true),
placement_discord.iter().map(|user| {
if not_signed_off.contains(user) { user.mention().to_string() } else { format!("~~{}~~", user.mention()) }
if not_signed_off.iter().find(|p| p.discord_ids.contains(&user.id.get())).is_some() {
user.mention().to_string()
} else {
format!("~~{}~~", user.mention())
}
}).join("\n")),
vec![
CreateActionRow::Buttons(vec![
Expand All @@ -207,16 +212,18 @@ pub(crate) async fn post(
.components(signoff_components)).await?
.into_message().await?;

while not_signed_off.len() > max_not_signing {
let not_signed_off_freeze = not_signed_off.clone();
let not_signed_off_arc = Arc::new(RwLock::new(not_signed_off));

while not_signed_off_arc.read().unwrap().len() > max_not_signing {
let not_signed_off_closure = not_signed_off_arc.clone();
match party_sign_stage_msg.await_component_interaction(&ctx.serenity_context().shard)
.filter(move |ixn| {
not_signed_off_freeze.contains(&ixn.user)
not_signed_off_closure.read().unwrap().iter().find(|p| p.discord_ids.contains(&ixn.user.id.get())).is_some()
})
.timeout(Duration::from_secs(5 * 60))
.await {
None => {
let (_, signoff_components) = make_signoff_msg(&not_signed_off, true);
let (_, signoff_components) = make_signoff_msg(&not_signed_off_arc.read().unwrap(), true);

party_sign_stage_msg.edit(
ctx.http(),
Expand All @@ -232,9 +239,12 @@ pub(crate) async fn post(
.content("ok, signed off on this game")
.ephemeral(true))).await?;

not_signed_off.remove(&ixn.user);
match not_signed_off_arc.read().unwrap().iter().find(|p| p.discord_ids.contains(&ixn.user.id.get())) {
Some(p) => { not_signed_off_arc.write().unwrap().remove(p); }
None => {}
}

let (signoff_content, signoff_components) = make_signoff_msg(&not_signed_off, false);
let (signoff_content, signoff_components) = make_signoff_msg(&not_signed_off_arc.read().unwrap(), false);
party_sign_stage_msg.edit(
ctx.http(),
EditMessage::new()
Expand All @@ -245,7 +255,7 @@ pub(crate) async fn post(
}
}

let (_, signoff_components) = make_signoff_msg(&not_signed_off, true);
let (_, signoff_components) = make_signoff_msg(&not_signed_off_arc.read().unwrap(), true);
party_sign_stage_msg.edit(
ctx.http(),
EditMessage::new()
Expand Down Expand Up @@ -275,7 +285,7 @@ pub(crate) async fn post(
let event = StandingEvent {
_id: available_event_number,
approval_status: if poster_not_moderator { None } else {
Some(ApprovalStatus { approved: true, reviewer: Some(poster_info._id) })
Some(ApprovalStatus { approved: true, reviewer: Some(poster_player._id) })
},
inner: GameEnd(signed_game),
when: submitted_time,
Expand Down Expand Up @@ -451,7 +461,7 @@ pub(crate) async fn log(
}

EmbedLinePaginator::new(lines, PaginatorOptions::new()
.max_lines(NonZeroUsize::new(10).unwrap())
.max_lines(NonZeroUsize::new(10).unwrap()),
).run(ctx).await?;

Ok(())
Expand Down
18 changes: 17 additions & 1 deletion src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ use chrono::Utc;
use serde::{Deserialize, Serialize};
use skillratings::trueskill::TrueSkillRating;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

pub(crate) type EventNumber = u32;
pub(crate) type GameID = i64;
pub(crate) type PlayerID = i32;
Expand Down Expand Up @@ -55,7 +57,7 @@ pub(crate) struct StandingEvent {
pub(crate) when: chrono::DateTime<Utc>,
}

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct Player {
pub(crate) _id: PlayerID,
pub(crate) username: String,
Expand All @@ -66,6 +68,20 @@ pub(crate) struct Player {
pub(crate) discord_ids: Vec<u64>,
}

impl PartialEq<Self> for Player {
fn eq(&self, other: &Self) -> bool {
self._id.eq(&other._id)
}
}

impl Eq for Player {}

impl Hash for Player {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self._id.hash(hasher)
}
}

impl Player {
pub(crate) fn rating_struct(&self) -> TrueSkillRating {
TrueSkillRating { rating: self.rating, uncertainty: self.deviation }
Expand Down

0 comments on commit c701b3f

Please sign in to comment.