Server action refactoring part 9 of N
authoralfadur <mail@none>
Wed, 06 Feb 2019 00:14:04 +0300
changeset 14707 9f98086de1b6
parent 14706 669eb45bda72
child 14708 5122c584804e
Server action refactoring part 9 of N
rust/hedgewars-server/src/server/actions.rs
rust/hedgewars-server/src/server/core.rs
rust/hedgewars-server/src/server/handlers/common.rs
rust/hedgewars-server/src/server/handlers/inroom.rs
rust/hedgewars-server/src/server/handlers/lobby.rs
rust/hedgewars-server/src/server/handlers/loggingin.rs
--- a/rust/hedgewars-server/src/server/actions.rs	Tue Feb 05 23:18:47 2019 +0300
+++ b/rust/hedgewars-server/src/server/actions.rs	Wed Feb 06 00:14:04 2019 +0300
@@ -103,7 +103,6 @@
 
 pub enum Action {
     ChangeMaster(RoomId, Option<ClientId>),
-    SendRoomUpdate(Option<String>),
     StartRoomGame(RoomId),
     SendTeamRemovalMessage(String),
     FinishRoomGame(RoomId),
@@ -113,10 +112,6 @@
         config: bool,
         flags: bool,
     },
-    AddVote {
-        vote: bool,
-        is_forced: bool,
-    },
     ApplyVoting(VoteType, RoomId),
 }
 
@@ -130,7 +125,6 @@
             config,
             flags,
         } => {
-            let mut actions = Vec::new();
             let room_id = server.clients[client_id].room_id;
             if let Some(r) = room_id.and_then(|id| server.rooms.get(id)) {
                 if config {
@@ -185,63 +179,6 @@
                     }
                 }
             }
-            server.react(client_id, actions);
-        }
-        AddVote { vote, is_forced } => {
-            let mut actions = Vec::new();
-            if let Some(r) = server.room(client_id) {
-                let mut result = None;
-                if let Some(ref mut voting) = r.voting {
-                    if is_forced || voting.votes.iter().all(|(id, _)| client_id != *id) {
-                        /*                        actions.push(
-                            server_chat("Your vote has been counted.".to_string())
-                                .send_self()
-                                .action(),
-                        )*/
-;
-                        voting.votes.push((client_id, vote));
-                        let i = voting.votes.iter();
-                        let pro = i.clone().filter(|(_, v)| *v).count();
-                        let contra = i.filter(|(_, v)| !*v).count();
-                        let success_quota = voting.voters.len() / 2 + 1;
-                        if is_forced && vote || pro >= success_quota {
-                            result = Some(true);
-                        } else if is_forced && !vote || contra > voting.voters.len() - success_quota
-                        {
-                            result = Some(false);
-                        }
-                    } else {
-                        /*                        actions.push(
-                            server_chat("You already have voted.".to_string())
-                                .send_self()
-                                .action(),
-                        )*/
-;
-                    }
-                } else {
-                    /*                    actions.push(
-                        server_chat("There's no voting going on.".to_string())
-                            .send_self()
-                            .action(),
-                    )*/
-;
-                }
-
-                if let Some(res) = result {
-                    /*actions.push(
-                        server_chat("Voting closed.".to_string())
-                            .send_all()
-                            .in_room(r.id)
-                            .action(),
-                    );*/
-                    let voting = replace(&mut r.voting, None).unwrap();
-                    if res {
-                        actions.push(ApplyVoting(voting.kind, r.id));
-                    }
-                }
-            }
-
-            server.react(client_id, actions);
         }
         ApplyVoting(kind, room_id) => {
             let mut actions = Vec::new();
@@ -265,7 +202,7 @@
                                 .in_room(room_id)
                                 .action(),
                         );*/
-                        actions.push(SendRoomUpdate(None));
+                        //actions.push(SendRoomUpdate(None));
                         for (_, c) in server.clients.iter() {
                             if c.room_id == Some(room_id) {
                                 actions.push(SendRoomData {
@@ -312,10 +249,8 @@
                     }));*/
                 }
             }
-            server.react(id, actions);
         }
         ChangeMaster(room_id, new_id) => {
-            let mut actions = Vec::new();
             let room_client_ids = server.room_clients(room_id);
             let new_id = if server
                 .room(client_id)
@@ -364,55 +299,38 @@
             if let Some(id) = new_id {
                 server.clients[id].set_is_master(true)
             }
-            server.react(client_id, actions);
-        }
-        SendRoomUpdate(old_name) => {
-            if let (c, Some(r)) = server.client_and_room(client_id) {
-                let name = old_name.unwrap_or_else(|| r.name.clone());
-                /*let actions = vec![RoomUpdated(name, r.info(Some(&c)))
-                    .send_all()
-                    .with_protocol(r.protocol_number)
-                    .action()];
-                server.react(client_id, actions);*/
-            }
         }
         StartRoomGame(room_id) => {
-            let actions = {
-                let (room_clients, room_nicks): (Vec<_>, Vec<_>) = server
-                    .clients
-                    .iter()
-                    .map(|(id, c)| (id, c.nick.clone()))
-                    .unzip();
-                let room = &mut server.rooms[room_id];
+            let (room_clients, room_nicks): (Vec<_>, Vec<_>) = server
+                .clients
+                .iter()
+                .map(|(id, c)| (id, c.nick.clone()))
+                .unzip();
+            let room = &mut server.rooms[room_id];
 
-                if !room.has_multiple_clans() {
-                    vec![/*Warn(
-                        "The game can't be started with less than two clans!".to_string(),
-                    )*/]
-                } else if room.protocol_number <= 43
-                    && room.players_number != room.ready_players_number
-                {
-                    vec![/*Warn("Not all players are ready".to_string())*/]
-                } else if room.game_info.is_some() {
-                    vec![/*Warn("The game is already in progress".to_string())*/]
-                } else {
-                    room.start_round();
-                    for id in room_clients {
-                        let c = &mut server.clients[id];
-                        c.set_is_in_game(false);
-                        c.team_indices = room.client_team_indices(c.id);
-                    }
-                    vec![
-                        /*RunGame.send_all().in_room(room.id).action(),*/
-                        SendRoomUpdate(None),
-                        /*ClientFlags("+g".to_string(), room_nicks)
-                        .send_all()
-                        .in_room(room.id)
-                        .action(),*/
-                    ]
+            if !room.has_multiple_clans() {
+                /*Warn(
+                    "The game can't be started with less than two clans!".to_string(),
+                )*/
+            } else if room.protocol_number <= 43 && room.players_number != room.ready_players_number
+            {
+                /*Warn("Not all players are ready".to_string())*/
+            } else if room.game_info.is_some() {
+                /*Warn("The game is already in progress".to_string())*/
+            } else {
+                room.start_round();
+                for id in room_clients {
+                    let c = &mut server.clients[id];
+                    c.set_is_in_game(false);
+                    c.team_indices = room.client_team_indices(c.id);
                 }
-            };
-            server.react(client_id, actions);
+                /*RunGame.send_all().in_room(room.id).action(),*/
+                //SendRoomUpdate(None),
+                /*ClientFlags("+g".to_string(), room_nicks)
+                .send_all()
+                .in_room(room.id)
+                .action(),*/
+            }
         }
         SendTeamRemovalMessage(team_name) => {
             let mut actions = Vec::new();
@@ -447,14 +365,13 @@
                     );*/
                 }
             }
-            server.react(client_id, actions);
         }
         FinishRoomGame(room_id) => {
             let mut actions = Vec::new();
 
             let r = &mut server.rooms[room_id];
             r.ready_players_number = 1;
-            actions.push(SendRoomUpdate(None));
+            //actions.push(SendRoomUpdate(None));
             //actions.push(RoundFinished.send_all().in_room(r.id).action());
 
             if let Some(info) = replace(&mut r.game_info, None) {
@@ -499,7 +416,6 @@
                 };
                 //actions.push(msg.send_all().in_room(room_id).action());
             }
-            server.react(client_id, actions);
         }
     }
 }
--- a/rust/hedgewars-server/src/server/core.rs	Tue Feb 05 23:18:47 2019 +0300
+++ b/rust/hedgewars-server/src/server/core.rs	Wed Feb 06 00:14:04 2019 +0300
@@ -105,12 +105,6 @@
         self.send(client_id, &message.destination, message.message)
     }
 
-    pub fn react(&mut self, client_id: ClientId, actions: Vec<actions::Action>) {
-        for action in actions {
-            actions::run_action(self, client_id, action);
-        }
-    }
-
     pub fn lobby(&self) -> &HWRoom {
         &self.rooms[self.lobby_id]
     }
--- a/rust/hedgewars-server/src/server/handlers/common.rs	Tue Feb 05 23:18:47 2019 +0300
+++ b/rust/hedgewars-server/src/server/handlers/common.rs	Wed Feb 06 00:14:04 2019 +0300
@@ -1,3 +1,4 @@
+use crate::protocol::messages::server_chat;
 use crate::server::client::HWClient;
 use crate::server::coretypes::ClientId;
 use crate::server::room::HWRoom;
@@ -14,6 +15,7 @@
 };
 use rand::{self, thread_rng, Rng};
 use std::iter::once;
+use std::mem::replace;
 
 pub fn rnd_reply(options: &[String]) -> HWServerMessage {
     let mut rng = thread_rng();
@@ -186,6 +188,52 @@
     response.add(Bye("User quit: ".to_string() + &msg).send_self());
 }
 
+pub fn get_room_update(
+    room_name: Option<String>,
+    room: &HWRoom,
+    client: Option<&HWClient>,
+    response: &mut super::Response,
+) {
+    let update_msg = RoomUpdated(room_name.unwrap_or(room.name.clone()), room.info(client));
+    response.add(update_msg.send_all().with_protocol(room.protocol_number));
+}
+
+pub fn add_vote(room: &mut HWRoom, response: &mut super::Response, vote: bool, is_forced: bool) {
+    let client_id = response.client_id;
+    let mut result = None;
+    if let Some(ref mut voting) = room.voting {
+        if is_forced || voting.votes.iter().all(|(id, _)| client_id != *id) {
+            response.add(server_chat("Your vote has been counted.".to_string()).send_self());
+            voting.votes.push((client_id, vote));
+            let i = voting.votes.iter();
+            let pro = i.clone().filter(|(_, v)| *v).count();
+            let contra = i.filter(|(_, v)| !*v).count();
+            let success_quota = voting.voters.len() / 2 + 1;
+            if is_forced && vote || pro >= success_quota {
+                result = Some(true);
+            } else if is_forced && !vote || contra > voting.voters.len() - success_quota {
+                result = Some(false);
+            }
+        } else {
+            response.add(server_chat("You already have voted.".to_string()).send_self());
+        }
+    } else {
+        response.add(server_chat("There's no voting going on.".to_string()).send_self());
+    }
+
+    if let Some(res) = result {
+        response.add(
+            server_chat("Voting closed.".to_string())
+                .send_all()
+                .in_room(room.id),
+        );
+        let voting = replace(&mut room.voting, None).unwrap();
+        if res {
+            //ApplyVoting(voting.kind, room.id));
+        }
+    }
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
--- a/rust/hedgewars-server/src/server/handlers/inroom.rs	Tue Feb 05 23:18:47 2019 +0300
+++ b/rust/hedgewars-server/src/server/handlers/inroom.rs	Wed Feb 06 00:14:04 2019 +0300
@@ -165,8 +165,7 @@
                 let client = &server.clients[client_id];
                 let room = &mut server.rooms[room_id];
                 swap(&mut room.name, &mut old_name);
-                let update_msg = RoomUpdated(old_name, room.info(Some(client)));
-                response.add(update_msg.send_all().with_protocol(room.protocol_number));
+                super::common::get_room_update(Some(old_name), room, Some(&client), response);
             };
         }
         ToggleReady => {
@@ -235,8 +234,7 @@
                             .in_room(room_id),
                     );
 
-                    let update_msg = RoomUpdated(room.name.clone(), room.info(Some(client)));
-                    response.add(update_msg.send_all().with_protocol(room.protocol_number));
+                    super::common::get_room_update(None, room, Some(&client), response);
                 }
             }
         }
@@ -458,9 +456,10 @@
                 None => {
                     let msg = voting_description(&kind);
                     let voting = Voting::new(kind, server.room_clients(client_id));
-                    server.rooms[room_id].voting = Some(voting);
+                    let room = &mut server.rooms[room_id];
+                    room.voting = Some(voting);
                     response.add(server_chat(msg).send_all().in_room(room_id));
-                    //AddVote{ vote: true, is_forced: false}
+                    super::common::add_vote(room, response, true, false);
                 }
                 Some(msg) => {
                     response.add(server_chat(msg).send_self());
@@ -468,31 +467,24 @@
             }
         }
         Vote(vote) => {
-            server.react(
-                client_id,
-                vec![AddVote {
-                    vote,
-                    is_forced: false,
-                }],
-            );
+            super::common::add_vote(&mut server.rooms[room_id], response, vote, false);
         }
         ForceVote(vote) => {
             let is_forced = server.clients[client_id].is_admin();
-            server.react(client_id, vec![AddVote { vote, is_forced }]);
+            super::common::add_vote(&mut server.rooms[room_id], response, vote, false);
         }
         ToggleRestrictJoin | ToggleRestrictTeams | ToggleRegisteredOnly => {
-            if server.clients[client_id].is_master() {
-                server.rooms[room_id]
-                    .flags
-                    .toggle(room_message_flag(&message));
+            let client = &server.clients[client_id];
+            let room = &mut server.rooms[room_id];
+            if client.is_master() {
+                room.flags.toggle(room_message_flag(&message));
+                super::common::get_room_update(None, room, Some(&client), response);
             }
-            server.react(client_id, vec![SendRoomUpdate(None)]);
         }
         StartGame => {
-            server.react(client_id, vec![StartRoomGame(room_id)]);
+            // StartRoomGame(room_id);
         }
         EngineMessage(em) => {
-            let mut actions = Vec::new();
             if let (c, Some(r)) = server.client_and_room(client_id) {
                 if c.teams_in_game > 0 {
                     let decoding = decode(&em[..]).unwrap();
@@ -529,10 +521,8 @@
                     }
                 }
             }
-            server.react(client_id, actions)
         }
         RoundFinished => {
-            let mut actions = Vec::new();
             if let (c, Some(r)) = server.client_and_room(client_id) {
                 if c.is_in_game() {
                     c.set_is_in_game(false);
@@ -543,12 +533,11 @@
                     );
                     if r.game_info.is_some() {
                         for team in r.client_teams(c.id) {
-                            actions.push(SendTeamRemovalMessage(team.name.clone()));
+                            //SendTeamRemovalMessage(team.name.clone());
                         }
                     }
                 }
             }
-            server.react(client_id, actions)
         }
         Rnd(v) => {
             let result = rnd_reply(&v);
--- a/rust/hedgewars-server/src/server/handlers/lobby.rs	Tue Feb 05 23:18:47 2019 +0300
+++ b/rust/hedgewars-server/src/server/handlers/lobby.rs	Wed Feb 06 00:14:04 2019 +0300
@@ -67,25 +67,25 @@
                 .filter(|(_, c)| c.room_id == room_id)
                 .map(|(_, c)| c.nick.clone())
                 .collect();
-            let c = &mut server.clients[client_id];
+            let client = &mut server.clients[client_id];
 
-            if let Some((_, r)) = room {
-                if c.protocol_number != r.protocol_number {
+            if let Some((_, room)) = room {
+                if client.protocol_number != room.protocol_number {
                     response.add(
                         Warning("Room version incompatible to your Hedgewars version!".to_string())
                             .send_self(),
                     );
-                } else if r.is_join_restricted() {
+                } else if room.is_join_restricted() {
                     response.add(
                         Warning(
                             "Access denied. This room currently doesn't allow joining.".to_string(),
                         )
                         .send_self(),
                     );
-                } else if r.players_number == u8::max_value() {
+                } else if room.players_number == u8::max_value() {
                     response.add(Warning("This room is already full".to_string()).send_self());
                 } else if let Some(room_id) = room_id {
-                    let nick = c.nick.clone();
+                    let nick = client.nick.clone();
                     server.move_to_room(client_id, room_id);
 
                     response.add(RoomJoined(vec![nick.clone()]).send_all().in_room(room_id));
--- a/rust/hedgewars-server/src/server/handlers/loggingin.rs	Tue Feb 05 23:18:47 2019 +0300
+++ b/rust/hedgewars-server/src/server/handlers/loggingin.rs	Wed Feb 06 00:14:04 2019 +0300
@@ -87,7 +87,7 @@
             //TODO enter lobby
             } else {
                 super::common::remove_client(server, response, "Authentication failed".to_string())
-            };
+            }
         }
         #[cfg(feature = "official-server")]
         HWProtocolMessage::Checker(protocol, nick, password) => {