ExamLiteController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.Options;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using TEAMModelOS.Filter;
  14. using TEAMModelOS.Models;
  15. using TEAMModelOS.SDK;
  16. using TEAMModelOS.SDK.DI;
  17. using TEAMModelOS.SDK.Extension;
  18. using TEAMModelOS.SDK.Models;
  19. using TEAMModelOS.SDK.Models.Cosmos.Common;
  20. using TEAMModelOS.SDK.Models.Service;
  21. namespace TEAMModelOS.Controllers.Common
  22. {
  23. [ProducesResponseType(StatusCodes.Status200OK)]
  24. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  25. [Route("common/ExamLite")]
  26. [ApiController]
  27. public class ExamLiteController : ControllerBase
  28. {
  29. private readonly AzureCosmosFactory _azureCosmos;
  30. private readonly SnowflakeId _snowflakeId;
  31. private readonly AzureServiceBusFactory _serviceBus;
  32. private readonly DingDing _dingDing;
  33. private readonly Option _option;
  34. private readonly AzureStorageFactory _azureStorage;
  35. private readonly AzureRedisFactory _azureRedis;
  36. private readonly CoreAPIHttpService _coreAPIHttpService;
  37. public IConfiguration _configuration { get; set; }
  38. public ExamLiteController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
  39. IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
  40. {
  41. _azureCosmos = azureCosmos;
  42. _serviceBus = serviceBus;
  43. _snowflakeId = snowflakeId;
  44. _dingDing = dingDing;
  45. _option = option?.Value;
  46. _azureStorage = azureStorage;
  47. _azureRedis = azureRedis;
  48. _configuration = configuration;
  49. _coreAPIHttpService = coreAPIHttpService;
  50. }
  51. /// <summary>
  52. /// 保存评测信息
  53. /// </summary>
  54. /// <param name="request"></param>
  55. /// <returns></returns>
  56. [ProducesDefaultResponseType]
  57. [AuthToken(Roles = "teacher,admin")]
  58. [HttpPost("save")]
  59. [Authorize(Roles = "IES")]
  60. public async Task<IActionResult> Save(JsonElement request)
  61. {
  62. try
  63. {
  64. var client = _azureCosmos.GetCosmosClient();
  65. ExamLite trExam = request.ToObject<ExamLite>();
  66. trExam.owner = "school";
  67. string id = await ExamService.saveMoreAsync(client, _dingDing, trExam);
  68. if (string.IsNullOrEmpty(id))
  69. {
  70. return Ok(new { code = (int)HttpStatusCode.BadRequest, msg = "评测信息异常" });
  71. }
  72. else
  73. {
  74. return Ok(new { id, code = (int)HttpStatusCode.OK });
  75. }
  76. }
  77. catch (Exception ex)
  78. {
  79. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  80. return BadRequest();
  81. }
  82. }
  83. /// <summary>
  84. /// 作答
  85. /// </summary>
  86. /// <param name="request"></param>
  87. /// <returns></returns>
  88. [ProducesDefaultResponseType]
  89. [Authorize(Roles = "IES")]
  90. [AuthToken(Roles = "teacher,admin")]
  91. [HttpPost("record-in")]
  92. public async Task<IActionResult> RecordIn(JsonElement request)
  93. {
  94. object userScope = null;
  95. object _standard = null;
  96. string standard = null;
  97. HttpContext?.Items?.TryGetValue("Scope", out userScope);
  98. if (userScope != null && $"{userScope}".Equals(Constant.ScopeTeacher))
  99. {
  100. HttpContext?.Items?.TryGetValue("Standard", out _standard);
  101. standard = _standard != null && string.IsNullOrEmpty($"{userScope}") ? _standard.ToString() : null;
  102. }
  103. var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
  104. try
  105. {
  106. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  107. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  108. if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  109. if (!request.TryGetProperty("ans", out JsonElement ans)) return BadRequest();
  110. var client = _azureCosmos.GetCosmosClient();
  111. List<List<string>> answer = ans.ToObject<List<List<string>>>();
  112. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  113. var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"ExamLite-{code}"));
  114. if (response.Status == (int)HttpStatusCode.OK)
  115. {
  116. var json = await JsonDocument.ParseAsync(response.ContentStream);
  117. ExamLite trExam = json.ToObject<ExamLite>();
  118. //List<List<string>> standard = trExam.items.answers;
  119. bool flag = trExam.teachers.Exists(s => s.id.Equals(tId.GetString()));
  120. List<string> ids = trExam.teachers.Select(e => e.id).ToList();
  121. int index = ids.IndexOf(tId.GetString());
  122. if (flag)
  123. {
  124. foreach (var record in trExam.teachers)
  125. {
  126. if (record.id.Equals(tId.GetString()))
  127. {
  128. record.answer = answer;
  129. record.time = now;
  130. }
  131. }
  132. }
  133. else {
  134. Record record = new();
  135. record.id = tId.GetString();
  136. record.answer = answer;
  137. record.time = now;
  138. trExam.teachers.Add(record);
  139. }
  140. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(trExam, trExam.id, new PartitionKey($"{trExam.code}"));
  141. if (!string.IsNullOrEmpty(standard) && !string.IsNullOrEmpty(school))
  142. {
  143. await StatisticsService.SendServiceBus( ($"{standard}", new List<string> { $"{userid}" }, $"{school}", new List<string>() { StatisticsService.TeacherExamLite }, 0) , _configuration, _serviceBus, client);
  144. }
  145. }
  146. else
  147. {
  148. return Ok(new { code = HttpStatusCode.NotFound });
  149. }
  150. return Ok(new { code = HttpStatusCode.OK });
  151. }
  152. catch (Exception ex)
  153. {
  154. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/record-in()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  155. return BadRequest();
  156. }
  157. }
  158. [ProducesDefaultResponseType]
  159. [AuthToken(Roles = "teacher,admin")]
  160. [HttpPost("delete")]
  161. [Authorize(Roles = "IES")]
  162. public async Task<IActionResult> Delete(JsonElement request)
  163. {
  164. try
  165. {
  166. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  167. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  168. var client = _azureCosmos.GetCosmosClient();
  169. var response = await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"ExamLite-{code}"));
  170. return Ok(new { id, code = response.Status });
  171. }
  172. catch (Exception e)
  173. {
  174. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/delete()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  175. return BadRequest();
  176. }
  177. }
  178. /// <param name="request"></param>
  179. /// <returns></returns>
  180. [ProducesDefaultResponseType]
  181. [Authorize(Roles = "IES")]
  182. [AuthToken(Roles = "teacher,admin")]
  183. [HttpPost("find")]
  184. public async Task<IActionResult> Find(JsonElement requert)
  185. {
  186. try
  187. {
  188. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  189. var client = _azureCosmos.GetCosmosClient();
  190. var query = $"select c.id,c.name,c.createTime from c ";
  191. string continuationToken = string.Empty;
  192. string token = default;
  193. //是否需要进行分页查询,默认不分页
  194. bool iscontinuation = false;
  195. if (requert.TryGetProperty("token", out JsonElement token_1))
  196. {
  197. token = token_1.GetString();
  198. iscontinuation = true;
  199. };
  200. //默认不指定返回大小
  201. int? topcout = null;
  202. if (requert.TryGetProperty("count", out JsonElement jcount))
  203. {
  204. if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
  205. {
  206. topcout = data;
  207. }
  208. }
  209. List<object> exam = new();
  210. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"ExamLite-{code}") }))
  211. {
  212. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  213. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  214. {
  215. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  216. {
  217. exam.Add(obj.ToObject<object>());
  218. }
  219. }
  220. if (iscontinuation)
  221. {
  222. continuationToken = item.GetContinuationToken();
  223. break;
  224. }
  225. }
  226. return Ok(new { exam });
  227. }
  228. catch (Exception e)
  229. {
  230. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  231. return BadRequest();
  232. }
  233. }
  234. [ProducesDefaultResponseType]
  235. [Authorize(Roles = "IES")]
  236. [AuthToken(Roles = "teacher,admin")]
  237. [HttpPost("find-summary")]
  238. public async Task<IActionResult> FindSummary(JsonElement requert)
  239. {
  240. try
  241. {
  242. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  243. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  244. var client = _azureCosmos.GetCosmosClient();
  245. List<ExamLite> trExams = new();
  246. ExamLite examLite = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<ExamLite>(id.GetString(), new PartitionKey($"ExamLite-{code}"));
  247. if (examLite != null)
  248. {
  249. (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetStutmdidListids(_coreAPIHttpService, client, _dingDing, examLite.tchLists, examLite.school);
  250. // (List<TmdInfo> tmdInfos, List<ClassListInfo> classInfos) = await TriggerStuActivity.GetTchList(client, _dingDing, ids, $"{school}");
  251. // (List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, examLite.tchLists, examLite.school);
  252. return Ok(new { examLite, teachers = tchList.Select(t => t.id).ToList(), status = 200 });
  253. }
  254. else
  255. {
  256. return Ok(new { examLite, status = 404 });
  257. }
  258. }
  259. catch (Exception e)
  260. {
  261. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  262. return Ok(new {status = 404 });
  263. }
  264. }
  265. /// <param name="request"></param>
  266. /// <returns></returns>
  267. [ProducesDefaultResponseType]
  268. [Authorize(Roles = "IES")]
  269. [AuthToken(Roles = "teacher,admin")]
  270. [HttpPost("find-by-teacher")]
  271. public async Task<IActionResult> FindByTeacher(JsonElement requert)
  272. {
  273. try
  274. {
  275. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  276. if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  277. var client = _azureCosmos.GetCosmosClient();
  278. var query = $"select c.id,c.name,c.createTime,A0.time from c join A0 in c.teachers where A0.id = '{tId}'";
  279. List<object> exams = new();
  280. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamLite-{code}") }))
  281. {
  282. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  283. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  284. {
  285. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  286. {
  287. exams.Add(obj.ToObject<object>());
  288. }
  289. }
  290. }
  291. return Ok(new { exams });
  292. }
  293. catch (Exception e)
  294. {
  295. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/find-by-teacher()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  296. return BadRequest();
  297. }
  298. }
  299. [ProducesDefaultResponseType]
  300. [Authorize(Roles = "IES")]
  301. [AuthToken(Roles = "teacher,admin")]
  302. [HttpPost("find-summary-by-teacher")]
  303. public async Task<IActionResult> FindSummaryByTeacher(JsonElement requert)
  304. {
  305. try
  306. {
  307. if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
  308. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  309. if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
  310. var client = _azureCosmos.GetCosmosClient();
  311. List<object> exams = new();
  312. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.teachers where A0.id = '{tId}' and c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamLite-{code}") }))
  313. {
  314. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  315. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  316. {
  317. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  318. {
  319. exams.Add(obj.ToObject<object>());
  320. }
  321. }
  322. }
  323. return Ok(new { exams });
  324. }
  325. catch (Exception e)
  326. {
  327. await _dingDing.SendBotMsg($"OS,{_option.Location},TrExam/find-summary-by-teacher()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  328. return BadRequest();
  329. }
  330. }
  331. }
  332. }