add basic app

This commit is contained in:
Dmitrii Kollerov 2022-03-10 15:39:31 +07:00
parent a3823f4bbd
commit 388ebd964b
15 changed files with 657 additions and 4 deletions

26
Chatter/Chatter.csproj Normal file
View File

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="System.Data.SQLite" Version="1.0.115.5" />
<PackageReference Include="System.Data.SQLite.EF6" Version="1.0.115.5" />
<PackageReference Include="System.Data.SQLite.Linq" Version="1.0.115.5" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Cuipod\Cuipod.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="static\index.gmi">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -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<MessageDto> 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<string, object>()
{
{ "@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<MessageDto> GetMessages()
{
var result = new List<MessageDto>();
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);
}
}
}

17
Chatter/Dto/MessageDto.cs Normal file
View File

@ -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; }
}
}

View File

@ -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<Request, Response, ILogger<App>> GetListAction() =>
(request, response, logger) => {
var service = new MessageService();
IEnumerable<MessageModel> 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<Request, Response, ILogger<App>> 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;
}
};
}
}

View File

@ -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; }
}
}

View File

@ -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; }
}
}

81
Chatter/Program.cs Normal file
View File

@ -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<App> logger = loggerFactory.CreateLogger<App>();
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;
}
}
}

View File

@ -0,0 +1,8 @@
{
"profiles": {
"Chatter": {
"commandName": "Project",
"commandLineArgs": "\"D:/cert/openssl.crt\" \"D:/cert/openssl.key\""
}
}
}

View File

@ -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<MessageDto> 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<MessageDto> GetMessages()
{
using (var connector = new SqLiteConnector())
{
return connector.GetMessages();
}
}
}
}

View File

@ -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<MessageModel> GetMessages();
void AddMessage(PostModel msg);
}
internal class MessageService : IMessageService
{
public readonly IMessageRepository _repository;
public MessageService()
{
_repository = new MessageRepository();
}
public IEnumerable<MessageModel> 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
});
}
}
}

9
Chatter/static/index.gmi Normal file
View File

@ -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

View File

@ -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

View File

@ -14,6 +14,21 @@
<ProjectReference Include="..\Cuipod\Cuipod.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="pages\index.gmi">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 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.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CuipodExample.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// 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() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[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;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 1.3
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">1.3</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1">this is my long string</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
[base64 mime encoded serialized .NET Framework object]
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
[base64 mime encoded string representing a byte array form of the .NET Framework object]
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>1.3</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>