CommonController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. using Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net.Http;
  10. using System.Net.Http.Json;
  11. using System.Text;
  12. using System.Text.Json;
  13. using System.Threading.Tasks;
  14. using TEAMModelOS.Filter;
  15. using TEAMModelOS.Models;
  16. using TEAMModelOS.SDK.DI;
  17. using TEAMModelOS.SDK.Models;
  18. using TEAMModelOS.SDK.Models.Cosmos.Common;
  19. namespace TEAMModelOS.Controllers.Common
  20. {
  21. [ProducesResponseType(StatusCodes.Status200OK)]
  22. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  23. //[Authorize(Roles = "IES5")
  24. [Route("common")]
  25. [ApiController]
  26. public class CommonController : ControllerBase
  27. {
  28. private readonly AzureCosmosFactory _azureCosmos;
  29. private readonly SnowflakeId _snowflakeId;
  30. private readonly AzureServiceBusFactory _serviceBus;
  31. private readonly DingDing _dingDing;
  32. private readonly Option _option;
  33. private readonly AzureStorageFactory _azureStorage;
  34. private readonly IHttpClientFactory _clientFactory;
  35. public CommonController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, IHttpClientFactory clientFactory)
  36. {
  37. _azureCosmos = azureCosmos;
  38. _serviceBus = serviceBus;
  39. _snowflakeId = snowflakeId;
  40. _dingDing = dingDing;
  41. _option = option?.Value;
  42. _azureStorage = azureStorage;
  43. _clientFactory = clientFactory;
  44. }
  45. //立即结束某个活动
  46. [ProducesDefaultResponseType]
  47. // [AuthToken(Roles = "teacher,admin")]
  48. [HttpPost("count-activity")]
  49. public async Task<IActionResult> countActivity(JsonElement element)
  50. {
  51. try
  52. {
  53. List<string> keys = new List<string> { "Vote","Exam", "Survey","Homework","Learn" };
  54. var client = _azureCosmos.GetCosmosClient();
  55. element.TryGetProperty("code", out JsonElement code) ;
  56. element.TryGetProperty("tmdid", out JsonElement tmdid);
  57. Dictionary<string, int> countall = new Dictionary<string, int>();
  58. foreach (var key in keys) {
  59. string queryList = $"select count(1) as countschool from c where c.pk='{key}' ";
  60. if (code.ValueKind.Equals(JsonValueKind.String)) {
  61. var queryschool = $"select count(1) as countschool from c where c.pk='{key}' ";
  62. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  63. queryText: queryschool, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{key}-{code}") }))
  64. {
  65. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  66. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  67. {
  68. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  69. {
  70. if (countall.ContainsKey(key.ToLower()))
  71. {
  72. countall[key.ToLower()] = countall[key.ToLower()] + obj.GetProperty("countprivate").GetInt32();
  73. }
  74. else
  75. {
  76. countall.Add(key.ToLower(), obj.GetProperty("countschool").GetInt32());
  77. }
  78. }
  79. }
  80. }
  81. }
  82. if (tmdid.ValueKind.Equals(JsonValueKind.String)) {
  83. var queryprivate = $"select count(1) as countprivate from c where c.pk='{key}' ";
  84. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
  85. queryText: queryprivate, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{key}-{tmdid}") }))
  86. {
  87. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  88. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  89. {
  90. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  91. {
  92. if (countall.ContainsKey(key.ToLower()))
  93. {
  94. countall[key.ToLower()] = countall[key.ToLower()] + obj.GetProperty("countprivate").GetInt32();
  95. }
  96. else
  97. {
  98. countall.Add(key.ToLower(), obj.GetProperty("countprivate").GetInt32());
  99. }
  100. }
  101. }
  102. }
  103. }
  104. }
  105. return Ok(new { countall });
  106. } catch (Exception ex) {
  107. await _dingDing.SendBotMsg($"OS,{_option.Location},common/count-activity\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  108. return BadRequest();
  109. }
  110. }
  111. //立即结束某个活动
  112. [ProducesDefaultResponseType]
  113. [AuthToken(Roles = "teacher,admin")]
  114. [HttpPost("finish")]
  115. public async Task<IActionResult> finish(JsonElement element)
  116. {
  117. //var (id, school) = HttpContext.GetAuthTokenInfo();
  118. try
  119. {
  120. if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  121. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  122. var client = _azureCosmos.GetCosmosClient();
  123. var data = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync($"{id}", new Azure.Cosmos.PartitionKey($"{code}"));
  124. using var json = await JsonDocument.ParseAsync(data.ContentStream);
  125. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  126. Dictionary<string, object> dy = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(json.RootElement.ToString());
  127. dy["endTime"] = now;
  128. dy["progress"] = "finish";
  129. await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Dictionary<string, object>>(dy, dy["id"].ToString(), new Azure.Cosmos.PartitionKey(dy["code"].ToString()));
  130. var httpClient = _clientFactory.CreateClient();
  131. var content = new { id = $"{id}", code = $"{code}" };
  132. var response = await httpClient.PostAsJsonAsync($"{_option.HttpTrigger }refresh-stu-activity", content);
  133. return Ok(await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync()));
  134. }
  135. catch (Exception ex)
  136. {
  137. await _dingDing.SendBotMsg($"OS,{_option.Location},common/finish\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  138. return BadRequest();
  139. }
  140. }
  141. //更新评测活动size
  142. [ProducesDefaultResponseType]
  143. //[AuthToken(Roles = "teacher,admin")]
  144. [HttpPost("exam-size")]
  145. public async Task<IActionResult> examSize(JsonElement element)
  146. {
  147. //var (id, school) = HttpContext.GetAuthTokenInfo();
  148. try
  149. {
  150. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  151. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  152. var client = _azureCosmos.GetCosmosClient();
  153. List<ExamInfo> examInfo = new();
  154. List<Task<ItemResponse<ExamInfo>>> tasks = new();
  155. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<ExamInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{code}") }))
  156. {
  157. examInfo.Add(item);
  158. }
  159. foreach (ExamInfo info in examInfo)
  160. {
  161. if (info.size == 0)
  162. {
  163. info.size = await _azureStorage.GetBlobContainerClient(info.school).GetBlobsSize($"exam/{info.id}");
  164. tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
  165. }
  166. }
  167. await Task.WhenAll(tasks);
  168. return Ok();
  169. }
  170. catch (Exception ex)
  171. {
  172. await _dingDing.SendBotMsg($"OS,{_option.Location},common/exam-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  173. return BadRequest();
  174. }
  175. }
  176. //更新投票活动size
  177. [ProducesDefaultResponseType]
  178. //[AuthToken(Roles = "teacher,admin")]
  179. [HttpPost("vote-size")]
  180. public async Task<IActionResult> voteSize(JsonElement element)
  181. {
  182. //var (id, school) = HttpContext.GetAuthTokenInfo();
  183. try
  184. {
  185. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  186. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  187. var client = _azureCosmos.GetCosmosClient();
  188. List<Vote> votes = new();
  189. List<Task<ItemResponse<Vote>>> tasks = new();
  190. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Vote>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Vote-{code}") }))
  191. {
  192. votes.Add(item);
  193. }
  194. foreach (Vote vote in votes)
  195. {
  196. if (vote.size == 0)
  197. {
  198. vote.size = await _azureStorage.GetBlobContainerClient(vote.school).GetBlobsSize($"vote/{vote.id}");
  199. tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(vote, vote.id, new PartitionKey($"{vote.code}")));
  200. }
  201. }
  202. await Task.WhenAll(tasks);
  203. return Ok();
  204. }
  205. catch (Exception ex)
  206. {
  207. await _dingDing.SendBotMsg($"OS,{_option.Location},common/vote-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  208. return BadRequest();
  209. }
  210. }
  211. //更新问卷活动size
  212. [ProducesDefaultResponseType]
  213. //[AuthToken(Roles = "teacher,admin")]
  214. [HttpPost("survey-size")]
  215. public async Task<IActionResult> surveySize(JsonElement element)
  216. {
  217. try
  218. {
  219. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  220. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  221. var client = _azureCosmos.GetCosmosClient();
  222. List<Survey> surveys = new();
  223. List<Task<ItemResponse<Survey>>> tasks = new();
  224. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Survey>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Survey-{code}") }))
  225. {
  226. surveys.Add(item);
  227. }
  228. foreach (Survey survey in surveys)
  229. {
  230. if (survey.size == 0)
  231. {
  232. survey.size = await _azureStorage.GetBlobContainerClient(survey.school).GetBlobsSize($"vote/{survey.id}");
  233. tasks.Add(client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"{survey.code}")));
  234. }
  235. }
  236. await Task.WhenAll(tasks);
  237. return Ok();
  238. }
  239. catch (Exception ex)
  240. {
  241. await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  242. return BadRequest();
  243. }
  244. }
  245. //更新试题库size
  246. [ProducesDefaultResponseType]
  247. //[AuthToken(Roles = "teacher,admin")]
  248. [HttpPost("item-size")]
  249. public async Task<IActionResult> itemSize(JsonElement element)
  250. {
  251. try
  252. {
  253. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  254. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  255. var client = _azureCosmos.GetCosmosClient();
  256. List<ItemInfo> items = new();
  257. List<Task<ItemResponse<ItemInfo>>> tasks = new();
  258. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemInfo>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  259. {
  260. items.Add(item);
  261. }
  262. foreach (ItemInfo info in items)
  263. {
  264. if (info.size == 0)
  265. {
  266. info.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"item/{info.id}");
  267. tasks.Add(client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(info, info.id, new PartitionKey($"{info.code}")));
  268. }
  269. }
  270. await Task.WhenAll(tasks);
  271. return Ok();
  272. }
  273. catch (Exception ex)
  274. {
  275. await _dingDing.SendBotMsg($"OS,{_option.Location},common/item-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  276. return BadRequest();
  277. }
  278. }
  279. //更新试卷库size
  280. [ProducesDefaultResponseType]
  281. //[AuthToken(Roles = "teacher,admin")]
  282. [HttpPost("paper-size")]
  283. public async Task<IActionResult> paperSize(JsonElement element)
  284. {
  285. try
  286. {
  287. //if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  288. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  289. var client = _azureCosmos.GetCosmosClient();
  290. List<Paper> papers = new();
  291. List<Task<ItemResponse<Paper>>> tasks = new();
  292. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<Paper>(queryText: $"select value(c) from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Paper-{code}") }))
  293. {
  294. papers.Add(item);
  295. }
  296. foreach (Paper paper in papers)
  297. {
  298. if (paper.size == 0)
  299. {
  300. paper.size = await _azureStorage.GetBlobContainerClient(code.ToString()).GetBlobsSize($"paper/{paper.name}");
  301. tasks.Add(client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(paper, paper.id, new PartitionKey($"{paper.code}")));
  302. }
  303. }
  304. await Task.WhenAll(tasks);
  305. return Ok();
  306. }
  307. catch (Exception ex)
  308. {
  309. await _dingDing.SendBotMsg($"OS,{_option.Location},common/paper-size\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  310. return BadRequest();
  311. }
  312. }
  313. /// <summary>
  314. ///
  315. /// </summary>
  316. /// <param name="element"></param>
  317. /// <returns></returns>
  318. [ProducesDefaultResponseType]
  319. [HttpPost("delete-activity")]
  320. [AuthToken(Roles = "teacher,admin,student")]
  321. public async Task<IActionResult> DeleteActivity(JsonElement element) {
  322. try {
  323. if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
  324. if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
  325. if (!element.TryGetProperty("role", out JsonElement role)) return BadRequest();
  326. var client = _azureCosmos.GetCosmosClient();
  327. if (role.ValueKind.Equals(JsonValueKind.String))
  328. {
  329. if (role.GetString().Equals("teacher") || role.GetString().Equals("admin"))
  330. {
  331. await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemAsync<StuActivity>($"{id}", new PartitionKey($"{code}"));
  332. }
  333. else if (role.GetString().Equals("student"))
  334. {
  335. await client.GetContainer("TEAMModelOS", "Student").DeleteItemAsync<StuActivity>($"{id}", new PartitionKey($"{code}"));
  336. }
  337. else
  338. {
  339. return Ok(new { status = 500 });
  340. }
  341. }
  342. else {
  343. return Ok(new { status = 500 });
  344. }
  345. return Ok(new { status = 200 });
  346. } catch (Exception ex) {
  347. await _dingDing.SendBotMsg($"OS,{_option.Location},common/delete-activity\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  348. return Ok(new { status = 500 });
  349. }
  350. }
  351. }
  352. }