Browse Source

Add cash entity

Tigran 4 years ago
parent
commit
80e5ef03b4

+ 18 - 4
CardCollector/Bot.cs

@@ -1,22 +1,36 @@
 using System;
-using System.Threading;
+using System.Timers;
+using CardCollector.DataBase;
+using CardCollector.Resources;
 using Telegram.Bot;
-using static CardCollector.Controllers.MessageController;
+using CancellationTokenSource = System.Threading.CancellationTokenSource;
 
 namespace CardCollector
 {
-    using static Resources.AppSettings;
+    using static Controllers.MessageController;
     public static class Bot
     {
         private static TelegramBotClient _client;
-        public static TelegramBotClient Client => _client ??= new TelegramBotClient(TOKEN);
+        public static TelegramBotClient Client => _client ??= new TelegramBotClient(AppSettings.TOKEN);
         
         public static void Main(string[] args)
         {
             var cts = new CancellationTokenSource();
             Client.StartReceiving(HandleUpdateAsync, HandleErrorAsync, cancellationToken: cts.Token);
+            var timer = new Timer
+            {
+                AutoReset = true,
+                Enabled = true,
+                Interval = Constants.SAVING_CHANGES_INTERVAL
+            };
+            timer.Elapsed += SavingChanges;
             Console.ReadLine();
             cts.Cancel();
         }
+
+        private static async void SavingChanges(object o, ElapsedEventArgs e)
+        {
+            await CardCollectorDatabase.Instance.SaveChangesAsync();
+        }
     }
 }

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

@@ -36,8 +36,8 @@ namespace CardCollector.Commands.Message
                 
                 // Возвращаем объект, если команда совпала
                 foreach (var item in List.Where(item => item.IsMatches(command)))
-                    if(Activator.CreateInstance(item.GetType(), user, update) is Message executor && executor.IsMatches(command))
-                        return executor;
+                    if(Activator.CreateInstance(item.GetType(), user, update) is Message executor)
+                        if (executor.IsMatches(command)) return executor;
             
                 // Возвращаем команда не найдена, если код дошел до сюда
                 return new CommandNotFound(user, update, command);
@@ -50,5 +50,6 @@ namespace CardCollector.Commands.Message
         }
 
         protected Message(UserEntity user, Update update) : base(user, update) { }
+        protected Message() { }
     }
 }

+ 9 - 11
CardCollector/Commands/Message/ProfileMessage.cs

@@ -6,17 +6,8 @@ using Telegram.Bot.Types.ReplyMarkups;
 
 namespace CardCollector.Commands.Message
 {
-    public class ProfileMessage:Message
+    public class ProfileMessage : Message
     {
-        public ProfileMessage():base(null,null)
-        {
-            
-        }
-        public ProfileMessage(UserEntity user, Update update) : base(user, update)
-        {
-            
-        }
-
         protected override string Command => "Профиль";
         public override async Task<Telegram.Bot.Types.Message> Execute()
         {
@@ -25,7 +16,14 @@ namespace CardCollector.Commands.Message
                     InlineKeyboardButton.WithCallbackData("Собрать прибыль")
                 }
             );
-            return await MessageController.SendMessage(User,$"{User.Username}", keyboard);
+            return await MessageController.SendMessage(User, 
+                $"{User.Username}\n" +
+                       $"Монеты: {User.Cash.Coins}\n" +
+                       $"Алмазы: {User.Cash.Gems}",
+                keyboard);
         }
+        
+        public ProfileMessage() { }
+        public ProfileMessage(UserEntity user, Update update) : base(user, update) { }
     }
 }

+ 9 - 17
CardCollector/Commands/Message/StartMessage.cs

@@ -1,35 +1,27 @@
 using System.Threading.Tasks;
 using CardCollector.Controllers;
 using CardCollector.DataBase.Entity;
+using Microsoft.EntityFrameworkCore.Metadata.Internal;
 using Telegram.Bot.Types;
 using Telegram.Bot.Types.ReplyMarkups;
 
 namespace CardCollector.Commands.Message
 {
-    public class StartMessage:Message
+    public class StartMessage : Message
     {
-        public StartMessage(UserEntity user, Update update) : base(user, update)
-        {
-            
-        }
-        public StartMessage():base(null,null)
-        {
-            
-        }
-
         protected override string Command => "/start";
         
         public override async Task<Telegram.Bot.Types.Message> Execute()
         {
             var keyboard = new ReplyKeyboardMarkup(new []
             {
-                new KeyboardButton("Профиль"),
-                new KeyboardButton("Коллекция"),
-                new KeyboardButton("Магазин"),
-                new KeyboardButton("Аукцион")
-            });
-            keyboard.ResizeKeyboard = true;
-            return await MessageController.SendMessage(User,$"Привет!", keyboard);
+                new KeyboardButton[] {"Профиль", "Коллекция"},
+                new KeyboardButton[] {"Магазин", "Аукцион"},
+            }) { ResizeKeyboard = true };
+            return await MessageController.SendMessage(User,"Привет!", keyboard);
         }
+        
+        public StartMessage(UserEntity user, Update update) : base(user, update) { }
+        public StartMessage() { }
     }
 }

+ 1 - 0
CardCollector/DataBase/CardCollectorDatabase.cs

@@ -23,6 +23,7 @@ namespace CardCollector.DataBase
         
         // Таблицы базы данных, представленные Entity объектами
         public DbSet<UserEntity> Users { get; set; }
+        public DbSet<CashEntity> CashTable { get; set; }
 
         
         // Конфигурация подключения к БД

+ 14 - 0
CardCollector/DataBase/Entity/CashEntity.cs

@@ -0,0 +1,14 @@
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace CardCollector.DataBase.Entity
+{
+    [Table("cash")]
+    public class CashEntity
+    {
+        [Key]
+        [Column("user_id"), MaxLength(127)] public long UserId { get; set; }
+        [Column("coins"), MaxLength(32)] public int Coins { get; set; } = 0;
+        [Column("gems"), MaxLength(32)] public int Gems { get; set; } = 0;
+    }
+}

+ 3 - 0
CardCollector/DataBase/Entity/UserEntity.cs

@@ -6,9 +6,12 @@ namespace CardCollector.DataBase.Entity
     [Table("users")]
     public class UserEntity
     {
+        [Key]
         [Column("id"), MaxLength(127)] public long Id { get; set; }
         [Column("chat_id"), MaxLength(127)] public long ChatId { get; set; }
         [Column("username"), MaxLength(256)] public string Username { get; set; }
         [Column("is_blocked"), MaxLength(11)] public bool IsBlocked { get; set; }
+        
+        [NotMapped] public CashEntity Cash { get; set; }
     }
 }

+ 24 - 0
CardCollector/DataBase/EntityDao/CashDao.cs

@@ -0,0 +1,24 @@
+using System.Threading.Tasks;
+using CardCollector.DataBase.Entity;
+using Microsoft.EntityFrameworkCore;
+
+namespace CardCollector.DataBase.EntityDao
+{
+    public class CashDao
+    {
+        private static readonly DbSet<CashEntity> Table = CardCollectorDatabase.Instance.CashTable;
+        
+        public static async Task<CashEntity> GetById(long userId)
+        {
+            var user = await Table.FindAsync(userId);
+            return user ?? await AddNew(userId);
+        }
+
+        private static async Task<CashEntity> AddNew(long userId)
+        {
+            var cash = new CashEntity { UserId = userId };
+            var result = await Table.AddAsync(cash);
+            return result.Entity;
+        }
+    }
+}

+ 3 - 0
CardCollector/DataBase/EntityDao/UserDao.cs

@@ -30,6 +30,9 @@ namespace CardCollector.DataBase.EntityDao
             {
                 var user = await DataBase.Users.FindAsync(userId);
                 
+                // Build user object
+                user.Cash = await CashDao.GetById(user.Id);
+                
                 ActiveUsers.Add(user.Id, user);
                 return user;
             }

+ 1 - 0
CardCollector/Resources/Constants.cs

@@ -5,5 +5,6 @@ namespace CardCollector.Resources
         public const bool DEBUG = true;
 
         public const int MEMORY_CLEANER_INTERVAL = 60 * 1000;
+        public const double SAVING_CHANGES_INTERVAL = DEBUG ? 10 * 1000 : 5 * 60 * 1000;
     }
 }