Skip to content
This repository has been archived by the owner on Dec 21, 2022. It is now read-only.

Commit

Permalink
Merge pull request #3 from MaaAssistantArknights/dev
Browse files Browse the repository at this point in the history
Release 0.1.4-alpha
  • Loading branch information
AlisaAkiron authored Jun 8, 2022
2 parents c8cc1c5 + 4fdad88 commit 09e427f
Show file tree
Hide file tree
Showing 72 changed files with 994 additions and 431 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,6 @@ FodyWeavers.xsd
*.usertasks

#Mono Project Files
*.resources
test-results/

### Windows template
Expand Down
4 changes: 4 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
FROM mcr.microsoft.com/dotnet/aspnet:6.0

ARG APP_VERSION=0.0.0

WORKDIR /app

COPY ./publish /app/
Expand All @@ -9,6 +11,8 @@ RUN ["mkdir", "/app/data"]
ENV DOTNET_RUNNING_IN_CONTAINER=true
ENV ASPNETCORE_URLS=http://+:80

ENV MAACOPILOT_APP_VERSION=$APP_VERSION

VOLUME ["/app/data"]

EXPOSE 80/tcp
Expand Down
9 changes: 9 additions & 0 deletions MaaCopilotServer.sln
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaaCopilotServer.Applicatio
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "App", "App", "{A1D2EB1C-F793-4CA9-86B6-8EB065CD75A7}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Resource", "Resource", "{649ECEA5-336F-4CF5-8D97-C9EA415A408B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaaCopilotServer.Resources", "src\MaaCopilotServer.Resources\MaaCopilotServer.Resources.csproj", "{0FC05A37-6FC9-49B6-9704-3488043D3A0D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -32,11 +36,16 @@ Global
{DB2CF416-793B-4546-B034-ADD57BDCD43B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB2CF416-793B-4546-B034-ADD57BDCD43B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB2CF416-793B-4546-B034-ADD57BDCD43B}.Release|Any CPU.Build.0 = Release|Any CPU
{0FC05A37-6FC9-49B6-9704-3488043D3A0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0FC05A37-6FC9-49B6-9704-3488043D3A0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0FC05A37-6FC9-49B6-9704-3488043D3A0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0FC05A37-6FC9-49B6-9704-3488043D3A0D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{5748A5AC-B6F8-4414-B6AA-A089407BC969} = {A1D2EB1C-F793-4CA9-86B6-8EB065CD75A7}
{DB2CF416-793B-4546-B034-ADD57BDCD43B} = {A1D2EB1C-F793-4CA9-86B6-8EB065CD75A7}
{2ED22FCD-5970-47F4-B5CB-3569F28788D3} = {A1D2EB1C-F793-4CA9-86B6-8EB065CD75A7}
{EC4E807F-B785-4425-B695-B284A01DAA5E} = {A1D2EB1C-F793-4CA9-86B6-8EB065CD75A7}
{0FC05A37-6FC9-49B6-9704-3488043D3A0D} = {649ECEA5-336F-4CF5-8D97-C9EA415A408B}
EndGlobalSection
EndGlobal
6 changes: 3 additions & 3 deletions build-docker.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
if [ -z "$1" ]; then
echo ">>>>> ERROR: Version could not be empty!"
exit
exit 1
fi

docker buildx build --load --platform linux/amd64 -t maa-copilot-server:"$1"-amd64 .
docker buildx build --load --platform linux/arm64 -t maa-copilot-server:"$1"-arm64 .
docker buildx build --load --build-arg APP_VERSION="$1" --platform linux/amd64 -t maa-copilot-server:"$1"-amd64 .
docker buildx build --load --build-arg APP_VERSION="$1" --platform linux/arm64 -t maa-copilot-server:"$1"-arm64 .
9 changes: 6 additions & 3 deletions src/MaaCopilotServer.Api/Helper/ConfigurationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

using System.Reflection;
using MaaCopilotServer.Application.Common.Extensions;
using ILogger = Serilog.ILogger;

namespace MaaCopilotServer.Api.Helper;

Expand All @@ -20,7 +19,7 @@ public static IConfiguration BuildConfiguration()
var dataDirectoryEnv = Environment.GetEnvironmentVariable("MAA_DATA_DIRECTORY");
var isInDocker = Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") ?? "false";

var assemblyDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.NotNull();
var assemblyDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.IsNotNull();
var dataDirectory = string.IsNullOrEmpty(dataDirectoryEnv)
? new DirectoryInfo(assemblyDirectory.FullName.CombinePath("data")).EnsureCreated()
: new DirectoryInfo(dataDirectoryEnv).EnsureCreated();
Expand Down Expand Up @@ -61,10 +60,14 @@ public static IConfiguration BuildConfiguration()

configurationBuilder.AddEnvironmentVariables("MAA_");

var appVersion = Environment.GetEnvironmentVariable("MAACOPILOT_APP_VERSION") ?? "0.0.0";

configurationBuilder.AddInMemoryCollection(new List<KeyValuePair<string, string>>
{
new("Application:AssemblyPath", assemblyDirectory.FullName),
new("Application:DataDirectory", dataDirectory.FullName)
new("Application:DataDirectory", dataDirectory.FullName),
new("Application:Version", appVersion),
new("ElasticApm:ServiceVersion", appVersion)
});

var configuration = configurationBuilder.Build();
Expand Down
58 changes: 58 additions & 0 deletions src/MaaCopilotServer.Api/Helper/LoggerConfigurationHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// This file is a part of MaaCopilotServer project.
// MaaCopilotServer belongs to the MAA organization.
// Licensed under the AGPL-3.0 license.

using Destructurama;
using Elastic.Apm.SerilogEnricher;
using Elastic.CommonSchema.Serilog;
using Serilog;
using Serilog.Sinks.Elasticsearch;

namespace MaaCopilotServer.Api.Helper;

public static class LoggerConfigurationHelper
{
public static LoggerConfiguration GetLoggerConfiguration(this IConfiguration configuration)
{
var loggerConfiguration = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Destructure.UsingAttributes();

if (configuration.GetValue<bool>("Switches:ElasticSearch") is false)
{
return loggerConfiguration;
}

var elasticUris = configuration.GetValue<string>("ElasticLogSink:Uris")
.Split(";").Select(x => new Uri(x)).ToArray();
var elasticPeriod = configuration.GetValue<int>("ElasticLogSink:Period");
var elasticAuthMethod = configuration.GetValue<string>("ElasticLogSink:Authentication:Method");
var elasticId = configuration.GetValue<string>("ElasticLogSink:Authentication:Secret:Id");
var elasticKey = configuration.GetValue<string>("ElasticLogSink:Authentication:Secret:Key");
var elasticApplicationName = configuration.GetValue<string>("ElasticLogSink:ApplicationName");
loggerConfiguration.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(elasticUris)
{
Period = TimeSpan.FromSeconds(elasticPeriod),
AutoRegisterTemplate = true,
IndexFormat = $"{elasticApplicationName}-{DateTimeOffset.UtcNow.AddHours(8):yyyy.MM}",
CustomFormatter = new EcsTextFormatter(),
TypeName = null,
ModifyConnectionSettings = c =>
{
switch (elasticAuthMethod)
{
case "Basic":
c.BasicAuthentication(elasticId, elasticKey);
break;
case "ApiKey":
c.ApiKeyAuthentication(elasticId, elasticKey);
break;
}
return c;
}
});
loggerConfiguration.Enrich.WithElasticApmCorrelationInfo();

return loggerConfiguration;
}
}
3 changes: 3 additions & 0 deletions src/MaaCopilotServer.Api/MaaCopilotServer.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@

<ItemGroup>
<PackageReference Include="Elastic.Apm.AspNetCore" Version="1.16.0" />
<PackageReference Include="Elastic.Apm.Elasticsearch" Version="1.16.0" />
<PackageReference Include="Elastic.Apm.EntityFrameworkCore" Version="1.16.0" />
<PackageReference Include="Elastic.Apm.SerilogEnricher" Version="1.6.0-alpha1" />
<PackageReference Include="Elastic.CommonSchema.Serilog" Version="1.6.0-alpha1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog.AspNetCore" Version="5.0.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Elasticsearch" Version="9.0.0-beta7" />
</ItemGroup>

Expand Down
14 changes: 14 additions & 0 deletions src/MaaCopilotServer.Api/Middleware/MiddlewareExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// This file is a part of MaaCopilotServer project.
// MaaCopilotServer belongs to the MAA organization.
// Licensed under the AGPL-3.0 license.

namespace MaaCopilotServer.Api.Middleware;

public static class MiddlewareExtension
{
public static IApplicationBuilder UseRequestCulture(this IApplicationBuilder app)
{
app.UseMiddleware<RequestCultureMiddleware>();
return app;
}
}
29 changes: 29 additions & 0 deletions src/MaaCopilotServer.Api/Middleware/RequestCultureMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// This file is a part of MaaCopilotServer project.
// MaaCopilotServer belongs to the MAA organization.
// Licensed under the AGPL-3.0 license.

using System.Globalization;
using MaaCopilotServer.Resources;

namespace MaaCopilotServer.Api.Middleware;

public class RequestCultureMiddleware
{
private readonly RequestDelegate _next;

public RequestCultureMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext context, ValidationErrorMessage validationErrorMessage, ApiErrorMessage apiErrorMessage)
{
var hasCulture = context.Request.Query.TryGetValue("culture", out var culture);
var info = hasCulture ? new CultureInfo(culture) : new CultureInfo("zh-cn");

validationErrorMessage.CultureInfo = info;
apiErrorMessage.CultureInfo = info;

await _next(context);
}
}
40 changes: 16 additions & 24 deletions src/MaaCopilotServer.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,23 @@
// Licensed under the AGPL-3.0 license.

using Elastic.Apm.AspNetCore;
using Elastic.Apm.AspNetCore.DiagnosticListener;
using Elastic.Apm.DiagnosticSource;
using Elastic.Apm.Elasticsearch;
using Elastic.Apm.EntityFrameworkCore;
using Elastic.CommonSchema.Serilog;
using MaaCopilotServer.Api;
using MaaCopilotServer.Api.Helper;
using MaaCopilotServer.Api.Middleware;
using MaaCopilotServer.Application;
using MaaCopilotServer.Infrastructure;
using MaaCopilotServer.Resources;
using Serilog;
using Serilog.Sinks.Elasticsearch;
using Serilog.Debugging;

var configuration = ConfigurationHelper.BuildConfiguration();

var loggerConfiguration = new LoggerConfiguration()
.ReadFrom.Configuration(configuration);

if (configuration.GetValue<bool>("Switches:ElasticSearch"))
{
var elasticUris = configuration.GetValue<string>("ElasticLogSink:Uris").Split(";").Select(x => new Uri(x)).ToArray();
var elasticPeriod = configuration.GetValue<int>("ElasticLogSink:Period");
var elasticApiId = configuration.GetValue<string>("ElasticLogSink:ApiId");
var elasticApiKey = configuration.GetValue<string>("ElasticLogSink:ApiKey");
loggerConfiguration.WriteTo.Elasticsearch(new ElasticsearchSinkOptions(elasticUris)
{
Period = TimeSpan.FromSeconds(elasticPeriod),
AutoRegisterTemplate = true,
IndexFormat = "maa-copilot-{0:yyyy.MM.dd}",
ModifyConnectionSettings = c =>
c.ApiKeyAuthentication(elasticApiId, elasticApiKey),
CustomFormatter = new EcsTextFormatter()
});
}

Log.Logger = loggerConfiguration.CreateLogger();
Log.Logger = configuration.GetLoggerConfiguration().CreateLogger();
SelfLog.Enable(Console.Error);

var builder = WebApplication.CreateBuilder();

Expand All @@ -43,6 +28,7 @@
builder.Configuration.AddConfiguration(configuration);

builder.Services.AddControllers();
builder.Services.AddResources();
builder.Services.AddInfrastructureServices();
builder.Services.AddApplicationServices();
builder.Services.AddApiServices(configuration);
Expand All @@ -53,9 +39,15 @@

if (configuration.GetValue<bool>("Switches:Apm"))
{
app.UseElasticApm(configuration, new EfCoreDiagnosticsSubscriber());
app.UseElasticApm(configuration,
new EfCoreDiagnosticsSubscriber(),
new ElasticsearchDiagnosticsSubscriber(),
new HttpDiagnosticsSubscriber(),
new AspNetCoreDiagnosticSubscriber(),
new AspNetCoreErrorDiagnosticsSubscriber());
}

app.UseRequestCulture();
app.UseAuthentication();
app.MapControllers();

Expand Down
69 changes: 69 additions & 0 deletions src/MaaCopilotServer.Api/appsettings.ElasticSearch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {ElasticApmTraceId} {ElasticApmTransactionId} {Level:u3}] {ThreadId} {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {ElasticApmTraceId} {ElasticApmTransactionId} {Level:u3}] {ThreadId} {Message:lj}{NewLine}{Exception}",
"path": "{{ DATA DIRECTORY }}/logs/log-.log",
"rollingInterval": "Day",
"shared": true
}
}
],
"Enrich": [
"FromLogContext",
"WithThreadId"
]
},
"Jwt": {
"Secret": "YOUR STRONG 32+ BIT LENGTH (RECOMMEND 128 BIT OR MORE) SECRET TOKEN",
"Issuer": "MaaCopilot",
"Audience": "Doctor",
"ExpireTime": 720
},
"Database": {
"ConnectionString": "Server=127.0.0.1;Port=5432;Database=maa_copilot;User Id=maa_admin;Password=m@@_@dmin_p@ss;"
},
"Switches": {
"ElasticSearch": true,
"Apm": true
},
"ElasticLogSink": {
"ApplicationName": "maa-copilot",
"Uris": "http://localhost:9200",
"Period": 10,
"Authentication": {
"Method": "Basic",
"Secret": {
"Id": "",
"Key": ""
}
}
},
"ElasticApm": {
"SecretToken": "",
"ServerUrl": "http://localhost:8200",
"ServiceName": "MaaCopilotServer",
"Environment": "production"
},
"AllowedHosts": "*"
}
11 changes: 8 additions & 3 deletions src/MaaCopilotServer.Api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
]
},
Expand All @@ -49,10 +48,16 @@
"Apm": false
},
"ElasticLogSink": {
"ApplicationName": "maa-copilot",
"Uris": "http://localhost:9200",
"Period": 10,
"ApiId": "",
"ApiKey": ""
"Authentication": {
"Method": "Basic",
"Secret": {
"Id": "",
"Key": ""
}
}
},
"ElasticApm": {
"SecretToken": "",
Expand Down
Loading

0 comments on commit 09e427f

Please sign in to comment.