ManageController.cs 54 KB

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