CommentController.cs 11 KB

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