ManageController.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. using ICSharpCode.SharpZipLib.GZip;
  2. using IES.ExamLibrary.Models;
  3. using IES.ExamServer.DI;
  4. using IES.ExamServer.DI.SignalRHost;
  5. using IES.ExamServer.Filters;
  6. using IES.ExamServer.Helper;
  7. using IES.ExamServer.Helpers;
  8. using IES.ExamServer.Models;
  9. using IES.ExamServer.Services;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.AspNetCore.SignalR;
  12. using Microsoft.Extensions.Caching.Memory;
  13. using Microsoft.Extensions.Configuration;
  14. using System;
  15. using System.Diagnostics.Eventing.Reader;
  16. using System.Linq.Expressions;
  17. using System.Net.Http;
  18. using System.Net.Http.Json;
  19. using System.Security.Cryptography.X509Certificates;
  20. using System.Text.Json;
  21. using System.Text.Json.Nodes;
  22. using System.Text.RegularExpressions;
  23. using static IES.ExamServer.Services.ManageService;
  24. using static System.Reflection.Metadata.BlobBuilder;
  25. namespace IES.ExamServer.Controllers
  26. {
  27. [ApiController]
  28. [Route("manage")]
  29. public class ManageController : BaseController
  30. {
  31. private readonly IConfiguration _configuration;
  32. private readonly IHttpClientFactory _httpClientFactory;
  33. private readonly IMemoryCache _memoryCache;
  34. private readonly ILogger<ManageController> _logger;
  35. private readonly LiteDBFactory _liteDBFactory;
  36. private readonly CenterServiceConnectionService _connectionService;
  37. private readonly int DelayMicro = 10;//微观数据延迟
  38. private readonly int DelayMacro = 100;//宏观数据延迟
  39. private readonly IHubContext<SignalRExamServerHub> _signalRExamServerHub;
  40. public ManageController(LiteDBFactory liteDBFactory, ILogger<ManageController> logger, IConfiguration configuration,
  41. IHttpClientFactory httpClientFactory, IMemoryCache memoryCache, CenterServiceConnectionService connectionService, IHubContext<SignalRExamServerHub> signalRExamServerHub)
  42. {
  43. _logger = logger;
  44. _configuration=configuration;
  45. _httpClientFactory=httpClientFactory;
  46. _memoryCache=memoryCache;
  47. _liteDBFactory=liteDBFactory;
  48. _connectionService=connectionService;
  49. _signalRExamServerHub=signalRExamServerHub;
  50. }
  51. ///通过线上回传数据需要鉴权验证等操作。
  52. ///通过离线包回传数据需要加密操作
  53. /// <summary>
  54. /// 清理缓存,列出缓存占用空间,type =list列出,type=clear清理,不能清理近期及正在激活的数据,并且提示清理中暂未上传或者导出的数据。
  55. /// </summary>
  56. /// <param name="json"></param>
  57. /// <returns></returns>
  58. [HttpPost("clean-cache")]
  59. [AuthToken("admin", "teacher", "visitor")]
  60. public async Task<IActionResult> CleanCache(JsonNode json)
  61. {
  62. return Ok();
  63. }
  64. //C#.NET 6 后端与前端流式通信
  65. //https://www.doubao.com/chat/collection/687687510791426?type=Thread
  66. //下载日志记录:1.步骤,检查,2.获取描述信息,3.分类型,4下载文件,5.前端处理,6.返回结果 , 正在下载...==> [INFO]https://www.doubao.com/chat/collection/687687510791426?type=Thread [Size=180kb] Ok...
  67. //进度条 展示下载文件总大小和已下载,末尾展示 文件总个数和已下载个数
  68. //https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.7/signalr.min.js
  69. /* int data = 0,blob=0, groupList=0
  70. {
  71. "evaluationId":"idssss",
  72. "shortCode":"1234567890",
  73. "ownerId":"hbcn/tmdid",
  74. "data":1,
  75. "blob":1,
  76. "groupList":1
  77. }
  78. */
  79. //如果要访问中心,则需要教师登录联网。
  80. [HttpPost("download-package")]
  81. [AuthToken("admin", "teacher", "visitor")]
  82. public async Task<IActionResult> DownloadPackage(JsonNode json)
  83. {
  84. var token = GetAuthTokenInfo();
  85. //检查试卷文件完整性
  86. List<string> successMsgs = new List<string>();
  87. List<string> errorMsgs = new List<string>();
  88. EvaluationCheckFileResult result = new EvaluationCheckFileResult() { successMsgs=successMsgs, errorMsgs=errorMsgs };
  89. if (token.scope.Equals(ExamConstant.ScopeTeacher) || token.scope.Equals(ExamConstant.ScopeVisitor))
  90. {
  91. if (_connectionService.centerIsConnected)
  92. {
  93. Teacher? teacher = _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().FindOne(x => x.id!.Equals(token.id));
  94. string id = $"{json["evaluationId"]}";
  95. string shortCode = $"{json["shortCode"]}";
  96. string deviceId = $"{json["deviceId"]}";
  97. EvaluationClient? evaluationClient = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().FindOne(x => x.id!.Equals(id) && x.shortCode!.Equals(shortCode));
  98. if (teacher != null && evaluationClient!= null)
  99. {
  100. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  101. var client = _httpClientFactory.CreateClient();
  102. if (client.DefaultRequestHeaders.Contains(Constant._X_Auth_AuthToken))
  103. {
  104. client.DefaultRequestHeaders.Remove(Constant._X_Auth_AuthToken);
  105. }
  106. client.DefaultRequestHeaders.Add(Constant._X_Auth_AuthToken, teacher.x_auth_token);
  107. HttpResponseMessage message = await client.PostAsJsonAsync($"{CenterUrl}/blob/sas-read", new { containerName = $"{evaluationClient.ownerId}" });
  108. string sas = string.Empty;
  109. string url = string.Empty;
  110. string cnt = string.Empty;
  111. if (message.IsSuccessStatusCode)
  112. {
  113. //url sas timeout name
  114. string content = await message.Content.ReadAsStringAsync();
  115. JsonNode? jsonNode = content.ToObject<JsonNode>();
  116. if (jsonNode != null)
  117. {
  118. sas = $"{jsonNode["sas"]}";
  119. cnt = $"{jsonNode["name"]}";
  120. url = $"{jsonNode["url"]}";
  121. }
  122. }
  123. var httpClient = _httpClientFactory.CreateClient();
  124. string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package");
  125. string evaluationPath = Path.Combine(packagePath, evaluationClient.id!);
  126. //删除文件夹
  127. FileHelper.DeleteFolder(evaluationPath);
  128. string evaluationDataPath = Path.Combine(evaluationPath, "data");
  129. if (!Directory.Exists(evaluationDataPath))
  130. {
  131. Directory.CreateDirectory(evaluationDataPath);
  132. }
  133. string evaluationData = string.Empty;
  134. {
  135. //evaluation
  136. string evaluationUrl = $"{url}/{cnt}/package/{json["evaluationId"]}/data/evaluation.json?{sas}";
  137. HttpResponseMessage dataMessage = await httpClient.GetAsync(evaluationUrl);
  138. if (dataMessage.IsSuccessStatusCode)
  139. {
  140. var content = await dataMessage.Content.ReadAsStringAsync();
  141. evaluationData=content;
  142. string path_evaluation = Path.Combine(evaluationDataPath, "evaluation.json");
  143. await System.IO.File.WriteAllTextAsync(path_evaluation, content);
  144. successMsgs.Add("评测信息文件evaluation.json文件下载成功!");
  145. }
  146. else
  147. {
  148. errorMsgs.Add("评测信息文件evaluation.json文件下载失败!");
  149. }
  150. }
  151. {
  152. //source.json
  153. string sourceUrl = $"{url}/{cnt}/package/{json["evaluationId"]}/data/source.json?{sas}";
  154. HttpResponseMessage dataMessage = await httpClient.GetAsync(sourceUrl);
  155. if (dataMessage.IsSuccessStatusCode)
  156. {
  157. var content = await dataMessage.Content.ReadAsStringAsync();
  158. string path_source = Path.Combine(evaluationDataPath, "source.json");
  159. await System.IO.File.WriteAllTextAsync(path_source, content);
  160. successMsgs.Add("评测数据原始文件source.json文件下载成功!");
  161. }
  162. else
  163. {
  164. errorMsgs.Add("评测数据原始文件source.json文件下载失败!");
  165. }
  166. }
  167. {
  168. //grouplist.json
  169. string grouplistUrl = $"{url}/{cnt}/package/{json["evaluationId"]}/data/grouplist.json?{sas}";
  170. HttpResponseMessage groupListMessage = await httpClient.GetAsync(grouplistUrl);
  171. if (groupListMessage.IsSuccessStatusCode)
  172. {
  173. var content = await groupListMessage.Content.ReadAsStringAsync();
  174. string path_groupList = Path.Combine(evaluationDataPath, "grouplist.json");
  175. await System.IO.File.WriteAllTextAsync(path_groupList, content);
  176. successMsgs.Add("评测名单grouplist.json文件下载成功!");
  177. }
  178. else
  179. {
  180. errorMsgs.Add("评测名单grouplist.json文件下载失败!");
  181. }
  182. }
  183. {
  184. //下载试卷文件
  185. List<EvaluationExam>? evaluationExams = evaluationData.ToObject<JsonNode>()?["evaluationExams"]?.ToObject<List<EvaluationExam>>();
  186. foreach (var evaluationExam in evaluationExams!)
  187. {
  188. foreach (var evaluationPaper in evaluationExam.papers)
  189. {
  190. string path_paper = Path.Combine(evaluationPath, $"papers/{evaluationPaper.paperId}");
  191. if (!Directory.Exists(path_paper))
  192. {
  193. Directory.CreateDirectory(path_paper);
  194. }
  195. //最多开启10个线程并行下载
  196. var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = 20 };
  197. // 使用 Parallel.ForEachAsync 并行处理每个 blob
  198. await Parallel.ForEachAsync(evaluationPaper.blobs, parallelOptions, async (blob, cancellationToken) =>
  199. {
  200. try
  201. {
  202. // 下载 Blob 文件到本地
  203. HttpResponseMessage blobMessage = await httpClient.GetAsync($"{url}/{cnt}/{blob.path}?{sas}", cancellationToken);
  204. if (blobMessage.IsSuccessStatusCode)
  205. {
  206. byte[] bytes = await blobMessage.Content.ReadAsByteArrayAsync(cancellationToken);
  207. string? extension = Path.GetExtension(blob.path);
  208. if (extension!=null)
  209. {
  210. if (extension.Equals(extension.ToUpper()))
  211. {
  212. string? fileNameWithoutExtension = Path.GetFileNameWithoutExtension(blob.path);
  213. await System.IO.File.WriteAllBytesAsync(Path.Combine(path_paper, $"{fileNameWithoutExtension!}_1{extension}"), bytes, cancellationToken);
  214. }
  215. else
  216. {
  217. string? fileName = Path.GetFileName(blob.path);
  218. await System.IO.File.WriteAllBytesAsync(Path.Combine(path_paper, fileName!), bytes, cancellationToken);
  219. }
  220. }
  221. }
  222. else
  223. {
  224. string? error = await blobMessage.Content.ReadAsStringAsync(cancellationToken);
  225. errorMsgs.Add($"{evaluationExam.subjectName},{evaluationPaper.paperName},{blob.path}文件下载失败,{blobMessage.StatusCode},{error}");
  226. // Console.WriteLine($"Error downloading {blob.path},{blobMessage.StatusCode},{error}");
  227. }
  228. }
  229. catch (Exception ex)
  230. {
  231. errorMsgs.Add($"{evaluationExam.subjectName},{evaluationPaper.paperName},{blob.path}文件下载错误,{ex.Message}");
  232. // 处理异常
  233. //Console.WriteLine($"Error downloading {blob.path}: {ex.Message}");
  234. }
  235. });
  236. }
  237. }
  238. }
  239. (successMsgs, errorMsgs) = await ManageService.CheckFile(evaluationClient, successMsgs, errorMsgs, _signalRExamServerHub, _memoryCache, _logger, deviceId, evaluationPath);
  240. //下载完成后,对数据进行检查,然后在加密压缩。
  241. string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "zip");
  242. if (!Directory.Exists(zipPath))
  243. {
  244. Directory.CreateDirectory(zipPath);
  245. }
  246. string zipFilePath = Path.Combine(zipPath, $"{evaluationClient.id}-{evaluationClient.blobHash}.zip");
  247. var zipInfo = ZipHelper.CreatePasswordProtectedZip(evaluationPath, zipFilePath, evaluationClient.openCode!);
  248. if (zipInfo.res)
  249. {
  250. successMsgs.Add("评测数据压缩包创建成功!");
  251. }
  252. else {
  253. errorMsgs.Add("评测数据压缩包创建失败!");
  254. }
  255. }
  256. else
  257. {
  258. string teacherMsg = teacher==null ? "未找到教师信息" : "";
  259. string evaluationMsg = evaluationClient==null ? "未找到评测信息" : "";
  260. errorMsgs.Add($"用户信息或未找到评测信息!{teacherMsg}{evaluationMsg}");
  261. }
  262. }
  263. else {
  264. errorMsgs.Add($"云端数据中心未连接");
  265. }
  266. }
  267. else
  268. {
  269. errorMsgs.Add($"请使用教师或访客账号登录!");
  270. }
  271. result.checkError=result.errorMsgs.Count();
  272. result.checkSuccess=result.successMsgs.Count();
  273. result.checkTotal=result.checkSuccess+result.checkError;
  274. if (result.errorMsgs.Count()==0)
  275. {
  276. return Ok(new { code = 200, msg = "下载成功!", result });
  277. }
  278. else {
  279. return Ok(new { code = 1, msg = "下载失败!", result });
  280. }
  281. }
  282. /// <summary>
  283. /// 输入开卷码,查询评测信息,并返回数据。
  284. /// </summary>
  285. /// <param name="json"></param>
  286. /// <returns></returns>
  287. [HttpPost("open-evaluation")]
  288. [AuthToken("admin", "teacher", "visitor")]
  289. public async Task<IActionResult> OpenEvaluation(JsonNode json)
  290. {
  291. string deviceId = $"{json["deviceId"]}";
  292. string evaluationId = $"{json["evaluationId"]}";
  293. string openCode = $"{json["openCode"]}";
  294. var token = GetAuthTokenInfo();
  295. List<string> successMsgs = new List<string>();
  296. List<string> errorMsgs = new List<string>();
  297. EvaluationCheckFileResult result = new EvaluationCheckFileResult() { successMsgs=successMsgs, errorMsgs =errorMsgs };
  298. if (!string.IsNullOrEmpty(openCode) && !string.IsNullOrEmpty(evaluationId))
  299. {
  300. EvaluationClient? evaluationLocal = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().FindOne(x => x.id!.Equals(evaluationId) && x.openCode!.Equals(openCode));
  301. if (evaluationLocal!=null)
  302. {
  303. await _signalRExamServerHub.SendMessage(_memoryCache, _logger, deviceId, Constant._Message_grant_type_check_file,
  304. new MessageContent { dataId=evaluationLocal.id, dataName=evaluationLocal.name, messageType=Constant._Message_type_message, status=0, content="开始检查评测信息文件.." });
  305. //判断文件包的压缩包是否存在。
  306. string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "zip");
  307. //校验本地文件数据
  308. string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package");
  309. string evaluationPath = Path.Combine(packagePath, evaluationLocal.id!);
  310. if (System.IO.File.Exists(Path.Combine(zipPath, $"{evaluationLocal.id}-{evaluationLocal.blobHash}.zip")))
  311. {
  312. successMsgs.Add("加载评测试卷文件包!");
  313. //删除文件夹
  314. FileHelper.DeleteFolder(evaluationPath);
  315. if (!Directory.Exists(evaluationPath))
  316. {
  317. Directory.CreateDirectory(evaluationPath);
  318. }
  319. //解压文件包
  320. var extractRes = ZipHelper.ExtractPasswordProtectedZip(Path.Combine(zipPath, $"{evaluationLocal.id}-{evaluationLocal.blobHash}.zip"), evaluationPath, evaluationLocal.openCode!);
  321. if (extractRes.res)
  322. {
  323. successMsgs.Add("评测试卷文件包解压成功!");
  324. (successMsgs, errorMsgs) = await ManageService.CheckFile(evaluationLocal, successMsgs, errorMsgs, _signalRExamServerHub, _memoryCache, _logger, deviceId, evaluationPath);
  325. }
  326. else {
  327. errorMsgs.Add("评测试卷文件包解压失败!");
  328. //return Ok(new { code = 3, msg = "评测试卷文件包解压失败!" });
  329. }
  330. }
  331. else {
  332. errorMsgs.Add("评测试卷文件包不存在!");
  333. //return Ok(new { code = 3, msg = "评测试卷文件包不存在!" });
  334. }
  335. }
  336. else {
  337. errorMsgs.Add("未找到评测信息!");
  338. // return Ok(new { code = 2, msg = "未找到评测信息!" });
  339. }
  340. }
  341. else
  342. {
  343. errorMsgs.Add("评测ID或提取码均未填写!");
  344. // return Ok(new { code = 1, msg = "评测ID或提取码均未填写!" });
  345. }
  346. result.checkTotal = result.errorMsgs.Count() + result.successMsgs.Count();
  347. result.checkError= result.errorMsgs.Count();
  348. result.checkSuccess = result.successMsgs.Count();
  349. if (result.errorMsgs.Count()==0)
  350. {
  351. return Ok(new { code = 200, msg = "校验成功!", result });
  352. }
  353. else
  354. {
  355. return Ok(new { code = 1, msg = "校验失败!", result });
  356. }
  357. }
  358. [HttpPost("check-evaluation")]
  359. [AuthToken("admin", "teacher", "visitor")]
  360. public async Task<IActionResult> CheckEvaluation(JsonNode json)
  361. {
  362. string shortCode = $"{json["shortCode"]}";
  363. string evaluationId = $"{json["evaluationId"]}";
  364. string checkCenter = $"{json["checkCenter"]}";
  365. string deviceId = $"{json["deviceId"]}";
  366. string centerCode = string.Empty, centerMsg = string.Empty;
  367. Expression<Func<EvaluationClient, bool>> predicate = x => true;
  368. var token = GetAuthTokenInfo();
  369. if (!string.IsNullOrEmpty(shortCode) || !string.IsNullOrEmpty(evaluationId))
  370. {
  371. if (!string.IsNullOrEmpty(shortCode))
  372. {
  373. predicate= predicate.And(x => !string.IsNullOrWhiteSpace(x.shortCode) && x.shortCode.Equals(shortCode));
  374. }
  375. if (!string.IsNullOrWhiteSpace(evaluationId))
  376. {
  377. predicate= predicate.And(x => x.id!.Equals(evaluationId));
  378. }
  379. }
  380. else
  381. {
  382. return Ok(new { code = 400, msg = "评测ID或提取码均未填写!" });
  383. }
  384. IEnumerable<EvaluationClient>? evaluationClients = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().Find(predicate);
  385. EvaluationClient? evaluationLocal = null;
  386. EvaluationClient? evaluationCloud = null;
  387. if (evaluationClients!=null && evaluationClients.Count()>0)
  388. {
  389. evaluationLocal= evaluationClients.First();
  390. }
  391. List<string> successMsgs = new List<string>();
  392. List<string> errorMsgs = new List<string>();
  393. //从数据中心搜索
  394. if ("1".Equals($"{checkCenter}"))
  395. {
  396. if (_connectionService.centerIsConnected)
  397. {
  398. if (token.scope.Equals(ExamConstant.ScopeTeacher) || token.scope.Equals(ExamConstant.ScopeVisitor))//由于已经绑定学校,访客教师也可以访问中心。
  399. {
  400. Teacher? teacher = _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().FindOne(x => x.id!.Equals(token.id));
  401. if (teacher != null)
  402. {
  403. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  404. var client = _httpClientFactory.CreateClient();
  405. if (client.DefaultRequestHeaders.Contains(Constant._X_Auth_AuthToken))
  406. {
  407. client.DefaultRequestHeaders.Remove(Constant._X_Auth_AuthToken);
  408. }
  409. client.DefaultRequestHeaders.Add(Constant._X_Auth_AuthToken, teacher.x_auth_token);
  410. try
  411. {
  412. HttpResponseMessage message = await client.PostAsJsonAsync($"{CenterUrl}/evaluation-sync/find-sync-info", new { shortCode, evaluationId });
  413. if (message.IsSuccessStatusCode)
  414. {
  415. string content = await message.Content.ReadAsStringAsync();
  416. JsonNode? jsonNode = content.ToObject<JsonNode>();
  417. if (jsonNode != null)
  418. {
  419. centerCode = $"{jsonNode["code"]}";
  420. centerMsg = $"{jsonNode["msg"]}";
  421. if ($"{jsonNode["code"]}".Equals("200"))
  422. {
  423. evaluationCloud = jsonNode["evaluation"]?.ToObject<EvaluationClient>();
  424. }
  425. }
  426. else
  427. {
  428. centerCode = "500";
  429. centerMsg = "数据转换异常";
  430. }
  431. }
  432. else
  433. {
  434. centerCode = $"{message.StatusCode}";
  435. centerMsg = "数据中心访问异常";
  436. }
  437. }
  438. catch (Exception ex)
  439. {
  440. centerCode = $"500";
  441. centerMsg = $"数据中心访问异常:{ex.Message}";
  442. }
  443. }
  444. else
  445. {
  446. centerCode = $"401";
  447. centerMsg = "当前登录账号未找到";
  448. }
  449. }
  450. }
  451. else
  452. {
  453. centerCode = $"404";
  454. centerMsg = "云端数据中心未连接";
  455. }
  456. if (centerCode.Equals("200"))
  457. {
  458. successMsgs.Add($"云端数据检测结果:{centerMsg},状态:{centerCode}");
  459. }
  460. else
  461. {
  462. errorMsgs.Add($"云端数据检测结果:{centerMsg},状态:{centerCode}");
  463. }
  464. }
  465. var checkDataResult = ManageService.CheckData(evaluationLocal, evaluationCloud, successMsgs, errorMsgs, _liteDBFactory);
  466. Dictionary<string, object?>? evaluation = null;
  467. if (evaluationLocal!=null)
  468. {
  469. string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "zip");
  470. //判断文件包的压缩包是否存在。
  471. if (!System.IO.File.Exists(Path.Combine(zipPath, $"{evaluationLocal.id}-{evaluationLocal.blobHash}.zip")))
  472. {
  473. checkDataResult.zip =1;
  474. checkDataResult.blob=1;
  475. checkDataResult.data=1;
  476. checkDataResult.groupList=1;
  477. checkDataResult.blobSize=evaluationLocal.blobSize;
  478. checkDataResult.dataSize=evaluationLocal.dataSize;
  479. checkDataResult.studentCount=evaluationLocal.studentCount;
  480. errorMsgs.Add($"评测文件包压缩包不存在,需要重新下载评测!");
  481. }
  482. var properties = evaluationLocal.GetType().GetProperties();
  483. evaluation = new Dictionary<string, object?>();
  484. foreach (var property in properties)
  485. {
  486. if (!property.Name.Equals("openCode"))
  487. {
  488. evaluation[property.Name] = property.GetValue(evaluationLocal);
  489. }
  490. }
  491. }
  492. return Ok(new
  493. {
  494. code = 200,
  495. evaluation = evaluation,
  496. result = checkDataResult
  497. });
  498. }
  499. /// <summary>
  500. /// 获取当前评测的开考设置信息
  501. /// </summary>
  502. /// <param name="json"></param>
  503. /// <returns></returns>
  504. [HttpPost("load-evaluation-round")]
  505. [AuthToken("admin", "teacher", "visitor")]
  506. public IActionResult LoadEvaluationRound(JsonNode json)
  507. {
  508. string evaluationId = $"{json["evaluationId"]}";
  509. string openCode = $"{json["openCode"]}";
  510. string shortCode = $"{json["shortCode"]}";
  511. EvaluationClient? evaluationClient = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>()
  512. .FindOne(x => x.id!.Equals(evaluationId) && x.shortCode!.Equals(shortCode) && x.openCode!.Equals(openCode));
  513. EvaluationRoundSetting? setting = null;
  514. if (evaluationClient!=null)
  515. {
  516. if (!string.IsNullOrWhiteSpace(evaluationClient.roundId))
  517. {
  518. setting = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationRoundSetting>().FindOne(x => x.id!.Equals(evaluationClient.roundId));
  519. }
  520. if (setting!=null)
  521. {
  522. IEnumerable<EvaluationStudentResult>? results = null;
  523. var members = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationMember>().Find(x => x.evaluationId!.Equals(evaluationClient.id) && x.roundId!.Equals(setting.id));
  524. //并获取学生的作答信息
  525. //顺便返回本轮的学生名单
  526. if (members!=null && members.Count()>0)
  527. {
  528. results = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>()
  529. .Find(x => members.Select(x => x.id).Contains(x.studentId)&&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  530. if (results.Count()==members.Count())
  531. {
  532. return Ok(new { code = 200, setting, results });
  533. }
  534. else {
  535. return Ok(new { code = 200,msg="学生作答信息数量不匹配", setting, results });
  536. }
  537. }
  538. else
  539. {
  540. return Ok(new { code = 200,msg="未分配学生名单,或名单没有学生!", setting , results });
  541. }
  542. }
  543. else
  544. {
  545. return Ok(new { code = 2, msg = "未设置开考信息!" });
  546. }
  547. }
  548. else {
  549. return Ok(new { code = 1, msg = "未找到评测信息!" });
  550. }
  551. }
  552. /// <summary>
  553. /// 设置评测开考信息(本轮名单,计时规则,分配试卷等)
  554. /// </summary>
  555. /// <param name="json"></param>
  556. /// <returns></returns>
  557. [HttpPost("setting-evaluation-round")]
  558. [AuthToken("admin", "teacher", "visitor")]
  559. public IActionResult SettingEvaluationRound(JsonNode json)
  560. {
  561. EvaluationRoundSetting? setting = json.ToObject<EvaluationRoundSetting>();
  562. if (setting!=null)
  563. {
  564. var db = _liteDBFactory.GetLiteDatabase();
  565. var collection = db.GetCollection<EvaluationClient>() ;
  566. //&& x.openCode!.Equals($"{json["openCode"]}")&& x.shortCode!.Equals($"{json["shortCode"]}")
  567. string shortCode = $"{json["shortCode"]}";
  568. string openCode = $"{json["openCode"]}";
  569. EvaluationClient ? evaluationClient = collection.FindOne(x => x.id!.Equals(setting.evaluationId)
  570. && !string.IsNullOrWhiteSpace(x.shortCode) && x.shortCode.Equals(x.shortCode)
  571. && !string.IsNullOrWhiteSpace(x.openCode) && x.openCode.Equals(openCode) );
  572. if (evaluationClient!=null)
  573. {
  574. IEnumerable<EvaluationClient> evaluationClients = collection.Find(x => x.activate==1);
  575. if (evaluationClients != null && evaluationClients.Count() > 0)
  576. {
  577. var datas = evaluationClients.ToList();
  578. foreach (EvaluationClient item in datas)
  579. {
  580. item.activate = 0;
  581. }
  582. collection.Upsert(datas);
  583. }
  584. /// 判断是否包含所有分组
  585. bool isAllContained = setting.groupList.All(x => evaluationClient.grouplist.Any(y => y.id == x.id));
  586. if (isAllContained && evaluationClient.grouplist.IsNotEmpty())
  587. {
  588. evaluationClient.countdownType = setting.countdownType;
  589. evaluationClient.countdown = setting.countdown;
  590. evaluationClient.deadline = setting.deadline;
  591. evaluationClient.startline = setting.startline;
  592. evaluationClient.activate = setting.activate;
  593. //增加排序,保证id的唯一性
  594. setting.id=ShaHashHelper.GetSHA1($"{evaluationClient.id}_{string.Join("", setting.groupList.Select(x => x.id)).OrderBy(x => x)}");
  595. setting.createTime= DateTimeOffset.Now.ToUnixTimeMilliseconds();
  596. evaluationClient.roundId = setting.id;
  597. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationRoundSetting>().Upsert(setting);
  598. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().Upsert(evaluationClient);
  599. /// 分配试卷
  600. var (roundStudentPapers, members, results,code,msg) = AssignStudentPaper(evaluationClient, setting);
  601. return Ok(new { code = code, msg =msg , setting, results });
  602. }
  603. else
  604. {
  605. return Ok(new { code = 3, msg = "开考名单不在当前评测中!" });
  606. }
  607. }
  608. else { return Ok(new { code = 2, msg = "未找到评测,请确认评测ID、提取码、开卷码是否正确!" }); }
  609. }
  610. else
  611. {
  612. return Ok(new { code = 1, msg = "未完善设置信息!" });
  613. }
  614. }
  615. /// <summary>
  616. /// 加载本地的活动列表
  617. /// </summary>
  618. /// <param name="json"></param>
  619. /// <returns></returns>
  620. [HttpPost("list-local-evaluation")]
  621. [AuthToken("admin", "teacher", "visitor")]
  622. public IActionResult ListLocalEvaluation(JsonNode json)
  623. {
  624. IEnumerable<EvaluationClient>? evaluationClients = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().FindAll().OrderByDescending(x=>x.activate).ThenByDescending(x=>x.stime);
  625. if (evaluationClients != null)
  626. {
  627. var result = evaluationClients.Select(client =>
  628. {
  629. var properties = client.GetType().GetProperties();
  630. var anonymousObject = new Dictionary<string, object?>();
  631. foreach (var property in properties)
  632. {
  633. if (!property.Name.Equals("openCode"))
  634. {
  635. anonymousObject[property.Name] = property.GetValue(client);
  636. }
  637. }
  638. return anonymousObject;
  639. });
  640. return Ok(new { code = 200, evaluation = result });
  641. }
  642. else {
  643. return Ok(new { code = 200, evaluation = new List<EvaluationClient> ()});
  644. }
  645. }
  646. /// <summary>
  647. /// 设置评测开考信息(本轮名单,计时规则等)
  648. /// </summary>
  649. /// <param name="json"></param>
  650. /// <returns></returns>
  651. //[HttpPost("assign-student-paper")]
  652. //[AuthToken("admin", "teacher", "visitor")]
  653. private (List<EvaluationStudentPaper> roundStudentPapers, List<EvaluationMember> members, List<EvaluationStudentResult> results, int code, string msg) AssignStudentPaper(EvaluationClient evaluationClient, EvaluationRoundSetting setting)
  654. {
  655. int code = 200;
  656. string msg = string.Empty;
  657. List<EvaluationStudentPaper> roundStudentPapers = new List<EvaluationStudentPaper>();
  658. List<EvaluationMember> members = new List<EvaluationMember>();
  659. List<EvaluationStudentResult> results = new List<EvaluationStudentResult>();
  660. string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package");
  661. string evaluationPath = Path.Combine(packagePath, evaluationClient.id!);
  662. string evaluationDataPath = Path.Combine(evaluationPath, "data");
  663. string path_groupList = Path.Combine(evaluationDataPath, "groupList.json");
  664. if (System.IO.File.Exists(path_groupList))
  665. {
  666. JsonNode? jsonNode = System.IO.File.ReadAllText(path_groupList).ToObject<JsonNode>();
  667. if (jsonNode!=null && jsonNode["groupList"]!=null)
  668. {
  669. List<EvaluationGroupList>? groupList = jsonNode["groupList"]?.ToObject<List<EvaluationGroupList>>();
  670. if (groupList!=null)
  671. {
  672. bool isAllContained = setting.groupList.All(x => groupList.Any(y => y.id == x.id));
  673. if (isAllContained)
  674. {
  675. foreach (var item in setting.groupList)
  676. {
  677. EvaluationGroupList? groupListItem = groupList.Find(x => x.id == item.id);
  678. if (groupListItem!=null)
  679. {
  680. groupListItem.members.ForEach(x =>
  681. {
  682. x.schoolId=_connectionService?.serverDevice?.school?.id;
  683. x.evaluationId=evaluationClient.id;
  684. x.classId= groupListItem.id;
  685. x.periodId= groupListItem.periodId;
  686. x.roundId=setting.id;
  687. x.className= groupListItem.name;
  688. });
  689. members.AddRange(groupListItem.members);
  690. }
  691. }
  692. //清空数据库,重新插入
  693. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationMember>().DeleteAll();
  694. //插入
  695. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationMember>().Upsert(members);
  696. foreach (var subject in evaluationClient.subjects)
  697. {
  698. var studentPaperIds = members.Select(x => ShaHashHelper.GetSHA1(x.id+evaluationClient.id+subject.examId+subject.subjectId));
  699. IEnumerable<EvaluationStudentPaper> evaluationStudentPapers = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentPaper>()
  700. .Find(x => studentPaperIds.Contains(x.id) && x.evaluationId!.Equals(evaluationClient.id));
  701. List<EvaluationStudentPaper> studentPapers = new List<EvaluationStudentPaper>();
  702. int paperIndex = 0;
  703. int paperCount = subject.papers.Count();
  704. //先把试卷顺序打乱
  705. subject.papers =subject.papers.OrderBy(x => Guid.NewGuid().ToString()).ToList();
  706. //将学生顺序打乱
  707. members = members.OrderBy(x => Guid.NewGuid().ToString()).ToList();
  708. foreach (var member in members)
  709. {
  710. SubjectExamPaper studentPaper = subject.papers[paperIndex];
  711. string id = ShaHashHelper.GetSHA1(member.id+evaluationClient.id+subject.examId+subject.subjectId);
  712. var paper = evaluationStudentPapers.Where(x => x.id!.Equals(id));
  713. if (paper== null || paper.Count()==0)
  714. {
  715. studentPapers.Add(new EvaluationStudentPaper
  716. {
  717. studentId=member.id,
  718. studentName=member.name,
  719. classId=member.classId,
  720. className=member.className,
  721. evaluationId=evaluationClient.id,
  722. examId=subject.examId,
  723. examName=subject.examName,
  724. subjectId=subject.subjectId,
  725. subjectName=subject.subjectName,
  726. paperId=studentPaper.paperId,
  727. paperName=studentPaper.paperName,
  728. id=id,
  729. });
  730. // 移动到下一个试卷
  731. paperIndex = (paperIndex + 1) % paperCount;
  732. }
  733. else
  734. {
  735. // Console.WriteLine("已经分配过试卷,跳过");
  736. //已经分配过试卷,跳过
  737. }
  738. }
  739. if (studentPapers.Count>0)
  740. {
  741. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentPaper>().Upsert(studentPapers);
  742. roundStudentPapers.AddRange(studentPapers);
  743. }
  744. if (evaluationStudentPapers!=null && evaluationStudentPapers.Count()>0)
  745. {
  746. roundStudentPapers.AddRange(evaluationStudentPapers);
  747. }
  748. }
  749. IEnumerable<EvaluationStudentResult> studentResults = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>()
  750. .Find(x => members.Select(x => x.id).Contains(x.studentId)&&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  751. foreach (var member in members)
  752. {
  753. EvaluationStudentResult? studentResult = null;
  754. //sha1(evaluationId-schoolId-studentId)
  755. string resultId = ShaHashHelper.GetSHA1(evaluationClient.id+_connectionService?.serverDevice?.school?.id+member.id);
  756. var result = studentResults.Where(x => x.id!.Equals(resultId) && !string.IsNullOrWhiteSpace(x.studentId) && x.studentId.Equals(member.id));
  757. if (result==null || result.Count()==0)
  758. {
  759. studentResult = new EvaluationStudentResult()
  760. {
  761. id = resultId,
  762. evaluationId = evaluationClient.id,
  763. schoolId = _connectionService?.serverDevice?.school?.id,
  764. studentId = member.id,
  765. studentName = member.name,
  766. classId = member.classId,
  767. className = member.className,
  768. ownerId= evaluationClient.ownerId,
  769. scope= evaluationClient.scope,
  770. type= evaluationClient.type,
  771. pid= evaluationClient.pid,
  772. };
  773. var studentPapers = roundStudentPapers.FindAll(x => !string.IsNullOrWhiteSpace(x.studentId) && x.studentId.Equals(member.id)
  774. &&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  775. if (studentPapers.IsNotEmpty())
  776. {
  777. foreach (var studentPaper in studentPapers)
  778. {
  779. studentResult.subjectResults.Add(new EvaluationSubjectResult()
  780. {
  781. id = ShaHashHelper.GetSHA1(evaluationClient.id+studentPaper.examId+studentPaper.subjectId+member.id),
  782. evaluationId = studentPaper.evaluationId,
  783. examId = studentPaper.examId,
  784. examName = studentPaper.examName,
  785. subjectId = studentPaper.subjectId,
  786. subjectName = studentPaper.subjectName,
  787. paperId = studentPaper.paperId,
  788. paperName = studentPaper.paperName,
  789. });
  790. }
  791. }
  792. // _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>().Upsert(studentResult);
  793. }
  794. else
  795. {
  796. studentResult = result.First();
  797. studentResult.studentName = member.name;
  798. studentResult.classId = member.classId;
  799. studentResult.className = member.className;
  800. var studentPapers = roundStudentPapers.FindAll(x => !string.IsNullOrWhiteSpace(x.studentId) && x.studentId.Equals(member.id)
  801. &&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  802. if (studentPapers.IsNotEmpty())
  803. {
  804. foreach (var studentPaper in studentPapers)
  805. {
  806. string subjectResultId = ShaHashHelper.GetSHA1(evaluationClient.id+studentPaper.examId+studentPaper.subjectId+member.id);
  807. var subjectResult = studentResult.subjectResults.Find(x => x.id!.Equals(subjectResultId));
  808. if (subjectResult==null)
  809. {
  810. studentResult.subjectResults.Add(new EvaluationSubjectResult()
  811. {
  812. id = ShaHashHelper.GetSHA1(evaluationClient.id+studentPaper.examId+studentPaper.subjectId+member.id),
  813. evaluationId = studentPaper.evaluationId,
  814. examId = studentPaper.examId,
  815. examName = studentPaper.examName,
  816. subjectId = studentPaper.subjectId,
  817. subjectName = studentPaper.subjectName,
  818. paperId = studentPaper.paperId,
  819. paperName = studentPaper.paperName,
  820. });
  821. }
  822. else
  823. {
  824. subjectResult.evaluationId = studentPaper.evaluationId;
  825. subjectResult.examId = studentPaper.examId;
  826. subjectResult.examName = studentPaper.examName;
  827. subjectResult.subjectId = studentPaper.subjectId;
  828. subjectResult.subjectName = studentPaper.subjectName;
  829. subjectResult.paperId = studentPaper.paperId;
  830. subjectResult.paperName = studentPaper.paperName;
  831. }
  832. }
  833. }
  834. //_liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>().Upsert(studentResult);
  835. }
  836. if (studentResult!=null)
  837. {
  838. results.Add(studentResult);
  839. }
  840. }
  841. if (results.Count>0)
  842. {
  843. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>().Upsert(results);
  844. }
  845. }
  846. else
  847. {
  848. msg = "开考名单不在当前评测中!";
  849. code = 4;
  850. }
  851. }
  852. else
  853. {
  854. msg = "名单文件字段提取为空!";
  855. code = 3;
  856. }
  857. }
  858. else
  859. {
  860. msg = "名单文件解析错误!";
  861. code = 2;
  862. }
  863. }
  864. else
  865. {
  866. msg = "名单文件不存在!";
  867. code = 1;
  868. }
  869. if (members.Count()!=results.Count())
  870. {
  871. code = 5;
  872. msg = "名单成员与作答记录数量不匹配!";
  873. }
  874. if (roundStudentPapers.Count()!= results.SelectMany(x => x.subjectResults).Count())
  875. {
  876. code = 6;
  877. msg = "学生分配的试卷与作答记录数量不匹配!";
  878. }
  879. return (roundStudentPapers, members, results, code, msg);
  880. }
  881. }
  882. }