CommonController.cs 20 KB

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