From 182a9cc6bc97b07ea5aab1da8f4a22e08539ff04 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Fri, 25 Oct 2019 12:51:48 +0300 Subject: [PATCH 01/17] Update HandleUserMessage --- src/StashBot/app/ITelegramUserMessage.cs | 7 ++++ .../AuthorizationStateHandler.cs | 40 ++++++++++++++----- .../AuthorizedStateHandler.cs | 16 ++++++-- .../CreateUserPasswordStateHandler.cs | 36 ++++++++++------- .../RegistrationStateHandler.cs | 7 +++- .../ChatStateHandler/StartStateHandler.cs | 7 +++- .../Module/Message/Handler/MessageHandler.cs | 2 +- src/StashBot/app/TelegramUserMessage.cs | 18 +++++++++ 8 files changed, 101 insertions(+), 32 deletions(-) diff --git a/src/StashBot/app/ITelegramUserMessage.cs b/src/StashBot/app/ITelegramUserMessage.cs index 952f9c1..c461f03 100644 --- a/src/StashBot/app/ITelegramUserMessage.cs +++ b/src/StashBot/app/ITelegramUserMessage.cs @@ -23,5 +23,12 @@ string Message { get; } + + string PhotoId + { + get; + } + + bool IsEmpty(); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs index c57981b..2dc0112 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs @@ -35,27 +35,45 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); - if (commands.ContainsKey(message.Message)) + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); } else { - bool success = userManager.LoginUser(message.ChatId, message.Message); - if (success) + if (!string.IsNullOrEmpty(message.Message)) { - const string successMessage = "Success!"; - messageManager.SendMessage(message.ChatId, successMessage); - context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized); - } - else - { - const string wrongMessage = "WRONG"; - messageManager.SendMessage(message.ChatId, wrongMessage); + LoginUser(message, context); } } } + private bool IsCommand(string message) + { + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + } + + private void LoginUser(ITelegramUserMessage message, IChatStateHandlerContext context) + { + IMessageManager messageManager = + ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = + ModulesManager.GetModulesManager().GetUserManager(); + + bool success = userManager.LoginUser(message.ChatId, message.Message); + if (success) + { + const string successMessage = "Success!"; + messageManager.SendMessage(message.ChatId, successMessage); + context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized); + } + else + { + const string wrongMessage = "WRONG"; + messageManager.SendMessage(message.ChatId, wrongMessage); + } + } + private void Cancel(long chatId, IChatStateHandlerContext context) { context.ChangeChatState(chatId, Session.ChatSessionState.Start); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index a23d202..c182ed7 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -32,22 +32,30 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { - if (commands.ContainsKey(message.Message)) + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); } else { - AddDataToStashHandle(message.ChatId, message.Message); + if (!string.IsNullOrEmpty(message.Message)) + { + SaveTextMessageToStash(message); + } } } - private void AddDataToStashHandle(long chatId, string message) + private bool IsCommand(string message) + { + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + } + + private void SaveTextMessageToStash(ITelegramUserMessage message) { IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - databaseManager.SaveMessageToStash(chatId, message); + databaseManager.SaveMessageToStash(message.ChatId, message.Message); } private void GetStash(long chatId, IChatStateHandlerContext context) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs index 9e5789d..67ff4cc 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs @@ -31,22 +31,38 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { - if (commands.ContainsKey(message.Message)) + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); } else { - if (CheckPassword(message.ChatId, message.Message)) + if (!string.IsNullOrEmpty(message.Message)) { - RegistrationUser(message.ChatId, message.Message, context); + RegistrationUser(message, context); } } } - private void Cancel(long chatId, IChatStateHandlerContext context) + private bool IsCommand(string message) { - context.ChangeChatState(chatId, Session.ChatSessionState.Start); + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + } + + private void RegistrationUser(ITelegramUserMessage message, IChatStateHandlerContext context) + { + IMessageManager messageManager = + ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = + ModulesManager.GetModulesManager().GetUserManager(); + + if (CheckPassword(message.ChatId, message.Message)) + { + userManager.CreateNewUser(message.ChatId, message.Message); + string successMessage = "Success!\nNow you can auth with password"; + messageManager.SendMessage(message.ChatId, successMessage); + context.ChangeChatState(message.ChatId, Session.ChatSessionState.Start); + } } private bool CheckPassword(long chatId, string password) @@ -85,16 +101,8 @@ private bool CheckPassword(long chatId, string password) return true; } - private void RegistrationUser(long chatId, string password, IChatStateHandlerContext context) + private void Cancel(long chatId, IChatStateHandlerContext context) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); - IUserManager userManager = - ModulesManager.GetModulesManager().GetUserManager(); - - userManager.CreateNewUser(chatId, password); - string successMessage = "Success!\nNow you can auth with password"; - messageManager.SendMessage(chatId, successMessage); context.ChangeChatState(chatId, Session.ChatSessionState.Start); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs index 610149d..7cdcc1a 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs @@ -30,7 +30,7 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { - if (commands.ContainsKey(message.Message)) + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); } @@ -40,6 +40,11 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon } } + private bool IsCommand(string message) + { + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + } + private void Registration(long chatId, IChatStateHandlerContext context) { context.ChangeChatState(chatId, Session.ChatSessionState.CreateUserPassword); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs index a2f63b5..133b74f 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs @@ -31,7 +31,7 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { - if (commands.ContainsKey(message.Message)) + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); } @@ -41,6 +41,11 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon } } + private bool IsCommand(string message) + { + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + } + private void Registration(long chatId, IChatStateHandlerContext context) { context.ChangeChatState(chatId, Session.ChatSessionState.Registration); diff --git a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs index 53c9594..372205b 100644 --- a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs @@ -17,7 +17,7 @@ public void HandleUserMessage(ITelegramUserMessage message) ISessionManager sessionManager = ModulesManager.GetModulesManager().GetSessionManager(); - if (string.IsNullOrEmpty(message.Message)) + if (message.IsEmpty()) { return; } diff --git a/src/StashBot/app/TelegramUserMessage.cs b/src/StashBot/app/TelegramUserMessage.cs index 0469c90..a529809 100644 --- a/src/StashBot/app/TelegramUserMessage.cs +++ b/src/StashBot/app/TelegramUserMessage.cs @@ -25,12 +25,30 @@ public string Message get; } + public string PhotoId + { + get; + } + internal TelegramUserMessage(Message message) { ChatId = message.Chat.Id; MessageId = message.MessageId; DateSent = message.Date; Message = message.Text; + if (message.Photo != null && message.Photo.Length > 0) + { + PhotoId = message.Photo[message.Photo.Length - 1].FileId; + } + else + { + PhotoId = null; + } + } + + public bool IsEmpty() + { + return string.IsNullOrEmpty(Message) && string.IsNullOrEmpty(PhotoId); } } } From 52d41faf05e76bfce31b2c4d2e927defc838a9e2 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sun, 27 Oct 2019 01:51:17 +0300 Subject: [PATCH 02/17] Update create TelegramUserMessage --- src/StashBot/app/ITelegramUserMessageFactory.cs | 9 +++++++++ src/StashBot/app/StashBot.cs | 7 +++++-- src/StashBot/app/TelegramUserMessage.cs | 14 +++++++------- src/StashBot/app/TelegramUserMessageFactory.cs | 12 ++++++++++++ 4 files changed, 33 insertions(+), 9 deletions(-) create mode 100644 src/StashBot/app/ITelegramUserMessageFactory.cs create mode 100644 src/StashBot/app/TelegramUserMessageFactory.cs diff --git a/src/StashBot/app/ITelegramUserMessageFactory.cs b/src/StashBot/app/ITelegramUserMessageFactory.cs new file mode 100644 index 0000000..2ba8f25 --- /dev/null +++ b/src/StashBot/app/ITelegramUserMessageFactory.cs @@ -0,0 +1,9 @@ +using Telegram.Bot.Types; + +namespace StashBot +{ + internal interface ITelegramUserMessageFactory + { + ITelegramUserMessage Create(Message telegramMessage); + } +} diff --git a/src/StashBot/app/StashBot.cs b/src/StashBot/app/StashBot.cs index d1d2f17..081abd2 100644 --- a/src/StashBot/app/StashBot.cs +++ b/src/StashBot/app/StashBot.cs @@ -6,10 +6,13 @@ namespace StashBot { - class StashBot + internal class StashBot { + private ITelegramUserMessageFactory telegramUserMessageFactory; + internal StashBot() { + telegramUserMessageFactory = new TelegramUserMessageFactory(); WriteBotStatus(); } @@ -39,7 +42,7 @@ private void OnMessage(object sender, MessageEventArgs e) IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - messageManager.HandleUserMessage(new TelegramUserMessage(e.Message)); + messageManager.HandleUserMessage(telegramUserMessageFactory.Create(e.Message)); } } } diff --git a/src/StashBot/app/TelegramUserMessage.cs b/src/StashBot/app/TelegramUserMessage.cs index a529809..4aa1005 100644 --- a/src/StashBot/app/TelegramUserMessage.cs +++ b/src/StashBot/app/TelegramUserMessage.cs @@ -30,15 +30,15 @@ public string PhotoId get; } - internal TelegramUserMessage(Message message) + internal TelegramUserMessage(Message telegramMessage) { - ChatId = message.Chat.Id; - MessageId = message.MessageId; - DateSent = message.Date; - Message = message.Text; - if (message.Photo != null && message.Photo.Length > 0) + ChatId = telegramMessage.Chat.Id; + MessageId = telegramMessage.MessageId; + DateSent = telegramMessage.Date; + Message = telegramMessage.Text; + if (telegramMessage.Photo != null && telegramMessage.Photo.Length > 0) { - PhotoId = message.Photo[message.Photo.Length - 1].FileId; + PhotoId = telegramMessage.Photo[telegramMessage.Photo.Length - 1].FileId; } else { diff --git a/src/StashBot/app/TelegramUserMessageFactory.cs b/src/StashBot/app/TelegramUserMessageFactory.cs new file mode 100644 index 0000000..a065edd --- /dev/null +++ b/src/StashBot/app/TelegramUserMessageFactory.cs @@ -0,0 +1,12 @@ +using Telegram.Bot.Types; + +namespace StashBot +{ + internal class TelegramUserMessageFactory : ITelegramUserMessageFactory + { + public ITelegramUserMessage Create(Message telegramMessage) + { + return new TelegramUserMessage(telegramMessage); + } + } +} From a45d49c8298834da7c6c78419eca1844457abd41 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sun, 27 Oct 2019 02:00:08 +0300 Subject: [PATCH 03/17] Update BotToken --- src/StashBot/app/AppSettings/BotToken.cs | 6 +++--- src/StashBot/app/Module/ModulesManager.cs | 2 +- src/StashBot/app/Program.cs | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/StashBot/app/AppSettings/BotToken.cs b/src/StashBot/app/AppSettings/BotToken.cs index 3be29b3..4164ea5 100644 --- a/src/StashBot/app/AppSettings/BotToken.cs +++ b/src/StashBot/app/AppSettings/BotToken.cs @@ -3,12 +3,12 @@ namespace StashBot.AppSetting { - internal class BotToken + internal static class BotToken { private const string BOT_TOKEN_FILE_NAME = "AppSettings.json"; private static string botToken; - internal string Get() + internal static string Get() { if (string.IsNullOrEmpty(botToken)) { @@ -20,7 +20,7 @@ internal string Get() return botToken; } - internal void Set(string newBotToken) + internal static void Set(string newBotToken) { if (string.IsNullOrEmpty(botToken) && !string.IsNullOrEmpty(newBotToken)) { diff --git a/src/StashBot/app/Module/ModulesManager.cs b/src/StashBot/app/Module/ModulesManager.cs index 642778a..225046f 100644 --- a/src/StashBot/app/Module/ModulesManager.cs +++ b/src/StashBot/app/Module/ModulesManager.cs @@ -21,7 +21,7 @@ internal class ModulesManager : IModulesManager private ModulesManager() { - telegramBotClient = new TelegramBotClient(new BotToken().Get()); + telegramBotClient = new TelegramBotClient(BotToken.Get()); messageManager = new MessageManager(); sessionManager = new SessionManager(); userManager = new UserManager(); diff --git a/src/StashBot/app/Program.cs b/src/StashBot/app/Program.cs index f4e78fc..76d4abc 100644 --- a/src/StashBot/app/Program.cs +++ b/src/StashBot/app/Program.cs @@ -22,8 +22,7 @@ private static void ParseArgs(string[] args) if (args.Length >= 1 && !string.IsNullOrEmpty(args[0])) { - BotToken botToken = new BotToken(); - botToken.Set(args[0]); + BotToken.Set(args[0]); } else { From 685bdf1d139eaf922c37048163dc46bb61d854b8 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sun, 27 Oct 2019 02:10:17 +0300 Subject: [PATCH 04/17] Update DatabaseManager --- .../app/Module/Database/{ => Account}/IUser.cs | 0 .../app/Module/Database/{ => Account}/User.cs | 0 src/StashBot/app/Module/Database/DatabaseManager.cs | 4 ++-- .../app/Module/Database/Stash/IStashMessage.cs | 9 +++++++++ .../app/Module/Database/Stash/StashMessage.cs | 12 ++++++++++++ 5 files changed, 23 insertions(+), 2 deletions(-) rename src/StashBot/app/Module/Database/{ => Account}/IUser.cs (100%) rename src/StashBot/app/Module/Database/{ => Account}/User.cs (100%) create mode 100644 src/StashBot/app/Module/Database/Stash/IStashMessage.cs create mode 100644 src/StashBot/app/Module/Database/Stash/StashMessage.cs diff --git a/src/StashBot/app/Module/Database/IUser.cs b/src/StashBot/app/Module/Database/Account/IUser.cs similarity index 100% rename from src/StashBot/app/Module/Database/IUser.cs rename to src/StashBot/app/Module/Database/Account/IUser.cs diff --git a/src/StashBot/app/Module/Database/User.cs b/src/StashBot/app/Module/Database/Account/User.cs similarity index 100% rename from src/StashBot/app/Module/Database/User.cs rename to src/StashBot/app/Module/Database/Account/User.cs diff --git a/src/StashBot/app/Module/Database/DatabaseManager.cs b/src/StashBot/app/Module/Database/DatabaseManager.cs index 68f4550..47dc2d7 100644 --- a/src/StashBot/app/Module/Database/DatabaseManager.cs +++ b/src/StashBot/app/Module/Database/DatabaseManager.cs @@ -6,8 +6,8 @@ namespace StashBot.Module.Database { internal class DatabaseManager : IDatabaseManager { - private IDatabaseAccount databaseAccount; - private IDatabaseStash databaseStash; + private readonly IDatabaseAccount databaseAccount; + private readonly IDatabaseStash databaseStash; internal DatabaseManager() { diff --git a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs new file mode 100644 index 0000000..b288df0 --- /dev/null +++ b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs @@ -0,0 +1,9 @@ +using System; + +namespace StashBot.Module.Database.Stash +{ + internal interface IStashMessage + { + + } +} diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs new file mode 100644 index 0000000..9f65db9 --- /dev/null +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -0,0 +1,12 @@ +using System; + +namespace StashBot.Module.Database.Stash +{ + internal class StashMessage : IStashMessage + { + internal StashMessage() + { + + } + } +} From 8922e131193219969be24be63a59c4bbed69f0f1 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sun, 27 Oct 2019 03:04:56 +0300 Subject: [PATCH 05/17] Update work with StashMessage --- .../app/Module/Database/Account/IUser.cs | 7 ++- .../app/Module/Database/Account/User.cs | 31 +++------- .../app/Module/Database/DatabaseManager.cs | 6 +- .../Database/Stash/DatabaseStashLocal.cs | 41 ++++++------ .../Module/Database/Stash/IDatabaseStash.cs | 4 +- .../Module/Database/Stash/IStashMessage.cs | 21 ++++++- .../Database/Stash/IStashMessageFactory.cs | 7 +++ .../app/Module/Database/Stash/StashMessage.cs | 62 ++++++++++++++++++- .../Database/Stash/StashMessageFactory.cs | 10 +++ .../AuthorizedStateHandler.cs | 14 +++-- 10 files changed, 143 insertions(+), 60 deletions(-) create mode 100644 src/StashBot/app/Module/Database/Stash/IStashMessageFactory.cs create mode 100644 src/StashBot/app/Module/Database/Stash/StashMessageFactory.cs diff --git a/src/StashBot/app/Module/Database/Account/IUser.cs b/src/StashBot/app/Module/Database/Account/IUser.cs index 0d52342..6dcccd5 100644 --- a/src/StashBot/app/Module/Database/Account/IUser.cs +++ b/src/StashBot/app/Module/Database/Account/IUser.cs @@ -2,10 +2,13 @@ { internal interface IUser { + string EncryptedPassword + { + get; + } + void Login(string password); void Logout(); bool ValidatePassword(string password); - string EncryptMessage(string secretMessage); - string DecryptMessage(string encryptedMessage); } } diff --git a/src/StashBot/app/Module/Database/Account/User.cs b/src/StashBot/app/Module/Database/Account/User.cs index 171da36..3affedf 100644 --- a/src/StashBot/app/Module/Database/Account/User.cs +++ b/src/StashBot/app/Module/Database/Account/User.cs @@ -6,7 +6,12 @@ internal class User : IUser { private readonly long chatId; private readonly string hashPassword; - private string encryptedPassword; + + public string EncryptedPassword + { + get; + private set; + } internal User(long chatId, string password) { @@ -15,7 +20,7 @@ internal User(long chatId, string password) this.chatId = chatId; hashPassword = secureManager.CalculateHash(password); - encryptedPassword = null; + EncryptedPassword = null; } public void Login(string password) @@ -23,12 +28,12 @@ public void Login(string password) ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); - encryptedPassword = secureManager.EncryptWithAes(password); + EncryptedPassword = secureManager.EncryptWithAes(password); } public void Logout() { - encryptedPassword = null; + EncryptedPassword = null; } public bool ValidatePassword(string password) @@ -38,23 +43,5 @@ public bool ValidatePassword(string password) return secureManager.CompareWithHash(password, hashPassword); } - - public string EncryptMessage(string secretMessage) - { - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); - - string password = secureManager.DecryptWithAes(encryptedPassword); - return secureManager.EncryptWithAesHmac(secretMessage, password); - } - - public string DecryptMessage(string encryptedMessage) - { - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); - - string password = secureManager.DecryptWithAes(encryptedPassword); - return secureManager.DecryptWithAesHmac(encryptedMessage, password); - } } } diff --git a/src/StashBot/app/Module/Database/DatabaseManager.cs b/src/StashBot/app/Module/Database/DatabaseManager.cs index 47dc2d7..d95af0b 100644 --- a/src/StashBot/app/Module/Database/DatabaseManager.cs +++ b/src/StashBot/app/Module/Database/DatabaseManager.cs @@ -30,12 +30,12 @@ public IUser GetUser(long chatId) return databaseAccount.GetUser(chatId); } - public void SaveMessageToStash(long chatId, string message) + public void SaveMessageToStash(IStashMessage stashMessage) { - databaseStash.SaveMessageToStash(chatId, message); + databaseStash.SaveMessageToStash(stashMessage); } - public List GetMessagesFromStash(long chatId) + public List GetMessagesFromStash(long chatId) { return databaseStash.GetMessagesFromStash(chatId); } diff --git a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs index 9deab4d..d24cad1 100644 --- a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs +++ b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs @@ -4,53 +4,54 @@ namespace StashBot.Module.Database.Stash { internal class DatabaseStashLocal : IDatabaseStash { - private readonly Dictionary> usersStashes; + private readonly Dictionary> usersStashes; internal DatabaseStashLocal() { - usersStashes = new Dictionary>(); + usersStashes = new Dictionary>(); } - public List GetMessagesFromStash(long chatId) + public void SaveMessageToStash(IStashMessage stashMessage) { IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - if (!usersStashes.ContainsKey(chatId)) + if (!usersStashes.ContainsKey(stashMessage.ChatId)) { - return new List(); + usersStashes.Add(stashMessage.ChatId, new List()); } - IUser user = databaseManager.GetUser(chatId); - if (user == null) - { - return new List(); - } - - List decryptedMessages = new List(); - foreach (string encryptedMessage in usersStashes[chatId]) + IUser user = databaseManager.GetUser(stashMessage.ChatId); + if (user != null) { - decryptedMessages.Add(user.DecryptMessage(encryptedMessage)); + stashMessage.Encrypt(user); + usersStashes[stashMessage.ChatId].Add(stashMessage); } - return decryptedMessages; } - public void SaveMessageToStash(long chatId, string message) + public List GetMessagesFromStash(long chatId) { IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); if (!usersStashes.ContainsKey(chatId)) { - usersStashes.Add(chatId, new List()); + return new List(); } IUser user = databaseManager.GetUser(chatId); - if (user != null) + if (user == null) { - string encryptedMessage = user.EncryptMessage(message); - usersStashes[chatId].Add(encryptedMessage); + return new List(); } + + List decryptedMessages = new List(); + foreach (IStashMessage encryptedMessage in usersStashes[chatId]) + { + encryptedMessage.Decrypt(user); + decryptedMessages.Add(encryptedMessage); + } + return decryptedMessages; } public void ClearStash(long chatId) diff --git a/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs b/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs index 9b91fdf..5cbe8d8 100644 --- a/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs +++ b/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs @@ -4,8 +4,8 @@ namespace StashBot.Module.Database.Stash { internal interface IDatabaseStash { - void SaveMessageToStash(long chatId, string message); - List GetMessagesFromStash(long chatId); + void SaveMessageToStash(IStashMessage stashMessage); + List GetMessagesFromStash(long chatId); void ClearStash(long chatId); } } diff --git a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs index b288df0..d314820 100644 --- a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs @@ -1,9 +1,24 @@ -using System; - -namespace StashBot.Module.Database.Stash +namespace StashBot.Module.Database.Stash { internal interface IStashMessage { + long ChatId + { + get; + } + + bool IsEncrypt + { + get; + } + + string Message + { + get; + } + void Encrypt(IUser user); + void Decrypt(IUser user); + void Send(); } } diff --git a/src/StashBot/app/Module/Database/Stash/IStashMessageFactory.cs b/src/StashBot/app/Module/Database/Stash/IStashMessageFactory.cs new file mode 100644 index 0000000..1658237 --- /dev/null +++ b/src/StashBot/app/Module/Database/Stash/IStashMessageFactory.cs @@ -0,0 +1,7 @@ +namespace StashBot.Module.Database.Stash +{ + internal interface IStashMessageFactory + { + IStashMessage Create(ITelegramUserMessage telegramMessage); + } +} diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs index 9f65db9..1c6a7d5 100644 --- a/src/StashBot/app/Module/Database/Stash/StashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -1,12 +1,70 @@ -using System; +using StashBot.Module.Message; +using StashBot.Module.Secure; namespace StashBot.Module.Database.Stash { internal class StashMessage : IStashMessage { - internal StashMessage() + public long ChatId { + get; + } + + public bool IsEncrypt + { + get; + private set; + } + + public string Message + { + get; + private set; + } + + internal StashMessage(ITelegramUserMessage telegramMessage) + { + ChatId = telegramMessage.ChatId; + IsEncrypt = false; + Message = telegramMessage.Message; + } + + public void Encrypt(IUser user) + { + ISecureManager secureManager = + ModulesManager.GetModulesManager().GetSecureManager(); + + if (IsEncrypt) + { + return; + } + + string password = secureManager.DecryptWithAes(user.EncryptedPassword); + Message = secureManager.EncryptWithAesHmac(Message, password); + IsEncrypt = true; + } + + public void Decrypt(IUser user) + { + ISecureManager secureManager = + ModulesManager.GetModulesManager().GetSecureManager(); + + if (!IsEncrypt) + { + return; + } + + string password = secureManager.DecryptWithAes(user.EncryptedPassword); + Message = secureManager.DecryptWithAesHmac(Message, password); + IsEncrypt = false; + } + + public void Send() + { + IMessageManager messageManager = + ModulesManager.GetModulesManager().GetMessageManager(); + messageManager.SendMessage(ChatId, Message); } } } diff --git a/src/StashBot/app/Module/Database/Stash/StashMessageFactory.cs b/src/StashBot/app/Module/Database/Stash/StashMessageFactory.cs new file mode 100644 index 0000000..f95913a --- /dev/null +++ b/src/StashBot/app/Module/Database/Stash/StashMessageFactory.cs @@ -0,0 +1,10 @@ +namespace StashBot.Module.Database.Stash +{ + internal class StashMessageFactory : IStashMessageFactory + { + public IStashMessage Create(ITelegramUserMessage telegramMessage) + { + return new StashMessage(telegramMessage); + } + } +} diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index c182ed7..249a16a 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using StashBot.Module.Database; +using StashBot.Module.Database.Stash; using StashBot.Module.User; namespace StashBot.Module.Message.Handler.ChatStateHandler @@ -8,9 +9,11 @@ internal class AuthorizedStateHandler : IChatStateHandler { private delegate void Command(long chatId, IChatStateHandlerContext context); private readonly Dictionary commands; + private readonly IStashMessageFactory stashMessageFactory; internal AuthorizedStateHandler() { + stashMessageFactory = new StashMessageFactory(); commands = new Dictionary(); InitializeCommands(); } @@ -55,20 +58,19 @@ private void SaveTextMessageToStash(ITelegramUserMessage message) IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - databaseManager.SaveMessageToStash(message.ChatId, message.Message); + IStashMessage stashMessage = stashMessageFactory.Create(message); + databaseManager.SaveMessageToStash(stashMessage); } private void GetStash(long chatId, IChatStateHandlerContext context) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - List messagesFromStash = databaseManager.GetMessagesFromStash(chatId); - foreach (string textMessage in messagesFromStash) + List messagesFromStash = databaseManager.GetMessagesFromStash(chatId); + foreach (IStashMessage stashMessage in messagesFromStash) { - messageManager.SendMessage(chatId, textMessage); + stashMessage.Send(); } } From 0cd34e2553d7d1ee6b9ffb50de004da70f43ba89 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Tue, 29 Oct 2019 12:08:42 +0300 Subject: [PATCH 06/17] Update code style --- .../app/Module/Database/Account/IUser.cs | 5 +++ .../app/Module/Database/Account/User.cs | 9 +++++ .../Database/Stash/DatabaseStashLocal.cs | 35 ++++++------------- .../app/Module/Database/Stash/StashMessage.cs | 20 +++++++---- .../AuthorizedStateHandler.cs | 21 ++++++++--- 5 files changed, 53 insertions(+), 37 deletions(-) diff --git a/src/StashBot/app/Module/Database/Account/IUser.cs b/src/StashBot/app/Module/Database/Account/IUser.cs index 6dcccd5..000d5ff 100644 --- a/src/StashBot/app/Module/Database/Account/IUser.cs +++ b/src/StashBot/app/Module/Database/Account/IUser.cs @@ -7,6 +7,11 @@ string EncryptedPassword get; } + bool IsAuthorized + { + get; + } + void Login(string password); void Logout(); bool ValidatePassword(string password); diff --git a/src/StashBot/app/Module/Database/Account/User.cs b/src/StashBot/app/Module/Database/Account/User.cs index 3affedf..8eb9bad 100644 --- a/src/StashBot/app/Module/Database/Account/User.cs +++ b/src/StashBot/app/Module/Database/Account/User.cs @@ -13,6 +13,12 @@ public string EncryptedPassword private set; } + public bool IsAuthorized + { + get; + private set; + } + internal User(long chatId, string password) { ISecureManager secureManager = @@ -21,6 +27,7 @@ internal User(long chatId, string password) this.chatId = chatId; hashPassword = secureManager.CalculateHash(password); EncryptedPassword = null; + IsAuthorized = false; } public void Login(string password) @@ -29,11 +36,13 @@ public void Login(string password) ModulesManager.GetModulesManager().GetSecureManager(); EncryptedPassword = secureManager.EncryptWithAes(password); + IsAuthorized = true; } public void Logout() { EncryptedPassword = null; + IsAuthorized = false; } public bool ValidatePassword(string password) diff --git a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs index d24cad1..dd9a424 100644 --- a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs +++ b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; namespace StashBot.Module.Database.Stash { @@ -13,45 +14,29 @@ internal DatabaseStashLocal() public void SaveMessageToStash(IStashMessage stashMessage) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + if (!stashMessage.IsEncrypt) + { + throw new ArgumentException( + "An unencrypted message cannot be stored in a stash", + nameof(stashMessage)); + } if (!usersStashes.ContainsKey(stashMessage.ChatId)) { usersStashes.Add(stashMessage.ChatId, new List()); } - IUser user = databaseManager.GetUser(stashMessage.ChatId); - if (user != null) - { - stashMessage.Encrypt(user); - usersStashes[stashMessage.ChatId].Add(stashMessage); - } + usersStashes[stashMessage.ChatId].Add(stashMessage); } public List GetMessagesFromStash(long chatId) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); - if (!usersStashes.ContainsKey(chatId)) { return new List(); } - IUser user = databaseManager.GetUser(chatId); - if (user == null) - { - return new List(); - } - - List decryptedMessages = new List(); - foreach (IStashMessage encryptedMessage in usersStashes[chatId]) - { - encryptedMessage.Decrypt(user); - decryptedMessages.Add(encryptedMessage); - } - return decryptedMessages; + return usersStashes[chatId]; } public void ClearStash(long chatId) diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs index 1c6a7d5..9960ee9 100644 --- a/src/StashBot/app/Module/Database/Stash/StashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -1,4 +1,5 @@ -using StashBot.Module.Message; +using System; +using StashBot.Module.Message; using StashBot.Module.Secure; namespace StashBot.Module.Database.Stash @@ -31,14 +32,14 @@ internal StashMessage(ITelegramUserMessage telegramMessage) public void Encrypt(IUser user) { - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); - if (IsEncrypt) { return; } + ISecureManager secureManager = + ModulesManager.GetModulesManager().GetSecureManager(); + string password = secureManager.DecryptWithAes(user.EncryptedPassword); Message = secureManager.EncryptWithAesHmac(Message, password); IsEncrypt = true; @@ -46,14 +47,14 @@ public void Encrypt(IUser user) public void Decrypt(IUser user) { - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); - if (!IsEncrypt) { return; } + ISecureManager secureManager = + ModulesManager.GetModulesManager().GetSecureManager(); + string password = secureManager.DecryptWithAes(user.EncryptedPassword); Message = secureManager.DecryptWithAesHmac(Message, password); IsEncrypt = false; @@ -61,6 +62,11 @@ public void Decrypt(IUser user) public void Send() { + if (IsEncrypt) + { + throw new ArgumentException("An encrypted message cannot send"); + } + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index 249a16a..ef70617 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -58,8 +58,13 @@ private void SaveTextMessageToStash(ITelegramUserMessage message) IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - IStashMessage stashMessage = stashMessageFactory.Create(message); - databaseManager.SaveMessageToStash(stashMessage); + IUser user = databaseManager.GetUser(message.ChatId); + if (user != null && user.IsAuthorized) + { + IStashMessage stashMessage = stashMessageFactory.Create(message); + stashMessage.Encrypt(user); + databaseManager.SaveMessageToStash(stashMessage); + } } private void GetStash(long chatId, IChatStateHandlerContext context) @@ -67,10 +72,16 @@ private void GetStash(long chatId, IChatStateHandlerContext context) IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - List messagesFromStash = databaseManager.GetMessagesFromStash(chatId); - foreach (IStashMessage stashMessage in messagesFromStash) + + IUser user = databaseManager.GetUser(chatId); + if (user != null && user.IsAuthorized) { - stashMessage.Send(); + List messagesFromStash = databaseManager.GetMessagesFromStash(chatId); + foreach(IStashMessage stashMessage in messagesFromStash) + { + stashMessage.Decrypt(user); + stashMessage.Send(); + } } } From 04c9557c3da86b4f0c8a844d4cc94b46fac6d033 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Tue, 29 Oct 2019 12:52:43 +0300 Subject: [PATCH 07/17] Add message download function --- src/StashBot/app/ITelegramUserMessage.cs | 4 ++-- .../Module/Database/Stash/IStashMessage.cs | 15 ++++++++++++- .../app/Module/Database/Stash/StashMessage.cs | 22 +++++++++++++++++++ src/StashBot/app/TelegramUserMessage.cs | 6 ++--- 4 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/StashBot/app/ITelegramUserMessage.cs b/src/StashBot/app/ITelegramUserMessage.cs index c461f03..fe62a25 100644 --- a/src/StashBot/app/ITelegramUserMessage.cs +++ b/src/StashBot/app/ITelegramUserMessage.cs @@ -9,12 +9,12 @@ long ChatId get; } - int MessageId + DateTime DateSent { get; } - DateTime DateSent + int MessageId { get; } diff --git a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs index d314820..7cadb48 100644 --- a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs @@ -1,4 +1,6 @@ -namespace StashBot.Module.Database.Stash +using System.Threading.Tasks; + +namespace StashBot.Module.Database.Stash { internal interface IStashMessage { @@ -12,11 +14,22 @@ bool IsEncrypt get; } + bool IsDownloaded + { + get; + } + string Message { get; } + string PhotoId + { + get; + } + + Task Download(); void Encrypt(IUser user); void Decrypt(IUser user); void Send(); diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs index 9960ee9..b279ef0 100644 --- a/src/StashBot/app/Module/Database/Stash/StashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -1,6 +1,9 @@ using System; +using System.IO; +using System.Threading.Tasks; using StashBot.Module.Message; using StashBot.Module.Secure; +using Telegram.Bot; namespace StashBot.Module.Database.Stash { @@ -9,6 +12,7 @@ internal class StashMessage : IStashMessage public long ChatId { get; + private set; } public bool IsEncrypt @@ -17,17 +21,35 @@ public bool IsEncrypt private set; } + public bool IsDownloaded + { + get; + private set; + } + public string Message { get; private set; } + public string PhotoId + { + get; + private set; + } + internal StashMessage(ITelegramUserMessage telegramMessage) { ChatId = telegramMessage.ChatId; IsEncrypt = false; Message = telegramMessage.Message; + PhotoId = telegramMessage.PhotoId; + IsDownloaded = string.IsNullOrEmpty(PhotoId); + } + + public async Task Download() + { } public void Encrypt(IUser user) diff --git a/src/StashBot/app/TelegramUserMessage.cs b/src/StashBot/app/TelegramUserMessage.cs index 4aa1005..94918c1 100644 --- a/src/StashBot/app/TelegramUserMessage.cs +++ b/src/StashBot/app/TelegramUserMessage.cs @@ -10,12 +10,12 @@ public long ChatId get; } - public int MessageId + public DateTime DateSent { get; } - public DateTime DateSent + public int MessageId { get; } @@ -33,8 +33,8 @@ public string PhotoId internal TelegramUserMessage(Message telegramMessage) { ChatId = telegramMessage.Chat.Id; - MessageId = telegramMessage.MessageId; DateSent = telegramMessage.Date; + MessageId = telegramMessage.MessageId; Message = telegramMessage.Text; if (telegramMessage.Photo != null && telegramMessage.Photo.Length > 0) { From 643adbf89cb6050ce93a4823864c33293d4fbcdc Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Wed, 30 Oct 2019 01:41:21 +0300 Subject: [PATCH 08/17] Update AuthorizedStateHandler.cs --- .../ChatStateHandler/AuthorizedStateHandler.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index ef70617..dd84ad1 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Threading.Tasks; using StashBot.Module.Database; using StashBot.Module.Database.Stash; using StashBot.Module.User; @@ -41,9 +42,9 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon } else { - if (!string.IsNullOrEmpty(message.Message)) + if (!message.IsEmpty()) { - SaveTextMessageToStash(message); + SaveMessageToStash(message); } } } @@ -53,7 +54,7 @@ private bool IsCommand(string message) return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); } - private void SaveTextMessageToStash(ITelegramUserMessage message) + private async Task SaveMessageToStash(ITelegramUserMessage message) { IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); @@ -62,6 +63,11 @@ private void SaveTextMessageToStash(ITelegramUserMessage message) if (user != null && user.IsAuthorized) { IStashMessage stashMessage = stashMessageFactory.Create(message); + if (!stashMessage.IsDownloaded) + { + await stashMessage.Download(); + } + stashMessage.Encrypt(user); databaseManager.SaveMessageToStash(stashMessage); } From b769eb0cf2482d36dc0dd0febe1459e4e5a3a485 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Wed, 30 Oct 2019 02:29:24 +0300 Subject: [PATCH 09/17] Save photo to stash --- .../Database/Stash/DatabaseStashLocal.cs | 7 +++ .../Module/Database/Stash/IStashMessage.cs | 2 +- .../app/Module/Database/Stash/StashMessage.cs | 55 +++++++++++++++++-- .../AuthorizationStateHandler.cs | 6 +- .../AuthorizedStateHandler.cs | 6 +- .../CreateUserPasswordStateHandler.cs | 12 ++-- .../FirstMessageStateHandler.cs | 2 +- .../RegistrationStateHandler.cs | 2 +- .../ChatStateHandler/StartStateHandler.cs | 4 +- .../app/Module/Message/MessageManager.cs | 10 +++- .../Module/Message/Sender/IMessageSender.cs | 7 ++- .../Module/Message/Sender/MessageSender.cs | 28 ++++++++-- 12 files changed, 110 insertions(+), 31 deletions(-) diff --git a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs index dd9a424..2ac0d90 100644 --- a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs +++ b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs @@ -14,6 +14,13 @@ internal DatabaseStashLocal() public void SaveMessageToStash(IStashMessage stashMessage) { + if (!stashMessage.IsDownloaded) + { + throw new ArgumentException( + "An undownloaded message cannot be stored in a stash", + nameof(stashMessage)); + } + if (!stashMessage.IsEncrypt) { throw new ArgumentException( diff --git a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs index 7cadb48..9147932 100644 --- a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs @@ -24,7 +24,7 @@ string Message get; } - string PhotoId + string Photo { get; } diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs index b279ef0..1406f75 100644 --- a/src/StashBot/app/Module/Database/Stash/StashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -33,23 +33,36 @@ public string Message private set; } - public string PhotoId + public string Photo { get; private set; } + private readonly string photoId; + internal StashMessage(ITelegramUserMessage telegramMessage) { ChatId = telegramMessage.ChatId; IsEncrypt = false; Message = telegramMessage.Message; - PhotoId = telegramMessage.PhotoId; - IsDownloaded = string.IsNullOrEmpty(PhotoId); + photoId = telegramMessage.PhotoId; + IsDownloaded = string.IsNullOrEmpty(photoId); } public async Task Download() { + ITelegramBotClient telegramBotClient = + ModulesManager.GetModulesManager().GetTelegramBotClient(); + + using (MemoryStream stream = new MemoryStream()) + { + await telegramBotClient.GetInfoAndDownloadFileAsync(photoId, stream); + byte[] imageBytes = stream.ToArray(); + Photo = Convert.ToBase64String(imageBytes); + } + + IsDownloaded = true; } public void Encrypt(IUser user) @@ -63,7 +76,15 @@ public void Encrypt(IUser user) ModulesManager.GetModulesManager().GetSecureManager(); string password = secureManager.DecryptWithAes(user.EncryptedPassword); - Message = secureManager.EncryptWithAesHmac(Message, password); + if (!string.IsNullOrEmpty(Message)) + { + Message = secureManager.EncryptWithAesHmac(Message, password); + } + if (!string.IsNullOrEmpty(Photo)) + { + Photo = secureManager.EncryptWithAesHmac(Photo, password); + } + IsEncrypt = true; } @@ -78,12 +99,26 @@ public void Decrypt(IUser user) ModulesManager.GetModulesManager().GetSecureManager(); string password = secureManager.DecryptWithAes(user.EncryptedPassword); - Message = secureManager.DecryptWithAesHmac(Message, password); + if (!string.IsNullOrEmpty(Message)) + { + Message = secureManager.DecryptWithAesHmac(Message, password); + } + if (!string.IsNullOrEmpty(Photo)) + { + Photo = secureManager.DecryptWithAesHmac(Photo, password); + + } + IsEncrypt = false; } public void Send() { + if (!IsDownloaded) + { + throw new ArgumentException("An undownloaded message cannot send"); + } + if (IsEncrypt) { throw new ArgumentException("An encrypted message cannot send"); @@ -92,7 +127,15 @@ public void Send() IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - messageManager.SendMessage(ChatId, Message); + if (!string.IsNullOrEmpty(Message)) + { + _ = messageManager.SendTextMessage(ChatId, Message); + } + if (!string.IsNullOrEmpty(Photo)) + { + byte[] imageBytes = Convert.FromBase64String(Photo); + _ = messageManager.SendPhotoMessage(ChatId, imageBytes); + } } } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs index 2dc0112..85dff73 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs @@ -25,7 +25,7 @@ public void StartStateMessage(long chatId) ModulesManager.GetModulesManager().GetMessageManager(); const string warningMessage = "Input your password or /back"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -64,13 +64,13 @@ private void LoginUser(ITelegramUserMessage message, IChatStateHandlerContext co if (success) { const string successMessage = "Success!"; - messageManager.SendMessage(message.ChatId, successMessage); + messageManager.SendTextMessage(message.ChatId, successMessage); context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized); } else { const string wrongMessage = "WRONG"; - messageManager.SendMessage(message.ChatId, wrongMessage); + messageManager.SendTextMessage(message.ChatId, wrongMessage); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index dd84ad1..cecb288 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -31,7 +31,7 @@ public void StartStateMessage(long chatId) ModulesManager.GetModulesManager().GetMessageManager(); const string loginMessage = "Input message to save it in stash.\nGet messages in stash: /stash\nLogout: /logout"; - messageManager.SendMessage(chatId, loginMessage); + messageManager.SendTextMessage(chatId, loginMessage); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -44,7 +44,7 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon { if (!message.IsEmpty()) { - SaveMessageToStash(message); + _ = SaveMessageToStash(message); } } } @@ -100,7 +100,7 @@ private void Logout(long chatId, IChatStateHandlerContext context) userManager.LogoutUser(chatId); const string logoutMessage = "You're logged out"; - messageManager.SendMessage(chatId, logoutMessage); + messageManager.SendTextMessage(chatId, logoutMessage); context.ChangeChatState(chatId, Session.ChatSessionState.Start); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs index 67ff4cc..dad6b3a 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs @@ -26,7 +26,7 @@ public void StartStateMessage(long chatId) ModulesManager.GetModulesManager().GetMessageManager(); const string warningMessage = "Input your password or /cancel"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -60,7 +60,7 @@ private void RegistrationUser(ITelegramUserMessage message, IChatStateHandlerCon { userManager.CreateNewUser(message.ChatId, message.Message); string successMessage = "Success!\nNow you can auth with password"; - messageManager.SendMessage(message.ChatId, successMessage); + messageManager.SendTextMessage(message.ChatId, successMessage); context.ChangeChatState(message.ChatId, Session.ChatSessionState.Start); } } @@ -73,28 +73,28 @@ private bool CheckPassword(long chatId, string password) if (string.IsNullOrEmpty(password)) { const string warningMessage = "Input password"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); return false; } if (password.Length < 12) { const string warningMessage = "Password min length 12!"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); return false; } if (password.Length > 25) { const string warningMessage = "Password max length 25!"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); return false; } if (!Regex.IsMatch(password, @"^[a-zA-Z0-9!""#$%&'()*+,-./:;<=>?@[\]^_`{|}~]+$")) { const string warningMessage = "Password can contain only letters, numbers and special characters!"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); return false; } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs index e193bea..45c808b 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs @@ -15,7 +15,7 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon ModulesManager.GetModulesManager().GetMessageManager(); const string welcomeMessage = "Hi, good to see you!"; - messageManager.SendMessage(message.ChatId, welcomeMessage); + messageManager.SendTextMessage(message.ChatId, welcomeMessage); context.ChangeChatState(message.ChatId, ChatSessionState.Start); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs index 7cdcc1a..70319ab 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs @@ -25,7 +25,7 @@ public void StartStateMessage(long chatId) ModulesManager.GetModulesManager().GetMessageManager(); const string warningMessage = "If you have already registered you will lose all your old data!\nAre you sure? /yes or /no"; - messageManager.SendMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, warningMessage); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs index 133b74f..abe3e55 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs @@ -26,7 +26,7 @@ public void StartStateMessage(long chatId) ModulesManager.GetModulesManager().GetMessageManager(); const string mainCommandsMessage = "Registration: /reg\nAuthorization: /auth\nInformation about me: /info\nClose chat in any time: /e or /exit"; - messageManager.SendMessage(chatId, mainCommandsMessage); + messageManager.SendTextMessage(chatId, mainCommandsMessage); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -62,7 +62,7 @@ private void Information(long chatId, IChatStateHandlerContext context) ModulesManager.GetModulesManager().GetMessageManager(); const string informationMessage = "This is open source bot for stashing in Telegram Messenger.\nThe code you can find here: https://github.com/dmitrydnl/StashBot"; - messageManager.SendMessage(chatId, informationMessage); + messageManager.SendTextMessage(chatId, informationMessage); } } } diff --git a/src/StashBot/app/Module/Message/MessageManager.cs b/src/StashBot/app/Module/Message/MessageManager.cs index 28e4048..92936b3 100644 --- a/src/StashBot/app/Module/Message/MessageManager.cs +++ b/src/StashBot/app/Module/Message/MessageManager.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Threading.Tasks; using StashBot.Module.Message.Handler; using StashBot.Module.Message.Sender; using StashBot.Module.Message.Delete; @@ -23,9 +24,14 @@ public void HandleUserMessage(ITelegramUserMessage message) messageHandler.HandleUserMessage(message); } - public void SendMessage(long chatId, string message) + public Task SendTextMessage(long chatId, string textMessage) { - messageSender.SendMessage(chatId, message); + return messageSender.SendTextMessage(chatId, textMessage); + } + + public Task SendPhotoMessage(long chatId, byte[] imageBytes) + { + return messageSender.SendPhotoMessage(chatId, imageBytes); } public void DeleteMessage(long chatId, int messageId) diff --git a/src/StashBot/app/Module/Message/Sender/IMessageSender.cs b/src/StashBot/app/Module/Message/Sender/IMessageSender.cs index b5e6e66..109967c 100644 --- a/src/StashBot/app/Module/Message/Sender/IMessageSender.cs +++ b/src/StashBot/app/Module/Message/Sender/IMessageSender.cs @@ -1,7 +1,10 @@ -namespace StashBot.Module.Message.Sender +using System.Threading.Tasks; + +namespace StashBot.Module.Message.Sender { internal interface IMessageSender { - void SendMessage(long chatId, string message); + Task SendTextMessage(long chatId, string message); + Task SendPhotoMessage(long chatId, byte[] imageBytes); } } diff --git a/src/StashBot/app/Module/Message/Sender/MessageSender.cs b/src/StashBot/app/Module/Message/Sender/MessageSender.cs index 49a11ae..4c0ab62 100644 --- a/src/StashBot/app/Module/Message/Sender/MessageSender.cs +++ b/src/StashBot/app/Module/Message/Sender/MessageSender.cs @@ -1,11 +1,14 @@ -using StashBot.Module.Session; +using System.IO; +using System.Threading.Tasks; +using StashBot.Module.Session; using Telegram.Bot; +using Telegram.Bot.Types.InputFiles; namespace StashBot.Module.Message.Sender { internal class MessageSender : IMessageSender { - public async void SendMessage(long chatId, string messageText) + public async Task SendTextMessage(long chatId, string messageText) { ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); @@ -13,10 +16,27 @@ public async void SendMessage(long chatId, string messageText) ModulesManager.GetModulesManager().GetSessionManager(); Telegram.Bot.Types.Message message = await telegramBotClient.SendTextMessageAsync( - chatId: chatId, - text: messageText + chatId: chatId, + text: messageText ); sessionManager.BotSentMessage(chatId, message.MessageId); } + + public async Task SendPhotoMessage(long chatId, byte[] imageBytes) + { + ITelegramBotClient telegramBotClient = + ModulesManager.GetModulesManager().GetTelegramBotClient(); + ISessionManager sessionManager = + ModulesManager.GetModulesManager().GetSessionManager(); + + using (Stream stream = new MemoryStream(imageBytes)) + { + Telegram.Bot.Types.Message message = await telegramBotClient.SendPhotoAsync( + chatId, + new InputOnlineFile(stream) + ); + sessionManager.BotSentMessage(chatId, message.MessageId); + } + } } } From 9bbfcfe3158c927777aa9cdea0a7f4ae17642ede Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Thu, 31 Oct 2019 01:36:33 +0300 Subject: [PATCH 10/17] Update Database module --- .../Database/Account/DatabaseAccountLocal.cs | 16 ++- .../Database/Account/IDatabaseAccount.cs | 2 +- .../app/Module/Database/Account/IUser.cs | 7 +- .../app/Module/Database/Account/User.cs | 25 +++- .../app/Module/Database/DatabaseManager.cs | 13 +- .../Database/Stash/DatabaseStashLocal.cs | 26 ++-- .../Module/Database/Stash/IDatabaseStash.cs | 1 + .../Module/Database/Stash/IStashMessage.cs | 10 -- .../app/Module/Database/Stash/StashMessage.cs | 130 ++++++++++++------ 9 files changed, 149 insertions(+), 81 deletions(-) diff --git a/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs b/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs index ca423bf..dde7216 100644 --- a/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs +++ b/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs @@ -16,10 +16,14 @@ public void CreateNewUser(long chatId, string password) IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); + if (databaseManager.IsStashExist(chatId)) + { + databaseManager.ClearStash(chatId); + } + User newUser = new User(chatId, password); if (IsUserExist(chatId)) { - databaseManager.ClearStash(chatId); usersDatabase[chatId] = newUser; } else @@ -28,11 +32,6 @@ public void CreateNewUser(long chatId, string password) } } - public bool IsUserExist(long chatId) - { - return usersDatabase.ContainsKey(chatId); - } - public IUser GetUser(long chatId) { if (IsUserExist(chatId)) @@ -42,5 +41,10 @@ public IUser GetUser(long chatId) return null; } + + public bool IsUserExist(long chatId) + { + return usersDatabase.ContainsKey(chatId); + } } } diff --git a/src/StashBot/app/Module/Database/Account/IDatabaseAccount.cs b/src/StashBot/app/Module/Database/Account/IDatabaseAccount.cs index 17fc32b..3d070ec 100644 --- a/src/StashBot/app/Module/Database/Account/IDatabaseAccount.cs +++ b/src/StashBot/app/Module/Database/Account/IDatabaseAccount.cs @@ -3,7 +3,7 @@ internal interface IDatabaseAccount { void CreateNewUser(long chatId, string password); - bool IsUserExist(long chatId); IUser GetUser(long chatId); + bool IsUserExist(long chatId); } } diff --git a/src/StashBot/app/Module/Database/Account/IUser.cs b/src/StashBot/app/Module/Database/Account/IUser.cs index 000d5ff..05cca02 100644 --- a/src/StashBot/app/Module/Database/Account/IUser.cs +++ b/src/StashBot/app/Module/Database/Account/IUser.cs @@ -2,7 +2,7 @@ { internal interface IUser { - string EncryptedPassword + long ChatId { get; } @@ -12,6 +12,11 @@ bool IsAuthorized get; } + string EncryptedPassword + { + get; + } + void Login(string password); void Logout(); bool ValidatePassword(string password); diff --git a/src/StashBot/app/Module/Database/Account/User.cs b/src/StashBot/app/Module/Database/Account/User.cs index 8eb9bad..fdefea7 100644 --- a/src/StashBot/app/Module/Database/Account/User.cs +++ b/src/StashBot/app/Module/Database/Account/User.cs @@ -1,13 +1,11 @@ -using StashBot.Module.Secure; +using System; +using StashBot.Module.Secure; namespace StashBot.Module.Database { internal class User : IUser { - private readonly long chatId; - private readonly string hashPassword; - - public string EncryptedPassword + public long ChatId { get; private set; @@ -19,15 +17,28 @@ public bool IsAuthorized private set; } + public string EncryptedPassword + { + get; + private set; + } + + private readonly string hashPassword; + internal User(long chatId, string password) { + if (string.IsNullOrEmpty(password)) + { + throw new ArgumentException("Password cannot be null"); + } + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); - this.chatId = chatId; + ChatId = chatId; + IsAuthorized = false; hashPassword = secureManager.CalculateHash(password); EncryptedPassword = null; - IsAuthorized = false; } public void Login(string password) diff --git a/src/StashBot/app/Module/Database/DatabaseManager.cs b/src/StashBot/app/Module/Database/DatabaseManager.cs index d95af0b..165d6e1 100644 --- a/src/StashBot/app/Module/Database/DatabaseManager.cs +++ b/src/StashBot/app/Module/Database/DatabaseManager.cs @@ -20,14 +20,14 @@ public void CreateNewUser(long chatId, string password) databaseAccount.CreateNewUser(chatId, password); } - public bool IsUserExist(long chatId) + public IUser GetUser(long chatId) { - return databaseAccount.IsUserExist(chatId); + return databaseAccount.GetUser(chatId); } - public IUser GetUser(long chatId) + public bool IsUserExist(long chatId) { - return databaseAccount.GetUser(chatId); + return databaseAccount.IsUserExist(chatId); } public void SaveMessageToStash(IStashMessage stashMessage) @@ -44,5 +44,10 @@ public void ClearStash(long chatId) { databaseStash.ClearStash(chatId); } + + public bool IsStashExist(long chatId) + { + return databaseStash.IsStashExist(chatId); + } } } diff --git a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs index 2ac0d90..4195094 100644 --- a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs +++ b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs @@ -14,23 +14,22 @@ internal DatabaseStashLocal() public void SaveMessageToStash(IStashMessage stashMessage) { - if (!stashMessage.IsDownloaded) + if (!stashMessage.IsEncrypt) { throw new ArgumentException( - "An undownloaded message cannot be stored in a stash", - nameof(stashMessage)); + "An unencrypted message cannot be stored in a stash"); } - if (!stashMessage.IsEncrypt) + if (!stashMessage.IsDownloaded) { throw new ArgumentException( - "An unencrypted message cannot be stored in a stash", - nameof(stashMessage)); + "An undownloaded message cannot be stored in a stash"); } - if (!usersStashes.ContainsKey(stashMessage.ChatId)) + if (!IsStashExist(stashMessage.ChatId)) { - usersStashes.Add(stashMessage.ChatId, new List()); + usersStashes + .Add(stashMessage.ChatId, new List()); } usersStashes[stashMessage.ChatId].Add(stashMessage); @@ -38,9 +37,9 @@ public void SaveMessageToStash(IStashMessage stashMessage) public List GetMessagesFromStash(long chatId) { - if (!usersStashes.ContainsKey(chatId)) + if (!IsStashExist(chatId)) { - return new List(); + usersStashes.Add(chatId, new List()); } return usersStashes[chatId]; @@ -48,10 +47,15 @@ public List GetMessagesFromStash(long chatId) public void ClearStash(long chatId) { - if (usersStashes.ContainsKey(chatId)) + if (IsStashExist(chatId)) { usersStashes[chatId].Clear(); } } + + public bool IsStashExist(long chatId) + { + return usersStashes.ContainsKey(chatId); + } } } diff --git a/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs b/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs index 5cbe8d8..c882d45 100644 --- a/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs +++ b/src/StashBot/app/Module/Database/Stash/IDatabaseStash.cs @@ -7,5 +7,6 @@ internal interface IDatabaseStash void SaveMessageToStash(IStashMessage stashMessage); List GetMessagesFromStash(long chatId); void ClearStash(long chatId); + bool IsStashExist(long chatId); } } diff --git a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs index 9147932..c4b668f 100644 --- a/src/StashBot/app/Module/Database/Stash/IStashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/IStashMessage.cs @@ -19,16 +19,6 @@ bool IsDownloaded get; } - string Message - { - get; - } - - string Photo - { - get; - } - Task Download(); void Encrypt(IUser user); void Decrypt(IUser user); diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs index 1406f75..fd61f45 100644 --- a/src/StashBot/app/Module/Database/Stash/StashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -27,41 +27,67 @@ public bool IsDownloaded private set; } - public string Message + private enum StashMessageType { - get; - private set; - } - - public string Photo - { - get; - private set; + Text, + Photo, + Empty } - private readonly string photoId; + private readonly StashMessageType type; + private string content; + private string photoId; internal StashMessage(ITelegramUserMessage telegramMessage) { ChatId = telegramMessage.ChatId; IsEncrypt = false; - Message = telegramMessage.Message; - photoId = telegramMessage.PhotoId; - IsDownloaded = string.IsNullOrEmpty(photoId); + if (!string.IsNullOrEmpty(telegramMessage.Message)) + { + content = telegramMessage.Message; + IsDownloaded = true; + type = StashMessageType.Text; + } + else if (!string.IsNullOrEmpty(telegramMessage.PhotoId)) + { + content = null; + photoId = telegramMessage.PhotoId; + IsDownloaded = false; + type = StashMessageType.Photo; + } + else + { + content = null; + IsDownloaded = true; + type = StashMessageType.Empty; + } } public async Task Download() { + if (IsEncrypt) + { + throw new ArgumentException( + "An encrypted message cannot download"); + } + + if (IsDownloaded) + { + return; + } + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); using (MemoryStream stream = new MemoryStream()) { - await telegramBotClient.GetInfoAndDownloadFileAsync(photoId, stream); + await telegramBotClient + .GetInfoAndDownloadFileAsync(photoId, stream); byte[] imageBytes = stream.ToArray(); - Photo = Convert.ToBase64String(imageBytes); + content = Convert.ToBase64String(imageBytes); } + photoId = null; IsDownloaded = true; } @@ -72,17 +98,26 @@ public void Encrypt(IUser user) return; } - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); + if (!IsDownloaded) + { + throw new ArgumentException( + "An undownloaded message cannot encrypt"); + } - string password = secureManager.DecryptWithAes(user.EncryptedPassword); - if (!string.IsNullOrEmpty(Message)) + if (!user.IsAuthorized) { - Message = secureManager.EncryptWithAesHmac(Message, password); + throw new ArgumentException( + "User is unauthorized, message cannot encrypt"); } - if (!string.IsNullOrEmpty(Photo)) + + ISecureManager secureManager = + ModulesManager.GetModulesManager().GetSecureManager(); + + string password = + secureManager.DecryptWithAes(user.EncryptedPassword); + if (type != StashMessageType.Empty) { - Photo = secureManager.EncryptWithAesHmac(Photo, password); + content = secureManager.EncryptWithAesHmac(content, password); } IsEncrypt = true; @@ -95,18 +130,26 @@ public void Decrypt(IUser user) return; } - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); - - string password = secureManager.DecryptWithAes(user.EncryptedPassword); - if (!string.IsNullOrEmpty(Message)) + if (!IsDownloaded) { - Message = secureManager.DecryptWithAesHmac(Message, password); + throw new ArgumentException( + "An undownloaded message cannot decrypt"); } - if (!string.IsNullOrEmpty(Photo)) + + if (!user.IsAuthorized) { - Photo = secureManager.DecryptWithAesHmac(Photo, password); + throw new ArgumentException( + "User is unauthorized, message cannot decrypt"); + } + + ISecureManager secureManager = + ModulesManager.GetModulesManager().GetSecureManager(); + string password = + secureManager.DecryptWithAes(user.EncryptedPassword); + if (type != StashMessageType.Empty) + { + content = secureManager.DecryptWithAesHmac(content, password); } IsEncrypt = false; @@ -114,27 +157,32 @@ public void Decrypt(IUser user) public void Send() { - if (!IsDownloaded) + if (IsEncrypt) { - throw new ArgumentException("An undownloaded message cannot send"); + throw new ArgumentException( + "An encrypted message cannot send"); } - if (IsEncrypt) + if (!IsDownloaded) { - throw new ArgumentException("An encrypted message cannot send"); + throw new ArgumentException( + "An undownloaded message cannot send"); } IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - if (!string.IsNullOrEmpty(Message)) - { - _ = messageManager.SendTextMessage(ChatId, Message); - } - if (!string.IsNullOrEmpty(Photo)) + switch (type) { - byte[] imageBytes = Convert.FromBase64String(Photo); - _ = messageManager.SendPhotoMessage(ChatId, imageBytes); + case StashMessageType.Text: + _ = messageManager.SendTextMessage(ChatId, content); + break; + case StashMessageType.Photo: + byte[] imageBytes = Convert.FromBase64String(content); + _ = messageManager.SendPhotoMessage(ChatId, imageBytes); + break; + case StashMessageType.Empty: + break; } } } From f19e684bdb9dcfd22b656c960b90f1f40bb60bcc Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Thu, 31 Oct 2019 02:10:13 +0300 Subject: [PATCH 11/17] Update code style --- .../Secure/AesCrypto/SecureAesCrypto.cs | 10 ++- .../AesHmacCrypto/ISecureAesHmacCrypto.cs | 10 ++- .../AesHmacCrypto/SecureAesHmacCrypto.cs | 89 +++++++++++++------ .../app/Module/Secure/Hash/SecureHash.cs | 30 ++++++- .../app/Module/Secure/ISecureManager.cs | 5 +- .../app/Module/Secure/SecureManager.cs | 20 ++++- .../app/Module/Session/ChatSession.cs | 13 +-- .../app/Module/Session/SessionManager.cs | 14 ++- .../User/Authorisation/UserAuthorisation.cs | 1 - src/StashBot/app/Module/User/IUserManager.cs | 4 +- src/StashBot/app/StashBot.cs | 3 +- src/StashBot/app/TelegramUserMessage.cs | 9 +- 12 files changed, 151 insertions(+), 57 deletions(-) diff --git a/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs b/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs index 1b29743..6f15470 100644 --- a/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs +++ b/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs @@ -17,7 +17,7 @@ public string EncryptWithAes(string secretMessage) { if (string.IsNullOrEmpty(secretMessage)) { - throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); + throw new ArgumentException("Secret message required"); } byte[] encryptedData; @@ -25,7 +25,8 @@ public string EncryptWithAes(string secretMessage) ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (MemoryStream msEncrypt = new MemoryStream()) { - using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) + using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, + encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { @@ -42,7 +43,7 @@ public string DecryptWithAes(string encryptedMessage) { if (string.IsNullOrEmpty(encryptedMessage)) { - throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage)); + throw new ArgumentException("Encrypted message required"); } byte[] encryptedData = AesStringToEncryptedData(encryptedMessage); @@ -51,7 +52,8 @@ public string DecryptWithAes(string encryptedMessage) ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream msDecrypt = new MemoryStream(encryptedData)) { - using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) + using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, + decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { diff --git a/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs b/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs index 6068789..234c201 100644 --- a/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs +++ b/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs @@ -2,7 +2,13 @@ { internal interface ISecureAesHmacCrypto { - string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null); - string DecryptWithAesHmac(string encryptedMessage, string password, int nonSecretPayloadLength = 0); + string EncryptWithAesHmac( + string secretMessage, + string password, + byte[] nonSecretPayload = null); + string DecryptWithAesHmac( + string encryptedMessage, + string password, + int nonSecretPayloadLength = 0); } } diff --git a/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs b/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs index 4e2cb2c..57471d5 100644 --- a/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs +++ b/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs @@ -13,57 +13,78 @@ internal class SecureAesHmacCrypto : ISecureAesHmacCrypto private const int ITERATIONS = 10000; private const int MIN_PASSWORD_LENGTH = 12; - internal SecureAesHmacCrypto() - { - - } - - public string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null) + public string EncryptWithAesHmac( + string secretMessage, + string password, + byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(secretMessage)) { - throw new ArgumentException("Secret Message Required!", nameof(secretMessage)); + throw new ArgumentException("Secret message required"); } - if (string.IsNullOrWhiteSpace(password) || password.Length < MIN_PASSWORD_LENGTH) + if (string.IsNullOrWhiteSpace(password) + || password.Length < MIN_PASSWORD_LENGTH) { - throw new ArgumentException(string.Format("Must have a password of at least {0} characters!", MIN_PASSWORD_LENGTH), nameof(password)); + throw new ArgumentException(string.Format( + "Must have a password of at least {0} characters!", + MIN_PASSWORD_LENGTH)); } byte[] plainText = Encoding.UTF8.GetBytes(secretMessage); - byte[] cipherText = EncryptWithPassword(plainText, password, nonSecretPayload); + byte[] cipherText = EncryptWithPassword( + plainText, + password, + nonSecretPayload); return Convert.ToBase64String(cipherText); } - public string DecryptWithAesHmac(string encryptedMessage, string password, int nonSecretPayloadLength = 0) + public string DecryptWithAesHmac( + string encryptedMessage, + string password, + int nonSecretPayloadLength = 0) { if (string.IsNullOrWhiteSpace(encryptedMessage)) { - throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage)); + throw new ArgumentException("Encrypted message required"); } - if (string.IsNullOrWhiteSpace(password) || password.Length < MIN_PASSWORD_LENGTH) + if (string.IsNullOrWhiteSpace(password) + || password.Length < MIN_PASSWORD_LENGTH) { - throw new ArgumentException(string.Format("Must have a password of at least {0} characters!", MIN_PASSWORD_LENGTH), nameof(password)); + throw new ArgumentException(string.Format( + "Must have a password of at least {0} characters!", + MIN_PASSWORD_LENGTH)); } byte[] cipherText = Convert.FromBase64String(encryptedMessage); - byte[] plainText = DecryptWithPassword(cipherText, password, nonSecretPayloadLength); - return plainText == null ? null : Encoding.UTF8.GetString(plainText); + byte[] plainText = DecryptWithPassword( + cipherText, + password, + nonSecretPayloadLength); + return plainText == null + ? null : Encoding.UTF8.GetString(plainText); } - private byte[] EncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null) + private byte[] EncryptWithPassword( + byte[] secretMessage, + string password, + byte[] nonSecretPayload = null) { nonSecretPayload = nonSecretPayload ?? new byte[] { }; - byte[] payload = new byte[(SALT_BIT_SIZE / 8 * 2) + nonSecretPayload.Length]; + byte[] payload = + new byte[(SALT_BIT_SIZE / 8 * 2) + nonSecretPayload.Length]; Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length); int payloadIndex = nonSecretPayload.Length; byte[] cryptKey; byte[] authKey; - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, SALT_BIT_SIZE / 8, ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( + password, + SALT_BIT_SIZE / 8, + ITERATIONS)) { byte[] salt = generator.Salt; cryptKey = generator.GetBytes(KEY_BIT_SIZE / 8); @@ -71,7 +92,10 @@ private byte[] EncryptWithPassword(byte[] secretMessage, string password, byte[] payloadIndex += salt.Length; } - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, SALT_BIT_SIZE / 8, ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( + password, + SALT_BIT_SIZE / 8, + ITERATIONS)) { byte[] salt = generator.Salt; authKey = generator.GetBytes(KEY_BIT_SIZE / 8); @@ -81,28 +105,41 @@ private byte[] EncryptWithPassword(byte[] secretMessage, string password, byte[] return Encrypt(secretMessage, cryptKey, authKey, payload); } - private byte[] DecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0) + private byte[] DecryptWithPassword( + byte[] encryptedMessage, + string password, + int nonSecretPayloadLength = 0) { byte[] cryptSalt = new byte[SALT_BIT_SIZE / 8]; byte[] authSalt = new byte[SALT_BIT_SIZE / 8]; - Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length); - Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length); + Array.Copy(encryptedMessage, nonSecretPayloadLength, + cryptSalt, 0, cryptSalt.Length); + Array.Copy(encryptedMessage, + nonSecretPayloadLength + cryptSalt.Length, + authSalt, 0, authSalt.Length); byte[] cryptKey; byte[] authKey; - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, cryptSalt, ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( + password, + cryptSalt, + ITERATIONS)) { cryptKey = generator.GetBytes(KEY_BIT_SIZE / 8); } - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, authSalt, ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( + password, + authSalt, + ITERATIONS)) { authKey = generator.GetBytes(KEY_BIT_SIZE / 8); } - return Decrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength); + return Decrypt(encryptedMessage, cryptKey, authKey, + cryptSalt.Length + authSalt.Length + nonSecretPayloadLength); } private byte[] Encrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) diff --git a/src/StashBot/app/Module/Secure/Hash/SecureHash.cs b/src/StashBot/app/Module/Secure/Hash/SecureHash.cs index 70e694b..6442a7a 100644 --- a/src/StashBot/app/Module/Secure/Hash/SecureHash.cs +++ b/src/StashBot/app/Module/Secure/Hash/SecureHash.cs @@ -8,18 +8,39 @@ internal class SecureHash : ISecureHash { public string CalculateHash(string text) { + if (string.IsNullOrEmpty(text)) + { + throw new ArgumentException( + "Text for hashing shouldn't be empty"); + } + byte[] salt = GenerateSalt(16); - byte[] bytes = KeyDerivation.Pbkdf2(text, salt, KeyDerivationPrf.HMACSHA512, 10000, 16); - return $"{Convert.ToBase64String(salt)}:" + $"{Convert.ToBase64String(bytes)}"; + byte[] bytes = KeyDerivation.Pbkdf2(text, salt, + KeyDerivationPrf.HMACSHA512, 10000, 16); + return $"{Convert.ToBase64String(salt)}:" + + $"{Convert.ToBase64String(bytes)}"; } public bool CompareWithHash(string text, string hash) { + if (string.IsNullOrEmpty(text)) + { + throw new ArgumentException( + "Text for comparing with hash shouldn't be empty"); + } + + if (string.IsNullOrEmpty(hash)) + { + throw new ArgumentException( + "Hash shouldn't be empty"); + } + try { string[] parts = hash.Split(':'); byte[] salt = Convert.FromBase64String(parts[0]); - byte[] bytes = KeyDerivation.Pbkdf2(text, salt, KeyDerivationPrf.HMACSHA512, 10000, 16); + byte[] bytes = KeyDerivation.Pbkdf2(text, salt, + KeyDerivationPrf.HMACSHA512, 10000, 16); return parts[1].Equals(Convert.ToBase64String(bytes)); } catch @@ -31,7 +52,8 @@ public bool CompareWithHash(string text, string hash) private byte[] GenerateSalt(int length) { byte[] salt = new byte[length]; - using (RandomNumberGenerator random = RandomNumberGenerator.Create()) + using (RandomNumberGenerator random + = RandomNumberGenerator.Create()) { random.GetBytes(salt); } diff --git a/src/StashBot/app/Module/Secure/ISecureManager.cs b/src/StashBot/app/Module/Secure/ISecureManager.cs index 245ac30..ac29a2b 100644 --- a/src/StashBot/app/Module/Secure/ISecureManager.cs +++ b/src/StashBot/app/Module/Secure/ISecureManager.cs @@ -4,7 +4,10 @@ namespace StashBot.Module.Secure { - internal interface ISecureManager : ISecureHash, ISecureAesCrypto, ISecureAesHmacCrypto + internal interface ISecureManager : + ISecureHash, + ISecureAesCrypto, + ISecureAesHmacCrypto { } diff --git a/src/StashBot/app/Module/Secure/SecureManager.cs b/src/StashBot/app/Module/Secure/SecureManager.cs index 7a5f2c4..c231308 100644 --- a/src/StashBot/app/Module/Secure/SecureManager.cs +++ b/src/StashBot/app/Module/Secure/SecureManager.cs @@ -37,14 +37,26 @@ public string DecryptWithAes(string encryptedMessage) return secureAesCrypto.DecryptWithAes(encryptedMessage); } - public string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null) + public string EncryptWithAesHmac( + string secretMessage, + string password, + byte[] nonSecretPayload = null) { - return secureAesHmacCrypto.EncryptWithAesHmac(secretMessage, password, nonSecretPayload); + return secureAesHmacCrypto.EncryptWithAesHmac( + secretMessage, + password, + nonSecretPayload); } - public string DecryptWithAesHmac(string encryptedMessage, string password, int nonSecretPayloadLength = 0) + public string DecryptWithAesHmac( + string encryptedMessage, + string password, + int nonSecretPayloadLength = 0) { - return secureAesHmacCrypto.DecryptWithAesHmac(encryptedMessage, password, nonSecretPayloadLength); + return secureAesHmacCrypto.DecryptWithAesHmac( + encryptedMessage, + password, + nonSecretPayloadLength); } } } diff --git a/src/StashBot/app/Module/Session/ChatSession.cs b/src/StashBot/app/Module/Session/ChatSession.cs index 6802fae..bb19981 100644 --- a/src/StashBot/app/Module/Session/ChatSession.cs +++ b/src/StashBot/app/Module/Session/ChatSession.cs @@ -9,11 +9,6 @@ internal class ChatSession : IChatSession { private const int CHAT_SESSION_LIVE_TIME_SEC = 60; - private DateTime lastUserMessage; - private DateTime lastBotMessage; - private readonly List userMessagesId; - private readonly List botMessagesId; - public long ChatId { get; @@ -25,6 +20,11 @@ public ChatSessionState State set; } + private DateTime lastUserMessage; + private DateTime lastBotMessage; + private readonly List userMessagesId; + private readonly List botMessagesId; + internal ChatSession(long chatId) { ChatId = chatId; @@ -63,7 +63,8 @@ public void Kill() public bool NeedKill() { - DateTime endLiveTime = lastUserMessage.AddSeconds(CHAT_SESSION_LIVE_TIME_SEC); + DateTime endLiveTime = + lastUserMessage.AddSeconds(CHAT_SESSION_LIVE_TIME_SEC); return endLiveTime <= DateTime.UtcNow; } } diff --git a/src/StashBot/app/Module/Session/SessionManager.cs b/src/StashBot/app/Module/Session/SessionManager.cs index 1a8ef9d..bca914b 100644 --- a/src/StashBot/app/Module/Session/SessionManager.cs +++ b/src/StashBot/app/Module/Session/SessionManager.cs @@ -54,14 +54,20 @@ public void KillChatSession(long chatId) public void UserSentMessage(long chatId, int messageId) { - IChatSession chatSession = currentChatSessions[chatId]; - chatSession.UserSentMessage(messageId); + if (IsChatSessionExist(chatId)) + { + IChatSession chatSession = currentChatSessions[chatId]; + chatSession.UserSentMessage(messageId); + } } public void BotSentMessage(long chatId, int messageId) { - IChatSession chatSession = currentChatSessions[chatId]; - chatSession.BotSentMessage(messageId); + if (IsChatSessionExist(chatId)) + { + IChatSession chatSession = currentChatSessions[chatId]; + chatSession.BotSentMessage(messageId); + } } private void StartClearChatSessionsTimer() diff --git a/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs b/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs index df3d2b0..f23099a 100644 --- a/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs +++ b/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs @@ -1,5 +1,4 @@ using StashBot.Module.Database; -using StashBot.Module.Session; namespace StashBot.Module.User.Authorisation { diff --git a/src/StashBot/app/Module/User/IUserManager.cs b/src/StashBot/app/Module/User/IUserManager.cs index 75d426a..380c19e 100644 --- a/src/StashBot/app/Module/User/IUserManager.cs +++ b/src/StashBot/app/Module/User/IUserManager.cs @@ -3,7 +3,9 @@ namespace StashBot.Module.User { - internal interface IUserManager : IUserRegistration, IUserAuthorisation + internal interface IUserManager : + IUserRegistration, + IUserAuthorisation { } diff --git a/src/StashBot/app/StashBot.cs b/src/StashBot/app/StashBot.cs index 081abd2..ad30b64 100644 --- a/src/StashBot/app/StashBot.cs +++ b/src/StashBot/app/StashBot.cs @@ -42,7 +42,8 @@ private void OnMessage(object sender, MessageEventArgs e) IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - messageManager.HandleUserMessage(telegramUserMessageFactory.Create(e.Message)); + messageManager.HandleUserMessage( + telegramUserMessageFactory.Create(e.Message)); } } } diff --git a/src/StashBot/app/TelegramUserMessage.cs b/src/StashBot/app/TelegramUserMessage.cs index 94918c1..87ec283 100644 --- a/src/StashBot/app/TelegramUserMessage.cs +++ b/src/StashBot/app/TelegramUserMessage.cs @@ -36,9 +36,11 @@ internal TelegramUserMessage(Message telegramMessage) DateSent = telegramMessage.Date; MessageId = telegramMessage.MessageId; Message = telegramMessage.Text; - if (telegramMessage.Photo != null && telegramMessage.Photo.Length > 0) + if (telegramMessage.Photo != null + && telegramMessage.Photo.Length > 0) { - PhotoId = telegramMessage.Photo[telegramMessage.Photo.Length - 1].FileId; + PhotoId = telegramMessage + .Photo[telegramMessage.Photo.Length - 1].FileId; } else { @@ -48,7 +50,8 @@ internal TelegramUserMessage(Message telegramMessage) public bool IsEmpty() { - return string.IsNullOrEmpty(Message) && string.IsNullOrEmpty(PhotoId); + return string.IsNullOrEmpty(Message) + && string.IsNullOrEmpty(PhotoId); } } } From 820de7342bc18e7af0f5fd1723975fff46486f9b Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sat, 2 Nov 2019 16:21:43 +0300 Subject: [PATCH 12/17] Code refactoring --- .../AuthorizationStateHandler.cs | 24 ++++++++++---- .../AuthorizedStateHandler.cs | 33 ++++++++++++------- .../ChatStateHandlerFactory.cs | 33 +++++++++++++++---- .../CreateUserPasswordStateHandler.cs | 5 +++ .../FirstMessageStateHandler.cs | 5 +++ .../ChatStateHandler/IChatStateHandler.cs | 4 ++- .../RegistrationStateHandler.cs | 5 +++ .../ChatStateHandler/StartStateHandler.cs | 5 +++ .../Module/Message/Handler/MessageHandler.cs | 18 ++++++---- .../app/Module/Message/IMessageManager.cs | 5 ++- .../Module/Message/Sender/MessageSender.cs | 10 ++++++ 11 files changed, 114 insertions(+), 33 deletions(-) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs index 85dff73..82312d4 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs @@ -5,7 +5,8 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class AuthorisationStateHandler : IChatStateHandler { - private delegate void Command(long chatId, IChatStateHandlerContext context); + private delegate void Command(long chatId, + IChatStateHandlerContext context); private readonly Dictionary commands; internal AuthorisationStateHandler() @@ -28,8 +29,15 @@ public void StartStateMessage(long chatId) messageManager.SendTextMessage(chatId, warningMessage); } - public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) + public void HandleUserMessage( + ITelegramUserMessage message, + IChatStateHandlerContext context) { + if (message == null || context == null) + { + return; + } + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); IUserManager userManager = @@ -50,22 +58,26 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) + && commands.ContainsKey(message); } - private void LoginUser(ITelegramUserMessage message, IChatStateHandlerContext context) + private void LoginUser(ITelegramUserMessage message, + IChatStateHandlerContext context) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); - bool success = userManager.LoginUser(message.ChatId, message.Message); + bool success = + userManager.LoginUser(message.ChatId, message.Message); if (success) { const string successMessage = "Success!"; messageManager.SendTextMessage(message.ChatId, successMessage); - context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized); + context.ChangeChatState(message.ChatId, + Session.ChatSessionState.Authorized); } else { diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index cecb288..0d529c2 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -8,7 +8,9 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class AuthorizedStateHandler : IChatStateHandler { - private delegate void Command(long chatId, IChatStateHandlerContext context); + private delegate void Command( + long chatId, + IChatStateHandlerContext context); private readonly Dictionary commands; private readonly IStashMessageFactory stashMessageFactory; @@ -30,12 +32,21 @@ public void StartStateMessage(long chatId) IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string loginMessage = "Input message to save it in stash.\nGet messages in stash: /stash\nLogout: /logout"; + const string loginMessage = + "Input message to save it in stash.\n" + + "Get messages in stash: /stash\nLogout: /logout"; messageManager.SendTextMessage(chatId, loginMessage); } - public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) + public void HandleUserMessage( + ITelegramUserMessage message, + IChatStateHandlerContext context) { + if (message == null || context == null) + { + return; + } + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); @@ -51,7 +62,8 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) + && commands.ContainsKey(message); } private async Task SaveMessageToStash(ITelegramUserMessage message) @@ -62,12 +74,9 @@ private async Task SaveMessageToStash(ITelegramUserMessage message) IUser user = databaseManager.GetUser(message.ChatId); if (user != null && user.IsAuthorized) { - IStashMessage stashMessage = stashMessageFactory.Create(message); - if (!stashMessage.IsDownloaded) - { - await stashMessage.Download(); - } - + IStashMessage stashMessage = + stashMessageFactory.Create(message); + await stashMessage.Download(); stashMessage.Encrypt(user); databaseManager.SaveMessageToStash(stashMessage); } @@ -78,11 +87,11 @@ private void GetStash(long chatId, IChatStateHandlerContext context) IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); - IUser user = databaseManager.GetUser(chatId); if (user != null && user.IsAuthorized) { - List messagesFromStash = databaseManager.GetMessagesFromStash(chatId); + List messagesFromStash = + databaseManager.GetMessagesFromStash(chatId); foreach(IStashMessage stashMessage in messagesFromStash) { stashMessage.Decrypt(user); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs index 0918098..138d2bb 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs @@ -9,14 +9,33 @@ internal class ChatStateHandlerFactory : IChatStateHandlerFactory internal ChatStateHandlerFactory() { - chatStateHandlers = new Dictionary + chatStateHandlers = + new Dictionary { - { ChatSessionState.FirstMessage, new FirstMessageStateHandler() }, - { ChatSessionState.Start, new StartStateHandler() }, - { ChatSessionState.Registration, new RegistrationStateHandler() }, - { ChatSessionState.CreateUserPassword, new CreateUserPasswordStateHandler() }, - { ChatSessionState.Authorisation, new AuthorisationStateHandler() }, - { ChatSessionState.Authorized, new AuthorizedStateHandler() } + { + ChatSessionState.FirstMessage, + new FirstMessageStateHandler() + }, + { + ChatSessionState.Start, + new StartStateHandler() + }, + { + ChatSessionState.Registration, + new RegistrationStateHandler() + }, + { + ChatSessionState.CreateUserPassword, + new CreateUserPasswordStateHandler() + }, + { + ChatSessionState.Authorisation, + new AuthorisationStateHandler() + }, + { + ChatSessionState.Authorized, + new AuthorizedStateHandler() + } }; } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs index dad6b3a..cf27b07 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs @@ -31,6 +31,11 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { + if (message == null || context == null) + { + return; + } + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs index 45c808b..fef4ff6 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs @@ -11,6 +11,11 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { + if (message == null || context == null) + { + return; + } + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs index d36d6d1..b787126 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs @@ -3,6 +3,8 @@ internal interface IChatStateHandler { void StartStateMessage(long chatId); - void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context); + void HandleUserMessage( + ITelegramUserMessage message, + IChatStateHandlerContext context); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs index 70319ab..02434ec 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs @@ -30,6 +30,11 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { + if (message == null || context == null) + { + return; + } + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs index abe3e55..3aa9a61 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs @@ -31,6 +31,11 @@ public void StartStateMessage(long chatId) public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { + if (message == null || context == null) + { + return; + } + if (IsCommand(message.Message)) { commands[message.Message](message.ChatId, context); diff --git a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs index 372205b..234541e 100644 --- a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs @@ -22,7 +22,8 @@ public void HandleUserMessage(ITelegramUserMessage message) return; } - IChatSession chatSession = sessionManager.GetChatSession(message.ChatId); + IChatSession chatSession = + sessionManager.GetChatSession(message.ChatId); if (chatSession == null) { sessionManager.CreateChatSession(message.ChatId); @@ -30,17 +31,20 @@ public void HandleUserMessage(ITelegramUserMessage message) } sessionManager.UserSentMessage(message.ChatId, message.MessageId); - if (string.Equals(message.Message, "/e") || string.Equals(message.Message, "/exit")) + if (string.Equals(message.Message, "/e") + || string.Equals(message.Message, "/exit")) { sessionManager.KillChatSession(message.ChatId); } else { - chatStateHandlerFactory.GetChatStateHandler(chatSession.State).HandleUserMessage(message, this); + chatStateHandlerFactory + .GetChatStateHandler(chatSession.State) + .HandleUserMessage(message, this); } } - public void ChangeChatState(long chatId, ChatSessionState newChatSessionState) + public void ChangeChatState(long chatId, ChatSessionState newState) { ISessionManager sessionManager = ModulesManager.GetModulesManager().GetSessionManager(); @@ -48,8 +52,10 @@ public void ChangeChatState(long chatId, ChatSessionState newChatSessionState) IChatSession chatSession = sessionManager.GetChatSession(chatId); if (chatSession != null) { - chatSession.State = newChatSessionState; - chatStateHandlerFactory.GetChatStateHandler(chatSession.State).StartStateMessage(chatId); + chatSession.State = newState; + chatStateHandlerFactory + .GetChatStateHandler(chatSession.State) + .StartStateMessage(chatId); } } } diff --git a/src/StashBot/app/Module/Message/IMessageManager.cs b/src/StashBot/app/Module/Message/IMessageManager.cs index e9edaf9..cd88025 100644 --- a/src/StashBot/app/Module/Message/IMessageManager.cs +++ b/src/StashBot/app/Module/Message/IMessageManager.cs @@ -4,7 +4,10 @@ namespace StashBot.Module.Message { - internal interface IMessageManager : IMessageDelete, IMessageHandler, IMessageSender + internal interface IMessageManager : + IMessageDelete, + IMessageHandler, + IMessageSender { } diff --git a/src/StashBot/app/Module/Message/Sender/MessageSender.cs b/src/StashBot/app/Module/Message/Sender/MessageSender.cs index 4c0ab62..baa8f3e 100644 --- a/src/StashBot/app/Module/Message/Sender/MessageSender.cs +++ b/src/StashBot/app/Module/Message/Sender/MessageSender.cs @@ -10,6 +10,11 @@ internal class MessageSender : IMessageSender { public async Task SendTextMessage(long chatId, string messageText) { + if (string.IsNullOrEmpty(messageText)) + { + return; + } + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); ISessionManager sessionManager = @@ -24,6 +29,11 @@ public async Task SendTextMessage(long chatId, string messageText) public async Task SendPhotoMessage(long chatId, byte[] imageBytes) { + if (imageBytes == null || imageBytes.Length == 0) + { + return; + } + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); ISessionManager sessionManager = From 4291e50bae53a8dfd1249095a4ed050db279da81 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sat, 2 Nov 2019 16:37:19 +0300 Subject: [PATCH 13/17] Code refactoring --- .../app/Module/Database/Account/User.cs | 5 +++ .../app/Module/Database/IDatabaseManager.cs | 4 +- .../AuthorizationStateHandler.cs | 7 +--- .../AuthorizedStateHandler.cs | 12 ++---- .../ChatStateHandlerFactory.cs | 3 +- .../RegistrationStateHandler.cs | 23 +++++++--- .../ChatStateHandler/StartStateHandler.cs | 42 ++++++++++++++----- .../Module/Message/Handler/MessageHandler.cs | 6 +-- .../app/Module/Secure/SecureManager.cs | 5 +-- .../User/Authorisation/UserAuthorisation.cs | 6 +-- .../User/Registration/UserRegistration.cs | 3 +- 11 files changed, 71 insertions(+), 45 deletions(-) diff --git a/src/StashBot/app/Module/Database/Account/User.cs b/src/StashBot/app/Module/Database/Account/User.cs index fdefea7..2b5daed 100644 --- a/src/StashBot/app/Module/Database/Account/User.cs +++ b/src/StashBot/app/Module/Database/Account/User.cs @@ -43,6 +43,11 @@ internal User(long chatId, string password) public void Login(string password) { + if (string.IsNullOrEmpty(password)) + { + throw new ArgumentException("Password cannot be null"); + } + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); diff --git a/src/StashBot/app/Module/Database/IDatabaseManager.cs b/src/StashBot/app/Module/Database/IDatabaseManager.cs index 142197b..5b630e2 100644 --- a/src/StashBot/app/Module/Database/IDatabaseManager.cs +++ b/src/StashBot/app/Module/Database/IDatabaseManager.cs @@ -3,7 +3,9 @@ namespace StashBot.Module.Database { - internal interface IDatabaseManager : IDatabaseAccount, IDatabaseStash + internal interface IDatabaseManager : + IDatabaseAccount, + IDatabaseStash { } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs index 82312d4..92a730e 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs @@ -29,9 +29,7 @@ public void StartStateMessage(long chatId) messageManager.SendTextMessage(chatId, warningMessage); } - public void HandleUserMessage( - ITelegramUserMessage message, - IChatStateHandlerContext context) + public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { if (message == null || context == null) { @@ -58,8 +56,7 @@ public void HandleUserMessage( private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) - && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); } private void LoginUser(ITelegramUserMessage message, diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index 0d529c2..9f405fb 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -68,14 +68,12 @@ private bool IsCommand(string message) private async Task SaveMessageToStash(ITelegramUserMessage message) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); IUser user = databaseManager.GetUser(message.ChatId); if (user != null && user.IsAuthorized) { - IStashMessage stashMessage = - stashMessageFactory.Create(message); + IStashMessage stashMessage = stashMessageFactory.Create(message); await stashMessage.Download(); stashMessage.Encrypt(user); databaseManager.SaveMessageToStash(stashMessage); @@ -84,14 +82,12 @@ private async Task SaveMessageToStash(ITelegramUserMessage message) private void GetStash(long chatId, IChatStateHandlerContext context) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); IUser user = databaseManager.GetUser(chatId); if (user != null && user.IsAuthorized) { - List messagesFromStash = - databaseManager.GetMessagesFromStash(chatId); + List messagesFromStash = databaseManager.GetMessagesFromStash(chatId); foreach(IStashMessage stashMessage in messagesFromStash) { stashMessage.Decrypt(user); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs index 138d2bb..35dc62a 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/ChatStateHandlerFactory.cs @@ -9,8 +9,7 @@ internal class ChatStateHandlerFactory : IChatStateHandlerFactory internal ChatStateHandlerFactory() { - chatStateHandlers = - new Dictionary + chatStateHandlers = new Dictionary { { ChatSessionState.FirstMessage, diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs index 02434ec..3877460 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs @@ -4,7 +4,9 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class RegistrationStateHandler : IChatStateHandler { - private delegate void Command(long chatId, IChatStateHandlerContext context); + private delegate void Command( + long chatId, + IChatStateHandlerContext context); private readonly Dictionary commands; internal RegistrationStateHandler() @@ -24,11 +26,15 @@ public void StartStateMessage(long chatId) IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string warningMessage = "If you have already registered you will lose all your old data!\nAre you sure? /yes or /no"; + const string warningMessage = + "If you have already registered " + + "you will lose all your old data!\nAre you sure? /yes or /no"; messageManager.SendTextMessage(chatId, warningMessage); } - public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) + public void HandleUserMessage( + ITelegramUserMessage message, + IChatStateHandlerContext context) { if (message == null || context == null) { @@ -47,12 +53,17 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) + && commands.ContainsKey(message); } - private void Registration(long chatId, IChatStateHandlerContext context) + private void Registration( + long chatId, + IChatStateHandlerContext context) { - context.ChangeChatState(chatId, Session.ChatSessionState.CreateUserPassword); + context.ChangeChatState( + chatId, + Session.ChatSessionState.CreateUserPassword); } private void Cancel(long chatId, IChatStateHandlerContext context) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs index 3aa9a61..bc37e39 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs @@ -4,7 +4,9 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class StartStateHandler : IChatStateHandler { - private delegate void Command(long chatId, IChatStateHandlerContext context); + private delegate void Command( + long chatId, + IChatStateHandlerContext context); private readonly Dictionary commands; internal StartStateHandler() @@ -25,11 +27,17 @@ public void StartStateMessage(long chatId) IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string mainCommandsMessage = "Registration: /reg\nAuthorization: /auth\nInformation about me: /info\nClose chat in any time: /e or /exit"; + const string mainCommandsMessage = + "Registration: /reg\n" + + "Authorization: /auth\n" + + "Information about me: /info\n" + + "Close chat in any time: /e or /exit"; messageManager.SendTextMessage(chatId, mainCommandsMessage); } - public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) + public void HandleUserMessage( + ITelegramUserMessage message, + IChatStateHandlerContext context) { if (message == null || context == null) { @@ -48,25 +56,39 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) + && commands.ContainsKey(message); } - private void Registration(long chatId, IChatStateHandlerContext context) + private void Registration( + long chatId, + IChatStateHandlerContext context) { - context.ChangeChatState(chatId, Session.ChatSessionState.Registration); + context.ChangeChatState( + chatId, + Session.ChatSessionState.Registration); } - private void Authorization(long chatId, IChatStateHandlerContext context) + private void Authorization( + long chatId, + IChatStateHandlerContext context) { - context.ChangeChatState(chatId, Session.ChatSessionState.Authorisation); + context.ChangeChatState( + chatId, + Session.ChatSessionState.Authorisation); } - private void Information(long chatId, IChatStateHandlerContext context) + private void Information( + long chatId, + IChatStateHandlerContext context) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string informationMessage = "This is open source bot for stashing in Telegram Messenger.\nThe code you can find here: https://github.com/dmitrydnl/StashBot"; + const string informationMessage = + "This is open source bot for stashing in Telegram Messenger." + + "\nThe code you can find here: " + + "https://github.com/dmitrydnl/StashBot"; messageManager.SendTextMessage(chatId, informationMessage); } } diff --git a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs index 234541e..fc43cc5 100644 --- a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs @@ -14,14 +14,14 @@ internal MessageHandler() public void HandleUserMessage(ITelegramUserMessage message) { - ISessionManager sessionManager = - ModulesManager.GetModulesManager().GetSessionManager(); - if (message.IsEmpty()) { return; } + ISessionManager sessionManager = + ModulesManager.GetModulesManager().GetSessionManager(); + IChatSession chatSession = sessionManager.GetChatSession(message.ChatId); if (chatSession == null) diff --git a/src/StashBot/app/Module/Secure/SecureManager.cs b/src/StashBot/app/Module/Secure/SecureManager.cs index c231308..12d8115 100644 --- a/src/StashBot/app/Module/Secure/SecureManager.cs +++ b/src/StashBot/app/Module/Secure/SecureManager.cs @@ -37,10 +37,7 @@ public string DecryptWithAes(string encryptedMessage) return secureAesCrypto.DecryptWithAes(encryptedMessage); } - public string EncryptWithAesHmac( - string secretMessage, - string password, - byte[] nonSecretPayload = null) + public string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null) { return secureAesHmacCrypto.EncryptWithAesHmac( secretMessage, diff --git a/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs b/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs index f23099a..e5bcfb8 100644 --- a/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs +++ b/src/StashBot/app/Module/User/Authorisation/UserAuthorisation.cs @@ -6,8 +6,7 @@ internal class UserAuthorisation : IUserAuthorisation { public bool LoginUser(long chatId, string password) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); IUser user = databaseManager.GetUser(chatId); if (user == null) @@ -26,8 +25,7 @@ public bool LoginUser(long chatId, string password) public void LogoutUser(long chatId) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); IUser user = databaseManager.GetUser(chatId); if (user != null) diff --git a/src/StashBot/app/Module/User/Registration/UserRegistration.cs b/src/StashBot/app/Module/User/Registration/UserRegistration.cs index 0a80379..d538c9a 100644 --- a/src/StashBot/app/Module/User/Registration/UserRegistration.cs +++ b/src/StashBot/app/Module/User/Registration/UserRegistration.cs @@ -6,8 +6,7 @@ internal class UserRegistration : IUserRegistration { public void CreateNewUser(long chatId, string password) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); databaseManager.CreateNewUser(chatId, password); } From f091b0501390d72a13c73647df8efe3d78d7f798 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sat, 2 Nov 2019 17:05:05 +0300 Subject: [PATCH 14/17] Code refactoring --- src/StashBot/app/AppSettings/BotToken.cs | 1 + .../Database/Account/DatabaseAccountLocal.cs | 3 +- .../app/Module/Database/Account/User.cs | 9 +- .../app/Module/Database/IDatabaseManager.cs | 4 +- .../Database/Stash/DatabaseStashLocal.cs | 9 +- .../app/Module/Database/Stash/StashMessage.cs | 48 ++++------- .../Module/Message/Delete/MessageDelete.cs | 3 +- .../AuthorizationStateHandler.cs | 24 ++---- .../AuthorizedStateHandler.cs | 24 ++---- .../CreateUserPasswordStateHandler.cs | 12 +-- .../FirstMessageStateHandler.cs | 3 +- .../ChatStateHandler/IChatStateHandler.cs | 4 +- .../RegistrationStateHandler.cs | 23 ++--- .../ChatStateHandler/StartStateHandler.cs | 48 +++-------- .../Module/Message/Handler/MessageHandler.cs | 20 ++--- .../app/Module/Message/IMessageManager.cs | 5 +- .../Module/Message/Sender/MessageSender.cs | 12 +-- .../Secure/AesCrypto/SecureAesCrypto.cs | 6 +- .../AesHmacCrypto/ISecureAesHmacCrypto.cs | 10 +-- .../AesHmacCrypto/SecureAesHmacCrypto.cs | 86 ++++++------------- .../app/Module/Secure/Hash/SecureHash.cs | 21 ++--- .../app/Module/Secure/ISecureManager.cs | 5 +- .../app/Module/Secure/SecureManager.cs | 15 +--- .../app/Module/Session/ChatSession.cs | 9 +- src/StashBot/app/Module/User/IUserManager.cs | 4 +- src/StashBot/app/StashBot.cs | 12 +-- src/StashBot/app/TelegramUserMessage.cs | 9 +- 27 files changed, 128 insertions(+), 301 deletions(-) diff --git a/src/StashBot/app/AppSettings/BotToken.cs b/src/StashBot/app/AppSettings/BotToken.cs index 4164ea5..c0099b0 100644 --- a/src/StashBot/app/AppSettings/BotToken.cs +++ b/src/StashBot/app/AppSettings/BotToken.cs @@ -6,6 +6,7 @@ namespace StashBot.AppSetting internal static class BotToken { private const string BOT_TOKEN_FILE_NAME = "AppSettings.json"; + private static string botToken; internal static string Get() diff --git a/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs b/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs index dde7216..d818f6d 100644 --- a/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs +++ b/src/StashBot/app/Module/Database/Account/DatabaseAccountLocal.cs @@ -13,8 +13,7 @@ internal DatabaseAccountLocal() public void CreateNewUser(long chatId, string password) { - IDatabaseManager databaseManager = - ModulesManager.GetModulesManager().GetDatabaseManager(); + IDatabaseManager databaseManager = ModulesManager.GetModulesManager().GetDatabaseManager(); if (databaseManager.IsStashExist(chatId)) { diff --git a/src/StashBot/app/Module/Database/Account/User.cs b/src/StashBot/app/Module/Database/Account/User.cs index 2b5daed..9932c79 100644 --- a/src/StashBot/app/Module/Database/Account/User.cs +++ b/src/StashBot/app/Module/Database/Account/User.cs @@ -32,8 +32,7 @@ internal User(long chatId, string password) throw new ArgumentException("Password cannot be null"); } - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); ChatId = chatId; IsAuthorized = false; @@ -48,8 +47,7 @@ public void Login(string password) throw new ArgumentException("Password cannot be null"); } - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); EncryptedPassword = secureManager.EncryptWithAes(password); IsAuthorized = true; @@ -63,8 +61,7 @@ public void Logout() public bool ValidatePassword(string password) { - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); return secureManager.CompareWithHash(password, hashPassword); } diff --git a/src/StashBot/app/Module/Database/IDatabaseManager.cs b/src/StashBot/app/Module/Database/IDatabaseManager.cs index 5b630e2..142197b 100644 --- a/src/StashBot/app/Module/Database/IDatabaseManager.cs +++ b/src/StashBot/app/Module/Database/IDatabaseManager.cs @@ -3,9 +3,7 @@ namespace StashBot.Module.Database { - internal interface IDatabaseManager : - IDatabaseAccount, - IDatabaseStash + internal interface IDatabaseManager : IDatabaseAccount, IDatabaseStash { } diff --git a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs index 4195094..1b320a9 100644 --- a/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs +++ b/src/StashBot/app/Module/Database/Stash/DatabaseStashLocal.cs @@ -16,20 +16,17 @@ public void SaveMessageToStash(IStashMessage stashMessage) { if (!stashMessage.IsEncrypt) { - throw new ArgumentException( - "An unencrypted message cannot be stored in a stash"); + throw new ArgumentException("An unencrypted message cannot be stored in a stash"); } if (!stashMessage.IsDownloaded) { - throw new ArgumentException( - "An undownloaded message cannot be stored in a stash"); + throw new ArgumentException("An undownloaded message cannot be stored in a stash"); } if (!IsStashExist(stashMessage.ChatId)) { - usersStashes - .Add(stashMessage.ChatId, new List()); + usersStashes.Add(stashMessage.ChatId, new List()); } usersStashes[stashMessage.ChatId].Add(stashMessage); diff --git a/src/StashBot/app/Module/Database/Stash/StashMessage.cs b/src/StashBot/app/Module/Database/Stash/StashMessage.cs index fd61f45..1d2616f 100644 --- a/src/StashBot/app/Module/Database/Stash/StashMessage.cs +++ b/src/StashBot/app/Module/Database/Stash/StashMessage.cs @@ -65,24 +65,21 @@ internal StashMessage(ITelegramUserMessage telegramMessage) public async Task Download() { - if (IsEncrypt) + if (IsDownloaded) { - throw new ArgumentException( - "An encrypted message cannot download"); + return; } - if (IsDownloaded) + if (IsEncrypt) { - return; + throw new ArgumentException("An encrypted message cannot download"); } - ITelegramBotClient telegramBotClient = - ModulesManager.GetModulesManager().GetTelegramBotClient(); + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); using (MemoryStream stream = new MemoryStream()) { - await telegramBotClient - .GetInfoAndDownloadFileAsync(photoId, stream); + await telegramBotClient.GetInfoAndDownloadFileAsync(photoId, stream); byte[] imageBytes = stream.ToArray(); content = Convert.ToBase64String(imageBytes); } @@ -100,21 +97,17 @@ public void Encrypt(IUser user) if (!IsDownloaded) { - throw new ArgumentException( - "An undownloaded message cannot encrypt"); + throw new ArgumentException("An undownloaded message cannot encrypt"); } if (!user.IsAuthorized) { - throw new ArgumentException( - "User is unauthorized, message cannot encrypt"); + throw new ArgumentException("User is unauthorized, message cannot encrypt"); } - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); - string password = - secureManager.DecryptWithAes(user.EncryptedPassword); + string password = secureManager.DecryptWithAes(user.EncryptedPassword); if (type != StashMessageType.Empty) { content = secureManager.EncryptWithAesHmac(content, password); @@ -132,21 +125,17 @@ public void Decrypt(IUser user) if (!IsDownloaded) { - throw new ArgumentException( - "An undownloaded message cannot decrypt"); + throw new ArgumentException("An undownloaded message cannot decrypt"); } if (!user.IsAuthorized) { - throw new ArgumentException( - "User is unauthorized, message cannot decrypt"); + throw new ArgumentException("User is unauthorized, message cannot decrypt"); } - ISecureManager secureManager = - ModulesManager.GetModulesManager().GetSecureManager(); + ISecureManager secureManager = ModulesManager.GetModulesManager().GetSecureManager(); - string password = - secureManager.DecryptWithAes(user.EncryptedPassword); + string password = secureManager.DecryptWithAes(user.EncryptedPassword); if (type != StashMessageType.Empty) { content = secureManager.DecryptWithAesHmac(content, password); @@ -159,18 +148,15 @@ public void Send() { if (IsEncrypt) { - throw new ArgumentException( - "An encrypted message cannot send"); + throw new ArgumentException("An encrypted message cannot send"); } if (!IsDownloaded) { - throw new ArgumentException( - "An undownloaded message cannot send"); + throw new ArgumentException("An undownloaded message cannot send"); } - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); switch (type) { diff --git a/src/StashBot/app/Module/Message/Delete/MessageDelete.cs b/src/StashBot/app/Module/Message/Delete/MessageDelete.cs index 6227fe4..8a7d542 100644 --- a/src/StashBot/app/Module/Message/Delete/MessageDelete.cs +++ b/src/StashBot/app/Module/Message/Delete/MessageDelete.cs @@ -7,8 +7,7 @@ internal class MessageDelete : IMessageDelete { public void DeleteMessage(long chatId, int messageId) { - ITelegramBotClient telegramBotClient = - ModulesManager.GetModulesManager().GetTelegramBotClient(); + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); telegramBotClient.DeleteMessageAsync(chatId, messageId); } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs index 92a730e..9d16151 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs @@ -5,8 +5,7 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class AuthorisationStateHandler : IChatStateHandler { - private delegate void Command(long chatId, - IChatStateHandlerContext context); + private delegate void Command(long chatId, IChatStateHandlerContext context); private readonly Dictionary commands; internal AuthorisationStateHandler() @@ -22,8 +21,7 @@ private void InitializeCommands() public void StartStateMessage(long chatId) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); const string warningMessage = "Input your password or /back"; messageManager.SendTextMessage(chatId, warningMessage); @@ -36,10 +34,8 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon return; } - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); - IUserManager userManager = - ModulesManager.GetModulesManager().GetUserManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); if (IsCommand(message.Message)) { @@ -62,19 +58,15 @@ private bool IsCommand(string message) private void LoginUser(ITelegramUserMessage message, IChatStateHandlerContext context) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); - IUserManager userManager = - ModulesManager.GetModulesManager().GetUserManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); - bool success = - userManager.LoginUser(message.ChatId, message.Message); + bool success = userManager.LoginUser(message.ChatId, message.Message); if (success) { const string successMessage = "Success!"; messageManager.SendTextMessage(message.ChatId, successMessage); - context.ChangeChatState(message.ChatId, - Session.ChatSessionState.Authorized); + context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized); } else { diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index 9f405fb..c72189e 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -8,9 +8,7 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class AuthorizedStateHandler : IChatStateHandler { - private delegate void Command( - long chatId, - IChatStateHandlerContext context); + private delegate void Command(long chatId, IChatStateHandlerContext context); private readonly Dictionary commands; private readonly IStashMessageFactory stashMessageFactory; @@ -29,18 +27,13 @@ private void InitializeCommands() public void StartStateMessage(long chatId) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string loginMessage = - "Input message to save it in stash.\n" + - "Get messages in stash: /stash\nLogout: /logout"; + const string loginMessage = "Input message to save it in stash.\nGet messages in stash: /stash\nLogout: /logout"; messageManager.SendTextMessage(chatId, loginMessage); } - public void HandleUserMessage( - ITelegramUserMessage message, - IChatStateHandlerContext context) + public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { if (message == null || context == null) { @@ -62,8 +55,7 @@ public void HandleUserMessage( private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) - && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); } private async Task SaveMessageToStash(ITelegramUserMessage message) @@ -98,10 +90,8 @@ private void GetStash(long chatId, IChatStateHandlerContext context) private void Logout(long chatId, IChatStateHandlerContext context) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); - IUserManager userManager = - ModulesManager.GetModulesManager().GetUserManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); userManager.LogoutUser(chatId); const string logoutMessage = "You're logged out"; diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs index cf27b07..30ad6ee 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs @@ -22,8 +22,7 @@ private void InitializeCommands() public void StartStateMessage(long chatId) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); const string warningMessage = "Input your password or /cancel"; messageManager.SendTextMessage(chatId, warningMessage); @@ -56,10 +55,8 @@ private bool IsCommand(string message) private void RegistrationUser(ITelegramUserMessage message, IChatStateHandlerContext context) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); - IUserManager userManager = - ModulesManager.GetModulesManager().GetUserManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); if (CheckPassword(message.ChatId, message.Message)) { @@ -72,8 +69,7 @@ private void RegistrationUser(ITelegramUserMessage message, IChatStateHandlerCon private bool CheckPassword(long chatId, string password) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); if (string.IsNullOrEmpty(password)) { diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs index fef4ff6..f61def5 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs @@ -16,8 +16,7 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon return; } - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); const string welcomeMessage = "Hi, good to see you!"; messageManager.SendTextMessage(message.ChatId, welcomeMessage); diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs index b787126..d36d6d1 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/IChatStateHandler.cs @@ -3,8 +3,6 @@ internal interface IChatStateHandler { void StartStateMessage(long chatId); - void HandleUserMessage( - ITelegramUserMessage message, - IChatStateHandlerContext context); + void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs index 3877460..02434ec 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs @@ -4,9 +4,7 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class RegistrationStateHandler : IChatStateHandler { - private delegate void Command( - long chatId, - IChatStateHandlerContext context); + private delegate void Command(long chatId, IChatStateHandlerContext context); private readonly Dictionary commands; internal RegistrationStateHandler() @@ -26,15 +24,11 @@ public void StartStateMessage(long chatId) IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string warningMessage = - "If you have already registered " + - "you will lose all your old data!\nAre you sure? /yes or /no"; + const string warningMessage = "If you have already registered you will lose all your old data!\nAre you sure? /yes or /no"; messageManager.SendTextMessage(chatId, warningMessage); } - public void HandleUserMessage( - ITelegramUserMessage message, - IChatStateHandlerContext context) + public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { if (message == null || context == null) { @@ -53,17 +47,12 @@ public void HandleUserMessage( private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) - && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); } - private void Registration( - long chatId, - IChatStateHandlerContext context) + private void Registration(long chatId, IChatStateHandlerContext context) { - context.ChangeChatState( - chatId, - Session.ChatSessionState.CreateUserPassword); + context.ChangeChatState(chatId, Session.ChatSessionState.CreateUserPassword); } private void Cancel(long chatId, IChatStateHandlerContext context) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs index bc37e39..1e69f4b 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs @@ -4,9 +4,7 @@ namespace StashBot.Module.Message.Handler.ChatStateHandler { internal class StartStateHandler : IChatStateHandler { - private delegate void Command( - long chatId, - IChatStateHandlerContext context); + private delegate void Command(long chatId, IChatStateHandlerContext context); private readonly Dictionary commands; internal StartStateHandler() @@ -24,20 +22,13 @@ private void InitializeCommands() public void StartStateMessage(long chatId) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string mainCommandsMessage = - "Registration: /reg\n" + - "Authorization: /auth\n" + - "Information about me: /info\n" + - "Close chat in any time: /e or /exit"; + const string mainCommandsMessage = "Registration: /reg\nAuthorization: /auth\nInformation about me: /info\nClose chat in any time: /e or /exit"; messageManager.SendTextMessage(chatId, mainCommandsMessage); } - public void HandleUserMessage( - ITelegramUserMessage message, - IChatStateHandlerContext context) + public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) { if (message == null || context == null) { @@ -56,39 +47,24 @@ public void HandleUserMessage( private bool IsCommand(string message) { - return !string.IsNullOrEmpty(message) - && commands.ContainsKey(message); + return !string.IsNullOrEmpty(message) && commands.ContainsKey(message); } - private void Registration( - long chatId, - IChatStateHandlerContext context) + private void Registration(long chatId, IChatStateHandlerContext context) { - context.ChangeChatState( - chatId, - Session.ChatSessionState.Registration); + context.ChangeChatState(chatId, Session.ChatSessionState.Registration); } - private void Authorization( - long chatId, - IChatStateHandlerContext context) + private void Authorization(long chatId, IChatStateHandlerContext context) { - context.ChangeChatState( - chatId, - Session.ChatSessionState.Authorisation); + context.ChangeChatState(chatId, Session.ChatSessionState.Authorisation); } - private void Information( - long chatId, - IChatStateHandlerContext context) + private void Information(long chatId, IChatStateHandlerContext context) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string informationMessage = - "This is open source bot for stashing in Telegram Messenger." + - "\nThe code you can find here: " + - "https://github.com/dmitrydnl/StashBot"; + const string informationMessage = "This is open source bot for stashing in Telegram Messenger.\nThe code you can find here: https://github.com/dmitrydnl/StashBot"; messageManager.SendTextMessage(chatId, informationMessage); } } diff --git a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs index fc43cc5..9c4a39c 100644 --- a/src/StashBot/app/Module/Message/Handler/MessageHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/MessageHandler.cs @@ -19,11 +19,9 @@ public void HandleUserMessage(ITelegramUserMessage message) return; } - ISessionManager sessionManager = - ModulesManager.GetModulesManager().GetSessionManager(); + ISessionManager sessionManager = ModulesManager.GetModulesManager().GetSessionManager(); - IChatSession chatSession = - sessionManager.GetChatSession(message.ChatId); + IChatSession chatSession = sessionManager.GetChatSession(message.ChatId); if (chatSession == null) { sessionManager.CreateChatSession(message.ChatId); @@ -31,31 +29,25 @@ public void HandleUserMessage(ITelegramUserMessage message) } sessionManager.UserSentMessage(message.ChatId, message.MessageId); - if (string.Equals(message.Message, "/e") - || string.Equals(message.Message, "/exit")) + if (string.Equals(message.Message, "/e") || string.Equals(message.Message, "/exit")) { sessionManager.KillChatSession(message.ChatId); } else { - chatStateHandlerFactory - .GetChatStateHandler(chatSession.State) - .HandleUserMessage(message, this); + chatStateHandlerFactory.GetChatStateHandler(chatSession.State).HandleUserMessage(message, this); } } public void ChangeChatState(long chatId, ChatSessionState newState) { - ISessionManager sessionManager = - ModulesManager.GetModulesManager().GetSessionManager(); + ISessionManager sessionManager = ModulesManager.GetModulesManager().GetSessionManager(); IChatSession chatSession = sessionManager.GetChatSession(chatId); if (chatSession != null) { chatSession.State = newState; - chatStateHandlerFactory - .GetChatStateHandler(chatSession.State) - .StartStateMessage(chatId); + chatStateHandlerFactory.GetChatStateHandler(chatSession.State).StartStateMessage(chatId); } } } diff --git a/src/StashBot/app/Module/Message/IMessageManager.cs b/src/StashBot/app/Module/Message/IMessageManager.cs index cd88025..e9edaf9 100644 --- a/src/StashBot/app/Module/Message/IMessageManager.cs +++ b/src/StashBot/app/Module/Message/IMessageManager.cs @@ -4,10 +4,7 @@ namespace StashBot.Module.Message { - internal interface IMessageManager : - IMessageDelete, - IMessageHandler, - IMessageSender + internal interface IMessageManager : IMessageDelete, IMessageHandler, IMessageSender { } diff --git a/src/StashBot/app/Module/Message/Sender/MessageSender.cs b/src/StashBot/app/Module/Message/Sender/MessageSender.cs index baa8f3e..1846ee5 100644 --- a/src/StashBot/app/Module/Message/Sender/MessageSender.cs +++ b/src/StashBot/app/Module/Message/Sender/MessageSender.cs @@ -15,10 +15,8 @@ public async Task SendTextMessage(long chatId, string messageText) return; } - ITelegramBotClient telegramBotClient = - ModulesManager.GetModulesManager().GetTelegramBotClient(); - ISessionManager sessionManager = - ModulesManager.GetModulesManager().GetSessionManager(); + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); + ISessionManager sessionManager = ModulesManager.GetModulesManager().GetSessionManager(); Telegram.Bot.Types.Message message = await telegramBotClient.SendTextMessageAsync( chatId: chatId, @@ -34,10 +32,8 @@ public async Task SendPhotoMessage(long chatId, byte[] imageBytes) return; } - ITelegramBotClient telegramBotClient = - ModulesManager.GetModulesManager().GetTelegramBotClient(); - ISessionManager sessionManager = - ModulesManager.GetModulesManager().GetSessionManager(); + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); + ISessionManager sessionManager = ModulesManager.GetModulesManager().GetSessionManager(); using (Stream stream = new MemoryStream(imageBytes)) { diff --git a/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs b/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs index 6f15470..527365d 100644 --- a/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs +++ b/src/StashBot/app/Module/Secure/AesCrypto/SecureAesCrypto.cs @@ -25,8 +25,7 @@ public string EncryptWithAes(string secretMessage) ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (MemoryStream msEncrypt = new MemoryStream()) { - using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, - encryptor, CryptoStreamMode.Write)) + using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { @@ -52,8 +51,7 @@ public string DecryptWithAes(string encryptedMessage) ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (MemoryStream msDecrypt = new MemoryStream(encryptedData)) { - using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, - decryptor, CryptoStreamMode.Read)) + using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { diff --git a/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs b/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs index 234c201..6068789 100644 --- a/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs +++ b/src/StashBot/app/Module/Secure/AesHmacCrypto/ISecureAesHmacCrypto.cs @@ -2,13 +2,7 @@ { internal interface ISecureAesHmacCrypto { - string EncryptWithAesHmac( - string secretMessage, - string password, - byte[] nonSecretPayload = null); - string DecryptWithAesHmac( - string encryptedMessage, - string password, - int nonSecretPayloadLength = 0); + string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null); + string DecryptWithAesHmac(string encryptedMessage, string password, int nonSecretPayloadLength = 0); } } diff --git a/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs b/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs index 57471d5..a959b48 100644 --- a/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs +++ b/src/StashBot/app/Module/Secure/AesHmacCrypto/SecureAesHmacCrypto.cs @@ -13,78 +13,52 @@ internal class SecureAesHmacCrypto : ISecureAesHmacCrypto private const int ITERATIONS = 10000; private const int MIN_PASSWORD_LENGTH = 12; - public string EncryptWithAesHmac( - string secretMessage, - string password, - byte[] nonSecretPayload = null) + public string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null) { if (string.IsNullOrEmpty(secretMessage)) { throw new ArgumentException("Secret message required"); } - if (string.IsNullOrWhiteSpace(password) - || password.Length < MIN_PASSWORD_LENGTH) + if (string.IsNullOrWhiteSpace(password) || password.Length < MIN_PASSWORD_LENGTH) { - throw new ArgumentException(string.Format( - "Must have a password of at least {0} characters!", - MIN_PASSWORD_LENGTH)); + throw new ArgumentException(string.Format("Must have a password of at least {0} characters!", MIN_PASSWORD_LENGTH)); } byte[] plainText = Encoding.UTF8.GetBytes(secretMessage); - byte[] cipherText = EncryptWithPassword( - plainText, - password, - nonSecretPayload); + byte[] cipherText = EncryptWithPassword(plainText, password, nonSecretPayload); return Convert.ToBase64String(cipherText); } - public string DecryptWithAesHmac( - string encryptedMessage, - string password, - int nonSecretPayloadLength = 0) + public string DecryptWithAesHmac(string encryptedMessage, string password, int nonSecretPayloadLength = 0) { if (string.IsNullOrWhiteSpace(encryptedMessage)) { throw new ArgumentException("Encrypted message required"); } - if (string.IsNullOrWhiteSpace(password) - || password.Length < MIN_PASSWORD_LENGTH) + if (string.IsNullOrWhiteSpace(password) || password.Length < MIN_PASSWORD_LENGTH) { - throw new ArgumentException(string.Format( - "Must have a password of at least {0} characters!", - MIN_PASSWORD_LENGTH)); + throw new ArgumentException(string.Format("Must have a password of at least {0} characters!", MIN_PASSWORD_LENGTH)); } byte[] cipherText = Convert.FromBase64String(encryptedMessage); - byte[] plainText = DecryptWithPassword( - cipherText, - password, - nonSecretPayloadLength); - return plainText == null - ? null : Encoding.UTF8.GetString(plainText); + byte[] plainText = DecryptWithPassword(cipherText, password, nonSecretPayloadLength); + return plainText == null ? null : Encoding.UTF8.GetString(plainText); } - private byte[] EncryptWithPassword( - byte[] secretMessage, - string password, - byte[] nonSecretPayload = null) + private byte[] EncryptWithPassword(byte[] secretMessage, string password, byte[] nonSecretPayload = null) { nonSecretPayload = nonSecretPayload ?? new byte[] { }; - byte[] payload = - new byte[(SALT_BIT_SIZE / 8 * 2) + nonSecretPayload.Length]; + byte[] payload = new byte[(SALT_BIT_SIZE / 8 * 2) + nonSecretPayload.Length]; Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length); int payloadIndex = nonSecretPayload.Length; byte[] cryptKey; byte[] authKey; - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( - password, - SALT_BIT_SIZE / 8, - ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, SALT_BIT_SIZE / 8, ITERATIONS)) { byte[] salt = generator.Salt; cryptKey = generator.GetBytes(KEY_BIT_SIZE / 8); @@ -92,10 +66,7 @@ private byte[] EncryptWithPassword( payloadIndex += salt.Length; } - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( - password, - SALT_BIT_SIZE / 8, - ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, SALT_BIT_SIZE / 8, ITERATIONS)) { byte[] salt = generator.Salt; authKey = generator.GetBytes(KEY_BIT_SIZE / 8); @@ -105,41 +76,28 @@ private byte[] EncryptWithPassword( return Encrypt(secretMessage, cryptKey, authKey, payload); } - private byte[] DecryptWithPassword( - byte[] encryptedMessage, - string password, - int nonSecretPayloadLength = 0) + private byte[] DecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0) { byte[] cryptSalt = new byte[SALT_BIT_SIZE / 8]; byte[] authSalt = new byte[SALT_BIT_SIZE / 8]; - Array.Copy(encryptedMessage, nonSecretPayloadLength, - cryptSalt, 0, cryptSalt.Length); - Array.Copy(encryptedMessage, - nonSecretPayloadLength + cryptSalt.Length, - authSalt, 0, authSalt.Length); + Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length); + Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length); byte[] cryptKey; byte[] authKey; - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( - password, - cryptSalt, - ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, cryptSalt, ITERATIONS)) { cryptKey = generator.GetBytes(KEY_BIT_SIZE / 8); } - using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes( - password, - authSalt, - ITERATIONS)) + using (Rfc2898DeriveBytes generator = new Rfc2898DeriveBytes(password, authSalt, ITERATIONS)) { authKey = generator.GetBytes(KEY_BIT_SIZE / 8); } - return Decrypt(encryptedMessage, cryptKey, authKey, - cryptSalt.Length + authSalt.Length + nonSecretPayloadLength); + return Decrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength); } private byte[] Encrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null) @@ -201,16 +159,22 @@ private byte[] Decrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int ivLength = (BLOCK_BIT_SIZE / 8); if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength) + { return null; + } Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length); int compare = 0; for (int i = 0; i < sentTag.Length; i++) + { compare |= sentTag[i] ^ calcTag[i]; + } if (compare != 0) + { return null; + } using (AesManaged aes = new AesManaged { diff --git a/src/StashBot/app/Module/Secure/Hash/SecureHash.cs b/src/StashBot/app/Module/Secure/Hash/SecureHash.cs index 6442a7a..2e8e7b2 100644 --- a/src/StashBot/app/Module/Secure/Hash/SecureHash.cs +++ b/src/StashBot/app/Module/Secure/Hash/SecureHash.cs @@ -10,37 +10,31 @@ public string CalculateHash(string text) { if (string.IsNullOrEmpty(text)) { - throw new ArgumentException( - "Text for hashing shouldn't be empty"); + throw new ArgumentException("Text for hashing shouldn't be empty"); } byte[] salt = GenerateSalt(16); - byte[] bytes = KeyDerivation.Pbkdf2(text, salt, - KeyDerivationPrf.HMACSHA512, 10000, 16); - return $"{Convert.ToBase64String(salt)}:" - + $"{Convert.ToBase64String(bytes)}"; + byte[] bytes = KeyDerivation.Pbkdf2(text, salt, KeyDerivationPrf.HMACSHA512, 10000, 16); + return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(bytes)}"; } public bool CompareWithHash(string text, string hash) { if (string.IsNullOrEmpty(text)) { - throw new ArgumentException( - "Text for comparing with hash shouldn't be empty"); + throw new ArgumentException("Text for comparing with hash shouldn't be empty"); } if (string.IsNullOrEmpty(hash)) { - throw new ArgumentException( - "Hash shouldn't be empty"); + throw new ArgumentException("Hash shouldn't be empty"); } try { string[] parts = hash.Split(':'); byte[] salt = Convert.FromBase64String(parts[0]); - byte[] bytes = KeyDerivation.Pbkdf2(text, salt, - KeyDerivationPrf.HMACSHA512, 10000, 16); + byte[] bytes = KeyDerivation.Pbkdf2(text, salt, KeyDerivationPrf.HMACSHA512, 10000, 16); return parts[1].Equals(Convert.ToBase64String(bytes)); } catch @@ -52,8 +46,7 @@ public bool CompareWithHash(string text, string hash) private byte[] GenerateSalt(int length) { byte[] salt = new byte[length]; - using (RandomNumberGenerator random - = RandomNumberGenerator.Create()) + using (RandomNumberGenerator random = RandomNumberGenerator.Create()) { random.GetBytes(salt); } diff --git a/src/StashBot/app/Module/Secure/ISecureManager.cs b/src/StashBot/app/Module/Secure/ISecureManager.cs index ac29a2b..245ac30 100644 --- a/src/StashBot/app/Module/Secure/ISecureManager.cs +++ b/src/StashBot/app/Module/Secure/ISecureManager.cs @@ -4,10 +4,7 @@ namespace StashBot.Module.Secure { - internal interface ISecureManager : - ISecureHash, - ISecureAesCrypto, - ISecureAesHmacCrypto + internal interface ISecureManager : ISecureHash, ISecureAesCrypto, ISecureAesHmacCrypto { } diff --git a/src/StashBot/app/Module/Secure/SecureManager.cs b/src/StashBot/app/Module/Secure/SecureManager.cs index 12d8115..7a5f2c4 100644 --- a/src/StashBot/app/Module/Secure/SecureManager.cs +++ b/src/StashBot/app/Module/Secure/SecureManager.cs @@ -39,21 +39,12 @@ public string DecryptWithAes(string encryptedMessage) public string EncryptWithAesHmac(string secretMessage, string password, byte[] nonSecretPayload = null) { - return secureAesHmacCrypto.EncryptWithAesHmac( - secretMessage, - password, - nonSecretPayload); + return secureAesHmacCrypto.EncryptWithAesHmac(secretMessage, password, nonSecretPayload); } - public string DecryptWithAesHmac( - string encryptedMessage, - string password, - int nonSecretPayloadLength = 0) + public string DecryptWithAesHmac(string encryptedMessage, string password, int nonSecretPayloadLength = 0) { - return secureAesHmacCrypto.DecryptWithAesHmac( - encryptedMessage, - password, - nonSecretPayloadLength); + return secureAesHmacCrypto.DecryptWithAesHmac(encryptedMessage, password, nonSecretPayloadLength); } } } diff --git a/src/StashBot/app/Module/Session/ChatSession.cs b/src/StashBot/app/Module/Session/ChatSession.cs index bb19981..8fdcd6d 100644 --- a/src/StashBot/app/Module/Session/ChatSession.cs +++ b/src/StashBot/app/Module/Session/ChatSession.cs @@ -49,10 +49,8 @@ public void BotSentMessage(int messageId) public void Kill() { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); - IUserManager userManager = - ModulesManager.GetModulesManager().GetUserManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); + IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); messageManager.DeleteListMessages(ChatId, botMessagesId); botMessagesId.Clear(); @@ -63,8 +61,7 @@ public void Kill() public bool NeedKill() { - DateTime endLiveTime = - lastUserMessage.AddSeconds(CHAT_SESSION_LIVE_TIME_SEC); + DateTime endLiveTime = lastUserMessage.AddSeconds(CHAT_SESSION_LIVE_TIME_SEC); return endLiveTime <= DateTime.UtcNow; } } diff --git a/src/StashBot/app/Module/User/IUserManager.cs b/src/StashBot/app/Module/User/IUserManager.cs index 380c19e..75d426a 100644 --- a/src/StashBot/app/Module/User/IUserManager.cs +++ b/src/StashBot/app/Module/User/IUserManager.cs @@ -3,9 +3,7 @@ namespace StashBot.Module.User { - internal interface IUserManager : - IUserRegistration, - IUserAuthorisation + internal interface IUserManager : IUserRegistration, IUserAuthorisation { } diff --git a/src/StashBot/app/StashBot.cs b/src/StashBot/app/StashBot.cs index ad30b64..d7b66c8 100644 --- a/src/StashBot/app/StashBot.cs +++ b/src/StashBot/app/StashBot.cs @@ -18,8 +18,7 @@ internal StashBot() private void WriteBotStatus() { - ITelegramBotClient telegramBotClient = - ModulesManager.GetModulesManager().GetTelegramBotClient(); + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); Telegram.Bot.Types.User me = telegramBotClient.GetMeAsync().Result; Console.WriteLine(DateTime.Now + " - Bot set up!"); @@ -30,8 +29,7 @@ private void WriteBotStatus() internal void Start() { - ITelegramBotClient telegramBotClient = - ModulesManager.GetModulesManager().GetTelegramBotClient(); + ITelegramBotClient telegramBotClient = ModulesManager.GetModulesManager().GetTelegramBotClient(); telegramBotClient.OnMessage += OnMessage; telegramBotClient.StartReceiving(); @@ -39,11 +37,9 @@ internal void Start() private void OnMessage(object sender, MessageEventArgs e) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - messageManager.HandleUserMessage( - telegramUserMessageFactory.Create(e.Message)); + messageManager.HandleUserMessage(telegramUserMessageFactory.Create(e.Message)); } } } diff --git a/src/StashBot/app/TelegramUserMessage.cs b/src/StashBot/app/TelegramUserMessage.cs index 87ec283..94918c1 100644 --- a/src/StashBot/app/TelegramUserMessage.cs +++ b/src/StashBot/app/TelegramUserMessage.cs @@ -36,11 +36,9 @@ internal TelegramUserMessage(Message telegramMessage) DateSent = telegramMessage.Date; MessageId = telegramMessage.MessageId; Message = telegramMessage.Text; - if (telegramMessage.Photo != null - && telegramMessage.Photo.Length > 0) + if (telegramMessage.Photo != null && telegramMessage.Photo.Length > 0) { - PhotoId = telegramMessage - .Photo[telegramMessage.Photo.Length - 1].FileId; + PhotoId = telegramMessage.Photo[telegramMessage.Photo.Length - 1].FileId; } else { @@ -50,8 +48,7 @@ internal TelegramUserMessage(Message telegramMessage) public bool IsEmpty() { - return string.IsNullOrEmpty(Message) - && string.IsNullOrEmpty(PhotoId); + return string.IsNullOrEmpty(Message) && string.IsNullOrEmpty(PhotoId); } } } From 7d7dfd2e15ea9c9ca1b81707b350107d52d8f75d Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sun, 3 Nov 2019 11:41:10 +0300 Subject: [PATCH 15/17] Move bot settings to json file --- src/StashBot/BotSettings.json | 4 ++ src/StashBot/StashBot.csproj | 9 ++++ src/StashBot/app/AppSettings/BotToken.cs | 4 +- .../app/BotSettings/ChatSessionSettings.cs | 54 +++++++++++++++++++ .../app/Module/Session/ChatSession.cs | 5 +- .../app/Module/Session/SessionManager.cs | 5 +- 6 files changed, 73 insertions(+), 8 deletions(-) create mode 100644 src/StashBot/BotSettings.json create mode 100644 src/StashBot/app/BotSettings/ChatSessionSettings.cs diff --git a/src/StashBot/BotSettings.json b/src/StashBot/BotSettings.json new file mode 100644 index 0000000..9ebc152 --- /dev/null +++ b/src/StashBot/BotSettings.json @@ -0,0 +1,4 @@ +{ + "chatSessionsClearInterval": 10, + "chatSessionLiveTime": 60 +} diff --git a/src/StashBot/StashBot.csproj b/src/StashBot/StashBot.csproj index 187b0bc..a5c3f4f 100644 --- a/src/StashBot/StashBot.csproj +++ b/src/StashBot/StashBot.csproj @@ -30,5 +30,14 @@ + + + + + + + + Always + diff --git a/src/StashBot/app/AppSettings/BotToken.cs b/src/StashBot/app/AppSettings/BotToken.cs index c0099b0..346b966 100644 --- a/src/StashBot/app/AppSettings/BotToken.cs +++ b/src/StashBot/app/AppSettings/BotToken.cs @@ -5,7 +5,7 @@ namespace StashBot.AppSetting { internal static class BotToken { - private const string BOT_TOKEN_FILE_NAME = "AppSettings.json"; + private const string APP_SETTINGS_FILE_NAME = "AppSettings.json"; private static string botToken; @@ -13,7 +13,7 @@ internal static string Get() { if (string.IsNullOrEmpty(botToken)) { - string text = File.ReadAllText(BOT_TOKEN_FILE_NAME); + string text = File.ReadAllText(APP_SETTINGS_FILE_NAME); dynamic jsonObject = JsonConvert.DeserializeObject(text); botToken = (string)jsonObject.botToken; } diff --git a/src/StashBot/app/BotSettings/ChatSessionSettings.cs b/src/StashBot/app/BotSettings/ChatSessionSettings.cs new file mode 100644 index 0000000..cb13e4a --- /dev/null +++ b/src/StashBot/app/BotSettings/ChatSessionSettings.cs @@ -0,0 +1,54 @@ +using System.IO; +using Newtonsoft.Json; + +namespace StashBot.BotSettings +{ + internal static class ChatSessionSettings + { + private const string BOT_SETTINGS_FILE_NAME = "BotSettings.json"; + + private static bool isSetUp; + private static int chatSessionsClearInterval; + private static int chatSessionLiveTime; + + internal static int ChatSessionsClearInterval + { + get + { + SetUpSettings(); + return chatSessionsClearInterval; + } + private set + { + chatSessionsClearInterval = value; + } + } + + internal static int ChatSessionLiveTime + { + get + { + SetUpSettings(); + return chatSessionLiveTime; + } + private set + { + chatSessionLiveTime = value; + } + } + + private static void SetUpSettings() + { + if (isSetUp) + { + return; + } + + string text = File.ReadAllText(BOT_SETTINGS_FILE_NAME); + dynamic jsonObject = JsonConvert.DeserializeObject(text); + ChatSessionsClearInterval = (int)jsonObject.chatSessionsClearInterval; + ChatSessionLiveTime = (int)jsonObject.chatSessionLiveTime; + isSetUp = true; + } + } +} diff --git a/src/StashBot/app/Module/Session/ChatSession.cs b/src/StashBot/app/Module/Session/ChatSession.cs index 8fdcd6d..62494a4 100644 --- a/src/StashBot/app/Module/Session/ChatSession.cs +++ b/src/StashBot/app/Module/Session/ChatSession.cs @@ -2,13 +2,12 @@ using System.Collections.Generic; using StashBot.Module.Message; using StashBot.Module.User; +using StashBot.BotSettings; namespace StashBot.Module.Session { internal class ChatSession : IChatSession { - private const int CHAT_SESSION_LIVE_TIME_SEC = 60; - public long ChatId { get; @@ -61,7 +60,7 @@ public void Kill() public bool NeedKill() { - DateTime endLiveTime = lastUserMessage.AddSeconds(CHAT_SESSION_LIVE_TIME_SEC); + DateTime endLiveTime = lastUserMessage.AddSeconds(ChatSessionSettings.ChatSessionLiveTime); return endLiveTime <= DateTime.UtcNow; } } diff --git a/src/StashBot/app/Module/Session/SessionManager.cs b/src/StashBot/app/Module/Session/SessionManager.cs index bca914b..2c23009 100644 --- a/src/StashBot/app/Module/Session/SessionManager.cs +++ b/src/StashBot/app/Module/Session/SessionManager.cs @@ -1,12 +1,11 @@ using System.Timers; using System.Collections.Generic; +using StashBot.BotSettings; namespace StashBot.Module.Session { internal class SessionManager : ISessionManager { - private const int TIMER_INTERVAL_CLEAR_CHAT_SESSIONS = 10; - private readonly Dictionary currentChatSessions; internal SessionManager() @@ -74,7 +73,7 @@ private void StartClearChatSessionsTimer() { Timer timer = new Timer(); timer.Elapsed += ClearSessions; - timer.Interval = TIMER_INTERVAL_CLEAR_CHAT_SESSIONS * 1000; + timer.Interval = ChatSessionSettings.ChatSessionsClearInterval * 1000; timer.Enabled = true; } From 425aad4ab2c197ef1b47291ae3432c171be97d60 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Sun, 3 Nov 2019 12:31:49 +0300 Subject: [PATCH 16/17] Move bot responses to json file --- src/StashBot/BotResponses.json | 17 +++++++ src/StashBot/StashBot.csproj | 5 ++ src/StashBot/app/BotResponses/ResponseType.cs | 21 +++++++++ src/StashBot/app/BotResponses/TextResponse.cs | 46 +++++++++++++++++++ .../AuthorizationStateHandler.cs | 10 ++-- .../AuthorizedStateHandler.cs | 7 ++- .../CreateUserPasswordStateHandler.cs | 19 +++----- .../FirstMessageStateHandler.cs | 4 +- .../RegistrationStateHandler.cs | 7 ++- .../ChatStateHandler/StartStateHandler.cs | 7 ++- src/StashBot/app/StashBot.cs | 2 + 11 files changed, 113 insertions(+), 32 deletions(-) create mode 100644 src/StashBot/BotResponses.json create mode 100644 src/StashBot/app/BotResponses/ResponseType.cs create mode 100644 src/StashBot/app/BotResponses/TextResponse.cs diff --git a/src/StashBot/BotResponses.json b/src/StashBot/BotResponses.json new file mode 100644 index 0000000..1c0c594 --- /dev/null +++ b/src/StashBot/BotResponses.json @@ -0,0 +1,17 @@ +{ + "welcomeMessage": "Hi, good to see you!", + "mainCommands": "Registration: /reg\nAuthorization: /auth\nInformation about me: /info\nClose chat in any time: /e or /exit", + "information": "This is open source bot for stashing in Telegram Messenger.\nThe code you can find here: https://github.com/dmitrydnl/StashBot", + "registrationWarning": "If you have already registered you will lose all your old data!\nAre you sure? /yes or /no", + "registrationReady": "Input your password or /cancel", + "successRegistration": "Success!\nNow you can auth with password", + "passwordEmpty": "Input password", + "passwordMinLength": "Password min length 12!", + "passwordMaxLength": "Password max length 25!", + "passwordCharacters": "Password can contain only letters, numbers and special characters!", + "authorisationReady": "Input your password or /back", + "successAuthorisation": "Success!", + "failAuthorisation": "WRONG", + "login": "Input message to save it in stash.\nGet messages in stash: /stash\nLogout: /logout", + "logout": "You're logged out" +} diff --git a/src/StashBot/StashBot.csproj b/src/StashBot/StashBot.csproj index a5c3f4f..b5edb15 100644 --- a/src/StashBot/StashBot.csproj +++ b/src/StashBot/StashBot.csproj @@ -31,13 +31,18 @@ + + Always + + Always + diff --git a/src/StashBot/app/BotResponses/ResponseType.cs b/src/StashBot/app/BotResponses/ResponseType.cs new file mode 100644 index 0000000..0b9462b --- /dev/null +++ b/src/StashBot/app/BotResponses/ResponseType.cs @@ -0,0 +1,21 @@ +namespace StashBot.BotResponses +{ + internal enum ResponseType + { + WelcomeMessage, + MainCommands, + Information, + RegistrationWarning, + RegistrationReady, + SuccessRegistration, + PasswordEmpty, + PasswordMinLength, + PasswordMaxLength, + PasswordCharacters, + AuthorisationReady, + SuccessAuthorisation, + FailAuthorisation, + Login, + Logout + } +} diff --git a/src/StashBot/app/BotResponses/TextResponse.cs b/src/StashBot/app/BotResponses/TextResponse.cs new file mode 100644 index 0000000..3b12a10 --- /dev/null +++ b/src/StashBot/app/BotResponses/TextResponse.cs @@ -0,0 +1,46 @@ +using System.IO; +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace StashBot.BotResponses +{ + internal static class TextResponse + { + private const string BOT_RESPONSES_FILE_NAME = "BotResponses.json"; + + private static Dictionary responses; + + internal static string Get(ResponseType responseType) + { + return responses[responseType]; + } + + internal static void SetUpResponses() + { + if (responses != null) + { + return; + } + + responses = new Dictionary(); + string text = File.ReadAllText(BOT_RESPONSES_FILE_NAME); + dynamic jsonObject = JsonConvert.DeserializeObject(text); + + responses.Add(ResponseType.WelcomeMessage, (string)jsonObject.welcomeMessage); + responses.Add(ResponseType.MainCommands, (string)jsonObject.mainCommands); + responses.Add(ResponseType.Information, (string)jsonObject.information); + responses.Add(ResponseType.RegistrationWarning, (string)jsonObject.registrationWarning); + responses.Add(ResponseType.RegistrationReady, (string)jsonObject.registrationReady); + responses.Add(ResponseType.SuccessRegistration, (string)jsonObject.successRegistration); + responses.Add(ResponseType.PasswordEmpty, (string)jsonObject.passwordEmpty); + responses.Add(ResponseType.PasswordMinLength, (string)jsonObject.passwordMinLength); + responses.Add(ResponseType.PasswordMaxLength, (string)jsonObject.passwordMaxLength); + responses.Add(ResponseType.PasswordCharacters, (string)jsonObject.passwordCharacters); + responses.Add(ResponseType.AuthorisationReady, (string)jsonObject.authorisationReady); + responses.Add(ResponseType.SuccessAuthorisation, (string)jsonObject.successAuthorisation); + responses.Add(ResponseType.FailAuthorisation, (string)jsonObject.failAuthorisation); + responses.Add(ResponseType.Login, (string)jsonObject.login); + responses.Add(ResponseType.Logout, (string)jsonObject.logout); + } + } +} diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs index 9d16151..f742ec6 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizationStateHandler.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using StashBot.Module.User; +using StashBot.BotResponses; namespace StashBot.Module.Message.Handler.ChatStateHandler { @@ -23,8 +24,7 @@ public void StartStateMessage(long chatId) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string warningMessage = "Input your password or /back"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.AuthorisationReady)); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -64,14 +64,12 @@ private void LoginUser(ITelegramUserMessage message, bool success = userManager.LoginUser(message.ChatId, message.Message); if (success) { - const string successMessage = "Success!"; - messageManager.SendTextMessage(message.ChatId, successMessage); + messageManager.SendTextMessage(message.ChatId, TextResponse.Get(ResponseType.SuccessAuthorisation)); context.ChangeChatState(message.ChatId, Session.ChatSessionState.Authorized); } else { - const string wrongMessage = "WRONG"; - messageManager.SendTextMessage(message.ChatId, wrongMessage); + messageManager.SendTextMessage(message.ChatId, TextResponse.Get(ResponseType.FailAuthorisation)); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs index c72189e..3ed98f4 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/AuthorizedStateHandler.cs @@ -3,6 +3,7 @@ using StashBot.Module.Database; using StashBot.Module.Database.Stash; using StashBot.Module.User; +using StashBot.BotResponses; namespace StashBot.Module.Message.Handler.ChatStateHandler { @@ -29,8 +30,7 @@ public void StartStateMessage(long chatId) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string loginMessage = "Input message to save it in stash.\nGet messages in stash: /stash\nLogout: /logout"; - messageManager.SendTextMessage(chatId, loginMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.Login)); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -94,8 +94,7 @@ private void Logout(long chatId, IChatStateHandlerContext context) IUserManager userManager = ModulesManager.GetModulesManager().GetUserManager(); userManager.LogoutUser(chatId); - const string logoutMessage = "You're logged out"; - messageManager.SendTextMessage(chatId, logoutMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.Logout)); context.ChangeChatState(chatId, Session.ChatSessionState.Start); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs index 30ad6ee..42b8b76 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/CreateUserPasswordStateHandler.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Text.RegularExpressions; using StashBot.Module.User; +using StashBot.BotResponses; namespace StashBot.Module.Message.Handler.ChatStateHandler { @@ -24,8 +25,7 @@ public void StartStateMessage(long chatId) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string warningMessage = "Input your password or /cancel"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.RegistrationReady)); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -61,8 +61,7 @@ private void RegistrationUser(ITelegramUserMessage message, IChatStateHandlerCon if (CheckPassword(message.ChatId, message.Message)) { userManager.CreateNewUser(message.ChatId, message.Message); - string successMessage = "Success!\nNow you can auth with password"; - messageManager.SendTextMessage(message.ChatId, successMessage); + messageManager.SendTextMessage(message.ChatId, TextResponse.Get(ResponseType.SuccessRegistration)); context.ChangeChatState(message.ChatId, Session.ChatSessionState.Start); } } @@ -73,29 +72,25 @@ private bool CheckPassword(long chatId, string password) if (string.IsNullOrEmpty(password)) { - const string warningMessage = "Input password"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.PasswordEmpty)); return false; } if (password.Length < 12) { - const string warningMessage = "Password min length 12!"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.PasswordMinLength)); return false; } if (password.Length > 25) { - const string warningMessage = "Password max length 25!"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.PasswordMaxLength)); return false; } if (!Regex.IsMatch(password, @"^[a-zA-Z0-9!""#$%&'()*+,-./:;<=>?@[\]^_`{|}~]+$")) { - const string warningMessage = "Password can contain only letters, numbers and special characters!"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.PasswordCharacters)); return false; } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs index f61def5..5a07a4f 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/FirstMessageStateHandler.cs @@ -1,4 +1,5 @@ using StashBot.Module.Session; +using StashBot.BotResponses; namespace StashBot.Module.Message.Handler.ChatStateHandler { @@ -18,8 +19,7 @@ public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerCon IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string welcomeMessage = "Hi, good to see you!"; - messageManager.SendTextMessage(message.ChatId, welcomeMessage); + messageManager.SendTextMessage(message.ChatId, TextResponse.Get(ResponseType.WelcomeMessage)); context.ChangeChatState(message.ChatId, ChatSessionState.Start); } } diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs index 02434ec..18e29dc 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/RegistrationStateHandler.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using StashBot.BotResponses; namespace StashBot.Module.Message.Handler.ChatStateHandler { @@ -21,11 +22,9 @@ private void InitializeCommands() public void StartStateMessage(long chatId) { - IMessageManager messageManager = - ModulesManager.GetModulesManager().GetMessageManager(); + IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string warningMessage = "If you have already registered you will lose all your old data!\nAre you sure? /yes or /no"; - messageManager.SendTextMessage(chatId, warningMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.RegistrationWarning)); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) diff --git a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs index 1e69f4b..f35dc35 100644 --- a/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs +++ b/src/StashBot/app/Module/Message/Handler/ChatStateHandler/StartStateHandler.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using StashBot.BotResponses; namespace StashBot.Module.Message.Handler.ChatStateHandler { @@ -24,8 +25,7 @@ public void StartStateMessage(long chatId) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string mainCommandsMessage = "Registration: /reg\nAuthorization: /auth\nInformation about me: /info\nClose chat in any time: /e or /exit"; - messageManager.SendTextMessage(chatId, mainCommandsMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.MainCommands)); } public void HandleUserMessage(ITelegramUserMessage message, IChatStateHandlerContext context) @@ -64,8 +64,7 @@ private void Information(long chatId, IChatStateHandlerContext context) { IMessageManager messageManager = ModulesManager.GetModulesManager().GetMessageManager(); - const string informationMessage = "This is open source bot for stashing in Telegram Messenger.\nThe code you can find here: https://github.com/dmitrydnl/StashBot"; - messageManager.SendTextMessage(chatId, informationMessage); + messageManager.SendTextMessage(chatId, TextResponse.Get(ResponseType.Information)); } } } diff --git a/src/StashBot/app/StashBot.cs b/src/StashBot/app/StashBot.cs index d7b66c8..5a1c273 100644 --- a/src/StashBot/app/StashBot.cs +++ b/src/StashBot/app/StashBot.cs @@ -1,6 +1,7 @@ using System; using StashBot.Module; using StashBot.Module.Message; +using StashBot.BotResponses; using Telegram.Bot; using Telegram.Bot.Args; @@ -13,6 +14,7 @@ internal class StashBot internal StashBot() { telegramUserMessageFactory = new TelegramUserMessageFactory(); + TextResponse.SetUpResponses(); WriteBotStatus(); } From 3b99c3aea00ca981adfd1f07f5ae21dffd87a5d6 Mon Sep 17 00:00:00 2001 From: Captious99 <48892069+Captious99@users.noreply.github.com> Date: Tue, 5 Nov 2019 02:07:56 +0300 Subject: [PATCH 17/17] Update version --- src/StashBot.sln | 2 +- src/StashBot/StashBot.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/StashBot.sln b/src/StashBot.sln index e19640b..d612bbb 100644 --- a/src/StashBot.sln +++ b/src/StashBot.sln @@ -32,6 +32,6 @@ Global $4.scope = text/x-json $0.StandardHeader = $5 $0.VersionControlPolicy = $6 - version = 0.2 + version = 0.3 EndGlobalSection EndGlobal diff --git a/src/StashBot/StashBot.csproj b/src/StashBot/StashBot.csproj index b5edb15..8f73e42 100644 --- a/src/StashBot/StashBot.csproj +++ b/src/StashBot/StashBot.csproj @@ -3,7 +3,7 @@ Exe netcoreapp2.1 - 0.2 + 0.3 false