Browse Source

Edit timer system to one-hour cleaner

Tigran 4 years ago
parent
commit
cc0b07341f

+ 2 - 5
MafiaTelegramBot/Controllers/RoomController.cs

@@ -25,7 +25,6 @@ namespace MafiaTelegramBot.Controllers
                 room.Players.Add(creator.Id, creator);
                 
                 room.SetTimer();
-                creator.StopTimer();
                 
                 return ResultCode.CodeOk;
             });
@@ -42,9 +41,8 @@ namespace MafiaTelegramBot.Controllers
                 if (!player.SetRoomName(roomName)) return ResultCode.UserAlreadyInGame;
                 OpenedGames[roomKey].Players.Add(player.Id, player);
 
-                if (OpenedGames[roomKey].Players.Count > Constants.PLAYER_DISABLE_TIMER)
+                if (OpenedGames[roomKey].Players.Count > Constants.MEMORY_CLEANER_INTERVAL)
                     OpenedGames[roomKey].StopTimer();
-                player.StopTimer();
                 
                 await OpenedGames[roomKey].PlayersCh.SendExcept(player.Id, $"{player.NickName} {strings.connected_to_game}");
                 return ResultCode.CodeOk;
@@ -65,9 +63,8 @@ namespace MafiaTelegramBot.Controllers
                 if (!await player.RemoveGame()) return ResultCode.UserNotInGame;
                 await OpenedGames[roomKey].Leave(player);
                 if (!OpenedGames[roomKey].IsRunning &&
-                    OpenedGames[roomKey].Players.Count <= Constants.PLAYER_DISABLE_TIMER)
+                    OpenedGames[roomKey].Players.Count <= Constants.MEMORY_CLEANER_INTERVAL)
                     OpenedGames[roomKey].StartTimer();
-                player.StartTimer();
                 if (OpenedGames[roomKey].Players.Count >= 0) return ResultCode.CodeOk;
                 RoomEncrypter.RemoveCode(roomName);
                 OpenedGames.Remove(roomKey);

+ 26 - 1
MafiaTelegramBot/DataBase/EntityDao/UserDao.cs

@@ -2,6 +2,7 @@ using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
+using System.Timers;
 using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.Game;
 using MafiaTelegramBot.Resources;
@@ -13,6 +14,17 @@ namespace MafiaTelegramBot.DataBase.EntityDao
     {
         public static readonly MafiaDataBase DataBase = MafiaDataBase.GetInstance();
         public static readonly Dictionary<long, Player> ActiveUsers = new();
+
+        static UserDao()
+        {
+            var memoryCleaner = new Timer
+            {
+                Interval = Constants.MEMORY_CLEANER_INTERVAL,
+                AutoReset = true
+            };
+            memoryCleaner.Elapsed += async (_, _) => await CleanupMemory();
+            memoryCleaner.Start();
+        }
         public static async Task<Player> GetPlayerById(long id)
         {
             if (ActiveUsers.ContainsKey(id)) return ActiveUsers[id];
@@ -21,7 +33,6 @@ namespace MafiaTelegramBot.DataBase.EntityDao
             player.OpenedRoles = await OpenedRolesDao.GetOpenedRolesById(id);
             player.Achievements = await AchievementsDao.GetAchievementsProgressById(id);
             ActiveUsers.Add(user.Id, player);
-            ActiveUsers[user.Id].SetTimer();
             return player;
         }
         
@@ -68,5 +79,19 @@ namespace MafiaTelegramBot.DataBase.EntityDao
             if (ActiveUsers.ContainsKey(id)) return true;
             return await DataBase.Users.AnyAsync(user => user.Id == id);
         }
+
+        private static async Task CleanupMemory()
+        {
+            await Task.Run(() =>
+            {
+                foreach (var (id, player) in ActiveUsers)
+                {
+                    if (player.GetLastActivityInterval()
+                            .CompareTo(Constants.PLAYER_INACTIVE_INTERVAL) == 1
+                        && player.IsPlaying == false)
+                        ActiveUsers.Remove(id);
+                }
+            });
+        }
     }
 }

+ 1 - 1
MafiaTelegramBot/Game/GameRooms/GameRoom.GameProcess.cs

@@ -582,7 +582,7 @@ namespace MafiaTelegramBot.Game.GameRooms
                     await Bot.SendWithMarkdown2(Owner.ChatId, strings.thanks_for_game, Keyboard.OwnerGameMenu);
                     await PlayersCh.SendExcept(Owner.Id, strings.thanks_for_game, Keyboard.PlayerGameMenu);
                 }
-                if (Players.Count <= Constants.PLAYER_DISABLE_TIMER) StartTimer();
+                if (Players.Count <= Constants.MEMORY_CLEANER_INTERVAL) StartTimer();
             });
         }
     }

+ 5 - 38
MafiaTelegramBot/Game/Player.cs

@@ -4,7 +4,6 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 using MafiaTelegramBot.CustomCollections;
-using MafiaTelegramBot.DataBase;
 using MafiaTelegramBot.DataBase.Entity;
 using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game.GameRoles;
@@ -20,8 +19,7 @@ namespace MafiaTelegramBot.Game
         public GameRooms.GameRoom.Role CurrentRole = new NoneRole();
         public int TurnOrder = -1;
         private string _roomName = "";
-
-        private static System.Timers.Timer _activeTime = new();
+        private DateTime _lastActivity;
         public bool IsSpeaker;
         public bool IsPlaying;
         public bool IsAlive = true;
@@ -44,45 +42,14 @@ namespace MafiaTelegramBot.Game
             return true;
         }
 
-        public void SetTimer()
-        {
-            _activeTime = new System.Timers.Timer(3600000);
-            _activeTime.Elapsed += async (x , y) =>
-            {
-                await Remove();
-            };
-            _activeTime.Enabled = true;
-        }
-
-        public void Restart()
-        {
-            if (_activeTime.Enabled)
-                _activeTime.Stop();
-            _activeTime.Start();
-        }
-
-        public void StopTimer()
+        public void SetActive()
         {
-            _activeTime.Stop();
+            _lastActivity = DateTime.Now;
         }
 
-        public void StartTimer()
+        public TimeSpan GetLastActivityInterval()
         {
-            _activeTime.Start();
-        }
-
-        private async Task Remove()
-        {
-            try
-            {
-                UserDao.ActiveUsers.Remove(Id);
-                _activeTime.Dispose();
-            }
-            catch (Exception)
-            {
-                await Console.Out.WriteLineAsync("Cant delete user!");
-            }
-            //await Bot.SendHyperLink(ChatId, "Inactive now!");
+            return DateTime.Now.Subtract(_lastActivity);
         }
         
         public static Player FromUserEntity(UserEntity b)

+ 3 - 5
MafiaTelegramBot/Models/Commands/Command.cs

@@ -29,16 +29,14 @@ namespace MafiaTelegramBot.Models.Commands
             var chatId = update.Message.Chat.Id;
             await Bot.Get().SendChatActionAsync(chatId, ChatAction.Typing);
             var userId = update.Message.From.Id;
+            var user = await UserDao.GetPlayerById(userId);
+            user.SetActive();
             var commands = Bot.Commands;
             var message = update.Message.Text;
             var startCommand = new StartCommand();
             //TODO refactor later
             if (message.Contains(startCommand.Name)) return await ((Command?) startCommand.Clone(chatId, userId))!.Execute(update);
-            
-            var user = await UserDao.GetPlayerById(userId);
-            
-            UserDao.GetPlayerById(userId).Result.Restart();
-            
+
             if (user.IsPlaying)
             {
                 var roomKey = RoomEncrypter.GetCode(user.GetRoomName());

+ 1 - 0
MafiaTelegramBot/Models/Inlines/Query.cs

@@ -24,6 +24,7 @@ namespace MafiaTelegramBot.Models.Inlines
             var data = update.CallbackQuery.Data;
             var userId = long.Parse(data.Split('|')[1]);
             var user = await UserDao.GetPlayerById(userId);
+            user.SetActive();
             if (user.IsPlaying)
             {
                 var roomKey = RoomEncrypter.GetCode(user.GetRoomName());

+ 3 - 1
MafiaTelegramBot/Resources/Constants.cs

@@ -1,3 +1,4 @@
+using System;
 using System.Collections.Generic;
 using Telegram.Bot.Types.Payments;
 
@@ -6,7 +7,8 @@ namespace MafiaTelegramBot.Resources
     public static class Constants
     {
         public const int PLAYER_LIMITS_MIN = 6;
-        public const int PLAYER_DISABLE_TIMER = 3;
+        public const int MEMORY_CLEANER_INTERVAL = 60 * 60 * 1000;
+        public static readonly TimeSpan PLAYER_INACTIVE_INTERVAL = new(1, 0, 0);
         public const int MINUTES_UNTIL_DISSOLVE = 10;
         public const int PLAYER_LIMITS_MAX = 16;
         public const int MAX_SHOWING_ROOMS = 10;