IndexController.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. using IES.ExamServer.Models;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.Extensions.Caching.Memory;
  4. using System.Diagnostics;
  5. using System.Text.Json.Nodes;
  6. using System.Text.Json;
  7. using IES.ExamServer.Helper;
  8. using System.IdentityModel.Tokens.Jwt;
  9. using IES.ExamServer.Services;
  10. using IES.ExamServer.DI;
  11. using IES.ExamServer.Helpers;
  12. using IES.ExamLibrary.Models;
  13. using System.Threading.Tasks;
  14. using Hardware.Info;
  15. using System.Net.NetworkInformation;
  16. namespace IES.ExamServer.Controllers
  17. {
  18. [ApiController]
  19. [Route("index")]
  20. public class IndexController : BaseController
  21. {
  22. private readonly IConfiguration _configuration;
  23. private readonly IHttpClientFactory _httpClientFactory;
  24. private readonly IMemoryCache _memoryCache;
  25. private readonly ILogger<IndexController> _logger;
  26. private readonly CenterServiceConnectionService _connectionService;
  27. private readonly LiteDBFactory _liteDBFactory;
  28. private readonly IHostApplicationLifetime _hostApplicationLifetime;
  29. public IndexController(ILogger<IndexController> logger, IConfiguration configuration, IHttpClientFactory httpClientFactory,
  30. IMemoryCache memoryCache,CenterServiceConnectionService connectionService, LiteDBFactory liteDBFactory, IHostApplicationLifetime hostApplicationLifetime)
  31. {
  32. _hostApplicationLifetime = hostApplicationLifetime;
  33. _logger = logger;
  34. _configuration=configuration;
  35. _httpClientFactory=httpClientFactory;
  36. _memoryCache=memoryCache;
  37. _connectionService=connectionService;
  38. _liteDBFactory=liteDBFactory;
  39. }
  40. [HttpGet("hardware")]
  41. public IActionResult hardware()
  42. {
  43. IHardwareInfo? hardwareInfo = null;
  44. try
  45. {
  46. hardwareInfo = new HardwareInfo();
  47. //hardwareInfo.RefreshOperatingSystem();
  48. //.....
  49. //刷新所有硬件信息
  50. hardwareInfo.RefreshAll();
  51. }
  52. catch (Exception ex)
  53. {
  54. Console.WriteLine(ex);
  55. }
  56. Console.WriteLine("输出操作系统信息" + Environment.NewLine);
  57. Console.WriteLine(hardwareInfo.OperatingSystem);
  58. Console.WriteLine("输出内存状态信息" + Environment.NewLine);
  59. Console.WriteLine(hardwareInfo.MemoryStatus);
  60. Console.WriteLine("输出电池信息" + Environment.NewLine);
  61. foreach (var hardware in hardwareInfo.BatteryList)
  62. Console.WriteLine(hardware);
  63. Console.WriteLine("输出 BIOS 信息" + Environment.NewLine);
  64. foreach (var hardware in hardwareInfo.BiosList)
  65. Console.WriteLine(hardware);
  66. Console.WriteLine("输出计算机系统信息" + Environment.NewLine);
  67. foreach (var hardware in hardwareInfo.ComputerSystemList)
  68. Console.WriteLine(hardware);
  69. Console.WriteLine("输出 CPU 信息" + Environment.NewLine);
  70. foreach (var cpu in hardwareInfo.CpuList)
  71. {
  72. Console.WriteLine(cpu);
  73. Console.WriteLine("输出 CPU 核心信息" + Environment.NewLine);
  74. foreach (var cpuCore in cpu.CpuCoreList)
  75. Console.WriteLine(cpuCore);
  76. }
  77. Console.WriteLine("输出磁盘驱动器信息" + Environment.NewLine);
  78. foreach (var drive in hardwareInfo.DriveList)
  79. {
  80. Console.WriteLine(drive);
  81. Console.WriteLine("输出驱动器分区信息" + Environment.NewLine);
  82. foreach (var partition in drive.PartitionList)
  83. {
  84. Console.WriteLine(partition);
  85. Console.WriteLine("输出分区卷信息" + Environment.NewLine);
  86. foreach (var volume in partition.VolumeList)
  87. Console.WriteLine(volume);
  88. }
  89. }
  90. Console.WriteLine("输出键盘信息" + Environment.NewLine);
  91. foreach (var hardware in hardwareInfo.KeyboardList)
  92. Console.WriteLine(hardware);
  93. Console.WriteLine("输出内存信息" + Environment.NewLine);
  94. foreach (var hardware in hardwareInfo.MemoryList)
  95. Console.WriteLine(hardware);
  96. Console.WriteLine("输出显示器信息" + Environment.NewLine);
  97. foreach (var hardware in hardwareInfo.MonitorList)
  98. Console.WriteLine(hardware);
  99. Console.WriteLine("输出主板信息" + Environment.NewLine);
  100. foreach (var hardware in hardwareInfo.MotherboardList)
  101. Console.WriteLine(hardware);
  102. Console.WriteLine("输出鼠标信息" + Environment.NewLine);
  103. foreach (var hardware in hardwareInfo.MouseList)
  104. Console.WriteLine(hardware);
  105. Console.WriteLine("输出网络适配器信息" + Environment.NewLine);
  106. foreach (var hardware in hardwareInfo.NetworkAdapterList)
  107. Console.WriteLine(hardware);
  108. Console.WriteLine("输出打印机信息" + Environment.NewLine);
  109. foreach (var hardware in hardwareInfo.PrinterList)
  110. Console.WriteLine(hardware);
  111. Console.WriteLine("输出声音设备信息" + Environment.NewLine);
  112. foreach (var hardware in hardwareInfo.SoundDeviceList)
  113. Console.WriteLine(hardware);
  114. Console.WriteLine("输出显卡信息" + Environment.NewLine);
  115. foreach (var hardware in hardwareInfo.VideoControllerList)
  116. Console.WriteLine(hardware);
  117. Console.WriteLine("输出 Ethernet 类型并且状态为 Up 的本地 IPv4 地址" + Environment.NewLine);
  118. foreach (var address in HardwareInfo.GetLocalIPv4Addresses(NetworkInterfaceType.Ethernet, OperationalStatus.Up))
  119. Console.WriteLine(address);
  120. Console.WriteLine();
  121. Console.WriteLine("输出 Wireless80211 类型的本地 IPv4 地址" + Environment.NewLine);
  122. foreach (var address in HardwareInfo.GetLocalIPv4Addresses(NetworkInterfaceType.Wireless80211))
  123. Console.WriteLine(address);
  124. Console.WriteLine();
  125. Console.WriteLine("输出状态为 Up 的网络接口卡的本地 IPv4 地址" + Environment.NewLine);
  126. foreach (var address in HardwareInfo.GetLocalIPv4Addresses(OperationalStatus.Up))
  127. Console.WriteLine(address);
  128. Console.WriteLine();
  129. Console.WriteLine("输出所有网络接口卡的本地 IPv4 地址" + Environment.NewLine);
  130. foreach (var address in HardwareInfo.GetLocalIPv4Addresses())
  131. Console.WriteLine(address);
  132. Console.WriteLine();
  133. Console.WriteLine("输出计算机当前时间" + Environment.NewLine);
  134. Console.WriteLine(DateTime.Now);
  135. Console.WriteLine("输出系统启动时间" + Environment.NewLine);
  136. Console.WriteLine(Environment.TickCount);
  137. return Ok();
  138. }
  139. /// <summary>
  140. /// 关闭当前进程的接口
  141. /// </summary>
  142. /// <returns></returns>
  143. [HttpGet("shutdown")]
  144. public IActionResult Shutdown(int delayMilliseconds = 200)
  145. {
  146. try
  147. {
  148. _ = Task.Run(async () =>
  149. {
  150. try
  151. {
  152. await Task.Delay(delayMilliseconds);
  153. _hostApplicationLifetime.StopApplication();
  154. }
  155. catch (Exception ex)
  156. {
  157. Console.Error.WriteLine($"Error during shutdown: {ex.Message}");
  158. }
  159. });
  160. return Ok("Shutdown process has been initiated.");
  161. }
  162. catch (Exception ex)
  163. {
  164. return StatusCode(500, $"Failed to initiate the shutdown process: {ex.Message}");
  165. }
  166. }
  167. [HttpGet("nowtime")]
  168. public async Task<IActionResult> NowTime()
  169. {
  170. if (_connectionService.centerIsConnected)
  171. {
  172. HttpResponseMessage response = await _httpClientFactory.CreateClient().GetAsync($"{_connectionService.centerUrl}/core/nowtime");
  173. if (response.IsSuccessStatusCode)
  174. {
  175. string content = await response.Content.ReadAsStringAsync();
  176. return Ok(content);
  177. }
  178. else {
  179. DateTimeOffset utc = DateTimeOffset.UtcNow;
  180. long timeStampUTC = utc.ToUnixTimeMilliseconds();
  181. return Ok(new { time = timeStampUTC });
  182. }
  183. }
  184. else {
  185. DateTimeOffset utc = DateTimeOffset.UtcNow;
  186. long timeStampUTC = utc.ToUnixTimeMilliseconds();
  187. return Ok(new { time = timeStampUTC });
  188. }
  189. }
  190. [HttpGet("health")]
  191. public IActionResult Health()
  192. {
  193. return Ok(new { code=200});
  194. }
  195. [HttpPost("generate-certificate")]
  196. public async Task<IActionResult> GenerateCertificate(JsonNode json)
  197. {
  198. try {
  199. ServerDevice serverDevice = _memoryCache.Get<ServerDevice>(Constant._KeyServerDevice);
  200. if (serverDevice!=null && serverDevice.networks.IsNotEmpty())
  201. {
  202. string mac = $"{json["mac"]}";
  203. var network = serverDevice.networks.Find(x => mac.Equals(x.mac));
  204. if (network!=null)
  205. {
  206. string pathBat = Path.Combine(Directory.GetCurrentDirectory(), "Configs", "cer", "certificate.bat");
  207. string pathCer = Path.Combine(Directory.GetCurrentDirectory(), "Configs", "cer", "certificate.cer");
  208. string text = await System.IO.File.ReadAllTextAsync(pathBat);
  209. text = text.Replace("192.168.8.132", network.ip);
  210. string pathCertificateBat = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "certificate.bat");
  211. await System.IO.File.WriteAllTextAsync(pathCertificateBat, text);
  212. string pathCertificateCer = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "certificate.cer");
  213. System.IO.File.Copy(pathCer, pathCertificateCer);
  214. return Ok(new { code = 200, msg = "生成成功。", bat = "package/certificate.bat", cer = "package/certificate.cer" });
  215. }
  216. else
  217. {
  218. msg="未找到匹配的网卡设备。";
  219. }
  220. }
  221. else
  222. {
  223. msg="服务端设备未找到,或网卡设备不存在。";
  224. }
  225. } catch (Exception ex)
  226. {
  227. _logger.LogError($"生成证书和自定义域名映射脚本错误。{ex.Message},{ex.StackTrace}");
  228. msg=$"服务端错误,{ex.Message}";
  229. }
  230. return Ok(new { code = 400, msg = msg });
  231. }
  232. [HttpPost("list-schools")]
  233. public async Task<IActionResult> ListSchool(JsonNode json)
  234. {
  235. string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "schools.json");
  236. string schoolText = await System.IO.File.ReadAllTextAsync(filePath);
  237. JsonNode? node = schoolText.ToObject<JsonNode>();
  238. return Ok(new {code =200, schools= node?["schools"] });
  239. }
  240. [HttpPost("bind-school")]
  241. public async Task<IActionResult> BindSchool(JsonNode json)
  242. {
  243. string id=$"{json["id"]}";
  244. string name= $"{json["name"]}";
  245. string fp = $"{json["fp"]}";
  246. if (!string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(name) && !string.IsNullOrWhiteSpace(fp))
  247. {
  248. string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package", "schools.json");
  249. string schoolText = await System.IO.File.ReadAllTextAsync(filePath);
  250. List<School>? schools = schoolText.ToObject<JsonNode>()?["schools"]?.ToObject<List<School>>();
  251. School? school = schools?.Find(x => id.Equals(x.id) && name.Equals(x.name));
  252. if (school!=null)
  253. {
  254. _liteDBFactory.GetLiteDatabase().GetCollection<School>().DeleteAll();
  255. _liteDBFactory.GetLiteDatabase().GetCollection<School>().Upsert(school);
  256. IEnumerable<School> schoolsDb = _liteDBFactory.GetLiteDatabase().GetCollection<School>().FindAll();
  257. School? schoolDb = schools?.FirstOrDefault();
  258. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  259. if (server!=null)
  260. {
  261. server.school = school;
  262. }
  263. string ip = GetIP();
  264. var device = IndexService.GetDeviceInit(HttpContext, $"{fp}", ip, _memoryCache);
  265. int hybrid = 0;
  266. _memoryCache.Set(Constant._KeyServerDevice, server);
  267. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  268. _memoryCache.TryGetValue(Constant._KeyServerDevice, out server);
  269. if (data!=null)
  270. {
  271. hybrid=1;
  272. msg="云端服务连接成功!";
  273. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = data["centerUrl"], region = data["region"], ip = data["ip"], nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  274. }
  275. else
  276. {
  277. msg="云端服务未连接!";
  278. return Ok(new { code = 200, msg, data = new { hybrid, device, centerUrl = "", region = "局域网·内网", ip = ip, nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(), server } });
  279. }
  280. }
  281. else
  282. {
  283. return Ok(new { code = 400, msg = "绑定失败!" });
  284. }
  285. }
  286. else {
  287. return Ok(new { code = 400, msg = "参数错误!" });
  288. }
  289. }
  290. [HttpPost("device")]
  291. public IActionResult Device(JsonElement json )
  292. {
  293. try
  294. {
  295. string ip= GetIP();
  296. json.TryGetProperty("fp", out JsonElement fp);
  297. var device = IndexService.GetDeviceInit(HttpContext, $"{fp}", ip, _memoryCache);
  298. int hybrid = 0, notify = 0 ;
  299. _memoryCache.TryGetValue(Constant._KeyServerCenter, out JsonNode? data);
  300. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  301. if (_connectionService.notifyIsConnected)
  302. {
  303. notify=1;
  304. }
  305. if (_connectionService.centerIsConnected)
  306. {
  307. hybrid=1;
  308. }
  309. msg="服务端检测成功!";
  310. return Ok(new { code = 200, msg, data = new {
  311. notify,
  312. hybrid,
  313. device,
  314. centerUrl = hybrid==1 ? _connectionService.centerUrl : "",
  315. notifyUrl = notify==1 ? _connectionService.notifyUrl : "",
  316. region = data?["region"],
  317. ip = data!=null ? data?["ip"] : ip,
  318. nowtime = DateTimeOffset.Now.ToUnixTimeMilliseconds(),
  319. server
  320. } });
  321. }
  322. catch (Exception ex)
  323. {
  324. code=500;
  325. msg="服务端异常!";
  326. }
  327. return Ok(new { code, msg });
  328. }
  329. /**
  330. {
  331. "type":"sms",//qrcode二维码扫码登录:randomCode必传; sms 短信验证登录:randomCode必传,mobile必传
  332. "randomCode",
  333. "mobile":"1528377****"
  334. }
  335. **/
  336. /// <summary>
  337. /// 登录验证
  338. /// </summary>
  339. /// <param name="randomCode"></param>
  340. /// <returns></returns>
  341. [HttpPost("login-check")]
  342. public async Task<IActionResult> LoginCheck(JsonNode json)
  343. {
  344. try
  345. {
  346. var type = json["type"];
  347. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  348. if (!string.IsNullOrWhiteSpace($"{type}"))
  349. {
  350. TmdidImplicit? token = null;
  351. string x_auth_token = string.Empty;
  352. List<School>? schools = null;
  353. JsonNode? jsonNode = null;
  354. long time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
  355. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  356. School? school = null;
  357. if (server!=null)
  358. {
  359. school = server.school;
  360. }
  361. switch (true)
  362. {
  363. //跳过忽略,但是仍然要以访客身份登录
  364. case bool when $"{type}".Equals(ExamConstant.ScopeVisitor):
  365. {
  366. string id = $"{DateTimeOffset.Now.ToUnixTimeSeconds()}";
  367. string name = $"{school?.name}教师-{Random.Shared.Next(100, 999)}";
  368. x_auth_token = JwtAuthExtension.CreateAuthToken("www.teammodel.cn",id ,name,picture: school?.picture
  369. , ExamConstant.JwtSecretKey,ExamConstant.ScopeVisitor,8,schoolID:school?.id,new string[] { "visitor" }, expire: 1);
  370. // _memoryCache.Set($"Teacher:{id}", new Teacher { id = id, name = $"{name}", implicit_token = token, picture = null, schools = schools, x_auth_token = x_auth_token });
  371. _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().Upsert(new Teacher { id = id, name = $"{name}", implicit_token = token, picture = null, schools = schools, x_auth_token = x_auth_token,loginTime=time });
  372. return Ok(new { code = 200,x_auth_token = x_auth_token });
  373. }
  374. case bool when $"{type}".Equals("qrcode"):
  375. {
  376. string randomCode = $"{json["randomCode"]}";
  377. System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
  378. var rc= _memoryCache.Get<string>($"Login:ExamServer:{school?.id}:{randomCode}");
  379. if (!string.IsNullOrWhiteSpace(rc))
  380. {
  381. var response = await _httpClientFactory.CreateClient().GetAsync($"{CenterUrl}/core/qrcode/check?randomcode={randomCode}&school={school?.id}&client=ExamServer");
  382. if (response.IsSuccessStatusCode)
  383. {
  384. string content = await response.Content.ReadAsStringAsync();
  385. if (!string.IsNullOrWhiteSpace(content))
  386. {
  387. jsonNode = content.ToObject<JsonNode>();
  388. }
  389. else
  390. {
  391. code=400;
  392. msg="随机码验证失败";
  393. }
  394. }
  395. else
  396. {
  397. code=400;
  398. msg="随机码验证错误";
  399. }
  400. }
  401. else
  402. {
  403. code=400;
  404. msg="二维码过期";
  405. }
  406. break;
  407. }
  408. case bool when $"{type}".Equals("smspin"):
  409. {
  410. string pin_code = $"{json["pin_code"]}";
  411. string account = $"{json["account"]}";
  412. var response = await _httpClientFactory.CreateClient().PostAsJsonAsync($"{CenterUrl}/core/sendsms/check", new { pin_code, account,school=school?.id });
  413. if (response.IsSuccessStatusCode)
  414. {
  415. string content = await response.Content.ReadAsStringAsync();
  416. if (!string.IsNullOrWhiteSpace(content))
  417. {
  418. jsonNode = content.ToObject<JsonNode>();
  419. }
  420. else
  421. {
  422. code=400;
  423. msg="短信验证返回结果为空";
  424. }
  425. }
  426. else
  427. {
  428. code=400;
  429. msg="短信验证错误";
  430. }
  431. break;
  432. }
  433. }
  434. if (jsonNode != null && $"{jsonNode["code"]}".Equals("200"))
  435. {
  436. token =jsonNode["implicit_token"]?.ToObject<TmdidImplicit>();
  437. x_auth_token = $"{jsonNode["x_auth_token"]}";
  438. schools =jsonNode["schools"]?.ToObject<List<School>>();
  439. var jwt = new JwtSecurityToken(token?.id_token);
  440. var id = jwt.Payload.Sub;
  441. jwt.Payload.TryGetValue("name", out object? name);
  442. jwt.Payload.TryGetValue("picture", out object? picture);
  443. //_memoryCache.Set($"Teacher:{id}", new Teacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token });
  444. _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().Upsert(new Teacher { id=id, name=$"{name}", implicit_token= token, picture=$"{picture}", schools=schools, x_auth_token=x_auth_token ,loginTime=time });
  445. return Ok(new { code=200,/* implicit_token = token, schools = schools , */ x_auth_token = x_auth_token });
  446. }
  447. else
  448. {
  449. code=400;
  450. msg="验证失败";
  451. }
  452. }
  453. else
  454. {
  455. code=400;
  456. msg="参数错误";
  457. }
  458. }
  459. catch (Exception ex)
  460. {
  461. code=500;
  462. msg="异常错误";
  463. }
  464. return Ok(new { code = code,msg });
  465. }
  466. /*
  467. */
  468. /// <summary>
  469. /// 登录模式初始化
  470. /// </summary>
  471. /// <returns></returns>
  472. [HttpPost("login-init")]
  473. public async Task<IActionResult> LoginInit(JsonNode json)
  474. {
  475. var type = json["type"];
  476. string qrcode = string.Empty;
  477. string randomcode = "";
  478. _memoryCache.TryGetValue(Constant._KeyServerDevice, out ServerDevice? server);
  479. School? school = null;
  480. if (server != null)
  481. {
  482. school = server.school;
  483. }
  484. if (school != null)
  485. {
  486. switch (true)
  487. {
  488. case bool when $"{type}".Equals("qrcode"):
  489. {
  490. //.NET Core使用SkiaSharp快速生成二维码 https://cloud.tencent.com/developer/article/2336486
  491. // 生成二维码图片
  492. Random random = new Random();
  493. randomcode = $"{random.Next(1000, 9999)}";
  494. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  495. CenterUrl = CenterUrl.Equals("https://localhost:5001") ? "https://www.teammodel.cn" : CenterUrl;
  496. string content = $"{CenterUrl}/qrcodelogin?randomcode=Login:ExamServer:{school?.id}:{randomcode}&m=%E6%89%AB%E7%A0%81%E7%99%BB%E5%BD%95&o=1";
  497. var str = QRCodeHelper.GenerateQRCode(content, 300, 300, QRCodeHelper.logo);
  498. qrcode = $"data:image/png;base64,{str}";
  499. int ttl = 180;
  500. string key = $"Login:ExamServer:{school?.id}:{randomcode}";
  501. _memoryCache.Set(key, randomcode, TimeSpan.FromSeconds(ttl));
  502. var device =IndexService.GetDevice(HttpContext,_memoryCache);
  503. _memoryCache.Set($"device:{key}", device);
  504. try {
  505. if (_connectionService.notifyIsConnected && _connectionService.serverDevice!=null)
  506. {
  507. string url = $"{_connectionService.notifyUrl!}/third/ies/qrcode-login-register";
  508. //扫描登录,远端设备登记临时随机码
  509. await _httpClientFactory.CreateClient().PostAsJsonAsync(url,new { randomcode= key, deviceid = _connectionService .serverDevice.deviceId});
  510. }
  511. } catch (Exception e) {
  512. _logger.LogError($"{e.Message},{e.StackTrace}");
  513. }
  514. return Ok(new { ttl,code = 200, randomCode = randomcode, qrcode, type });
  515. }
  516. //case bool when $"{type}".Equals("xqrcode"):
  517. // {
  518. // // 生成二维码图片
  519. // Random random = new Random();
  520. // randomcode = $"{random.Next(1000, 9999)}";
  521. // string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  522. // CenterUrl = CenterUrl.Equals("https://localhost:5001") ? "https://www.teammodel.cn" : CenterUrl;
  523. // string content = $"{CenterUrl}/qrcodelogin?randomcode=Login:ExamServer:{school?.id}:{randomcode}&m=%E6%89%AB%E7%A0%81%E7%99%BB%E5%BD%95&o=1";
  524. // Bitmap qrCodeImage = QRCodeHelper.GetBitmap(content, 200, 200);
  525. // using (MemoryStream stream = new MemoryStream())
  526. // {
  527. // qrCodeImage.Save(stream, ImageFormat.Png);
  528. // byte[] data = stream.ToArray();
  529. // qrcode = $"data:image/png;base64,{Convert.ToBase64String(data)}";
  530. // }
  531. // int ttl = 60;
  532. // _memoryCache.Set($"Login:ExamServer:{school?.id}:{randomcode}", randomcode, TimeSpan.FromSeconds(ttl));
  533. // return Ok(new {ttl, code = 200, randomCode = randomcode, qrcode, type });
  534. // }
  535. case bool when $"{type}".Equals("smspin"):
  536. {
  537. int send = 0;
  538. if (!string.IsNullOrWhiteSpace($"{json["area"]}") && !string.IsNullOrWhiteSpace($"{json["to"]}"))
  539. {
  540. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  541. string url = $"{CenterUrl}/core/sendsms/pin";
  542. HttpResponseMessage message = await _httpClientFactory.CreateClient().PostAsJsonAsync(url, new { area = json["area"], to = json["to"], lang = "zh-cn" });
  543. if (message.IsSuccessStatusCode)
  544. {
  545. string content = await message.Content.ReadAsStringAsync();
  546. JsonNode? jsonNode = content?.ToObject<JsonNode>();
  547. if (jsonNode != null && int.TryParse($"{jsonNode["send"]}", out int s))
  548. {
  549. send = s;
  550. }
  551. }
  552. }
  553. return Ok(new { code = 200, send, type });
  554. }
  555. }
  556. }
  557. else if (school == null)
  558. {
  559. return Ok(new { code = 400,msg="未绑定学校" });
  560. }
  561. return Ok(new { code = 400 });
  562. }
  563. }
  564. }