CommentController.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IdentityModel.Tokens.Jwt;
  7. using System.Text.Json;
  8. using System.Threading.Tasks;
  9. using TEAMModelOS.Models.Dto;
  10. using TEAMModelOS.SDK.Models;
  11. using TEAMModelOS.SDK;
  12. using TEAMModelOS.SDK.DI;
  13. using TEAMModelOS.SDK.Extension;
  14. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  15. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  16. using TEAMModelOS.Models;
  17. using Microsoft.Extensions.Options;
  18. using System.Text;
  19. using Azure.Messaging.ServiceBus;
  20. using Microsoft.Extensions.Configuration;
  21. using System.Linq;
  22. namespace TEAMModelOS.Controllers
  23. {
  24. [ProducesResponseType(StatusCodes.Status200OK)]
  25. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  26. //[Authorize(Roles = "IES5")]
  27. [Route("teacher/comment")]
  28. [ApiController]
  29. public class CommentController : ControllerBase
  30. {
  31. private readonly AzureCosmosFactory _azureCosmos;
  32. private readonly DingDing _dingDing;
  33. private readonly Option _option;
  34. private readonly AzureStorageFactory _azureStorage;
  35. public IConfiguration _configuration { get; set; }
  36. private readonly AzureServiceBusFactory _serviceBus;
  37. public CommentController(AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IConfiguration configuration)
  38. {
  39. _azureCosmos = azureCosmos;
  40. _dingDing = dingDing;
  41. _option = option?.Value;
  42. _azureStorage = azureStorage;
  43. _serviceBus = serviceBus;
  44. _configuration = configuration;
  45. }
  46. /// <summary>
  47. /// 添加教师评语快捷回复
  48. /// </summary>
  49. /// <param name="request"></param>
  50. /// <returns></returns>
  51. [ProducesDefaultResponseType]
  52. [HttpPost("add-comment")]
  53. public async Task<IActionResult> AddComment(JsonElement request)
  54. {
  55. //var id = "Comment-" + request.TEAMModelId.Replace("#", "");
  56. //ResponseBuilder builder = ResponseBuilder.custom();
  57. //List<Comment> comments = await _azureCosmos.FindByDict<Comment>(new Dictionary<string, object> { { "code", request.TEAMModelId }, { "id", id } });
  58. //Comment comment = new Comment();
  59. //if (comments.IsEmpty())
  60. //{
  61. // comment.id = id;
  62. // comment.code = request.TEAMModelId;
  63. // comment.comment.Add(request.comment);
  64. // comments.Add(comment);
  65. //}
  66. //else {
  67. // comment = comments[0];
  68. // comment.comment.Add(request.comment);
  69. //}
  70. //builder.Data(await _azureCosmos.SaveOrUpdate(comment));
  71. //return builder.build();
  72. //return Ok(await _azureCosmos.SaveOrUpdate(comment));
  73. return Ok();
  74. }
  75. /// <summary>
  76. /// 查询教师评语罐头
  77. /// </summary>
  78. /// <param name="request"></param>
  79. /// <returns></returns>
  80. [ProducesDefaultResponseType]
  81. [HttpPost("find-comment")]
  82. public async Task<IActionResult> findComment(JsonElement requert)
  83. {
  84. //var client = _azureCosmos.GetCosmosClient();
  85. //if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  86. ////var (id, name, picture, _) = HttpContext.GetAuthTokenInfo();
  87. //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  88. //var jwt = new JwtSecurityToken(id_token.GetString());
  89. //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.Ordinal)) return BadRequest();
  90. //var id = jwt.Payload.Sub;
  91. //List<object> comments = new List<object>();
  92. //var query = $"select c.id,c.comment from c";
  93. //await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Comment-{id}") }))
  94. //{
  95. // using var json = await JsonDocument.ParseAsync(item.ContentStream);
  96. // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  97. // {
  98. // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  99. // {
  100. // comments.Add(obj.ToObject<object>());
  101. // }
  102. // }
  103. //}
  104. return Ok();
  105. }
  106. /// <summary>
  107. /// 更新保存教师评语罐头,如果评语列表为空则删除
  108. /// </summary>
  109. /// <param name="request"></param>
  110. /// <returns></returns>
  111. [ProducesDefaultResponseType]
  112. [HttpPost("upsert-comment")]
  113. public async Task<IActionResult> UpsertComment(Comment request)
  114. {
  115. // request.TryAdd("PartitionKey", request.lang);
  116. //ResponseBuilder builder = ResponseBuilder.custom();
  117. //Comment comment = null;
  118. //if (request.comment.Count > 0)
  119. //{
  120. // if (string.IsNullOrEmpty(request.id)) {
  121. // request.id = "Comment-" + request.code.Replace("#", "");
  122. // }
  123. // comment = await _azureCosmos.SaveOrUpdate<Comment>(request);
  124. //}
  125. //else {
  126. // if (!string.IsNullOrEmpty(request.id))
  127. // {
  128. // IdPk idPk = await _azureCosmos.DeleteAsync<Comment>(request.id, request.code);
  129. // }
  130. //}
  131. ////return builder.Data(comment).build();
  132. return Ok();
  133. }
  134. //批注
  135. [ProducesDefaultResponseType]
  136. //[AuthToken(Roles = "Teacher")]
  137. [HttpPost("upsert-answer")]
  138. public async Task<IActionResult> upsertAnswer(JsonElement request)
  139. {
  140. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  141. if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
  142. if (!request.TryGetProperty("studentId", out JsonElement studentId)) return BadRequest();
  143. if (!request.TryGetProperty("tmdId", out JsonElement tId)) return BadRequest();
  144. if (!request.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
  145. if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
  146. if (!request.TryGetProperty("index", out JsonElement itemIndex)) return BadRequest();
  147. //根据不同评测的类型返回对应的编码
  148. if (!request.TryGetProperty("code", out JsonElement school)) return BadRequest();
  149. try
  150. {
  151. var client = _azureCosmos.GetCosmosClient();
  152. List<ExamClassResult> examClassResults = new List<ExamClassResult>();
  153. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  154. queryText: $"select value(c) from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
  155. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
  156. {
  157. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  158. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  159. {
  160. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  161. {
  162. examClassResults.Add(obj.ToObject<ExamClassResult>());
  163. }
  164. }
  165. }
  166. ExamClassResult classResult = new ExamClassResult();
  167. Details ans = answer.ToObject<Details>();
  168. List<List<string>> standard = new List<List<string>>();
  169. List<double> points = new List<double>();
  170. List<Task<string>> tasks = new List<Task<string>>();
  171. foreach (ExamClassResult result in examClassResults)
  172. {
  173. int index = result.studentIds.IndexOf(studentId.ToString());
  174. /*StringBuilder builder = new StringBuilder();
  175. builder.Append(result.examId).Append("/");
  176. builder.Append(result.subjectId).Append("/");
  177. builder.Append(studentId).Append("mark").Append("/");
  178. //builder.Append(tId).Append('/');
  179. builder.Append("ans.json");
  180. *//*string FileName = result.examId + "/" + result.subjectId + "/" + studentId;
  181. string blob = FileName + "/" + "ans.json";*//*
  182. tasks.Add(_azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", builder.ToString(), false));
  183. //result.studentAnswers[newIndex].Add(builder.ToString());
  184. *//*string FileName = result.examId + "/" + result.subjectId + "/" + studentId + "mark";
  185. string blob = await _azureStorage.UploadFileByContainer(school.ToString(), ans.ToJsonString(), "exam", FileName + "/" + "ans.json");*//*
  186. //result.studentAnswers[index].Add(blob);*/
  187. List<Details> details = result.mark[index][itemIndex.GetInt32()];
  188. if (details.Count > 0)
  189. {
  190. List<Details> ds = details.Where(x => x.tmdId.Equals(tId.GetString())).ToList();
  191. if (ds.Count > 0)
  192. {
  193. foreach (Details de in ds)
  194. {
  195. if (de.tmdId.Equals(ans.tmdId))
  196. {
  197. de.mark = ans.mark;
  198. de.sc = ans.sc;
  199. de.index = ans.index;
  200. }
  201. }
  202. }
  203. else {
  204. result.mark[index][itemIndex.GetInt32()].Add(ans);
  205. }
  206. }
  207. else {
  208. result.mark[index][itemIndex.GetInt32()].Add(ans);
  209. }
  210. /*result.mark[index][itemIndex.GetInt32()].Add(ans);
  211. if (result.mark == null || result.mark.Count == 0)
  212. {
  213. List<List<string>> annotation = new List<List<string>>();
  214. foreach (string ids in result.studentIds)
  215. {
  216. annotation.Add(new List<string>());
  217. }
  218. result.mark = annotation;
  219. }
  220. result.mark[index].Add(builder.ToString());*/
  221. classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(result, result.id, new PartitionKey($"{result.code}"));
  222. }
  223. await Task.WhenAll(tasks);
  224. /* //变更blob 大小
  225. ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new Azure.Cosmos.PartitionKey($"Exam-{school}"));
  226. info.size = await _azureStorage.GetBlobContainerClient(school.ToString()).GetBlobsSize($"exam/{id}");
  227. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "annotation", root = $"exam/{id}", name = school }.ToJsonString());
  228. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  229. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  230. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);*/
  231. return Ok(new { classResult });
  232. }
  233. catch (Exception e)
  234. {
  235. await _dingDing.SendBotMsg($"OS,{_option.Location},teacher/comment/upsertAnswer()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  236. return BadRequest();
  237. }
  238. }
  239. }
  240. }