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