From 388ebd964bb546d14d436ca7262c89146c1489bf Mon Sep 17 00:00:00 2001 From: Dmitrii Kollerov Date: Thu, 10 Mar 2022 15:39:31 +0700 Subject: [PATCH] add basic app --- Chatter/Chatter.csproj | 26 ++++ Chatter/Connector/SqLiteConnector.cs | 133 ++++++++++++++++++ Chatter/Dto/MessageDto.cs | 17 +++ Chatter/Logic/Actions/ListActionManager.cs | 72 ++++++++++ Chatter/Models/MessageModel.cs | 17 +++ Chatter/Models/PostModel.cs | 13 ++ Chatter/Program.cs | 81 +++++++++++ Chatter/Properties/launchSettings.json | 8 ++ Chatter/Repository/MessageRepository.cs | 43 ++++++ Chatter/Service/MessageService.cs | 49 +++++++ Chatter/static/index.gmi | 9 ++ Cuipod.sln | 14 +- CuipodExample/CuipodExample.csproj | 15 ++ .../Properties/Resources.Designer.cs | 63 +++++++++ CuipodExample/Properties/Resources.resx | 101 +++++++++++++ 15 files changed, 657 insertions(+), 4 deletions(-) create mode 100644 Chatter/Chatter.csproj create mode 100644 Chatter/Connector/SqLiteConnector.cs create mode 100644 Chatter/Dto/MessageDto.cs create mode 100644 Chatter/Logic/Actions/ListActionManager.cs create mode 100644 Chatter/Models/MessageModel.cs create mode 100644 Chatter/Models/PostModel.cs create mode 100644 Chatter/Program.cs create mode 100644 Chatter/Properties/launchSettings.json create mode 100644 Chatter/Repository/MessageRepository.cs create mode 100644 Chatter/Service/MessageService.cs create mode 100644 Chatter/static/index.gmi create mode 100644 CuipodExample/Properties/Resources.Designer.cs create mode 100644 CuipodExample/Properties/Resources.resx diff --git a/Chatter/Chatter.csproj b/Chatter/Chatter.csproj new file mode 100644 index 0000000..9645ce5 --- /dev/null +++ b/Chatter/Chatter.csproj @@ -0,0 +1,26 @@ + + + + Exe + net5.0 + + + + + + + + + + + + + + + + + Always + + + + diff --git a/Chatter/Connector/SqLiteConnector.cs b/Chatter/Connector/SqLiteConnector.cs new file mode 100644 index 0000000..9a4797d --- /dev/null +++ b/Chatter/Connector/SqLiteConnector.cs @@ -0,0 +1,133 @@ +using Chatter.Dto; +using System; +using System.Collections.Generic; +using System.Data.SQLite; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Connector +{ + public interface IDbConnector: IDisposable + { + IEnumerable GetMessages(); + + void AddMessage(MessageDto msg); + } + + + //Not building a context will do it quick and dirty without entity framework + internal class SqLiteConnector : IDbConnector + { + private readonly SQLiteConnectionStringBuilder _connectionStringBuilder; + private readonly SQLiteConnection _connection; + private readonly string _addCommand = "INSERT INTO messages(text, createdate, user) VALUES (@text, @createdate, @user);"; + private readonly string _getCommand = "SELECT text, createdate, user FROM messages ORDER BY createdate DESC;"; + + private readonly string _createCommand = "CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL, createdate DATETIME NOT NULL, user varchar);"; + + private bool disposedValue; + + public SqLiteConnector() + { + _connectionStringBuilder = new SQLiteConnectionStringBuilder() { DataSource = ":memory:", Version = 3 }; + //_connectionStringBuilder = new SQLiteConnectionStringBuilder() { DataSource = "D:\\sql.s3db", Version = 3 }; + _connection = GetDbConnection(); + _connection.Open(); + PrepareTable(); + } + + SQLiteConnection GetDbConnection() + { + return new SQLiteConnection(_connectionStringBuilder.ToString()); + } + + private void PrepareTable() + { + //_connection.Open(); + + using (var cmd = new SQLiteCommand(_createCommand, _connection)) + { + var data = cmd.ExecuteNonQuery(); + } + + //_connection.Close(); // no async for you today + + } + + public void AddMessage(MessageDto msg) + { + //_connection.Open(); + + using (var cmd = new SQLiteCommand(_addCommand, _connection)) + { + var arguments = new Dictionary() + { + { "@text", msg.Text ?? string.Empty }, + { "@createdate", msg.CreateDate }, + { "@user", msg.User } + }; + + foreach (var pair in arguments) + { + cmd.Parameters.AddWithValue(pair.Key, pair.Value); + } + + cmd.ExecuteNonQuery(); + } + + //_connection.Close(); // no async for you today + } + + public IEnumerable GetMessages() + { + var result = new List(); + + + using (var cmd = new SQLiteCommand(_getCommand, _connection)) + { + using (var reader = cmd.ExecuteReader()) + { + while(reader.Read()) + { + var text = reader.GetString(0); + var createDate = reader.GetString(1); + var user = reader.GetValue(2); + + var message = new MessageDto() + { + Text = text, + CreateDate = DateTime.Parse(createDate), + User = user?.ToString() + }; + result.Add(message); + } + } + } + + //_connection.Close(); // no async for you today + + return result; + } + + protected virtual void Dispose(bool disposing) + { + if (!disposedValue) + { + if (disposing) + { + _connection.Close(); + _connection.Dispose(); + } + + disposedValue = true; + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } +} diff --git a/Chatter/Dto/MessageDto.cs b/Chatter/Dto/MessageDto.cs new file mode 100644 index 0000000..d529331 --- /dev/null +++ b/Chatter/Dto/MessageDto.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Dto +{ + public class MessageDto + { + public string Text { set; get; } + + public DateTime CreateDate { set; get; } + + public string User { set; get; } + } +} diff --git a/Chatter/Logic/Actions/ListActionManager.cs b/Chatter/Logic/Actions/ListActionManager.cs new file mode 100644 index 0000000..c31f031 --- /dev/null +++ b/Chatter/Logic/Actions/ListActionManager.cs @@ -0,0 +1,72 @@ +using Chatter.Models; +using Chatter.Service; +using Cuipod; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Logic.Actions +{ + public static class ListActionManager + { + public static Action> GetListAction() => + (request, response, logger) => { + var service = new MessageService(); + + IEnumerable messages = service.GetMessages(); + + response.RenderPlainTextLine("# Chatter"); + response.RenderPlainTextLine(""); + response.RenderPlainTextLine("## Message list"); + response.RenderPlainTextLine("=> /post Post"); + response.RenderPlainTextLine("==============================================="); + + foreach(var msg in messages) + { + response.RenderPlainTextLine(""); + + var dateString = msg.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"); + response.RenderPlainTextLine( + string.IsNullOrWhiteSpace(msg.User) + ? string.Format("### [{0}]", dateString) + : string.Format("### [{0}] {1}", dateString, msg.User) + ); + + response.RenderPlainTextLine(msg.Text); + + + response.RenderPlainTextLine(""); + response.RenderPlainTextLine(""); + } + + response.RenderPlainTextLine("==============================================="); + response.RenderPlainTextLine("=> /post Post"); + //todo: pagination here? + }; + + public static Action> PostAction() => + (request, response, logger) => { + if (string.IsNullOrEmpty(request.Parameters)) + { + response.SetInputHint("Your message: "); + response.Status = StatusCode.Input; + } + else + { + // redirect to show/ route with input parameters + var model = new PostModel() + { + Text = request.Parameters + }; + var service = new MessageService(); + service.AddMessage(model); + + response.SetRedirectURL(request.BaseURL + "/list"); + response.Status = StatusCode.RedirectTemp; + } + }; + } +} diff --git a/Chatter/Models/MessageModel.cs b/Chatter/Models/MessageModel.cs new file mode 100644 index 0000000..e4aca4d --- /dev/null +++ b/Chatter/Models/MessageModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Models +{ + public class MessageModel + { + public DateTime CreateDate { set; get; } + + public string Text { set; get; } + + public string User { set; get; } + } +} diff --git a/Chatter/Models/PostModel.cs b/Chatter/Models/PostModel.cs new file mode 100644 index 0000000..6ff814a --- /dev/null +++ b/Chatter/Models/PostModel.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Models +{ + public class PostModel + { + public string Text { set; get; } + } +} diff --git a/Chatter/Program.cs b/Chatter/Program.cs new file mode 100644 index 0000000..3017fc8 --- /dev/null +++ b/Chatter/Program.cs @@ -0,0 +1,81 @@ +using Chatter.Logic.Actions; +using Cuipod; +using Microsoft.Extensions.CommandLineUtils; +using Microsoft.Extensions.Logging; +using System; +using System.Security.Cryptography.X509Certificates; + +namespace Chatter +{ + internal class Program + { + static int Main(string[] args) + { + CommandLineApplication commandLineApplication = new CommandLineApplication(); + commandLineApplication.HelpOption("-h | --help"); + CommandArgument certificateFile = commandLineApplication.Argument( + "certificate", + "Path to certificate (required)" + ); + CommandArgument privateRSAKeyFilePath = commandLineApplication.Argument( + "key", + "Path to private Pkcs8 RSA key (required)" + ); + commandLineApplication.OnExecute(() => + { + if (certificateFile.Value == null || privateRSAKeyFilePath.Value == null) + { + commandLineApplication.ShowHelp(); + return 1; + } + + X509Certificate2 cert = CertificateUtils.LoadCertificate(certificateFile.Value, privateRSAKeyFilePath.Value); + + return AppMain("static/", cert); + }); + + try + { + return commandLineApplication.Execute(args); + } + catch (Exception e) + { + Console.WriteLine("Error: {0}", e.Message); + return 1; + } + } + + private static int AppMain(string directoryToServe, X509Certificate2 certificate) + { + using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => + builder + .AddSimpleConsole(options => + { + options.SingleLine = true; + options.TimestampFormat = "hh:mm:ss "; + }) + .SetMinimumLevel(LogLevel.Debug) + ); + + ILogger logger = loggerFactory.CreateLogger(); + + App app = new App( + directoryToServe, + certificate, + logger + ); + + // Serve files + app.OnRequest("/", (request, response, logger) => { + response.RenderFileContent("index.gmi"); + }); + + app.OnRequest("/list", ListActionManager.GetListAction()); + app.OnRequest("/post", ListActionManager.PostAction()); + + app.Run(); + + return 0; + } + } +} diff --git a/Chatter/Properties/launchSettings.json b/Chatter/Properties/launchSettings.json new file mode 100644 index 0000000..2273e95 --- /dev/null +++ b/Chatter/Properties/launchSettings.json @@ -0,0 +1,8 @@ +{ + "profiles": { + "Chatter": { + "commandName": "Project", + "commandLineArgs": "\"D:/cert/openssl.crt\" \"D:/cert/openssl.key\"" + } + } +} \ No newline at end of file diff --git a/Chatter/Repository/MessageRepository.cs b/Chatter/Repository/MessageRepository.cs new file mode 100644 index 0000000..96d8b59 --- /dev/null +++ b/Chatter/Repository/MessageRepository.cs @@ -0,0 +1,43 @@ +using Chatter.Connector; +using Chatter.Dto; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Repository +{ + public interface IMessageRepository + { + IEnumerable GetMessages(); + + void AddMessage(MessageDto msg); + } + + + internal class MessageRepository : IMessageRepository + { + private readonly IDbConnector _connector; + + public MessageRepository() + { + } + + public void AddMessage(MessageDto msg) + { + using (var connector = new SqLiteConnector()) + { + connector.AddMessage(msg); + } + } + + public IEnumerable GetMessages() + { + using (var connector = new SqLiteConnector()) + { + return connector.GetMessages(); + } + } + } +} diff --git a/Chatter/Service/MessageService.cs b/Chatter/Service/MessageService.cs new file mode 100644 index 0000000..3f5ba62 --- /dev/null +++ b/Chatter/Service/MessageService.cs @@ -0,0 +1,49 @@ +using Chatter.Models; +using Chatter.Repository; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Chatter.Service +{ + public interface IMessageService + { + IEnumerable GetMessages(); + + void AddMessage(PostModel msg); + } + + + internal class MessageService : IMessageService + { + public readonly IMessageRepository _repository; + + public MessageService() + { + _repository = new MessageRepository(); + } + + public IEnumerable GetMessages() + { + var messages = _repository.GetMessages(); + return messages.Select(x => new MessageModel() + { + CreateDate = x.CreateDate, + Text = x.Text, + User = x.User + }); + } + + public void AddMessage(PostModel msg) + { + _repository.AddMessage(new Dto.MessageDto() + { + Text = msg.Text, + User = null, + CreateDate = DateTime.Now + }); + } + } +} diff --git a/Chatter/static/index.gmi b/Chatter/static/index.gmi new file mode 100644 index 0000000..7c4e3e7 --- /dev/null +++ b/Chatter/static/index.gmi @@ -0,0 +1,9 @@ +# Chatter gemini app +This is chatter gemini app. An application can be used for chat with several different users. The idea of the project is to have the least amount of data stored permanently. + +## Requirements: +* redis -- messages +* nosql database -- permanent userdata + +=> /list Message list +=> /post Post message \ No newline at end of file diff --git a/Cuipod.sln b/Cuipod.sln index a994de8..8aad270 100644 --- a/Cuipod.sln +++ b/Cuipod.sln @@ -1,11 +1,13 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30621.155 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31919.166 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Cuipod", "Cuipod\Cuipod.csproj", "{2B6AD5A5-F10B-4FC3-BF12-5DD26FAF3796}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cuipod", "Cuipod\Cuipod.csproj", "{2B6AD5A5-F10B-4FC3-BF12-5DD26FAF3796}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CuipodExample", "CuipodExample\CuipodExample.csproj", "{BD343B0B-29EB-4498-8CD2-D9483B6BDA98}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CuipodExample", "CuipodExample\CuipodExample.csproj", "{BD343B0B-29EB-4498-8CD2-D9483B6BDA98}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Chatter", "Chatter\Chatter.csproj", "{20C8B6F9-63FB-458D-921E-5DFD6EBE4435}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -21,6 +23,10 @@ Global {BD343B0B-29EB-4498-8CD2-D9483B6BDA98}.Debug|Any CPU.Build.0 = Debug|Any CPU {BD343B0B-29EB-4498-8CD2-D9483B6BDA98}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD343B0B-29EB-4498-8CD2-D9483B6BDA98}.Release|Any CPU.Build.0 = Release|Any CPU + {20C8B6F9-63FB-458D-921E-5DFD6EBE4435}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {20C8B6F9-63FB-458D-921E-5DFD6EBE4435}.Debug|Any CPU.Build.0 = Debug|Any CPU + {20C8B6F9-63FB-458D-921E-5DFD6EBE4435}.Release|Any CPU.ActiveCfg = Release|Any CPU + {20C8B6F9-63FB-458D-921E-5DFD6EBE4435}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CuipodExample/CuipodExample.csproj b/CuipodExample/CuipodExample.csproj index e370129..b64e548 100644 --- a/CuipodExample/CuipodExample.csproj +++ b/CuipodExample/CuipodExample.csproj @@ -14,6 +14,21 @@ + + + True + True + Resources.resx + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + Always diff --git a/CuipodExample/Properties/Resources.Designer.cs b/CuipodExample/Properties/Resources.Designer.cs new file mode 100644 index 0000000..90dd654 --- /dev/null +++ b/CuipodExample/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace CuipodExample.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CuipodExample.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/CuipodExample/Properties/Resources.resx b/CuipodExample/Properties/Resources.resx new file mode 100644 index 0000000..4fdb1b6 --- /dev/null +++ b/CuipodExample/Properties/Resources.resx @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file