ManageController.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. string shortCode = $"{json["shortCode"]}";
  295. var token = GetAuthTokenInfo();
  296. List<string> successMsgs = new List<string>();
  297. List<string> errorMsgs = new List<string>();
  298. EvaluationCheckFileResult result = new EvaluationCheckFileResult() { successMsgs=successMsgs, errorMsgs =errorMsgs };
  299. if (!string.IsNullOrEmpty(openCode) && !string.IsNullOrEmpty(evaluationId))
  300. {
  301. EvaluationClient? evaluationLocal = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().FindOne(x => x.id!.Equals(evaluationId) && x.openCode!.Equals(openCode) && x.shortCode!.Equals(shortCode));
  302. if (evaluationLocal!=null)
  303. {
  304. //ManageService.CheckData(evaluationLocal, null, successMsgs, errorMsgs, _liteDBFactory);
  305. await _signalRExamServerHub.SendMessage(_memoryCache, _logger, deviceId, Constant._Message_grant_type_check_file,
  306. new MessageContent { dataId=evaluationLocal.id, dataName=evaluationLocal.name, messageType=Constant._Message_type_message, status=0, content="开始检查评测信息文件.." });
  307. //判断文件包的压缩包是否存在。
  308. string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "zip");
  309. //校验本地文件数据
  310. string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package");
  311. string evaluationPath = Path.Combine(packagePath, evaluationLocal.id!);
  312. if (System.IO.File.Exists(Path.Combine(zipPath, $"{evaluationLocal.id}-{evaluationLocal.blobHash}.zip")))
  313. {
  314. string key = $"{Constant._KeyEvaluationZipExtract}:{evaluationId}:{openCode}";
  315. successMsgs.Add("加载评测试卷文件包!");
  316. //string keyData = _memoryCache.Get<string>(key);
  317. //if (!string.IsNullOrWhiteSpace(keyData))
  318. //{
  319. //}
  320. //else {
  321. //}
  322. //删除文件夹
  323. FileHelper.DeleteFolder(evaluationPath);
  324. if (!Directory.Exists(evaluationPath))
  325. {
  326. Directory.CreateDirectory(evaluationPath);
  327. }
  328. //解压文件包
  329. var extractRes = ZipHelper.ExtractPasswordProtectedZip(Path.Combine(zipPath, $"{evaluationLocal.id}-{evaluationLocal.blobHash}.zip"), evaluationPath, evaluationLocal.openCode!);
  330. if (extractRes.res)
  331. {
  332. _memoryCache.Set(key,key,TimeSpan.FromSeconds(30));
  333. successMsgs.Add("评测试卷文件包解压成功!");
  334. (successMsgs, errorMsgs) = await ManageService.CheckFile(evaluationLocal, successMsgs, errorMsgs, _signalRExamServerHub, _memoryCache, _logger, deviceId, evaluationPath);
  335. }
  336. else {
  337. errorMsgs.Add("评测试卷文件包解压失败!");
  338. //return Ok(new { code = 3, msg = "评测试卷文件包解压失败!" });
  339. }
  340. }
  341. else {
  342. errorMsgs.Add("评测试卷文件包不存在!");
  343. //return Ok(new { code = 3, msg = "评测试卷文件包不存在!" });
  344. }
  345. }
  346. else {
  347. errorMsgs.Add("未找到评测信息!");
  348. // return Ok(new { code = 2, msg = "未找到评测信息!" });
  349. }
  350. }
  351. else
  352. {
  353. errorMsgs.Add("评测ID或提取码均未填写!");
  354. // return Ok(new { code = 1, msg = "评测ID或提取码均未填写!" });
  355. }
  356. result.checkTotal = result.errorMsgs.Count() + result.successMsgs.Count();
  357. result.checkError= result.errorMsgs.Count();
  358. result.checkSuccess = result.successMsgs.Count();
  359. if (result.errorMsgs.Count()==0)
  360. {
  361. return Ok(new { code = 200, msg = "校验成功!", result });
  362. }
  363. else
  364. {
  365. return Ok(new { code = 1, msg = "校验失败!", result });
  366. }
  367. }
  368. [HttpPost("check-evaluation")]
  369. [AuthToken("admin", "teacher", "visitor")]
  370. public async Task<IActionResult> CheckEvaluation(JsonNode json)
  371. {
  372. string shortCode = $"{json["shortCode"]}";
  373. string evaluationId = $"{json["evaluationId"]}";
  374. string checkCenter = $"{json["checkCenter"]}";
  375. string deviceId = $"{json["deviceId"]}";
  376. string centerCode = string.Empty, centerMsg = string.Empty;
  377. Expression<Func<EvaluationClient, bool>> predicate = x => true;
  378. var token = GetAuthTokenInfo();
  379. if (!string.IsNullOrEmpty(shortCode) || !string.IsNullOrEmpty(evaluationId))
  380. {
  381. if (!string.IsNullOrEmpty(shortCode))
  382. {
  383. predicate= predicate.And(x => !string.IsNullOrWhiteSpace(x.shortCode) && x.shortCode.Equals(shortCode));
  384. }
  385. if (!string.IsNullOrWhiteSpace(evaluationId))
  386. {
  387. predicate= predicate.And(x => x.id!.Equals(evaluationId));
  388. }
  389. }
  390. else
  391. {
  392. return Ok(new { code = 400, msg = "评测ID或提取码均未填写!" });
  393. }
  394. IEnumerable<EvaluationClient>? evaluationClients = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().Find(predicate);
  395. EvaluationClient? evaluationLocal = null;
  396. EvaluationClient? evaluationCloud = null;
  397. if (evaluationClients!=null && evaluationClients.Count()>0)
  398. {
  399. evaluationLocal= evaluationClients.First();
  400. }
  401. List<string> successMsgs = new List<string>();
  402. List<string> errorMsgs = new List<string>();
  403. //从数据中心搜索
  404. if ("1".Equals($"{checkCenter}"))
  405. {
  406. if (_connectionService.centerIsConnected)
  407. {
  408. if (token.scope.Equals(ExamConstant.ScopeTeacher) || token.scope.Equals(ExamConstant.ScopeVisitor))//由于已经绑定学校,访客教师也可以访问中心。
  409. {
  410. Teacher? teacher = _liteDBFactory.GetLiteDatabase().GetCollection<Teacher>().FindOne(x => x.id!.Equals(token.id));
  411. if (teacher != null)
  412. {
  413. string? CenterUrl = _configuration.GetValue<string>("ExamServer:CenterUrl");
  414. var client = _httpClientFactory.CreateClient();
  415. if (client.DefaultRequestHeaders.Contains(Constant._X_Auth_AuthToken))
  416. {
  417. client.DefaultRequestHeaders.Remove(Constant._X_Auth_AuthToken);
  418. }
  419. client.DefaultRequestHeaders.Add(Constant._X_Auth_AuthToken, teacher.x_auth_token);
  420. try
  421. {
  422. HttpResponseMessage message = await client.PostAsJsonAsync($"{CenterUrl}/evaluation-sync/find-sync-info", new { shortCode, evaluationId });
  423. if (message.IsSuccessStatusCode)
  424. {
  425. string content = await message.Content.ReadAsStringAsync();
  426. JsonNode? jsonNode = content.ToObject<JsonNode>();
  427. if (jsonNode != null)
  428. {
  429. centerCode = $"{jsonNode["code"]}";
  430. centerMsg = $"{jsonNode["msg"]}";
  431. if ($"{jsonNode["code"]}".Equals("200"))
  432. {
  433. evaluationCloud = jsonNode["evaluation"]?.ToObject<EvaluationClient>();
  434. }
  435. }
  436. else
  437. {
  438. centerCode = "500";
  439. centerMsg = "数据转换异常";
  440. }
  441. }
  442. else
  443. {
  444. centerCode = $"{message.StatusCode}";
  445. centerMsg = "数据中心访问异常";
  446. }
  447. }
  448. catch (Exception ex)
  449. {
  450. centerCode = $"500";
  451. centerMsg = $"数据中心访问异常:{ex.Message}";
  452. }
  453. }
  454. else
  455. {
  456. centerCode = $"401";
  457. centerMsg = "当前登录账号未找到";
  458. }
  459. }
  460. }
  461. else
  462. {
  463. centerCode = $"404";
  464. centerMsg = "云端数据中心未连接";
  465. }
  466. if (centerCode.Equals("200"))
  467. {
  468. successMsgs.Add($"云端数据检测结果:{centerMsg},状态:{centerCode}");
  469. }
  470. else
  471. {
  472. errorMsgs.Add($"云端数据检测结果:{centerMsg},状态:{centerCode}");
  473. }
  474. }
  475. EvaluationCheckDataResult checkDataResult;
  476. (checkDataResult, evaluationLocal) = ManageService.CheckData( evaluationLocal, evaluationCloud, successMsgs, errorMsgs, _liteDBFactory);
  477. Dictionary<string, object?>? evaluation = null;
  478. if (evaluationLocal!=null)
  479. {
  480. string zipPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "zip");
  481. //判断文件包的压缩包是否存在。
  482. if (!System.IO.File.Exists(Path.Combine(zipPath, $"{evaluationLocal.id}-{evaluationLocal.blobHash}.zip")))
  483. {
  484. checkDataResult.zip =1;
  485. checkDataResult.blob=1;
  486. checkDataResult.data=1;
  487. checkDataResult.groupList=1;
  488. checkDataResult.blobSize=evaluationLocal.blobSize;
  489. checkDataResult.dataSize=evaluationLocal.dataSize;
  490. checkDataResult.studentCount=evaluationLocal.studentCount;
  491. errorMsgs.Add($"评测文件包压缩包不存在,需要重新下载评测!");
  492. }
  493. var properties = evaluationLocal.GetType().GetProperties();
  494. evaluation = new Dictionary<string, object?>();
  495. foreach (var property in properties)
  496. {
  497. if (!property.Name.Equals("openCode"))
  498. {
  499. evaluation[property.Name] = property.GetValue(evaluationLocal);
  500. }
  501. }
  502. }
  503. return Ok(new
  504. {
  505. code = 200,
  506. evaluation = evaluation,
  507. result = checkDataResult
  508. });
  509. }
  510. /// <summary>
  511. /// 获取当前评测的开考设置信息
  512. /// </summary>
  513. /// <param name="json"></param>
  514. /// <returns></returns>
  515. [HttpPost("load-evaluation-round")]
  516. [AuthToken("admin", "teacher", "visitor")]
  517. public IActionResult LoadEvaluationRound(JsonNode json)
  518. {
  519. string evaluationId = $"{json["evaluationId"]}";
  520. string openCode = $"{json["openCode"]}";
  521. string shortCode = $"{json["shortCode"]}";
  522. EvaluationClient? evaluationClient = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>()
  523. .FindOne(x => x.id!.Equals(evaluationId) && x.shortCode!.Equals(shortCode) && x.openCode!.Equals(openCode));
  524. EvaluationRoundSetting? setting = null;
  525. if (evaluationClient!=null)
  526. {
  527. if (!string.IsNullOrWhiteSpace(evaluationClient.roundId))
  528. {
  529. setting = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationRoundSetting>().FindOne(x => x.id!.Equals(evaluationClient.roundId));
  530. }
  531. if (setting!=null)
  532. {
  533. IEnumerable<EvaluationStudentResult>? results = null;
  534. var members = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationMember>().Find(x => x.evaluationId!.Equals(evaluationClient.id) && x.roundId!.Equals(setting.id));
  535. //并获取学生的作答信息
  536. //顺便返回本轮的学生名单
  537. if (members!=null && members.Count()>0)
  538. {
  539. results = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>()
  540. .Find(x => members.Select(x => x.id).Contains(x.studentId)&&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  541. if (results.Count()==members.Count())
  542. {
  543. return Ok(new { code = 200, setting, results });
  544. }
  545. else {
  546. return Ok(new { code = 200,msg="学生作答信息数量不匹配", setting, results });
  547. }
  548. }
  549. else
  550. {
  551. return Ok(new { code = 200,msg="未分配学生名单,或名单没有学生!", setting , results });
  552. }
  553. }
  554. else
  555. {
  556. return Ok(new { code = 2, msg = "未设置开考信息!" });
  557. }
  558. }
  559. else {
  560. return Ok(new { code = 1, msg = "未找到评测信息!" });
  561. }
  562. }
  563. /// <summary>
  564. /// 设置评测开考信息(本轮名单,计时规则,分配试卷等)
  565. /// </summary>
  566. /// <param name="json"></param>
  567. /// <returns></returns>
  568. [HttpPost("setting-evaluation-round")]
  569. [AuthToken("admin", "teacher", "visitor")]
  570. public IActionResult SettingEvaluationRound(JsonNode json)
  571. {
  572. EvaluationRoundSetting? setting = json.ToObject<EvaluationRoundSetting>();
  573. if (setting!=null)
  574. {
  575. var db = _liteDBFactory.GetLiteDatabase();
  576. var collection = db.GetCollection<EvaluationClient>() ;
  577. //&& x.openCode!.Equals($"{json["openCode"]}")&& x.shortCode!.Equals($"{json["shortCode"]}")
  578. string shortCode = $"{json["shortCode"]}";
  579. string openCode = $"{json["openCode"]}";
  580. EvaluationClient ? evaluationClient = collection.FindOne(x => x.id!.Equals(setting.evaluationId)
  581. && !string.IsNullOrWhiteSpace(x.shortCode) && x.shortCode.Equals(x.shortCode)
  582. && !string.IsNullOrWhiteSpace(x.openCode) && x.openCode.Equals(openCode) );
  583. if (evaluationClient!=null)
  584. {
  585. IEnumerable<EvaluationClient> evaluationClients = collection.Find(x => x.activate==1);
  586. if (evaluationClients != null && evaluationClients.Count() > 0)
  587. {
  588. var datas = evaluationClients.ToList();
  589. foreach (EvaluationClient item in datas)
  590. {
  591. item.activate = 0;
  592. }
  593. collection.Upsert(datas);
  594. }
  595. /// 判断是否包含所有分组
  596. bool isAllContained = setting.groupList.All(x => evaluationClient.grouplist.Any(y => y.id == x.id));
  597. if (isAllContained && evaluationClient.grouplist.IsNotEmpty())
  598. {
  599. evaluationClient.countdownType = setting.countdownType;
  600. evaluationClient.countdown = setting.countdown;
  601. evaluationClient.deadline = setting.deadline;
  602. evaluationClient.startline = setting.startline;
  603. evaluationClient.activate = setting.activate;
  604. //增加排序,保证id的唯一性
  605. setting.id=ShaHashHelper.GetSHA1($"{evaluationClient.id}_{string.Join("", setting.groupList.Select(x => x.id)).OrderBy(x => x)}");
  606. setting.createTime= DateTimeOffset.Now.ToUnixTimeMilliseconds();
  607. evaluationClient.roundId = setting.id;
  608. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationRoundSetting>().Upsert(setting);
  609. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().Upsert(evaluationClient);
  610. /// 分配试卷
  611. var (roundStudentPapers, members, results,code,msg) = AssignStudentPaper(evaluationClient, setting);
  612. return Ok(new { code = code, msg =msg , setting, results });
  613. }
  614. else
  615. {
  616. return Ok(new { code = 3, msg = "开考名单不在当前评测中!" });
  617. }
  618. }
  619. else { return Ok(new { code = 2, msg = "未找到评测,请确认评测ID、提取码、开卷码是否正确!" }); }
  620. }
  621. else
  622. {
  623. return Ok(new { code = 1, msg = "未完善设置信息!" });
  624. }
  625. }
  626. /// <summary>
  627. /// 加载本地的活动列表
  628. /// </summary>
  629. /// <param name="json"></param>
  630. /// <returns></returns>
  631. [HttpPost("list-local-evaluation")]
  632. [AuthToken("admin", "teacher", "visitor")]
  633. public IActionResult ListLocalEvaluation(JsonNode json)
  634. {
  635. IEnumerable<EvaluationClient>? evaluationClients = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationClient>().FindAll().OrderByDescending(x=>x.activate).ThenByDescending(x=>x.stime);
  636. if (evaluationClients != null)
  637. {
  638. var result = evaluationClients.Select(client =>
  639. {
  640. var properties = client.GetType().GetProperties();
  641. var anonymousObject = new Dictionary<string, object?>();
  642. foreach (var property in properties)
  643. {
  644. if (!property.Name.Equals("openCode"))
  645. {
  646. anonymousObject[property.Name] = property.GetValue(client);
  647. }
  648. }
  649. return anonymousObject;
  650. });
  651. return Ok(new { code = 200, evaluation = result });
  652. }
  653. else {
  654. return Ok(new { code = 200, evaluation = new List<EvaluationClient> ()});
  655. }
  656. }
  657. /// <summary>
  658. /// 设置评测开考信息(本轮名单,计时规则等)
  659. /// </summary>
  660. /// <param name="json"></param>
  661. /// <returns></returns>
  662. //[HttpPost("assign-student-paper")]
  663. //[AuthToken("admin", "teacher", "visitor")]
  664. private (List<EvaluationStudentPaper> roundStudentPapers, List<EvaluationMember> members, List<EvaluationStudentResult> results, int code, string msg) AssignStudentPaper(EvaluationClient evaluationClient, EvaluationRoundSetting setting)
  665. {
  666. int code = 200;
  667. string msg = string.Empty;
  668. List<EvaluationStudentPaper> roundStudentPapers = new List<EvaluationStudentPaper>();
  669. List<EvaluationMember> members = new List<EvaluationMember>();
  670. List<EvaluationStudentResult> results = new List<EvaluationStudentResult>();
  671. string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package");
  672. string evaluationPath = Path.Combine(packagePath, evaluationClient.id!);
  673. string evaluationDataPath = Path.Combine(evaluationPath, "data");
  674. string path_groupList = Path.Combine(evaluationDataPath, "groupList.json");
  675. if (System.IO.File.Exists(path_groupList))
  676. {
  677. JsonNode? jsonNode = System.IO.File.ReadAllText(path_groupList).ToObject<JsonNode>();
  678. if (jsonNode!=null && jsonNode["groupList"]!=null)
  679. {
  680. List<EvaluationGroupList>? groupList = jsonNode["groupList"]?.ToObject<List<EvaluationGroupList>>();
  681. if (groupList!=null)
  682. {
  683. bool isAllContained = setting.groupList.All(x => groupList.Any(y => y.id == x.id));
  684. if (isAllContained)
  685. {
  686. foreach (var item in setting.groupList)
  687. {
  688. EvaluationGroupList? groupListItem = groupList.Find(x => x.id == item.id);
  689. if (groupListItem!=null)
  690. {
  691. groupListItem.members.ForEach(x =>
  692. {
  693. x.schoolId=_connectionService?.serverDevice?.school?.id;
  694. x.evaluationId=evaluationClient.id;
  695. x.classId= groupListItem.id;
  696. x.periodId= groupListItem.periodId;
  697. x.roundId=setting.id;
  698. x.className= groupListItem.name;
  699. });
  700. members.AddRange(groupListItem.members);
  701. }
  702. }
  703. //清空数据库,重新插入
  704. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationMember>().DeleteAll();
  705. //插入
  706. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationMember>().Upsert(members);
  707. foreach (var subject in evaluationClient.subjects)
  708. {
  709. var studentPaperIds = members.Select(x => ShaHashHelper.GetSHA1(x.id+evaluationClient.id+subject.examId+subject.subjectId));
  710. IEnumerable<EvaluationStudentPaper> evaluationStudentPapers = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentPaper>()
  711. .Find(x => studentPaperIds.Contains(x.id) && x.evaluationId!.Equals(evaluationClient.id));
  712. List<EvaluationStudentPaper> studentPapers = new List<EvaluationStudentPaper>();
  713. int paperIndex = 0;
  714. int paperCount = subject.papers.Count();
  715. //先把试卷顺序打乱
  716. subject.papers =subject.papers.OrderBy(x => Guid.NewGuid().ToString()).ToList();
  717. //将学生顺序打乱
  718. members = members.OrderBy(x => Guid.NewGuid().ToString()).ToList();
  719. foreach (var member in members)
  720. {
  721. SubjectExamPaper studentPaper = subject.papers[paperIndex];
  722. string id = ShaHashHelper.GetSHA1(member.id+evaluationClient.id+subject.examId+subject.subjectId);
  723. var paper = evaluationStudentPapers.Where(x => x.id!.Equals(id));
  724. if (paper== null || paper.Count()==0)
  725. {
  726. studentPapers.Add(new EvaluationStudentPaper
  727. {
  728. studentId=member.id,
  729. studentName=member.name,
  730. classId=member.classId,
  731. className=member.className,
  732. evaluationId=evaluationClient.id,
  733. examId=subject.examId,
  734. examName=subject.examName,
  735. subjectId=subject.subjectId,
  736. subjectName=subject.subjectName,
  737. paperId=studentPaper.paperId,
  738. paperName=studentPaper.paperName,
  739. id=id,
  740. });
  741. // 移动到下一个试卷
  742. paperIndex = (paperIndex + 1) % paperCount;
  743. }
  744. else
  745. {
  746. // Console.WriteLine("已经分配过试卷,跳过");
  747. //已经分配过试卷,跳过
  748. }
  749. }
  750. if (studentPapers.Count>0)
  751. {
  752. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentPaper>().Upsert(studentPapers);
  753. roundStudentPapers.AddRange(studentPapers);
  754. }
  755. if (evaluationStudentPapers!=null && evaluationStudentPapers.Count()>0)
  756. {
  757. roundStudentPapers.AddRange(evaluationStudentPapers);
  758. }
  759. }
  760. IEnumerable<EvaluationStudentResult> studentResults = _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>()
  761. .Find(x => members.Select(x => x.id).Contains(x.studentId)&&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  762. foreach (var member in members)
  763. {
  764. EvaluationStudentResult? studentResult = null;
  765. //sha1(evaluationId-schoolId-studentId)
  766. string resultId = ShaHashHelper.GetSHA1(evaluationClient.id+_connectionService?.serverDevice?.school?.id+member.id);
  767. var result = studentResults.Where(x => x.id!.Equals(resultId) && !string.IsNullOrWhiteSpace(x.studentId) && x.studentId.Equals(member.id));
  768. if (result==null || result.Count()==0)
  769. {
  770. studentResult = new EvaluationStudentResult()
  771. {
  772. id = resultId,
  773. evaluationId = evaluationClient.id,
  774. schoolId = _connectionService?.serverDevice?.school?.id,
  775. studentId = member.id,
  776. studentName = member.name,
  777. classId = member.classId,
  778. className = member.className,
  779. ownerId= evaluationClient.ownerId,
  780. scope= evaluationClient.scope,
  781. type= evaluationClient.type,
  782. pid= evaluationClient.pid,
  783. };
  784. var studentPapers = roundStudentPapers.FindAll(x => !string.IsNullOrWhiteSpace(x.studentId) && x.studentId.Equals(member.id)
  785. &&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  786. if (studentPapers.IsNotEmpty())
  787. {
  788. foreach (var studentPaper in studentPapers)
  789. {
  790. studentResult.subjectResults.Add(new EvaluationSubjectResult()
  791. {
  792. id = ShaHashHelper.GetSHA1(evaluationClient.id+studentPaper.examId+studentPaper.subjectId+member.id),
  793. evaluationId = studentPaper.evaluationId,
  794. examId = studentPaper.examId,
  795. examName = studentPaper.examName,
  796. subjectId = studentPaper.subjectId,
  797. subjectName = studentPaper.subjectName,
  798. paperId = studentPaper.paperId,
  799. paperName = studentPaper.paperName,
  800. });
  801. }
  802. }
  803. // _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>().Upsert(studentResult);
  804. }
  805. else
  806. {
  807. studentResult = result.First();
  808. studentResult.studentName = member.name;
  809. studentResult.classId = member.classId;
  810. studentResult.className = member.className;
  811. var studentPapers = roundStudentPapers.FindAll(x => !string.IsNullOrWhiteSpace(x.studentId) && x.studentId.Equals(member.id)
  812. &&!string.IsNullOrWhiteSpace(x.evaluationId) && x.evaluationId.Equals(evaluationClient.id));
  813. if (studentPapers.IsNotEmpty())
  814. {
  815. foreach (var studentPaper in studentPapers)
  816. {
  817. string subjectResultId = ShaHashHelper.GetSHA1(evaluationClient.id+studentPaper.examId+studentPaper.subjectId+member.id);
  818. var subjectResult = studentResult.subjectResults.Find(x => x.id!.Equals(subjectResultId));
  819. if (subjectResult==null)
  820. {
  821. studentResult.subjectResults.Add(new EvaluationSubjectResult()
  822. {
  823. id = ShaHashHelper.GetSHA1(evaluationClient.id+studentPaper.examId+studentPaper.subjectId+member.id),
  824. evaluationId = studentPaper.evaluationId,
  825. examId = studentPaper.examId,
  826. examName = studentPaper.examName,
  827. subjectId = studentPaper.subjectId,
  828. subjectName = studentPaper.subjectName,
  829. paperId = studentPaper.paperId,
  830. paperName = studentPaper.paperName,
  831. });
  832. }
  833. else
  834. {
  835. subjectResult.evaluationId = studentPaper.evaluationId;
  836. subjectResult.examId = studentPaper.examId;
  837. subjectResult.examName = studentPaper.examName;
  838. subjectResult.subjectId = studentPaper.subjectId;
  839. subjectResult.subjectName = studentPaper.subjectName;
  840. subjectResult.paperId = studentPaper.paperId;
  841. subjectResult.paperName = studentPaper.paperName;
  842. }
  843. }
  844. }
  845. //_liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>().Upsert(studentResult);
  846. }
  847. if (studentResult!=null)
  848. {
  849. results.Add(studentResult);
  850. }
  851. }
  852. if (results.Count>0)
  853. {
  854. foreach (var item in results)
  855. {
  856. item.subjectResults= item.subjectResults.DistinctBy(x => x.id).ToList();
  857. }
  858. _liteDBFactory.GetLiteDatabase().GetCollection<EvaluationStudentResult>().Upsert(results);
  859. }
  860. }
  861. else
  862. {
  863. msg = "开考名单不在当前评测中!";
  864. code = 4;
  865. }
  866. }
  867. else
  868. {
  869. msg = "名单文件字段提取为空!";
  870. code = 3;
  871. }
  872. }
  873. else
  874. {
  875. msg = "名单文件解析错误!";
  876. code = 2;
  877. }
  878. }
  879. else
  880. {
  881. msg = "名单文件不存在!";
  882. code = 1;
  883. }
  884. if (members.Count()!=results.Count())
  885. {
  886. code = 5;
  887. msg = "名单成员与作答记录数量不匹配!";
  888. }
  889. if (roundStudentPapers.Count()!= results.SelectMany(x => x.subjectResults).Count())
  890. {
  891. code = 6;
  892. msg = "学生分配的试卷与作答记录数量不匹配!";
  893. }
  894. return (roundStudentPapers, members, results, code, msg);
  895. }
  896. }
  897. }