diff --git a/.gitignore b/.gitignore index 914c3fc..c962b4b 100644 --- a/.gitignore +++ b/.gitignore @@ -331,3 +331,4 @@ ASALocalRun/ /nupkgs /src/JT808.DotNetty.Admin/tools/protoc-gen-grpc-web-1.0.3-windows-x86_64.exe /src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/.config/dotnet-tools.json +/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/wwwroot/logs/JT808.Gateway diff --git a/api/README_Pipeline.md b/api/README_Pipeline.md index 1f7b65c..230acd4 100644 --- a/api/README_Pipeline.md +++ b/api/README_Pipeline.md @@ -35,7 +35,7 @@ |请求Url|请求方式|说明| |:------|:------|:------| | 127.0.0.1:828/jt808api/Tcp/Session/GetAll| GET| 基于Tcp管理会话服务-获取会话集合| -| 127.0.0.1:828/jt808api/Tcp/Session/QueryTcpSessionByTerminalPhoneNo| POST| 基于Tcp管理会话服务-通过设备终端号查询对应会话| +| 127.0.0.1:828/jt808api/Tcp/Session/QuerySessionByTerminalPhoneNo| POST| 基于Tcp管理会话服务-通过设备终端号查询对应会话| | 127.0.0.1:828/jt808api/Tcp/Session/RemoveByTerminalPhoneNo| POST| 基于Tcp管理会话服务-通过设备终端号移除对应会话| ### 基于Udp接口请求 @@ -43,8 +43,8 @@ |请求Url|请求方式|说明| |:------|:------|:------| | 127.0.0.1:828/jt808api/Udp/Session/GetAll| GET| 基于Udp管理会话服务-获取会话集合| -| 127.0.0.1:828/jt808api/Udp/Session/QueryUdpSessionByTerminalPhoneNo| POST| 基于Udp管理会话服务-通过设备终端号查询对应会话| -| 127.0.0.1:828/jt808api/Udp/Session/RemoveUdpByTerminalPhoneNo| POST| 基于Udp管理会话服务-通过设备终端号移除对应会话| +| 127.0.0.1:828/jt808api/Udp/Session/QuerySessionByTerminalPhoneNo| POST| 基于Udp管理会话服务-通过设备终端号查询对应会话| +| 127.0.0.1:828/jt808api/Udp/Session/RemoveByTerminalPhoneNo| POST| 基于Udp管理会话服务-通过设备终端号移除对应会话| ### SIM黑名单管理接口请求 @@ -52,7 +52,7 @@ |:------|:------|:------| | 127.0.0.1:828/jt808api/Blacklist/Add| POST| SIM卡黑名单服务-将对应SIM号加入黑名单| | 127.0.0.1:828/jt808api/Blacklist/Remove| POST| SIM卡黑名单服务-将对应SIM号移除黑名单| -| 127.0.0.1:828/jt808api/Blacklist/Get| Get| SIM卡黑名单服务-获取所有sim的黑名单列表| +| 127.0.0.1:828/jt808api/Blacklist/GetAll| Get| SIM卡黑名单服务-获取所有sim的黑名单列表| ### 统一对象返回 JT808ResultDto\ @@ -154,7 +154,7 @@ #### 2.通过设备终端号查询对应会话 -请求地址:Tcp/Session/QueryTcpSessionByTerminalPhoneNo +请求地址:Tcp/Session/QuerySessionByTerminalPhoneNo 请求方式:POST @@ -272,7 +272,7 @@ #### 2.通过设备终端号查询对应会话 -请求地址:Udp/Session/QueryUdpSessionByTerminalPhoneNo +请求地址:Udp/Session/QuerySessionByTerminalPhoneNo 请求方式:POST @@ -415,7 +415,7 @@ #### 3.获取sim卡黑名单 -请求地址:Blacklist/Get +请求地址:Blacklist/GetAll 请求方式:GET diff --git a/src/JT808.Gateway.Abstractions/IJT808Authorization.cs b/src/JT808.Gateway.Abstractions/IJT808Authorization.cs deleted file mode 100644 index 1c92f40..0000000 --- a/src/JT808.Gateway.Abstractions/IJT808Authorization.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Security.Principal; -using System.Text; - -namespace JT808.Gateway.Abstractions -{ - public interface IJT808Authorization - { - bool Authorization(HttpListenerContext context, out IPrincipal principal); - } -} diff --git a/src/JT808.Gateway.Abstractions/JT808.Gateway.Abstractions.xml b/src/JT808.Gateway.Abstractions/JT808.Gateway.Abstractions.xml index 40a83d0..392acdf 100644 --- a/src/JT808.Gateway.Abstractions/JT808.Gateway.Abstractions.xml +++ b/src/JT808.Gateway.Abstractions/JT808.Gateway.Abstractions.xml @@ -464,10 +464,5 @@ - - - 初始化消息处理业务 - - diff --git a/src/JT808.Gateway.Abstractions/JT808GatewayConstants.cs b/src/JT808.Gateway.Abstractions/JT808GatewayConstants.cs index 9d507cc..3637c53 100644 --- a/src/JT808.Gateway.Abstractions/JT808GatewayConstants.cs +++ b/src/JT808.Gateway.Abstractions/JT808GatewayConstants.cs @@ -28,7 +28,7 @@ /// /// 会话服务-通过设备终端号查询对应会话 /// - public static string QueryTcpSessionByTerminalPhoneNo = $"{RouteTablePrefix}/{TcpPrefix}/{SessionPrefix}/QueryTcpSessionByTerminalPhoneNo"; + public static string QueryTcpSessionByTerminalPhoneNo = $"{RouteTablePrefix}/{TcpPrefix}/{SessionPrefix}/QuerySessionByTerminalPhoneNo"; /// /// 统一下发信息 /// @@ -40,11 +40,11 @@ /// /// 会话服务-通过设备终端号移除对应会话 /// - public static string RemoveUdpByTerminalPhoneNo = $"{RouteTablePrefix}/{UdpPrefix}/{SessionPrefix}/RemoveUdpByTerminalPhoneNo"; + public static string RemoveUdpByTerminalPhoneNo = $"{RouteTablePrefix}/{UdpPrefix}/{SessionPrefix}/RemoveByTerminalPhoneNo"; /// /// 会话服务-通过设备终端号查询对应会话 /// - public static string QueryUdpSessionByTerminalPhoneNo = $"{RouteTablePrefix}/{UdpPrefix}/{SessionPrefix}/QueryUdpSessionByTerminalPhoneNo"; + public static string QueryUdpSessionByTerminalPhoneNo = $"{RouteTablePrefix}/{UdpPrefix}/{SessionPrefix}/QuerySessionByTerminalPhoneNo"; /// /// 黑名单添加 /// @@ -56,7 +56,7 @@ /// /// 黑名单查询 /// - public static string BlacklistGet = $"{RouteTablePrefix}/Blacklist/Get"; + public static string BlacklistGet = $"{RouteTablePrefix}/Blacklist/GetAll"; } } } diff --git a/src/JT808.Gateway.Abstractions/JT808MsgIdHttpHandlerBase.cs b/src/JT808.Gateway.Abstractions/JT808MsgIdHttpHandlerBase.cs deleted file mode 100644 index 1a94939..0000000 --- a/src/JT808.Gateway.Abstractions/JT808MsgIdHttpHandlerBase.cs +++ /dev/null @@ -1,90 +0,0 @@ -using JT808.Gateway.Abstractions.Dtos; -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; - -namespace JT808.Gateway.Abstractions -{ - public abstract class JT808MsgIdHttpHandlerBase - { - public Dictionary> HandlerDict { get; } - - /// - /// 初始化消息处理业务 - /// - protected JT808MsgIdHttpHandlerBase() - { - HandlerDict = new Dictionary>(); - } - - protected void CreateRoute(string url, Func func) - { - if (!HandlerDict.ContainsKey(url)) - { - HandlerDict.Add(url, func); - } - else - { - // 替换 - HandlerDict[url] = func; - } - } - - protected byte[] CreateHttpResponse(dynamic dynamicObject) - { - byte[] data = JsonSerializer.SerializeToUtf8Bytes(dynamicObject); - return data; - } - - public byte[] DefaultHttpResponse() - { - byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808DefaultResultDto()); - return json; - } - - public byte[] EmptyHttpResponse() - { - byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto() - { - Code = JT808ResultCode.Empty, - Message = "内容为空", - Data = "Content Empty" - }); - return json; - } - - public byte[] NotFoundHttpResponse() - { - byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto() - { - Code = JT808ResultCode.NotFound, - Message = "没有该服务", - Data = "没有该服务" - }); - return json; - } - - public byte[] AuthFailHttpResponse() - { - byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto() - { - Code = JT808ResultCode.AuthFail, - Message = "token认证失败", - Data = "token认证失败" - }); - return json; - } - - public byte[] ErrorHttpResponse(Exception ex) - { - byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto() - { - Code = JT808ResultCode.Error, - Message = ex.StackTrace, - Data = ex.Message - }); - return json; - } - } -} diff --git a/src/JT808.Gateway.Services/JT808.Gateway.Transmit/JT808TransmitService.cs b/src/JT808.Gateway.Services/JT808.Gateway.Transmit/JT808TransmitService.cs index 4ee3b13..fed580e 100644 --- a/src/JT808.Gateway.Services/JT808.Gateway.Transmit/JT808TransmitService.cs +++ b/src/JT808.Gateway.Services/JT808.Gateway.Transmit/JT808TransmitService.cs @@ -147,27 +147,30 @@ namespace JT808.Gateway.Transmit { await Task.Delay(time); List lastRemoteServers = new List(); - foreach (var item in optionsMonitor.CurrentValue.DataTransfer) + if (optionsMonitor.CurrentValue != null && optionsMonitor.CurrentValue.DataTransfer!=null) { - if (item.TerminalNos != null && item.TerminalNos.Any()) + foreach (var item in optionsMonitor.CurrentValue.DataTransfer) { - foreach (var terminal in item.TerminalNos) + if (item.TerminalNos != null && item.TerminalNos.Any()) { - string tmpKey = $"{terminal}_{item.Host}"; - if (!channeldic.ContainsKey(tmpKey)) + foreach (var terminal in item.TerminalNos) { - lastRemoteServers.Add(tmpKey); + string tmpKey = $"{terminal}_{item.Host}"; + if (!channeldic.ContainsKey(tmpKey)) + { + lastRemoteServers.Add(tmpKey); + } } - } - } - else - { - string key = $"all_{item.Host}"; - if (!channeldic.ContainsKey(key)) + } + else { - lastRemoteServers.Add(key); + string key = $"all_{item.Host}"; + if (!channeldic.ContainsKey(key)) + { + lastRemoteServers.Add(key); + } } - } + } } foreach (var item in lastRemoteServers) { diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Customs/JT808HttpClientExt.cs b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Customs/JT808HttpClientExt.cs new file mode 100644 index 0000000..e60bee7 --- /dev/null +++ b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Customs/JT808HttpClientExt.cs @@ -0,0 +1,30 @@ +using JT808.Gateway.Abstractions.Dtos; +using JT808.Gateway.WebApiClientTool; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; + +namespace JT808.Gateway.NormalHosting.Customs +{ + public class JT808HttpClientExt : JT808HttpClient + { + public static string index1 = $"jt808apiext/index1"; + public JT808HttpClientExt(HttpClient httpClient) : base(httpClient) + { + } + + /// + /// ext + /// + /// + public async ValueTask> GetIndex1() + { + var request = new HttpRequestMessage(HttpMethod.Get, index1); + var response = await HttpClient.SendAsync(request); + response.EnsureSuccessStatusCode(); + var data = await response.Content.ReadAsStreamAsync(); + var value = await JsonSerializer.DeserializeAsync>(data); + return value; + } + } +} diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Customs/JT808WebApiExt.cs b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Customs/JT808WebApiExt.cs new file mode 100644 index 0000000..08e1555 --- /dev/null +++ b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Customs/JT808WebApiExt.cs @@ -0,0 +1,31 @@ +using JT808.Gateway.Abstractions.Dtos; +using JT808.Gateway.Services; +using JT808.Gateway.Session; +using Microsoft.AspNetCore.Mvc; + +namespace JT808.Gateway.NormalHosting.Customs +{ + [Route("jt808apiext")] + [ApiController] + public class JT808WebApiExt : ControllerBase + { + public JT808WebApiExt(JT808SessionManager jT808SessionManager, JT808BlacklistManager jT808BlacklistManager) + { + + } + + /// + /// index1 + /// + /// + [HttpGet] + [Route("index1")] + public ActionResult> Index1() + { + JT808ResultDto resultDto = new JT808ResultDto(); + resultDto.Data = "Hello,JT808 WebApi Ext"; + resultDto.Code = JT808ResultCode.Ok; + return resultDto; + } + } +} diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/JT808.Gateway.NormalHosting.csproj b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/JT808.Gateway.NormalHosting.csproj index f87c610..4a89cd7 100644 --- a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/JT808.Gateway.NormalHosting.csproj +++ b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/JT808.Gateway.NormalHosting.csproj @@ -5,8 +5,24 @@ net6 + + + + + + + + + + + + + + + + @@ -37,4 +53,9 @@ + + + + + diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Jobs/CallHttpClientJob.cs b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Jobs/CallHttpClientJob.cs index c2c4dd4..c87b8d6 100644 --- a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Jobs/CallHttpClientJob.cs +++ b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Jobs/CallHttpClientJob.cs @@ -10,6 +10,7 @@ using JT808.Protocol.Extensions; using Microsoft.Extensions.Options; using JT808.Gateway.Abstractions.Configurations; using JT808.Gateway.WebApiClientTool; +using JT808.Gateway.NormalHosting.Customs; namespace JT808.Gateway.NormalHosting.Jobs { @@ -17,10 +18,10 @@ namespace JT808.Gateway.NormalHosting.Jobs { private readonly ILogger Logger; - private JT808HttpClient jT808HttpClient; + private JT808HttpClientExt jT808HttpClient; public CallHttpClientJob( ILoggerFactory loggerFactory, - JT808HttpClient jT808HttpClient) + JT808HttpClientExt jT808HttpClient) { Logger = loggerFactory.CreateLogger(); this.jT808HttpClient = jT808HttpClient; @@ -32,12 +33,14 @@ namespace JT808.Gateway.NormalHosting.Jobs { while (!cancellationToken.IsCancellationRequested) { + var result1 = await jT808HttpClient.GetIndex1(); var result2 = await jT808HttpClient.GetTcpSessionAll(); var result3 = await jT808HttpClient.UnificationSend(new Abstractions.Dtos.JT808UnificationSendRequestDto { TerminalPhoneNo= "123456789012", HexData= "7E02000026123456789012007D02000000010000000200BA7F0E07E4F11C0028003C00001810151010100104000000640202007D01137E" }); + Logger.LogInformation($"[GetIndex Ext]:{JsonSerializer.Serialize(result1)}"); Logger.LogInformation($"[GetTcpAtomicCounter]:{JsonSerializer.Serialize(result2)}"); Logger.LogInformation($"[GetTcpSessionAll]:{JsonSerializer.Serialize(result3)}"); Thread.Sleep(3000); diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Program.cs b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Program.cs index 5ebb574..f57fecf 100644 --- a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Program.cs +++ b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/Program.cs @@ -18,6 +18,12 @@ using JT808.Gateway.WebApiClientTool; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Server; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration.Json; +using JT808.Gateway.Abstractions.Configurations; +using System.Net; +using JT808.Gateway.Extensions; +using JT808.Gateway.NormalHosting.Customs; namespace JT808.Gateway.NormalHosting { @@ -25,10 +31,9 @@ namespace JT808.Gateway.NormalHosting { static void Main(string[] args) { - var builder = WebApplication.CreateBuilder(args); + var builder = WebApplication.CreateBuilder(); builder.Host.ConfigureAppConfiguration((hostingContext, config) => { - config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{ hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true); @@ -42,8 +47,6 @@ namespace JT808.Gateway.NormalHosting }) .ConfigureServices((hostContext, services) => { - services.AddSingleton(); - services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); //使用内存队列实现会话通知 services.AddSingleton(); services.AddSingleton(); @@ -56,7 +59,7 @@ namespace JT808.Gateway.NormalHosting .AddClient() .Builder() //方式1:客户端webapi调用 - .AddWebApiClientTool(hostContext.Configuration) + .AddWebApiClientTool(hostContext.Configuration) .AddGateway(hostContext.Configuration) .AddMessageHandler() .AddMsgReplyConsumer() @@ -64,18 +67,36 @@ namespace JT808.Gateway.NormalHosting .AddSessionNotice() .AddTransmit(hostContext.Configuration) .AddTcp() - .AddUdp() - .AddHttp(); + .AddUdp(); //方式2:客户端webapi调用 //services.AddJT808WebApiClientTool(hostContext.Configuration); //httpclient客户端调用 - //services.AddHostedService(); + services.AddHostedService(); //客户端测试 依赖AddClient()服务 //services.AddHostedService(); + + //需要跨域的 + services.AddCors(options => + options.AddPolicy("jt808", builder => + builder.AllowAnyMethod() + .AllowAnyHeader() + .AllowCredentials() + .SetIsOriginAllowed(o => true))); + }); + builder.WebHost.UseKestrel((app, serverOptions) => + { + //1.配置webapi端口监听 + var jT808Configuration = app.Configuration.GetSection(nameof(JT808Configuration)).Get(); + serverOptions.ListenAnyIP(jT808Configuration.WebApiPort); + }) + .ConfigureServices((hostContext, services) => + { + services.AddControllers(); }); - var app = builder.Build(); - app.UseJT808MiniWebApi(); + + app.UseCors(); + app.MapControllers().RequireCors("jt808"); app.Run(); } diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/appsettings.json b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/appsettings.json index b6938ce..40d4925 100644 --- a/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/appsettings.json +++ b/src/JT808.Gateway.Tests/JT808.Gateway.NormalHosting/appsettings.json @@ -1,9 +1,16 @@ { + "Logging": { + "LogLevel": { + "Default": "Debug", + "Microsoft.AspNetCore.Mvc": "Information", + "Microsoft.AspNetCore.Server.Kestrel": "Information" + } + }, "JT808Configuration": { "TcpPort": 808, "UdpPort": 808, "WebApiPort": 828, - "Token": "123456", + "Token": "1234567", "MiniNumBufferSize": 51200, "SoBacklog": 65535 }, @@ -13,10 +20,10 @@ }, "RemoteServerOptions": { "DataTransfer": [ - { - "Host": "127.0.0.1:20000", - "TerminalNos": [ "1234567890", "1234567891" ] - } + //{ + // "Host": "127.0.0.1:20000", + // "TerminalNos": [ "1234567890", "1234567891" ] + //} ] } } diff --git a/src/JT808.Gateway.Tests/JT808.Gateway.QueueHosting/Program.cs b/src/JT808.Gateway.Tests/JT808.Gateway.QueueHosting/Program.cs index 349499b..d3df772 100644 --- a/src/JT808.Gateway.Tests/JT808.Gateway.QueueHosting/Program.cs +++ b/src/JT808.Gateway.Tests/JT808.Gateway.QueueHosting/Program.cs @@ -66,8 +66,7 @@ namespace JT808.Gateway.QueueHosting .AddServerKafkaSessionProducer(hostContext.Configuration) .AddServerKafkaMsgReplyConsumer(hostContext.Configuration) .AddTcp() - .AddUdp() - .AddHttp(); + .AddUdp(); //方式2:客户端webapi调用 //services.AddJT808WebApiClientTool(hostContext.Configuration); //httpclient客户端调用 diff --git a/src/JT808.Gateway.WebApiClientTool/JT808.Gateway.WebApiClientTool.xml b/src/JT808.Gateway.WebApiClientTool/JT808.Gateway.WebApiClientTool.xml index 4a3ce85..09e863c 100644 --- a/src/JT808.Gateway.WebApiClientTool/JT808.Gateway.WebApiClientTool.xml +++ b/src/JT808.Gateway.WebApiClientTool/JT808.Gateway.WebApiClientTool.xml @@ -120,6 +120,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/JT808.Gateway.WebApiClientTool/JT808HttpClientExtensions.cs b/src/JT808.Gateway.WebApiClientTool/JT808HttpClientExtensions.cs index c61d3d6..e902b9e 100644 --- a/src/JT808.Gateway.WebApiClientTool/JT808HttpClientExtensions.cs +++ b/src/JT808.Gateway.WebApiClientTool/JT808HttpClientExtensions.cs @@ -13,6 +13,7 @@ namespace JT808.Gateway.WebApiClientTool /// public static class JT808HttpClientExtensions { + const int timeout = 15; /// /// /// @@ -26,7 +27,7 @@ namespace JT808.Gateway.WebApiClientTool { c.DefaultRequestHeaders.Add("token", token); c.BaseAddress = webapiUri; - c.Timeout = TimeSpan.FromSeconds(3); + c.Timeout = TimeSpan.FromSeconds(timeout); }) .AddTypedClient(); return serviceDescriptors; @@ -44,7 +45,7 @@ namespace JT808.Gateway.WebApiClientTool { c.DefaultRequestHeaders.Add("token", configuration.GetSection("JT808WebApiClientToolConfig:Token").Get()); c.BaseAddress = new Uri(configuration.GetSection("JT808WebApiClientToolConfig:Uri").Get()); - c.Timeout = TimeSpan.FromSeconds(3); + c.Timeout = TimeSpan.FromSeconds(timeout); }) .AddTypedClient(); return serviceDescriptors; @@ -62,7 +63,7 @@ namespace JT808.Gateway.WebApiClientTool { c.DefaultRequestHeaders.Add("token", configuration.GetSection("JT808WebApiClientToolConfig:Token").Get()); c.BaseAddress = new Uri(configuration.GetSection("JT808WebApiClientToolConfig:Uri").Get()); - c.Timeout = TimeSpan.FromSeconds(3); + c.Timeout = TimeSpan.FromSeconds(timeout); }) .AddTypedClient(); return jT808Builder; @@ -81,10 +82,88 @@ namespace JT808.Gateway.WebApiClientTool { c.DefaultRequestHeaders.Add("token", token); c.BaseAddress = webapiUri; - c.Timeout = TimeSpan.FromSeconds(3); + c.Timeout = TimeSpan.FromSeconds(timeout); }) .AddTypedClient(); return jT808Builder; } + + /// + /// + /// + /// + /// + /// + /// + public static IServiceCollection AddJT808WebApiClientTool(this IServiceCollection serviceDescriptors, Uri webapiUri, string token) + where TJT808HttpClient : JT808HttpClient + { + serviceDescriptors.AddHttpClient("JT808WebApiClientTool", c => + { + c.DefaultRequestHeaders.Add("token", token); + c.BaseAddress = webapiUri; + c.Timeout = TimeSpan.FromSeconds(timeout); + }) + .AddTypedClient(); + return serviceDescriptors; + } + + /// + /// + /// + /// + /// + /// + public static IServiceCollection AddJT808WebApiClientTool(this IServiceCollection serviceDescriptors, IConfiguration configuration) + where TJT808HttpClient : JT808HttpClient + { + serviceDescriptors.AddHttpClient("JT808WebApiClientTool", c => + { + c.DefaultRequestHeaders.Add("token", configuration.GetSection("JT808WebApiClientToolConfig:Token").Get()); + c.BaseAddress = new Uri(configuration.GetSection("JT808WebApiClientToolConfig:Uri").Get()); + c.Timeout = TimeSpan.FromSeconds(timeout); + }) + .AddTypedClient(); + return serviceDescriptors; + } + + /// + /// + /// + /// + /// + /// + public static IJT808Builder AddWebApiClientTool(this IJT808Builder jT808Builder, IConfiguration configuration) + where TJT808HttpClient : JT808HttpClient + { + jT808Builder.Services.AddHttpClient("JT808WebApiClientTool", c => + { + c.DefaultRequestHeaders.Add("token", configuration.GetSection("JT808WebApiClientToolConfig:Token").Get()); + c.BaseAddress = new Uri(configuration.GetSection("JT808WebApiClientToolConfig:Uri").Get()); + c.Timeout = TimeSpan.FromSeconds(timeout); + }) + .AddTypedClient(); + return jT808Builder; + } + + /// + /// + /// + /// + /// + /// + /// + public static IJT808Builder AddWebApiClientTool(this IJT808Builder jT808Builder, Uri webapiUri, string token) + where TJT808HttpClient: JT808HttpClient + { + jT808Builder.Services.AddHttpClient("JT808WebApiClientTool", c => + { + c.DefaultRequestHeaders.Add("token", token); + c.BaseAddress = webapiUri; + c.Timeout = TimeSpan.FromSeconds(timeout); + }) + .AddTypedClient(); + return jT808Builder; + } } } diff --git a/src/JT808.Gateway.sln b/src/JT808.Gateway.sln index 9f3e85c..ab5a8ea 100644 --- a/src/JT808.Gateway.sln +++ b/src/JT808.Gateway.sln @@ -42,6 +42,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{2336747A-28A3-443E-8E23-4B25E3F2D971}" ProjectSection(SolutionItems) = preProject PipelineInfo.props = PipelineInfo.props + ..\api\README_Pipeline.md = ..\api\README_Pipeline.md EndProjectSection EndProject Global diff --git a/src/JT808.Gateway/Authorization/JT808AuthorizationDefault.cs b/src/JT808.Gateway/Authorization/JT808AuthorizationDefault.cs deleted file mode 100644 index 2782bbe..0000000 --- a/src/JT808.Gateway/Authorization/JT808AuthorizationDefault.cs +++ /dev/null @@ -1,48 +0,0 @@ -using JT808.Gateway.Abstractions; -using JT808.Gateway.Abstractions.Configurations; -using Microsoft.Extensions.Options; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Security.Claims; -using System.Security.Principal; -using System.Text; - -namespace JT808.Gateway.Authorization -{ - class JT808AuthorizationDefault : IJT808Authorization - { - private IOptionsMonitor optionsMonitor; - public JT808AuthorizationDefault(IOptionsMonitor optionsMonitor) - { - this.optionsMonitor = optionsMonitor; - } - public bool Authorization(HttpListenerContext context, out IPrincipal principal) - { - var uriSpan = context.Request.Url.AbsoluteUri.AsSpan(); - var uriParamStr = uriSpan.Slice(uriSpan.IndexOf('?')+1).ToString().ToLower(); - var uriParams = uriParamStr.Split('&'); - var tokenParam = uriParams.FirstOrDefault(m => m.Contains("token")); - string tokenValue = string.Empty; - if (!string.IsNullOrEmpty(tokenParam)) - { - tokenValue = tokenParam.Split('=')[1]; - } - else - { - tokenValue = context.Request.Headers.Get("token"); - } - if (optionsMonitor.CurrentValue.WebApiToken == tokenValue) - { - principal = new ClaimsPrincipal(new GenericIdentity(tokenValue)); - return true; - } - else - { - principal = null; - return false; - } - } - } -} diff --git a/src/JT808.Gateway/Authorization/JT808TokenAttribute.cs b/src/JT808.Gateway/Authorization/JT808TokenAttribute.cs new file mode 100644 index 0000000..7933717 --- /dev/null +++ b/src/JT808.Gateway/Authorization/JT808TokenAttribute.cs @@ -0,0 +1,63 @@ +using JT808.Gateway.Abstractions; +using JT808.Gateway.Abstractions.Configurations; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Net; +using System.Security.Principal; +using System.Threading.Tasks; +using Microsoft.Extensions.Primitives; +using Microsoft.AspNetCore.Mvc; +using JT808.Gateway.Abstractions.Dtos; +using Microsoft.AspNetCore.Authorization; +using Microsoft.Extensions.Options; + +namespace JT808.Gateway.Authorization +{ + /// + /// + /// + public class JT808TokenAttribute : Attribute, IAuthorizationFilter + { + const string token = "token"; + /// + /// + /// + /// + public void OnAuthorization(AuthorizationFilterContext context) + { + IOptions jT808Configuration = context.HttpContext.RequestServices.GetRequiredService>(); + StringValues tokenValue; + if (context.HttpContext.Request.Query.TryGetValue(token, out tokenValue)) + { + if(jT808Configuration.Value.WebApiToken != tokenValue) + { + JT808ResultDto resultDto = new JT808ResultDto(); + resultDto.Message = "auth error"; + resultDto.Data = "auth error"; + resultDto.Code = 401; + context.Result =new OkObjectResult(resultDto); + } + } + else if (context.HttpContext.Request.Headers.TryGetValue(token, out tokenValue)) + { + if (jT808Configuration.Value.WebApiToken != tokenValue) + { + JT808ResultDto resultDto = new JT808ResultDto(); + resultDto.Message = "auth error"; + resultDto.Data = "auth error"; + resultDto.Code = 401; + context.Result = new OkObjectResult(resultDto); + } + } + else + { + JT808ResultDto resultDto = new JT808ResultDto(); + resultDto.Message = "auth error"; + resultDto.Data = "auth error"; + resultDto.Code = 401; + context.Result = new OkObjectResult(resultDto); + } + } + } +} diff --git a/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs b/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs deleted file mode 100644 index 34b0fe9..0000000 --- a/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.Extensions -{ - public static class JT808HttpContextExtensions - { - private const string jsonType = "application/json"; - - public static void Http204(this HttpListenerContext context) - { - context.Response.StatusCode = (int)HttpStatusCode.NoContent; - context.Response.KeepAlive = false; - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void Http401(this HttpListenerContext context) - { - byte[] b = Encoding.UTF8.GetBytes("auth error"); - context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; - context.Response.ContentType = jsonType; - context.Response.KeepAlive = false; - context.Response.ContentLength64 = b.Length; - var output = context.Response.OutputStream; - output.Write(b, 0, b.Length); - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void Http400(this HttpListenerContext context) - { - byte[] b = Encoding.UTF8.GetBytes($"sim and channel parameter required."); - context.Response.StatusCode = (int)HttpStatusCode.BadRequest; - context.Response.KeepAlive = false; - context.Response.ContentType = jsonType; - context.Response.ContentLength64 = b.Length; - var output = context.Response.OutputStream; - output.Write(b, 0, b.Length); - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void Http404(this HttpListenerContext context) - { - context.Response.StatusCode = (int)HttpStatusCode.NotFound; - context.Response.KeepAlive = false; - context.Response.ContentType = jsonType; - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void Http405(this HttpListenerContext context) - { - context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; - context.Response.KeepAlive = false; - context.Response.ContentType = jsonType; - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void Http500(this HttpListenerContext context) - { - byte[] b = Encoding.UTF8.GetBytes("inner error"); - context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; - context.Response.KeepAlive = false; - context.Response.ContentType = jsonType; - context.Response.ContentLength64 = b.Length; - var output = context.Response.OutputStream; - output.Write(b,0, b.Length); - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void HttpSend(this HttpListenerContext context, ReadOnlyMemory buffer) - { - context.Response.StatusCode = (int)HttpStatusCode.OK; - context.Response.KeepAlive = false; - context.Response.ContentType = jsonType; - context.Response.ContentLength64 = buffer.Length; - context.Response.OutputStream.Write(buffer.ToArray(),0, buffer.Length); - context.Response.OutputStream.Close(); - context.Response.Close(); - } - - public static void HttpSend(this HttpListenerContext context, string json) - { - byte[] b = Encoding.UTF8.GetBytes(json); - context.Response.StatusCode = (int)HttpStatusCode.OK; - context.Response.KeepAlive = false; - context.Response.ContentType = jsonType; - context.Response.ContentLength64 = b.Length; - context.Response.OutputStream.Write(b,0, b.Length); - context.Response.OutputStream.Close(); - context.Response.Close(); - } - } -} diff --git a/src/JT808.Gateway/Extensions/JT808WebApiExtensions.cs b/src/JT808.Gateway/Extensions/JT808WebApiExtensions.cs new file mode 100644 index 0000000..b05c6bc --- /dev/null +++ b/src/JT808.Gateway/Extensions/JT808WebApiExtensions.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace JT808.Gateway.Extensions +{ + public static class JT808WebApiExtensions + { + public static IServiceCollection AddJT808Cors(this IServiceCollection serviceDescriptors) + { + serviceDescriptors.AddCors(options => + options.AddPolicy("jt808", builder => + builder.AllowAnyMethod() + .AllowAnyHeader() + .AllowCredentials() + .SetIsOriginAllowed(o => true))); + return serviceDescriptors; + } + + public static IApplicationBuilder UseJT808Cors(this IApplicationBuilder app) + { + app.UseCors("jt808"); + return app; + } + } +} diff --git a/src/JT808.Gateway/JT808.Gateway.xml b/src/JT808.Gateway/JT808.Gateway.xml index 001106c..4a192f1 100644 --- a/src/JT808.Gateway/JT808.Gateway.xml +++ b/src/JT808.Gateway/JT808.Gateway.xml @@ -4,242 +4,213 @@ JT808.Gateway - + - 默认消息处理业务实现 + - + - - + - + - 会话服务集合 + JT808网关注册扩展 - - - + - 通过终端手机号查询对应会话 + 添加808网关 - + + - + - 会话服务-通过设备终端号移除对应会话 + 添加808网关 - + + - + - 会话服务集合 + 添加tcp服务器 - + - + - 通过终端手机号查询对应会话 + 添加udp服务器 - + - + - 会话服务-通过设备终端号移除对应会话 + 添加消息业务处理程序 - + + - + - 统一下发信息 + 添加消息生产者 - + + - + - 添加sim卡黑名单 + 添加消息应答后的应答生产者 - + + - + - 移除sim卡黑名单 + 添加消息应答消费者 - + + - + - 查询sim卡黑名单 + 添加公共模块 - + - + - + 808 tcp服务器 - + - + 初始化服务注册 + + + + + + + + - + - - - - JT808网关注册扩展 - - - - - 添加808网关 - - - + - + - 添加808网关 + - - + - + - 添加tcp服务器 + jt808 webapi - - - + - 添加udp服务器 + - - - + - 添加http服务器 + - - - + - 添加http服务器 + - - - + + - + - 添加消息业务处理程序 + index - - - + - 添加Http服务认证机制 + 统一下发设备消息服务 - - - + - 添加消息生产者 + 会话服务-Tcp会话查询 - - - + - 添加消息应答后的应答生产者 + 会话服务-通过设备终端号查询对应会话 - - + - + - 添加消息应答消费者 + 会话服务-通过设备终端号移除对应会话 - - + - + - 添加公共模块 + 会话服务-Udp会话查询 - - + - + 会话服务-通过设备终端号查询对应会话 + + - + - + 会话服务-通过设备终端号移除对应会话 - + - + - 808 tcp服务器 + 黑名单添加 + - - - 初始化服务注册 - - - - - - - - - - - + - + 黑名单删除 - - + - + 黑名单查询 - diff --git a/src/JT808.Gateway/JT808GatewayExtensions.cs b/src/JT808.Gateway/JT808GatewayExtensions.cs index d71d566..c685871 100644 --- a/src/JT808.Gateway/JT808GatewayExtensions.cs +++ b/src/JT808.Gateway/JT808GatewayExtensions.cs @@ -1,7 +1,6 @@ using JT808.Gateway.Abstractions; using JT808.Gateway.Authorization; using JT808.Gateway.Abstractions.Configurations; -using JT808.Gateway.Handlers; using JT808.Gateway.Internal; using JT808.Gateway.Services; using JT808.Gateway.Session; @@ -71,32 +70,6 @@ namespace JT808.Gateway return config; } /// - /// 添加http服务器 - /// - /// - /// - public static IJT808GatewayBuilder AddHttp(this IJT808GatewayBuilder config) - { - config.JT808Builder.Services.AddSingleton(); - config.JT808Builder.Services.AddSingleton(); - config.JT808Builder.Services.AddHostedService(); - return config; - } - /// - /// 添加http服务器 - /// - /// - /// - /// - public static IJT808GatewayBuilder AddHttp(this IJT808GatewayBuilder config) - where TJT808MsgIdDefaultWebApiHandler: JT808MsgIdDefaultWebApiHandler - { - config.JT808Builder.Services.AddSingleton(); - config.JT808Builder.Services.AddSingleton(typeof(JT808MsgIdDefaultWebApiHandler),typeof(TJT808MsgIdDefaultWebApiHandler)); - config.JT808Builder.Services.AddHostedService(); - return config; - } - /// /// 添加消息业务处理程序 /// /// @@ -109,18 +82,6 @@ namespace JT808.Gateway return config; } /// - /// 添加Http服务认证机制 - /// - /// - /// - /// - public static IJT808GatewayBuilder AddHttpAuthorization(this IJT808GatewayBuilder config) - where TJT808Authorization : IJT808Authorization - { - config.JT808Builder.Services.Replace(new ServiceDescriptor(typeof(IJT808Authorization), typeof(TJT808Authorization), ServiceLifetime.Singleton)); - return config; - } - /// /// 添加消息生产者 /// /// diff --git a/src/JT808.Gateway/JT808HttpServer.cs b/src/JT808.Gateway/JT808HttpServer.cs deleted file mode 100644 index c2f480b..0000000 --- a/src/JT808.Gateway/JT808HttpServer.cs +++ /dev/null @@ -1,180 +0,0 @@ -using JT808.Gateway.Abstractions; -using JT808.Gateway.Abstractions.Configurations; -using JT808.Gateway.Extensions; -using JT808.Gateway.Handlers; -using JT808.Gateway.Session; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using System; -using System.Buffers; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.WebSockets; -using System.Security.Principal; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway -{ - public class JT808HttpServer : IHostedService - { - private readonly ILogger Logger; - - private readonly JT808Configuration Configuration; - - private readonly IJT808Authorization authorization; - - private HttpListener listener; - - private readonly JT808MsgIdDefaultWebApiHandler MsgIdDefaultWebApiHandler; - - public JT808HttpServer( - JT808MsgIdDefaultWebApiHandler jT808MsgIdDefaultWebApiHandler, - IOptions jT808ConfigurationAccessor, - IJT808Authorization authorization, - ILoggerFactory loggerFactory) - { - Logger = loggerFactory.CreateLogger(); - Configuration = jT808ConfigurationAccessor.Value; - MsgIdDefaultWebApiHandler = jT808MsgIdDefaultWebApiHandler; - this.authorization = authorization; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - if (!HttpListener.IsSupported) - { - Logger.LogWarning("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); - return Task.CompletedTask; - } - listener = new HttpListener(); - listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; - try - { - listener.Prefixes.Add($"http://*:{Configuration.WebApiPort}/"); - listener.Start(); - } - catch (System.Net.HttpListenerException ex) - { - Logger.LogWarning(ex, $"{ex.Message}:使用cmd命令[netsh http add urlacl url=http://*:{Configuration.WebApiPort}/ user=Everyone]"); - } - Logger.LogInformation($"JT808 Http Server start at {IPAddress.Any}:{Configuration.WebApiPort}."); - Task.Factory.StartNew(() => - { - while (listener.IsListening) - { - var context = listener.GetContext(); - try - { - if (context.Request.RawUrl.StartsWith("/favicon.ico")) - { - context.Http404(); - continue; - } - // 增加CORS - // https://stackoverflow.com/questions/25437405/cors-access-for-httplistener - context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); - if (context.Request.HttpMethod == HttpMethod.Options.Method) - { - context.Response.AddHeader("Access-Control-Allow-Headers", "*"); - context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); - context.Response.AddHeader("Access-Control-Max-Age", "1728000"); - context.Http204(); - } - if (authorization.Authorization(context, out var principal)) - { - DateTime start = DateTime.Now; - if (Logger.IsEnabled(LogLevel.Debug)) - { - Logger.LogDebug($"ProcessRequestAsync Start:{context.Request.RemoteEndPoint}-{context.Request.RawUrl}"); - } - ProcessRequest(context, principal); - if (Logger.IsEnabled(LogLevel.Debug)) - { - double time = (DateTime.Now - start).TotalMilliseconds; - Logger.LogDebug($"ProcessRequestAsync End:{context.Request.RemoteEndPoint}-{context.Request.RawUrl} {time}ms"); - } - } - else - { - context.Http401(); - } - } - catch (AggregateException ex) - { - context.Http500(); - Logger.LogError(ex, ex.StackTrace); - } - catch (Exception ex) - { - context.Http500(); - Logger.LogError(ex, ex.StackTrace); - } - } - }, cancellationToken); - return Task.CompletedTask; - } - - private void ProcessRequest(HttpListenerContext context, IPrincipal principal) - { - var router = MsgIdDefaultWebApiHandler.HandlerDict.FirstOrDefault(f => context.Request.RawUrl.StartsWith(f.Key)); - if (router.Key == null) - { - context.Http404(); - return; - } - byte[] response; - if (context.Request.HttpMethod == HttpMethod.Get.Method) - { - var index = context.Request.Url.AbsoluteUri.IndexOf('?'); - if (index > 0) - { - var uriParamStr = context.Request.Url.AbsoluteUri[(index + 1)..].ToString(); - response = router.Value(uriParamStr); - context.HttpSend(response); - } - else - { - response = router.Value(""); - context.HttpSend(response); - } - } - else if(context.Request.HttpMethod == HttpMethod.Post.Method) - { - string json = string.Empty; - using (var reader = new StreamReader(context.Request.InputStream,context.Request.ContentEncoding)) - { - json = reader.ReadToEnd(); - } - response = router.Value(json); - context.HttpSend(response); - } - else - { - context.Http405(); - } - } - - public Task StopAsync(CancellationToken cancellationToken) - { - try - { - listener.Stop(); - } - catch (System.ObjectDisposedException ex) - { - Logger.LogError(ex, ""); - } - catch (Exception ex) - { - Logger.LogError(ex, ""); - } - return Task.CompletedTask; - } - } -} diff --git a/src/JT808.Gateway/JT808MiniWebApi.cs b/src/JT808.Gateway/JT808MiniWebApi.cs deleted file mode 100644 index 4fbe9bd..0000000 --- a/src/JT808.Gateway/JT808MiniWebApi.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Http; -using JT808.Gateway.Abstractions; -using JT808.Gateway.Abstractions.Dtos; -using System.Text.Json; -using Microsoft.Extensions.DependencyInjection; -using JT808.Gateway.Session; -using JT808.Gateway.Services; -using System; - -namespace JT808.Gateway -{ - /// - /// - /// - public static class JT808MiniWebApi - { - /// - /// - /// - /// - /// - public static void UseJT808MiniWebApi(this WebApplication app) - { - //CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.UnificationSend, UnificationSend); - //CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.BlacklistAdd, BlacklistAdd); - //CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.BlacklistRemove, BlacklistRemove); - //CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.BlacklistGet, QueryBlacklist); - app.MapPost(JT808GatewayConstants.JT808WebApiRouteTable.UnificationSend,async context => - { - JT808ResultDto resultDto = new JT808ResultDto(); - JT808SessionManager SessionManager = context.RequestServices.GetRequiredService(); - JT808BlacklistManager BlacklistManager = context.RequestServices.GetRequiredService(); - try - { - JT808UnificationSendRequestDto jT808UnificationSendRequestDto = JsonSerializer.Deserialize(context.Request.Body); - resultDto.Data = await SessionManager.TrySendByTerminalPhoneNoAsync(jT808UnificationSendRequestDto.TerminalPhoneNo,Convert.FromHexString(jT808UnificationSendRequestDto.HexData)); - resultDto.Code = JT808ResultCode.Ok; - } - catch (Exception ex) - { - resultDto.Data = false; - resultDto.Code = JT808ResultCode.Error; - resultDto.Message = ex.StackTrace; - } - await context.Response.WriteAsJsonAsync(resultDto); - }); - } - } -} diff --git a/src/JT808.Gateway/Handlers/JT808MsgIdDefaultWebApiHandler.cs b/src/JT808.Gateway/JT808WebApi.cs similarity index 56% rename from src/JT808.Gateway/Handlers/JT808MsgIdDefaultWebApiHandler.cs rename to src/JT808.Gateway/JT808WebApi.cs index f99c9dd..839119e 100644 --- a/src/JT808.Gateway/Handlers/JT808MsgIdDefaultWebApiHandler.cs +++ b/src/JT808.Gateway/JT808WebApi.cs @@ -1,45 +1,92 @@ using JT808.Gateway.Abstractions; using JT808.Gateway.Abstractions.Dtos; +using JT808.Gateway.Authorization; using JT808.Gateway.Services; using JT808.Gateway.Session; -using JT808.Protocol.Extensions; +using Microsoft.AspNetCore.Cors; +using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; -using System.Text.Json; using System.Threading.Tasks; -namespace JT808.Gateway.Handlers +namespace JT808.Gateway { /// - /// 默认消息处理业务实现 + /// jt808 webapi /// - public class JT808MsgIdDefaultWebApiHandler : JT808MsgIdHttpHandlerBase + [ApiController] + [Route("jt808api")] + public sealed class JT808WebApi:ControllerBase { - private JT808SessionManager SessionManager; - private JT808BlacklistManager BlacklistManager; + /// + /// + /// + JT808SessionManager SessionManager; + /// + /// + /// + JT808BlacklistManager BlacklistManager; + /// /// /// /// /// - public JT808MsgIdDefaultWebApiHandler( + public JT808WebApi( JT808SessionManager jT808SessionManager, JT808BlacklistManager jT808BlacklistManager) { this.SessionManager = jT808SessionManager; this.BlacklistManager = jT808BlacklistManager; - InitTcpRoute(); - InitUdpRoute(); - InitCommontRoute(); } /// - /// 会话服务集合 + /// index + /// + /// + [HttpGet] + [Route("index")] + public ActionResult> Index() + { + JT808ResultDto resultDto = new JT808ResultDto(); + resultDto.Data = "Hello,JT808 WebApi"; + resultDto.Code = JT808ResultCode.Ok; + return resultDto; + } + + /// + /// 统一下发设备消息服务 + /// + /// + [HttpPost] + [Route("UnificationSend")] + [JT808Token] + public async Task>> UnificationSend([FromBody] JT808UnificationSendRequestDto parameter) + { + JT808ResultDto resultDto = new JT808ResultDto(); + try + { + resultDto.Data = await SessionManager.TrySendByTerminalPhoneNoAsync(parameter.TerminalPhoneNo, Convert.FromHexString(parameter.HexData)); + resultDto.Code = JT808ResultCode.Ok; + } + catch (Exception ex) + { + resultDto.Data = false; + resultDto.Code = JT808ResultCode.Error; + resultDto.Message = ex.StackTrace; + } + return resultDto; + } + + /// + /// 会话服务-Tcp会话查询 /// - /// /// - public byte[] GetTcpSessionAll(string json) + [HttpGet] + [Route("/Tcp/Session/GetAll")] + [JT808Token] + public ActionResult>> SessionTcpGetAll() { JT808ResultDto> resultDto = new JT808ResultDto>(); try @@ -51,33 +98,31 @@ namespace JT808.Gateway.Handlers TerminalPhoneNo = s.TerminalPhoneNo, RemoteAddressIP = s.RemoteEndPoint.ToString(), }).ToList(); + resultDto.Code = JT808ResultCode.Ok; } catch (Exception ex) { - resultDto.Data = null; + resultDto.Data = new List(); resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// - /// 通过终端手机号查询对应会话 + /// 会话服务-通过设备终端号查询对应会话 /// - /// + /// /// - public byte[] QueryTcpSessionByTerminalPhoneNo(string json) + [HttpPost] + [Route("/Tcp/Session/QuerySessionByTerminalPhoneNo")] + [JT808Token] + public ActionResult> QueryTcpSessionByTerminalPhoneNo([FromBody] JT808TerminalPhoneNoDto parameter) { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } - JT808ResultDto resultDto = new JT808ResultDto(); try { - JT808TerminalPhoneNoDto parameter = JsonSerializer.Deserialize(json); resultDto.Data = SessionManager.GetTcpAll(w => w.TerminalPhoneNo == parameter.TerminalPhoneNo).Select(s => new JT808TcpSessionInfoDto { LastActiveTime = s.ActiveTime, @@ -93,49 +138,43 @@ namespace JT808.Gateway.Handlers resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// /// 会话服务-通过设备终端号移除对应会话 /// - /// + /// /// - public byte[] RemoveSessionByTerminalPhoneNo(string json) + [HttpPost] + [Route("/Tcp/Session/RemoveByTerminalPhoneNo")] + [JT808Token] + public ActionResult> SessionTcpRemoveByTerminalPhoneNo([FromBody] JT808TerminalPhoneNoDto parameter) { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } JT808ResultDto resultDto = new JT808ResultDto(); try { - JT808TerminalPhoneNoDto parameter = JsonSerializer.Deserialize(json); SessionManager.RemoveByTerminalPhoneNo(parameter.TerminalPhoneNo); resultDto.Code = JT808ResultCode.Ok; resultDto.Data = true; } - catch (AggregateException ex) - { - resultDto.Data = false; - resultDto.Code = 500; - resultDto.Message = ex.StackTrace; - } catch (Exception ex) { resultDto.Data = false; resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// - /// 会话服务集合 + /// 会话服务-Udp会话查询 /// - /// /// - public byte[] GetUdpSessionAll(string json) + [HttpGet] + [Route("/Udp/Session/GetAll")] + [JT808Token] + public ActionResult>> SessionUdpGetAll() { JT808ResultDto> resultDto = new JT808ResultDto>(); try @@ -147,32 +186,30 @@ namespace JT808.Gateway.Handlers TerminalPhoneNo = s.TerminalPhoneNo, RemoteAddressIP = s.RemoteEndPoint.ToString(), }).ToList(); + resultDto.Code = JT808ResultCode.Ok; } catch (Exception ex) { - resultDto.Data = null; + resultDto.Data = new List(); resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } - /// - /// 通过终端手机号查询对应会话 + /// 会话服务-通过设备终端号查询对应会话 /// - /// + /// /// - public byte[] QueryUdpSessionByTerminalPhoneNo(string json) + [HttpPost] + [Route("/Udp/Session/QuerySessionByTerminalPhoneNo")] + [JT808Token] + public ActionResult> QueryUdpSessionByTerminalPhoneNo([FromBody] JT808TerminalPhoneNoDto parameter) { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } JT808ResultDto resultDto = new JT808ResultDto(); try { - JT808TerminalPhoneNoDto parameter = JsonSerializer.Deserialize(json); resultDto.Data = SessionManager.GetUdpAll(w => w.TerminalPhoneNo == parameter.TerminalPhoneNo).Select(s => new JT808UdpSessionInfoDto { LastActiveTime = s.ActiveTime, @@ -188,90 +225,50 @@ namespace JT808.Gateway.Handlers resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// /// 会话服务-通过设备终端号移除对应会话 /// - /// + /// /// - public byte[] RemoveUdpByTerminalPhoneNo(string json) + [HttpPost] + [Route("/Udp/Session/RemoveByTerminalPhoneNo")] + [JT808Token] + public ActionResult> SessionUdpRemoveByTerminalPhoneNo([FromBody] JT808TerminalPhoneNoDto parameter) { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } JT808ResultDto resultDto = new JT808ResultDto(); try { - JT808TerminalPhoneNoDto parameter = JsonSerializer.Deserialize(json); SessionManager.RemoveByTerminalPhoneNo(parameter.TerminalPhoneNo); resultDto.Code = JT808ResultCode.Ok; resultDto.Data = true; } - catch (AggregateException ex) - { - resultDto.Data = false; - resultDto.Code = 500; - resultDto.Message = ex.StackTrace; - } catch (Exception ex) { resultDto.Data = false; resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// - /// 统一下发信息 + /// 黑名单添加 /// - /// /// - public byte[] UnificationSend(string json) + [HttpPost] + [Route("/Blacklist/Add")] + [JT808Token] + public ActionResult> BlacklistAdd([FromBody] JT808TerminalPhoneNoDto parameter) { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } JT808ResultDto resultDto = new JT808ResultDto(); try { - JT808UnificationSendRequestDto jT808UnificationSendRequestDto = JsonSerializer.Deserialize(json); - resultDto.Data = SessionManager.TrySendByTerminalPhoneNoAsync(jT808UnificationSendRequestDto.TerminalPhoneNo, jT808UnificationSendRequestDto.HexData.ToHexBytes()) - .GetAwaiter() - .GetResult(); - resultDto.Code = JT808ResultCode.Ok; - } - catch (Exception ex) - { - resultDto.Data = false; - resultDto.Code = JT808ResultCode.Error; - resultDto.Message = ex.StackTrace; - } - return CreateHttpResponse(resultDto); - } - - /// - /// 添加sim卡黑名单 - /// - /// - /// - public byte[] BlacklistAdd(string json) - { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } - JT808ResultDto resultDto = new JT808ResultDto(); - try - { - JT808TerminalPhoneNoDto parameter = JsonSerializer.Deserialize(json); BlacklistManager.Add(parameter.TerminalPhoneNo); - resultDto.Data = true; resultDto.Code = JT808ResultCode.Ok; + resultDto.Data = true; } catch (Exception ex) { @@ -279,27 +276,24 @@ namespace JT808.Gateway.Handlers resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// - /// 移除sim卡黑名单 + /// 黑名单删除 /// - /// /// - public byte[] BlacklistRemove(string json) + [HttpPost] + [Route("/Blacklist/Remove")] + [JT808Token] + public ActionResult> BlacklistRemove([FromBody] JT808TerminalPhoneNoDto parameter) { - if (string.IsNullOrEmpty(json)) - { - return EmptyHttpResponse(); - } JT808ResultDto resultDto = new JT808ResultDto(); try { - JT808TerminalPhoneNoDto parameter = JsonSerializer.Deserialize(json); BlacklistManager.Remove(parameter.TerminalPhoneNo); - resultDto.Data = true; resultDto.Code = JT808ResultCode.Ok; + resultDto.Data = true; } catch (Exception ex) { @@ -307,60 +301,32 @@ namespace JT808.Gateway.Handlers resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); + return resultDto; } /// - /// 查询sim卡黑名单 + /// 黑名单查询 /// - /// /// - public byte[] QueryBlacklist(string json) + [HttpGet] + [Route("/Blacklist/GetAll")] + [JT808Token] + public ActionResult>> BlacklistGetAll() { JT808ResultDto> resultDto = new JT808ResultDto>(); try { - resultDto.Data = BlacklistManager.GetAll(); resultDto.Code = JT808ResultCode.Ok; + resultDto.Data = BlacklistManager.GetAll(); } catch (Exception ex) { - resultDto.Data = null; + resultDto.Data = new List(); resultDto.Code = JT808ResultCode.Error; resultDto.Message = ex.StackTrace; } - return CreateHttpResponse(resultDto); - } - - /// - /// - /// - protected virtual void InitCommontRoute() - { - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.UnificationSend, UnificationSend); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.BlacklistAdd, BlacklistAdd); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.BlacklistRemove, BlacklistRemove); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.BlacklistGet, QueryBlacklist); - } - - /// - /// - /// - protected virtual void InitTcpRoute() - { - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.SessionTcpGetAll, GetTcpSessionAll); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.QueryTcpSessionByTerminalPhoneNo, QueryTcpSessionByTerminalPhoneNo); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.SessionRemoveByTerminalPhoneNo, RemoveSessionByTerminalPhoneNo); + return resultDto; } - /// - /// - /// - protected virtual void InitUdpRoute() - { - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.SessionUdpGetAll, GetUdpSessionAll); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.QueryUdpSessionByTerminalPhoneNo, QueryUdpSessionByTerminalPhoneNo); - CreateRoute(JT808GatewayConstants.JT808WebApiRouteTable.RemoveUdpByTerminalPhoneNo, RemoveUdpByTerminalPhoneNo); - } } }