Compare commits
5 Commits
a3a6a34e57
...
5d280daf74
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d280daf74 | ||
|
|
388ebd964b | ||
|
|
a3823f4bbd | ||
|
|
faf8ae7c77 | ||
|
|
b74707aac8 |
4
.gitignore
vendored
4
.gitignore
vendored
@ -354,3 +354,7 @@ CuipodExample/Properties/launchSettings.json
|
||||
.vscode/
|
||||
.hg/
|
||||
.hgignore
|
||||
|
||||
Cuipod/nuget.config
|
||||
|
||||
nuget.config
|
||||
|
||||
27
Chatter/Chatter.csproj
Normal file
27
Chatter/Chatter.csproj
Normal file
@ -0,0 +1,27 @@
|
||||
<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.DependencyInjection" Version="6.0.0" />
|
||||
<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.Net.Http" Version="4.3.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Cuipod\Cuipod.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="static\index.gmi">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
133
Chatter/Connector/SqLiteConnector.cs
Normal file
133
Chatter/Connector/SqLiteConnector.cs
Normal 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
17
Chatter/Dto/MessageDto.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
81
Chatter/Logic/Actions/ListActionManager.cs
Normal file
81
Chatter/Logic/Actions/ListActionManager.cs
Normal file
@ -0,0 +1,81 @@
|
||||
using Chatter.Models;
|
||||
using Chatter.Service;
|
||||
using Cuipod;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
|
||||
namespace Chatter.Logic.Actions
|
||||
{
|
||||
public class ListActionManager
|
||||
{
|
||||
public readonly IMessageService _messageService;
|
||||
|
||||
public ListActionManager(IMessageService messageService)
|
||||
{
|
||||
_messageService = messageService;
|
||||
}
|
||||
|
||||
public Action<Request, Response, ILogger<App>> GetListAction() =>
|
||||
(request, response, logger) => {
|
||||
IEnumerable<MessageModel> messages = _messageService.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 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 = WebUtility.UrlDecode(request.Parameters)
|
||||
};
|
||||
_messageService.AddMessage(model);
|
||||
|
||||
response.SetRedirectURL(request.BaseURL + "/list");
|
||||
response.Status = StatusCode.RedirectTemp;
|
||||
}
|
||||
};
|
||||
|
||||
public Action<Request, Response, ILogger<App>> LoginAction() =>
|
||||
(request, response, logger) => {
|
||||
response.RenderPlainTextLine("Cert required");
|
||||
response.Status = StatusCode.ClientCertRequired;
|
||||
};
|
||||
}
|
||||
}
|
||||
17
Chatter/Models/MessageModel.cs
Normal file
17
Chatter/Models/MessageModel.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
13
Chatter/Models/PostModel.cs
Normal file
13
Chatter/Models/PostModel.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
99
Chatter/Program.cs
Normal file
99
Chatter/Program.cs
Normal file
@ -0,0 +1,99 @@
|
||||
using Chatter.Connector;
|
||||
using Chatter.Logic.Actions;
|
||||
using Chatter.Repository;
|
||||
using Chatter.Service;
|
||||
using Cuipod;
|
||||
using Microsoft.Extensions.CommandLineUtils;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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 ServiceProvider GetServiceProvider()
|
||||
{
|
||||
var serviceCollection = new ServiceCollection();
|
||||
serviceCollection.AddSingleton<IDbConnector, SqLiteConnector>();
|
||||
serviceCollection.AddScoped<IMessageService, MessageService>();
|
||||
serviceCollection.AddScoped<IMessageRepository, MessageRepository>();
|
||||
serviceCollection.AddScoped<ListActionManager>();
|
||||
|
||||
return serviceCollection.BuildServiceProvider();
|
||||
}
|
||||
|
||||
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)
|
||||
);
|
||||
|
||||
using var serviceProvider = GetServiceProvider();
|
||||
|
||||
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", serviceProvider.GetService<ListActionManager>().GetListAction());
|
||||
app.OnRequest("/post", serviceProvider.GetService<ListActionManager>().PostAction());
|
||||
app.OnRequest("/login", serviceProvider.GetService<ListActionManager>().LoginAction());
|
||||
|
||||
app.Run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
8
Chatter/Properties/launchSettings.json
Normal file
8
Chatter/Properties/launchSettings.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"profiles": {
|
||||
"Chatter": {
|
||||
"commandName": "Project",
|
||||
"commandLineArgs": "\"D:/cert/openssl.crt\" \"D:/cert/openssl.key\""
|
||||
}
|
||||
}
|
||||
}
|
||||
38
Chatter/Repository/MessageRepository.cs
Normal file
38
Chatter/Repository/MessageRepository.cs
Normal file
@ -0,0 +1,38 @@
|
||||
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(IDbConnector connector)
|
||||
{
|
||||
_connector = connector;
|
||||
}
|
||||
|
||||
public void AddMessage(MessageDto msg)
|
||||
{
|
||||
_connector.AddMessage(msg);
|
||||
}
|
||||
|
||||
public IEnumerable<MessageDto> GetMessages()
|
||||
{
|
||||
return _connector.GetMessages();
|
||||
}
|
||||
}
|
||||
}
|
||||
49
Chatter/Service/MessageService.cs
Normal file
49
Chatter/Service/MessageService.cs
Normal 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(IMessageRepository repository)
|
||||
{
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
7
Chatter/static/index.gmi
Normal file
7
Chatter/static/index.gmi
Normal file
@ -0,0 +1,7 @@
|
||||
# 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. This project uses sqlite in-memory database to store messages which means every time you reload it you lose all data.
|
||||
|
||||
|
||||
=> /list Message list
|
||||
=> /post Post message
|
||||
16
Cuipod.sln
16
Cuipod.sln
@ -1,11 +1,11 @@
|
||||
|
||||
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}") = "Chatter", "Chatter\Chatter.csproj", "{20C8B6F9-63FB-458D-921E-5DFD6EBE4435}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -17,10 +17,10 @@ Global
|
||||
{2B6AD5A5-F10B-4FC3-BF12-5DD26FAF3796}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2B6AD5A5-F10B-4FC3-BF12-5DD26FAF3796}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2B6AD5A5-F10B-4FC3-BF12-5DD26FAF3796}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{BD343B0B-29EB-4498-8CD2-D9483B6BDA98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{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
|
||||
|
||||
113
Cuipod/App.cs
113
Cuipod/App.cs
@ -8,35 +8,30 @@ using System.Text;
|
||||
using System.Security.Authentication;
|
||||
using System.IO;
|
||||
|
||||
using RequestCallback = System.Action<Cuipod.Request, Cuipod.Response>;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Cuipod
|
||||
{
|
||||
using RequestCallback = System.Action<Cuipod.Request, Cuipod.Response, ILogger<App>>;
|
||||
|
||||
public class App
|
||||
{
|
||||
private readonly TcpListener _listener = new TcpListener(IPAddress.Any, 1965);
|
||||
private readonly Dictionary<string, RequestCallback> _requestCallbacks = new Dictionary<string, RequestCallback>();
|
||||
private readonly byte[] _buffer = new byte[4096];
|
||||
private readonly Decoder _decoder = Encoding.UTF8.GetDecoder();
|
||||
|
||||
private readonly string _directoryToServe;
|
||||
private readonly TcpListener _listener;
|
||||
private readonly X509Certificate2 _serverCertificate;
|
||||
private readonly Dictionary<string, RequestCallback> _requestCallbacks;
|
||||
private readonly ILogger<App> _logger;
|
||||
|
||||
private RequestCallback _onBadRequestCallback;
|
||||
|
||||
//somewhat flaky implementation - probably deprecate it
|
||||
public App(string directoryToServe, string certificateFile, string privateRSAKeyFilePath)
|
||||
public App(string directoryToServe, X509Certificate2 certificate, ILogger<App> logger)
|
||||
{
|
||||
_directoryToServe = directoryToServe;
|
||||
_listener = new TcpListener(IPAddress.Any, 1965);
|
||||
_requestCallbacks = new Dictionary<string, RequestCallback>();
|
||||
_serverCertificate = CertificateUtils.LoadCertificate(certificateFile, privateRSAKeyFilePath);
|
||||
}
|
||||
|
||||
public App(string directoryToServe, X509Certificate2 certificate)
|
||||
{
|
||||
|
||||
_directoryToServe = directoryToServe;
|
||||
_listener = new TcpListener(IPAddress.Any, 1965);
|
||||
_requestCallbacks = new Dictionary<string, RequestCallback>();
|
||||
_serverCertificate = certificate;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public void OnRequest(string route, RequestCallback callback)
|
||||
@ -49,13 +44,14 @@ namespace Cuipod
|
||||
_onBadRequestCallback = callback;
|
||||
}
|
||||
|
||||
public int Run()
|
||||
public void Run()
|
||||
{
|
||||
int status = 0;
|
||||
Console.WriteLine("Serving capsule on 0.0.0.0:1965");
|
||||
try
|
||||
{
|
||||
_listener.Start();
|
||||
|
||||
_logger.LogInformation("Serving capsule on {0}", _listener.Server.LocalEndPoint.ToString());
|
||||
|
||||
while (true)
|
||||
{
|
||||
ProcessRequest(_listener.AcceptTcpClient());
|
||||
@ -63,15 +59,12 @@ namespace Cuipod
|
||||
}
|
||||
catch (SocketException e)
|
||||
{
|
||||
Console.WriteLine("SocketException: {0}", e);
|
||||
status = 1;
|
||||
_logger.LogError("SocketException: {0}", e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_listener.Stop();
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
private void ProcessRequest(TcpClient client)
|
||||
@ -86,16 +79,16 @@ namespace Cuipod
|
||||
}
|
||||
catch (AuthenticationException e)
|
||||
{
|
||||
Console.WriteLine("Exception: {0}", e.Message);
|
||||
_logger.LogError("AuthenticationException: {0}", e.Message);
|
||||
if (e.InnerException != null)
|
||||
{
|
||||
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
|
||||
_logger.LogError("Inner exception: {0}", e.InnerException.Message);
|
||||
}
|
||||
Console.WriteLine("Authentication failed - closing the connection.");
|
||||
_logger.LogError("Authentication failed - closing the connection.");
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
Console.WriteLine("Exception: {0}", e.Message);
|
||||
_logger.LogError("IOException: {0}", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@ -107,36 +100,55 @@ namespace Cuipod
|
||||
private Response ProcessRequest(SslStream sslStream)
|
||||
{
|
||||
sslStream.ReadTimeout = 5000;
|
||||
sslStream.AuthenticateAsServer(_serverCertificate, false, SslProtocols.Tls12 | SslProtocols.Tls13, false);
|
||||
sslStream.AuthenticateAsServer(new SslServerAuthenticationOptions()
|
||||
{
|
||||
ServerCertificate = _serverCertificate,
|
||||
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
|
||||
ClientCertificateRequired = false,
|
||||
CertificateRevocationCheckMode = X509RevocationMode.NoCheck
|
||||
});
|
||||
//sslStream.AuthenticateAsServer(_serverCertificate, false, , false);
|
||||
//var clientCertificate = sslStream.RemoteCertificate;
|
||||
//var clientCertificateHash = Convert.ToBase64String(clientCertificate.GetCertHash());
|
||||
|
||||
//var username = clientCertificate.Issuer;
|
||||
//if (sslStream.IsMutuallyAuthenticated)
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
// Read a message from the client.
|
||||
string rawURL = ReadRequest(sslStream);
|
||||
string rawRequest = ReadRequest(sslStream);
|
||||
|
||||
Response response = new Response(_directoryToServe);
|
||||
|
||||
if (rawURL == null)
|
||||
if (rawRequest == null)
|
||||
{
|
||||
_logger.LogDebug("rawRequest is null - bad request");
|
||||
response.Status = StatusCode.BadRequest;
|
||||
return response;
|
||||
}
|
||||
|
||||
Console.WriteLine(rawURL);
|
||||
_logger.LogDebug("Raw request: \"{0}\"", rawRequest);
|
||||
|
||||
int protocolDelimiter = rawURL.IndexOf("://");
|
||||
const string protocol= "gemini";
|
||||
const string protocolSeparator = "://";
|
||||
|
||||
int protocolDelimiter = rawRequest.IndexOf(protocolSeparator);
|
||||
if (protocolDelimiter == -1)
|
||||
{
|
||||
response.Status = StatusCode.BadRequest;
|
||||
return response;
|
||||
}
|
||||
|
||||
string protocol = rawURL.Substring(0, protocolDelimiter);
|
||||
if (protocol != "gemini")
|
||||
string requestProtocol = rawRequest.Substring(0, protocolDelimiter);
|
||||
if (requestProtocol != protocol)
|
||||
{
|
||||
response.Status = StatusCode.BadRequest;
|
||||
return response;
|
||||
}
|
||||
|
||||
string url = rawURL.Substring(protocolDelimiter + 3);
|
||||
string url = rawRequest.Substring(protocolDelimiter + protocolSeparator.Length);
|
||||
int domainNameDelimiter = url.IndexOf("/");
|
||||
if (domainNameDelimiter == -1)
|
||||
{
|
||||
@ -144,22 +156,38 @@ namespace Cuipod
|
||||
return response;
|
||||
}
|
||||
string domainName = url.Substring(0, domainNameDelimiter);
|
||||
string baseURL = protocol + protocolSeparator + domainName;
|
||||
|
||||
Request request = new Request("gemini://" + domainName , url.Substring(domainNameDelimiter));
|
||||
string route = url.Substring(domainNameDelimiter);
|
||||
string parameters = "";
|
||||
int parametersDelimiter = route.IndexOf("?");
|
||||
if (parametersDelimiter != -1)
|
||||
{
|
||||
parameters = route.Substring(parametersDelimiter + 1);
|
||||
route = route.Substring(0, parametersDelimiter);
|
||||
}
|
||||
|
||||
_logger.LogDebug("Request info:");
|
||||
_logger.LogDebug("\tBaseURL: \"{0}\"", baseURL);
|
||||
_logger.LogDebug("\tRoute: \"{0}\"", route);
|
||||
_logger.LogDebug("\tParameters: \"{0}\"", parameters);
|
||||
|
||||
Request request = new Request(baseURL, route, parameters);
|
||||
if (response.Status == StatusCode.Success)
|
||||
{
|
||||
RequestCallback callback;
|
||||
_requestCallbacks.TryGetValue(request.Route, out callback);
|
||||
if (callback != null)
|
||||
{
|
||||
callback(request, response);
|
||||
callback(request, response, _logger);
|
||||
}
|
||||
else if (_onBadRequestCallback != null)
|
||||
{
|
||||
_onBadRequestCallback(request, response);
|
||||
_onBadRequestCallback(request, response, _logger);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning("Bad request: No suitable request callback");
|
||||
response.Status = StatusCode.BadRequest;
|
||||
return response;
|
||||
}
|
||||
@ -170,13 +198,10 @@ namespace Cuipod
|
||||
|
||||
private string ReadRequest(SslStream sslStream)
|
||||
{
|
||||
byte[] buffer = new byte[2048];
|
||||
Decoder decoder = Encoding.UTF8.GetDecoder();
|
||||
|
||||
StringBuilder requestData = new StringBuilder();
|
||||
int bytes = sslStream.Read(buffer, 0, buffer.Length);
|
||||
char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
|
||||
decoder.GetChars(buffer, 0, bytes, chars, 0);
|
||||
int bytes = sslStream.Read(_buffer, 0, _buffer.Length);
|
||||
char[] chars = new char[_decoder.GetCharCount(_buffer, 0, bytes)];
|
||||
_decoder.GetChars(_buffer, 0, bytes, chars, 0);
|
||||
string line = new string(chars);
|
||||
if (line.EndsWith("\r\n"))
|
||||
{
|
||||
|
||||
@ -2,6 +2,19 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
<PackageProjectUrl>https://github.com/aegis-dev/cuipod</PackageProjectUrl>
|
||||
<PackageLicenseExpression></PackageLicenseExpression>
|
||||
<RepositoryUrl>https://github.com/aegis-dev/cuipod</RepositoryUrl>
|
||||
<PackageTags>gemini</PackageTags>
|
||||
<Description>Simple yet flexible framework for Gemini protocol server</Description>
|
||||
<Copyright>Copyright © 2021 Egidijus Lileika</Copyright>
|
||||
<PackageReleaseNotes></PackageReleaseNotes>
|
||||
<SignAssembly>false</SignAssembly>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Cuipod
|
||||
namespace Cuipod
|
||||
{
|
||||
public class Request
|
||||
{
|
||||
@ -10,20 +6,11 @@ namespace Cuipod
|
||||
public string Route { get; internal set; }
|
||||
public string Parameters { get; internal set; }
|
||||
|
||||
public Request(string baseURL, string route)
|
||||
internal Request(string baseURL, string route, string parameters)
|
||||
{
|
||||
BaseURL = baseURL;
|
||||
|
||||
int parametersDelimiter = route.IndexOf("?");
|
||||
if (parametersDelimiter != -1)
|
||||
{
|
||||
Parameters = route.Substring(parametersDelimiter + 1);
|
||||
Route = route.Substring(0, parametersDelimiter);
|
||||
}
|
||||
else
|
||||
{
|
||||
Route = route;
|
||||
}
|
||||
Route = route;
|
||||
Parameters = parameters;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -8,10 +8,10 @@ namespace Cuipod
|
||||
{
|
||||
public StatusCode Status { get; set; }
|
||||
|
||||
private string _directoryToServe;
|
||||
private readonly string _directoryToServe;
|
||||
private string _requestBody = "";
|
||||
|
||||
public Response(string directoryToServe)
|
||||
internal Response(string directoryToServe)
|
||||
{
|
||||
_directoryToServe = directoryToServe;
|
||||
Status = StatusCode.Success;
|
||||
|
||||
@ -7,10 +7,32 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
63
CuipodExample/Properties/Resources.Designer.cs
generated
Normal file
63
CuipodExample/Properties/Resources.Designer.cs
generated
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
101
CuipodExample/Properties/Resources.resx
Normal file
101
CuipodExample/Properties/Resources.resx
Normal 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>
|
||||
@ -1,5 +1,6 @@
|
||||
using Cuipod;
|
||||
using Microsoft.Extensions.CommandLineUtils;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
@ -11,30 +12,25 @@ namespace CuipodExample
|
||||
{
|
||||
CommandLineApplication commandLineApplication = new CommandLineApplication();
|
||||
commandLineApplication.HelpOption("-h | --help");
|
||||
CommandArgument directoryToServe = commandLineApplication.Argument(
|
||||
"directory",
|
||||
"Directory to server (required)"
|
||||
);
|
||||
CommandArgument certificateFile = commandLineApplication.Argument(
|
||||
"pfx certificate file",
|
||||
"certificate",
|
||||
"Path to certificate (required)"
|
||||
);
|
||||
CommandArgument pfxPassword = commandLineApplication.Argument(
|
||||
"pfx password",
|
||||
"pfx password"
|
||||
CommandArgument privateRSAKeyFilePath = commandLineApplication.Argument(
|
||||
"key",
|
||||
"Path to private Pkcs8 RSA key (required)"
|
||||
);
|
||||
commandLineApplication.OnExecute(() =>
|
||||
{
|
||||
if (directoryToServe.Value == null || certificateFile.Value == null )
|
||||
if (certificateFile.Value == null || privateRSAKeyFilePath.Value == null)
|
||||
{
|
||||
commandLineApplication.ShowHelp();
|
||||
return 1;
|
||||
}
|
||||
|
||||
var pass = (pfxPassword != null) ? pfxPassword.Value.ToString() : "";
|
||||
var cert = new X509Certificate2(certificateFile.Value.ToString(), pass);
|
||||
X509Certificate2 cert = CertificateUtils.LoadCertificate(certificateFile.Value, privateRSAKeyFilePath.Value);
|
||||
|
||||
return AppMain(directoryToServe.Value, cert);
|
||||
return AppMain("pages/", cert);
|
||||
});
|
||||
|
||||
try
|
||||
@ -49,18 +45,31 @@ namespace CuipodExample
|
||||
|
||||
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
|
||||
certificate,
|
||||
logger
|
||||
);
|
||||
|
||||
// Serve files
|
||||
app.OnRequest("/", (request, response) => {
|
||||
app.OnRequest("/", (request, response, logger) => {
|
||||
response.RenderFileContent("index.gmi");
|
||||
});
|
||||
|
||||
// Input example
|
||||
app.OnRequest("/input", (request, response) => {
|
||||
app.OnRequest("/input", (request, response, logger) => {
|
||||
if (request.Parameters == null)
|
||||
{
|
||||
response.SetInputHint("Please enter something: ");
|
||||
@ -74,7 +83,7 @@ namespace CuipodExample
|
||||
}
|
||||
});
|
||||
|
||||
app.OnRequest("/show", (request, response) => {
|
||||
app.OnRequest("/show", (request, response, logger) => {
|
||||
if (request.Parameters == null)
|
||||
{
|
||||
// redirect to input
|
||||
@ -89,18 +98,19 @@ namespace CuipodExample
|
||||
});
|
||||
|
||||
// Or dynamically render content
|
||||
app.OnRequest("/dynamic/content", (request, response) => {
|
||||
response.RenderPlainTextLine("# woah much content!");
|
||||
response.RenderPlainTextLine("More utilities to render content will come soon!");
|
||||
app.OnRequest("/dynamic/content", (request, response, logger) => {
|
||||
response.RenderPlainTextLine("# woah much dynamic content!");
|
||||
});
|
||||
|
||||
// Optional but nice. In case it is specified and client will do a bad route
|
||||
// request we will respond with Success status and render result from this lambda
|
||||
app.OnBadRequest((request, response) => {
|
||||
app.OnBadRequest((request, response, logger) => {
|
||||
response.RenderPlainTextLine("# Ohh No!!! Request is bad :(");
|
||||
});
|
||||
|
||||
return app.Run();
|
||||
app.Run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
1
CuipodExample/pages/index.gmi
Normal file
1
CuipodExample/pages/index.gmi
Normal file
@ -0,0 +1 @@
|
||||
# Hello world!
|
||||
56
README.md
56
README.md
@ -1,12 +1,16 @@
|
||||
# cuipod
|
||||
Simple yet flexible framework for Gemini protocol servers
|
||||
|
||||
Framework is written in C# and based on .NET 5.0 framework.
|
||||
The project is still in very early stage so bugs are expected. Feel free to raise an issue ticket or even raise PR!
|
||||
Simple yet flexible framework for Gemini protocol servers written in C# (.NET 5.0)
|
||||
|
||||
## Example
|
||||
For testing purposes you can generate certificate with this command
|
||||
```
|
||||
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout privatekey.key -out certificate.crt
|
||||
```
|
||||
|
||||
```csharp
|
||||
using System;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Cuipod;
|
||||
|
||||
namespace CuipodExample
|
||||
@ -15,19 +19,35 @@ namespace CuipodExample
|
||||
{
|
||||
static int Main(string[] args)
|
||||
{
|
||||
X509Certificate2 cert = CertificateUtils.LoadCertificate(
|
||||
"<dir_with_cert>/certificate.crt", // Path to certificate
|
||||
"<dir_with_cert>/privatekey.key" // Path to private Pkcs8 RSA key
|
||||
);
|
||||
|
||||
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(
|
||||
"<directory_to_serve>/", // directory to serve
|
||||
"<dir_with_cert>/certificate.crt", // path to certificate
|
||||
"<dir_with_cert>/privatekey.key" // path to private Pkcs8 RSA key
|
||||
"pages/", // Directory to serve
|
||||
certificate,
|
||||
logger
|
||||
);
|
||||
|
||||
// Serve files
|
||||
app.OnRequest("/", (request, response) => {
|
||||
app.OnRequest("/", (request, response, logger) => {
|
||||
response.RenderFileContent("index.gmi");
|
||||
});
|
||||
|
||||
// Input example
|
||||
app.OnRequest("/input", (request, response) => {
|
||||
app.OnRequest("/input", (request, response, logger) => {
|
||||
if (request.Parameters == null)
|
||||
{
|
||||
response.SetInputHint("Please enter something: ");
|
||||
@ -41,7 +61,7 @@ namespace CuipodExample
|
||||
}
|
||||
});
|
||||
|
||||
app.OnRequest("/show", (request, response) => {
|
||||
app.OnRequest("/show", (request, response, logger) => {
|
||||
if (request.Parameters == null)
|
||||
{
|
||||
// redirect to input
|
||||
@ -56,19 +76,25 @@ namespace CuipodExample
|
||||
});
|
||||
|
||||
// Or dynamically render content
|
||||
app.OnRequest("/dynamic/content", (request, response) => {
|
||||
response.RenderPlainTextLine("# woah much content!");
|
||||
response.RenderPlainTextLine("More utilities to render content will come soon!");
|
||||
app.OnRequest("/dynamic/content", (request, response, logger) => {
|
||||
response.RenderPlainTextLine("# woah much dynamic content!");
|
||||
});
|
||||
|
||||
// Optional but nice. In case it is specified and client will do a bad route
|
||||
// request we will respond with Success status and render result from this lambda
|
||||
app.OnBadRequest((request, response) => {
|
||||
app.OnBadRequest((request, response, logger) => {
|
||||
response.RenderPlainTextLine("# Ohh No!!! Request is bad :(");
|
||||
});
|
||||
|
||||
return app.Run();
|
||||
app.Run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Full example project is in `CuipodExample` directory
|
||||
|
||||
# Contribution
|
||||
Feel free to raise an issue ticket or even raise a pull request.
|
||||
Reference in New Issue
Block a user