瀏覽代碼

Stop command complete

Tigran 4 年之前
父節點
當前提交
ecf85f7c66

+ 2 - 2
CardCollector.sln.DotSettings.user

@@ -1,11 +1,11 @@
 <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
 	
-	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FCommand/@EntryIndexedValue">False</s:Boolean>
+	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FCommand/@EntryIndexedValue">True</s:Boolean>
 	
 	
 	
 	
-	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FMessages/@EntryIndexedValue">True</s:Boolean>
+	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FMessages/@EntryIndexedValue">False</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FSortingTypes/@EntryIndexedValue">False</s:Boolean>
 	<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=CardCollector_002FResources_002FText/@EntryIndexedValue">False</s:Boolean>
 	

+ 20 - 9
CardCollector/Bot.cs

@@ -1,5 +1,6 @@
 using System;
 using System.Collections.Generic;
+using System.Threading;
 using System.Timers;
 using CardCollector.DataBase;
 using CardCollector.DataBase.EntityDao;
@@ -7,6 +8,7 @@ using CardCollector.Resources;
 using Telegram.Bot;
 using Telegram.Bot.Types;
 using CancellationTokenSource = System.Threading.CancellationTokenSource;
+using Timer = System.Timers.Timer;
 
 namespace CardCollector
 {
@@ -16,6 +18,13 @@ namespace CardCollector
         private static TelegramBotClient _client;
         public static TelegramBotClient Client => _client ??= new TelegramBotClient(AppSettings.TOKEN);
 
+        private static readonly ManualResetEvent _end = new(false);
+        private static readonly Timer _timer = new () {
+            AutoReset = true,
+            Enabled = true,
+            Interval = Constants.SAVING_CHANGES_INTERVAL
+        };
+
         private static readonly IEnumerable<BotCommand> _commands = new[]
         {
             new BotCommand {Command = "/menu", Description = "Показать меню"},
@@ -28,22 +37,24 @@ namespace CardCollector
             var cts = new CancellationTokenSource();
             Client.StartReceiving(HandleUpdateAsync, HandleErrorAsync, cancellationToken: cts.Token);
             Client.SetMyCommandsAsync(_commands, BotCommandScope.AllPrivateChats(), cancellationToken: cts.Token);
-            RunMemoryCleaner();
             
-            Console.ReadLine();
+            _timer.Elapsed += SavingChanges;
+            _timer.Elapsed += UserDao.ClearMemory;
+            
+            _end.WaitOne();
+            Logs.LogOut("Stopping program");
+            
             cts.Cancel();
         }
 
-        private static void RunMemoryCleaner()
+        public static void StopProgram()
         {
-            var timer = new Timer
+            _timer.Elapsed += (_, _) =>
             {
-                AutoReset = true,
-                Enabled = true,
-                Interval = Constants.SAVING_CHANGES_INTERVAL
+                _timer.Stop();
+                UserDao.EndOfProgram();
+                _end.Set();
             };
-            timer.Elapsed += SavingChanges;
-            timer.Elapsed += UserDao.ClearMemory;
         }
 
         private static void SavingChanges(object o, ElapsedEventArgs e)

+ 3 - 1
CardCollector/Commands/Message/Message.cs

@@ -46,7 +46,9 @@ namespace CardCollector.Commands.Message
                 new DownloadStickerPackMessage(),
 
                 // Команда "Показать пример"
-                new ShowSampleMessage()
+                new ShowSampleMessage(),
+                // Команда "Остановить"
+                new StopBot()
             },
             FileCommandsList = new() {
                 /* Выгрузка файлов к боту */

+ 30 - 0
CardCollector/Commands/Message/TextMessage/StopBot.cs

@@ -0,0 +1,30 @@
+using System.Threading.Tasks;
+using CardCollector.Controllers;
+using CardCollector.DataBase.Entity;
+using CardCollector.Resources;
+using Telegram.Bot.Types;
+
+namespace CardCollector.Commands.Message.TextMessage
+{
+    public class StopBot : Message
+    {
+        protected override string CommandText => Command.stop_bot;
+        
+        public override async Task Execute()
+        {
+            var message = await MessageController.SendMessage(User, "Stopping bot");
+            User.Session.Messages.Add(message.MessageId);
+            Bot.StopProgram();
+        }
+
+        protected internal override bool IsMatches(string command)
+        {
+            return User == null 
+                ? base.IsMatches(command)
+                : User.PrivilegeLevel >= Constants.PROGRAMMER_PRIVILEGE_LEVEL || Constants.DEBUG;
+        }
+
+        public StopBot() { }
+        public StopBot(UserEntity user, Update update) : base(user, update) { }
+    }
+}

+ 11 - 1
CardCollector/DataBase/EntityDao/UserDao.cs

@@ -6,6 +6,7 @@ using CardCollector.DataBase.Entity;
 using CardCollector.Resources;
 using Microsoft.EntityFrameworkCore;
 using Telegram.Bot.Types;
+using File = System.IO.File;
 
 namespace CardCollector.DataBase.EntityDao
 {
@@ -76,7 +77,16 @@ namespace CardCollector.DataBase.EntityDao
             foreach (var (id, user) in ActiveUsers)
             {
                 if (user.Session.GetLastAccessInterval() <= Constants.SESSION_ACTIVE_PERIOD) continue;
-                user.Session.Dispose();
+                user.Session.EndSession();
+                ActiveUsers.Remove(id);
+            }
+        }
+
+        public static void EndOfProgram()
+        {
+            foreach (var (id, user) in ActiveUsers)
+            {
+                user.Session.EndSession();
                 ActiveUsers.Remove(id);
             }
         }

+ 1 - 7
CardCollector/Others/Session.cs

@@ -9,7 +9,7 @@ using CardCollector.Resources;
 
 namespace CardCollector.Others
 {
-    public class UserSession : IDisposable
+    public class UserSession
     {
         private DateTime _lastAccess = DateTime.Now;
 
@@ -146,12 +146,6 @@ namespace CardCollector.Others
             CombineList.Clear();
         }
 
-        public void Dispose()
-        {
-            EndSession();
-            GC.SuppressFinalize(this);
-        }
-
         public string GetCombineMessage()
         {
             var message = $"{Text.added_stickers} {GetCombineCount()}/{Constants.COMBINE_COUNT}:";

+ 9 - 0
CardCollector/Resources/Command.Designer.cs

@@ -294,6 +294,15 @@ namespace CardCollector.Resources {
             }
         }
         
+        /// <summary>
+        ///   Looks up a localized string similar to Остановить.
+        /// </summary>
+        internal static string stop_bot {
+            get {
+                return ResourceManager.GetString("stop_bot", resourceCulture);
+            }
+        }
+        
         /// <summary>
         ///   Looks up a localized string similar to tier.
         /// </summary>

+ 3 - 0
CardCollector/Resources/Command.resx

@@ -102,4 +102,7 @@
     <data name="combine_stickers" xml:space="preserve">
         <value>comb_stickers</value>
     </data>
+    <data name="stop_bot" xml:space="preserve">
+        <value>Остановить</value>
+    </data>
 </root>