黄贺彬 5 months ago
parent
commit
30a1631262

+ 26 - 2
IES.ExamServer/App.xaml.cs

@@ -1,8 +1,14 @@
-using Microsoft.AspNetCore.Builder;
+using IES.ExamServer.DI.SignalRHost;
+using Microsoft.AspNetCore.Builder;
 using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.StaticFiles;
+using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using System.IO;
 using System.Windows;
+using TEAMModelOS.SDK;
+using TEAMModelOS.SDK.DI;
 
 namespace IES.ExamServer
 {
@@ -23,11 +29,28 @@ namespace IES.ExamServer
         {
             // 这里是创建 ASP.NET 版通用主机的代码
             var builder = WebApplication.CreateBuilder(Environment.GetCommandLineArgs());
-            builder.WebHost.UseUrls("http://*:5000;https://*:5001");
+            builder.Configuration.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
+            //builder.WebHost.UseUrls("http://*:5000;https://*:5001");
+          
             // 注册主窗口和其他服务
             builder.Services.AddControllersWithViews();
             builder.Services.AddSingleton<MainWindow>();
             builder.Services.AddSingleton(this);
+            builder.Services.AddHttpClient();
+            builder.Services.AddSignalR();
+            builder.Services.AddHttpContextAccessor();
+            string path = $"{builder.Environment.ContentRootPath}/Configs";
+            builder.Services.AddCors(options =>
+            {
+                options.AddDefaultPolicy(
+                builder =>
+                {
+
+                    builder.AllowAnyOrigin()
+                            .AllowAnyHeader()
+                            .AllowAnyMethod();
+                });
+            });
             var app = builder.Build();
             // 这里是文件类型映射,如果你的静态文件在浏览器中加载报 404,那么需要在这里注册,这里我加载一个 3D 场景文件的类型
             var contentTypeProvider = new FileExtensionContentTypeProvider();
@@ -47,6 +70,7 @@ namespace IES.ExamServer
             app.UseAuthentication();
             app.UseAuthorization();
             app.MapControllers();
+            app.MapHub<SignalRExamServerHub>("/signalr/screen").RequireCors("any");
             WebApplication = app;
             // 处理退出事件,退出 App 时关闭 ASP.NET Core
             Exit += async (s, e) => await WebApplication.StopAsync();

File diff suppressed because it is too large
+ 42708 - 0
IES.ExamServer/Configs/latlng.json


+ 45 - 2
IES.ExamServer/Controllers/HomeController.cs

@@ -1,14 +1,57 @@
-using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Http.HttpResults;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Net.Http;
+using System.Net.Http.Json;
 using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
 using System.Threading.Tasks;
 
 namespace IES.ExamServer.Controllers
 {
-    public class HomeController
+    [Route("core")]
+    [ApiController]
+    public class HomeController:ControllerBase
     {
+        private readonly IConfiguration _configuration;
+        private readonly IHttpClientFactory _httpClientFactory;
+        public HomeController(IConfiguration configuration,IHttpClientFactory httpClientFactory) 
+        {
+            _configuration=configuration;
+            _httpClientFactory=httpClientFactory;
+        }
+        [HttpGet("/init")]
+        public async Task<IActionResult> Init() 
+        {
+            int code =0;
+            string msg = string.Empty;
+            try {
+                string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
+                var httpclient = _httpClientFactory.CreateClient();
+                httpclient.Timeout=  TimeSpan.FromSeconds(10);
+                HttpResponseMessage message =  await httpclient.PostAsJsonAsync($"{CenterUrl}/core/system-info", new { });
+                if (message.IsSuccessStatusCode)
+                {
+                    string content = await message.Content.ReadAsStringAsync();
+                    var data = JsonSerializer.Deserialize<JsonNode>(content);
+                    data!["centerUrl"]=CenterUrl;
+                    return Ok(new { code=200, msg="云端服务连接成功!", data = data });
+                }
+                else {
+                    code=500;
+                    msg="云端服务未连接!";
+                }
+            } catch (Exception ex) 
+            {
+                code=500;
+                msg="云端服务未连接!";
+            }
+            return Ok(new { code,msg} );
+        }
         [HttpGet("/hello")]
         public string Get() => "Hello World";
     }

+ 65 - 0
IES.ExamServer/DI/SignalRHost/SignalRExamServerHub.cs

@@ -0,0 +1,65 @@
+using Microsoft.AspNetCore.SignalR;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK;
+
+
+namespace IES.ExamServer.DI.SignalRHost
+{
+    public  class SignalRExamServerHub : Hub<IClient>
+    {
+        private readonly ILogger<SignalRExamServerHub> _logger;
+      
+        public SignalRExamServerHub(ILogger<SignalRExamServerHub> logger)
+        {
+            _logger = logger;
+           
+        }
+    }
+    public interface IClient
+    {
+        Task ReceiveMessage(MessageBody message);
+        Task ReceiveConnection(MessageBody message);
+        Task ReceiveDisConnection(MessageBody message);
+    }
+    public abstract class MessageBody
+    {
+        public MessageBody()
+        {
+            time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+        }
+        /// <summary>
+        /// 连接id
+        /// </summary>
+        public virtual string? connid { get; set; }
+        /// <summary>
+        /// 客户端id
+        /// </summary>
+        public virtual string? clientid { get; set; }
+        /// <summary>
+        /// 状态  busy 忙碌,free 空闲,down 离线,error 错误
+        /// </summary>
+        public virtual string? status { get; set; }
+        /// <summary>
+        /// 消息内容
+        /// </summary>
+        public virtual string? content { get; set; }
+        /// <summary>
+        /// 消息创建时间
+        /// </summary>
+        public virtual long time { get; }
+        /// <summary>
+        /// 授权类型,bookjs_api 
+        /// </summary>
+        public virtual string? grant_type { get; set; }
+        /// <summary>
+        /// 消息类型
+        /// </summary>
+        public virtual MessageType message_type { get; set; }
+
+    }
+}

+ 20 - 0
IES.ExamServer/IES.ExamServer.csproj

@@ -8,6 +8,18 @@
     <UseWPF>true</UseWPF>
   </PropertyGroup>
 
+  <ItemGroup>
+    <None Remove="Configs\latlng.json" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Content Include="Configs\latlng.json">
+      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </Content>
+  </ItemGroup>
+
   <ItemGroup>
     <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" />
     <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
@@ -18,10 +30,18 @@
   <ItemGroup>
 	<FrameworkReference Include="Microsoft.AspNetCore.App" />
   </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\TEAMModelOS.SDK\TEAMModelOS.SDK.csproj" />
+  </ItemGroup>
   <ItemGroup>
 	<!-- 这里模仿 ASP.NET Core,将 SPA 资源文件存于 wwwroot 文件夹下 -->
 	<None Update="wwwroot\**">
 		<CopyToOutputDirectory>Always</CopyToOutputDirectory>
 	</None>
   </ItemGroup>
+  <ItemGroup>
+    <None Update="appsettings.json">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </None>
+  </ItemGroup>
 </Project>

+ 1 - 1
IES.ExamServer/MainWindow.xaml

@@ -12,6 +12,6 @@
     <Grid>
         <!-- 这里插入 WebView2 控件,我们默认可以让 Source 是 http://localhost:5000,这是 ASP.NET Core 的默认监听地址 -->
         <wv2:WebView2 Name="webView"
-          Source="{Binding SourceUrl, FallbackValue='https://localhost:5000'}" AllowDrop="True" SnapsToDevicePixels="True"/>
+          Source="{Binding SourceUrl, FallbackValue='https://localhost:5000/hello'}" AllowDrop="True" SnapsToDevicePixels="True"/>
     </Grid>
 </Window>

+ 1 - 1
IES.ExamServer/MainWindow.xaml.cs

@@ -28,7 +28,7 @@ namespace IES.ExamServer
             InitializeComponent();
             // 这里通过注入的 IServer 对象来获取监听的 Url
             var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses;
-            SourceUrl = addresses is not null ? (addresses.FirstOrDefault() ?? "https://localhost:5001/") : "https://localhost:5001";
+            SourceUrl = addresses is not null ? (addresses.FirstOrDefault() ?? "https://localhost:5001/hello") : "https://localhost:5001/hello";
             // 无 VM,用自身当 VM
             DataContext = this;
         }

+ 7 - 2
IES.ExamServer/appsettings.json

@@ -9,11 +9,16 @@
   "Kestrel": {
     "Endpoints": {
       "Http": {
-        "Url": "http://localhost:5000"
+        "Url": "http://*:5000"
       },
       "Https": {
-        "Url": "https://localhost:5001"
+        "Url": "https://*:5001"
       }
     }
+  },
+  "ExamServer": {
+    "Timeout": 30000,
+    "Delay": 500,
+    "CenterUrl": "https://www.teammodel.cn"
   }
 }